├── .gitignore
├── .gitmodules
├── LICENSE
├── README.md
├── address.go
├── api.go
├── const.go
├── device.go
├── download.go
├── driver.go
├── error.go
├── examples
└── passthru
│ └── passthru.go
├── go.mod
├── go.sum
├── handle.go
├── header.go
├── helper.go
├── interface.go
├── internal
├── iana
│ ├── const.go
│ └── gen.go
└── utils
│ ├── addr.go
│ ├── appfilter.go
│ ├── ipfilter.go
│ ├── iphelper_windows.go
│ ├── iptree.go
│ ├── iptree
│ ├── iptree.go
│ ├── node32.go
│ └── node64.go
│ ├── resolver.go
│ └── suffixtree.go
├── packet.go
├── types.go
├── vars.go
├── windivert.go
└── windivert_device.go
/.gitignore:
--------------------------------------------------------------------------------
1 | # Operating System Files
2 | ## Windows
3 | Thumbs.db
4 | ehthumbs.db
5 | Desktop.ini
6 | $RECYCLE.BIN/
7 | *.lnk
8 |
9 | ## macOS
10 | .DS_Store
11 | .AppleDouble
12 | .LSOverride
13 | Icon
14 | ._*
15 | .Spotlight-V100
16 | .Trashes
17 |
18 | ## Linux
19 | *~
20 | .fuse_hidden*
21 | .directory
22 | .Trash-*
23 | .nfs*
24 |
25 | # IDE Files
26 | ## VSCode
27 | .vscode/*
28 | !.vscode/settings.json
29 | !.vscode/tasks.json
30 | !.vscode/launch.json
31 | !.vscode/extensions.json
32 | *.code-workspace
33 | .history/
34 |
35 | ## Cursor
36 | .cursor/
37 | .cursorrules
38 |
39 | # Project specific
40 | ## Third party code directory
41 | 3rd/*
42 | !3rd/.gitkeep
43 |
44 | # Temporary files
45 | *.log
46 | *.tmp
47 | *.temp
48 |
--------------------------------------------------------------------------------
/.gitmodules:
--------------------------------------------------------------------------------
1 | [submodule "3rd/WinDivert"]
2 | path = 3rd/WinDivert
3 | url = https://github.com/basil00/Divert.git
4 |
5 | [submodule "3rd/shadow"]
6 | path = 3rd/shadow
7 | url = https://github.com/imgk/shadow.git
8 |
9 | [submodule "3rd/go-windivert"]
10 | path = 3rd/go-windivert
11 | url = https://github.com/clmul/go-windivert.git
12 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 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 General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # go-WinDivert2
2 |
3 | Go bindings for [WinDivert 2.x](https://reqrypt.org/windivert.html)
4 |
5 | ## ChangeLogs
6 |
7 | - Initialization codes are mostly copied from [clmul/go-windivert](https://github.com/clmul/go-windivert).
8 | - Rebase to [github.com/imgk/shadow/device/windivert](https://github.com/imgk/shadow/tree/master/device/windivert)
9 |
10 | ## Thanks
11 |
12 | - [clmul/go-windivert](https://github.com/clmul/go-windivert)
13 | - [github.com/imgk/shadow/device/windivert](https://github.com/imgk/shadow/tree/master/device/windivert)
14 |
--------------------------------------------------------------------------------
/address.go:
--------------------------------------------------------------------------------
1 | package windivert
2 |
3 | import (
4 | "unsafe"
5 | )
6 |
7 | // PacketInfo contains parsed packet information
8 | type PacketInfo struct {
9 | IPv4Header *IPv4Header
10 | IPv6Header *IPv6Header
11 | ICMPHeader *ICMPHeader
12 | ICMPv6Header *ICMPv6Header
13 | TCPHeader *TCPHeader
14 | UDPHeader *UDPHeader
15 | Data []byte
16 | }
17 |
18 | // Ethernet represents ethernet layer information
19 | type Ethernet struct {
20 | InterfaceIndex uint32
21 | SubInterfaceIndex uint32
22 | _ [7]uint64
23 | }
24 |
25 | // Network represents network layer information
26 | type Network struct {
27 | InterfaceIndex uint32
28 | SubInterfaceIndex uint32
29 | _ [7]uint64
30 | }
31 |
32 | // Socket represents socket layer information
33 | type Socket struct {
34 | EndpointID uint64
35 | ParentEndpointID uint64
36 | ProcessID uint32
37 | LocalAddress [16]uint8
38 | RemoteAddress [16]uint8
39 | LocalPort uint16
40 | RemotePort uint16
41 | Protocol uint8
42 | _ [3]uint8
43 | _ uint32
44 | }
45 |
46 | // Flow represents flow layer information
47 | type Flow struct {
48 | EndpointID uint64
49 | ParentEndpointID uint64
50 | ProcessID uint32
51 | LocalAddress [16]uint8
52 | RemoteAddress [16]uint8
53 | LocalPort uint16
54 | RemotePort uint16
55 | Protocol uint8
56 | _ [3]uint8
57 | _ uint32
58 | }
59 |
60 | // Reflect represents reflect layer information
61 | type Reflect struct {
62 | TimeStamp int64
63 | ProcessID uint32
64 | layer uint32
65 | Flags uint64
66 | Priority int16
67 | _ int16
68 | _ int32
69 | _ [4]uint64
70 | }
71 |
72 | // Layer returns the layer type for reflect information
73 | func (r *Reflect) Layer() Layer {
74 | return Layer(r.layer)
75 | }
76 |
77 | // Address represents a WinDivert address
78 | type Address struct {
79 | Timestamp int64
80 | LayerType Layer // renamed from Layer
81 | EventType Event // renamed from Event
82 | IsSniffed uint8 // renamed from Sniffed
83 | IsOutbound uint8 // renamed from Outbound
84 | HasIPChecksum uint8 // renamed from IPChecksum
85 | HasTCPChecksum uint8 // renamed from TCPChecksum
86 | HasUDPChecksum uint8 // renamed from UDPChecksum
87 | Flags uint8
88 | union [64]byte
89 | length uint64
90 | }
91 |
92 | // GetLayer returns the layer type
93 | func (a *Address) Layer() Layer {
94 | return a.LayerType
95 | }
96 |
97 | // SetLayer sets the layer type
98 | func (a *Address) SetLayer(layer Layer) {
99 | a.LayerType = layer
100 | }
101 |
102 | // GetEvent returns the event type
103 | func (a *Address) Event() Event {
104 | return Event(a.EventType)
105 | }
106 |
107 | // SetEvent sets the event type
108 | func (a *Address) SetEvent(event Event) {
109 | a.EventType = Event(event)
110 | }
111 |
112 | // IsSniffed returns whether the packet was sniffed
113 | func (a *Address) Sniffed() bool {
114 | return (a.Flags & uint8(0x01<<0)) == uint8(0x01<<0)
115 | }
116 |
117 | // SetSniffed sets the sniffed flag
118 | func (a *Address) SetSniffed() {
119 | a.Flags |= uint8(0x01 << 0)
120 | }
121 |
122 | // UnsetSniffed unsets the sniffed flag
123 | func (a *Address) UnsetSniffed() {
124 | a.Flags &= ^uint8(0x01 << 0)
125 | }
126 |
127 | // IsOutbound returns whether the packet is outbound
128 | func (a *Address) Outbound() bool {
129 | return (a.Flags & uint8(0x01<<1)) == uint8(0x01<<1)
130 | }
131 |
132 | // SetOutbound sets the outbound flag
133 | func (a *Address) SetOutbound() {
134 | a.Flags |= uint8(0x01 << 1)
135 | }
136 |
137 | // UnsetOutbound unsets the outbound flag
138 | func (a *Address) UnsetOutbound() {
139 | a.Flags &= ^uint8(0x01 << 1)
140 | }
141 |
142 | // HasIPChecksum returns whether IP checksum is present
143 | func (a *Address) IPChecksum() bool {
144 | return (a.Flags & uint8(0x01<<5)) == uint8(0x01<<5)
145 | }
146 |
147 | // SetIPChecksum sets the IP checksum flag
148 | func (a *Address) SetIPChecksum() {
149 | a.Flags |= uint8(0x01 << 5)
150 | }
151 |
152 | // UnsetIPChecksum unsets the IP checksum flag
153 | func (a *Address) UnsetIPChecksum() {
154 | a.Flags &= ^uint8(0x01 << 5)
155 | }
156 |
157 | // HasTCPChecksum returns whether TCP checksum is present
158 | func (a *Address) TCPChecksum() bool {
159 | return (a.Flags & uint8(0x01<<6)) == uint8(0x01<<6)
160 | }
161 |
162 | // SetTCPChecksum sets the TCP checksum flag
163 | func (a *Address) SetTCPChecksum() {
164 | a.Flags |= uint8(0x01 << 6)
165 | }
166 |
167 | // UnsetTCPChecksum unsets the TCP checksum flag
168 | func (a *Address) UnsetTCPChecksum() {
169 | a.Flags &= ^uint8(0x01 << 6)
170 | }
171 |
172 | // HasUDPChecksum returns whether UDP checksum is present
173 | func (a *Address) UDPChecksum() bool {
174 | return (a.Flags & uint8(0x01<<7)) == uint8(0x01<<7)
175 | }
176 |
177 | // SetUDPChecksum sets the UDP checksum flag
178 | func (a *Address) SetUDPChecksum() {
179 | a.Flags |= uint8(0x01 << 7)
180 | }
181 |
182 | // UnsetUDPChecksum unsets the UDP checksum flag
183 | func (a *Address) UnsetUDPChecksum() {
184 | a.Flags &= ^uint8(0x01 << 7)
185 | }
186 |
187 | func (a *Address) Length() uint32 {
188 | return uint32(a.length >> 12)
189 | }
190 |
191 | func (a *Address) SetLength(n uint32) {
192 | a.length = uint64(n << 12)
193 | }
194 |
195 | func (a *Address) Ethernet() *Ethernet {
196 | return (*Ethernet)(unsafe.Pointer(&a.union))
197 | }
198 |
199 | func (a *Address) Network() *Network {
200 | return (*Network)(unsafe.Pointer(&a.union))
201 | }
202 |
203 | func (a *Address) Socket() *Socket {
204 | return (*Socket)(unsafe.Pointer(&a.union))
205 | }
206 |
207 | func (a *Address) Flow() *Flow {
208 | return (*Flow)(unsafe.Pointer(&a.union))
209 | }
210 |
211 | func (a *Address) Reflect() *Reflect {
212 | return (*Reflect)(unsafe.Pointer(&a.union))
213 | }
214 |
215 | type AddressHelper interface {
216 | CalcChecksums(packet []byte, flags uint64) error
217 | ParseIPv4Header(packet []byte) (*IPv4Header, error)
218 | ParseIPv6Header(packet []byte) (*IPv6Header, error)
219 | ParseTCPHeader(packet []byte) (*TCPHeader, error)
220 | ParseUDPHeader(packet []byte) (*UDPHeader, error)
221 | }
222 |
--------------------------------------------------------------------------------
/api.go:
--------------------------------------------------------------------------------
1 | package windivert
2 |
3 | /*
4 | #include
5 | #include
6 | */
7 | import "C"
8 |
9 | import (
10 | "sync"
11 | "unsafe"
12 | )
13 |
14 | // Handle represents a WinDivert handle
15 | type Handle struct {
16 | handle C.HANDLE
17 | mutex sync.Mutex
18 | }
19 |
20 | // Open opens a WinDivert handle
21 | func Open(filter string, layer Layer, priority int16, flags uint64) (*Handle, error) {
22 | cfilter := C.CString(filter)
23 | defer C.free(unsafe.Pointer(cfilter))
24 |
25 | handle := C.WinDivertOpen(cfilter, C.WINDIVERT_LAYER(layer), C.INT16(priority), C.UINT64(flags))
26 | if handle == C.INVALID_HANDLE_VALUE {
27 | return nil, getLastError()
28 | }
29 |
30 | return &Handle{handle: handle}, nil
31 | }
32 |
33 | // Close closes the WinDivert handle
34 | func (h *Handle) Close() error {
35 | if h.handle != C.INVALID_HANDLE_VALUE {
36 | if C.WinDivertClose(h.handle) == 0 {
37 | return getLastError()
38 | }
39 | h.handle = C.INVALID_HANDLE_VALUE
40 | }
41 | return nil
42 | }
43 |
44 | // Recv receives a single packet
45 | func (h *Handle) Recv(packet []byte, addr *Address) (uint, error) {
46 | nr, _, err := h.RecvEx([][]byte{packet}, []Address{*addr}, 0)
47 | if err != nil {
48 | return 0, err
49 | }
50 | return nr, nil
51 | }
52 |
53 | // Send sends a single packet
54 | func (h *Handle) Send(packet []byte, addr *Address) (uint, error) {
55 | nw, err := h.SendEx([][]byte{packet}, []Address{*addr}, 0)
56 | if err != nil {
57 | return 0, err
58 | }
59 | return nw, nil
60 | }
61 |
--------------------------------------------------------------------------------
/const.go:
--------------------------------------------------------------------------------
1 | package windivert
2 |
3 | // Layer represents WinDivert layers
4 | type Layer int
5 |
6 | const (
7 | LayerNetwork Layer = 0
8 | LayerNetworkForward Layer = 1
9 | LayerFlow Layer = 2
10 | LayerSocket Layer = 3
11 | LayerReflect Layer = 4
12 | )
13 |
14 | func (l Layer) String() string {
15 | switch l {
16 | case LayerNetwork:
17 | return "WINDIVERT_LAYER_NETWORK"
18 | case LayerNetworkForward:
19 | return "WINDIVERT_LAYER_NETWORK_FORWARD"
20 | case LayerFlow:
21 | return "WINDIVERT_LAYER_FLOW"
22 | case LayerSocket:
23 | return "WINDIVERT_LAYER_SOCKET"
24 | case LayerReflect:
25 | return "WINDIVERT_LAYER_REFLECT"
26 | default:
27 | return ""
28 | }
29 | }
30 |
31 | // Event represents WinDivert events
32 | type Event int
33 |
34 | const (
35 | EventNetworkPacket Event = 0
36 | EventFlowEstablished Event = 1
37 | EventFlowDeleted Event = 2
38 | EventSocketBind Event = 3
39 | EventSocketConnect Event = 4
40 | EventSocketListen Event = 5
41 | EventSocketAccept Event = 6
42 | EventSocketClose Event = 7
43 | EventReflectOpen Event = 8
44 | EventReflectClose Event = 9
45 | EventEthernetFrame Event = 10
46 | )
47 |
48 | // ShutdownType represents WinDivert shutdown types
49 | type ShutdownType uint32
50 |
51 | const (
52 | ShutdownRecv ShutdownType = 0
53 | ShutdownSend ShutdownType = 1
54 | ShutdownBoth ShutdownType = 2
55 | )
56 |
57 | // Param represents WinDivert parameters
58 | type Param uint32
59 |
60 | const (
61 | QueueLength Param = 0
62 | QueueTime Param = 1
63 | QueueSize Param = 2
64 | VersionMajor Param = 3
65 | VersionMinor Param = 4
66 | )
67 |
68 | // Flags for WinDivertOpen()
69 | const (
70 | FlagDefault uint64 = 0
71 | FlagSniff uint64 = 1
72 | FlagDrop uint64 = 2
73 | FlagDebug uint64 = 4
74 | FlagRecvOnly uint64 = 8
75 | FlagSendOnly uint64 = 16
76 | FlagNoInstall uint64 = 32
77 | FlagFragments uint64 = 64
78 | )
79 |
80 | // Default values
81 | const (
82 | PriorityDefault = 0
83 | QueueLengthDefault = 512
84 | QueueLengthMin = 32
85 | QueueLengthMax = 16384
86 | QueueTimeDefault = 2000
87 | QueueTimeMin = 100
88 | QueueTimeMax = 16000
89 | QueueSizeDefault = 4194304
90 | QueueSizeMin = 65535
91 | QueueSizeMax = 33554432
92 | )
93 |
94 | const (
95 | BatchMax = 0xff
96 | MTUMax = 40 + 0xffff
97 | )
98 |
99 | // CtlCode represents a control code
100 | type CtlCode uint32
101 |
102 | const (
103 | CtlCodeInitialize = CtlCode(0x921)
104 | CtlCodeStartup = CtlCode(0x922)
105 | CtlCodeRecv = CtlCode(0x923)
106 | CtlCodeSend = CtlCode(0x924)
107 | CtlCodeSetParam = CtlCode(0x925)
108 | CtlCodeGetParam = CtlCode(0x926)
109 | CtlCodeShutdown = CtlCode(0x927)
110 | )
111 |
--------------------------------------------------------------------------------
/device.go:
--------------------------------------------------------------------------------
1 | package windivert
2 |
3 | import (
4 | "errors"
5 | "fmt"
6 | "io"
7 | "net"
8 | "time"
9 | "unsafe"
10 |
11 | "golang.org/x/net/ipv4"
12 | "golang.org/x/net/ipv6"
13 | "golang.org/x/sys/windows"
14 |
15 | "github.com/sbilly/go-windivert2/internal/iana"
16 | "github.com/sbilly/go-windivert2/internal/utils"
17 | )
18 |
19 | var (
20 | ErrNoData = windows.WSAEWOULDBLOCK
21 | ErrHostUnreachable = windows.WSAEHOSTUNREACH
22 | )
23 |
24 | // Device represents a WinDivert handle
25 | type Device struct {
26 | *Address
27 | *io.PipeReader
28 | *io.PipeWriter
29 | *utils.AppFilter
30 | *utils.IPFilter
31 | *Handle
32 | TCP [65536]uint8
33 | UDP [65536]uint8
34 | TCP6 [65536]uint8
35 | UDP6 [65536]uint8
36 | active chan struct{}
37 | event chan struct{}
38 | }
39 |
40 | func NewDevice(filter string) (dev *Device, err error) {
41 | CloseWhenError := func(hd *Handle) {
42 | if err != nil {
43 | hd.Close()
44 | }
45 | }
46 |
47 | ifIdx, subIfIdx, er := GetInterfaceIndex()
48 | if er != nil {
49 | err = er
50 | return
51 | }
52 |
53 | filter = fmt.Sprintf("ifIdx = %d and ", ifIdx) + filter
54 | hd, er := Open(filter, LayerNetwork, PriorityDefault, FlagDefault)
55 | if er != nil {
56 | err = fmt.Errorf("open handle error: %v", er)
57 | return
58 | }
59 | defer CloseWhenError(hd)
60 |
61 | if er := hd.SetParam(QueueLength, QueueLengthMax); er != nil {
62 | err = fmt.Errorf("set handle parameter queue length error %v", er)
63 | return
64 | }
65 | if er := hd.SetParam(QueueTime, QueueTimeMax); er != nil {
66 | err = fmt.Errorf("set handle parameter queue time error %v", er)
67 | return
68 | }
69 | if er := hd.SetParam(QueueSize, QueueSizeMax); er != nil {
70 | err = fmt.Errorf("set handle parameter queue size error %v", er)
71 | return
72 | }
73 |
74 | r, w := io.Pipe()
75 | dev = &Device{
76 | Address: new(Address),
77 | PipeReader: r,
78 | PipeWriter: w,
79 | AppFilter: utils.NewAppFilter(),
80 | IPFilter: utils.NewIPFilter(),
81 | Handle: hd,
82 | active: make(chan struct{}),
83 | event: make(chan struct{}, 1),
84 | }
85 |
86 | go dev.writeLoop()
87 |
88 | nw := dev.Address.Network()
89 | nw.InterfaceIndex = ifIdx
90 | nw.SubInterfaceIndex = subIfIdx
91 |
92 | return
93 | }
94 |
95 | func (d *Device) Close() error {
96 | select {
97 | case <-d.active:
98 | return nil
99 | default:
100 | close(d.active)
101 | }
102 | defer d.Handle.Close()
103 |
104 | d.PipeReader.Close()
105 | d.PipeWriter.Close()
106 |
107 | if err := d.Handle.Shutdown(ShutdownBoth); err != nil {
108 | return fmt.Errorf("shutdown handle error: %v", err)
109 | }
110 |
111 | if err := d.Handle.Close(); err != nil {
112 | return fmt.Errorf("close handle error: %v", err)
113 | }
114 |
115 | return nil
116 | }
117 |
118 | func (d *Device) WriteTo(w io.Writer) (n int64, err error) {
119 | a := make([]Address, BatchMax)
120 | b := make([]byte, 1500*BatchMax)
121 |
122 | const f = uint8(0x01<<7) | uint8(0x01<<6) | uint8(0x01<<5) | uint8(0x01<<3)
123 |
124 | for {
125 | var (
126 | nr, nx uint
127 | er error
128 | )
129 |
130 | nr32, nx32, er := d.Handle.RecvEx([][]byte{b}, a[:1], 0)
131 | nr = uint(nr32)
132 | nx = uint(nx32)
133 | if er != nil {
134 | select {
135 | case <-d.active:
136 | default:
137 | if er != ErrNoData {
138 | err = fmt.Errorf("RecvEx in WriteTo error: %v", er)
139 | }
140 | }
141 | return
142 | }
143 |
144 | if nr == 0 || nx == 0 {
145 | continue
146 | }
147 |
148 | n += int64(nr)
149 |
150 | bb := b[:nr]
151 | for i := uint(0); i < nx; i++ {
152 | switch bb[0] >> 4 {
153 | case ipv4.Version:
154 | l := int(bb[2])<<8 | int(bb[3])
155 |
156 | if d.CheckIPv4(bb) {
157 | _, er := w.Write(bb[:l])
158 | if er != nil {
159 | select {
160 | case <-d.active:
161 | default:
162 | err = fmt.Errorf("Write in WriteTo error: %v", er)
163 | }
164 |
165 | return
166 | }
167 |
168 | a[i].Flags |= f
169 |
170 | bb[8] = 0
171 | }
172 |
173 | bb = bb[l:]
174 | case ipv6.Version:
175 | l := int(bb[4])<<8 | int(bb[5]) + ipv6.HeaderLen
176 |
177 | if d.CheckIPv6(bb) {
178 | _, er := w.Write(bb[:l])
179 | if er != nil {
180 | select {
181 | case <-d.active:
182 | default:
183 | err = fmt.Errorf("Write in WriteTo error: %v", er)
184 | }
185 |
186 | return
187 | }
188 |
189 | a[i].Flags |= f
190 |
191 | bb[7] = 0
192 | }
193 |
194 | bb = bb[l:]
195 | default:
196 | err = errors.New("invalid ip version")
197 | return
198 | }
199 | }
200 |
201 | d.Handle.Lock()
202 | _, er = d.Handle.SendEx([][]byte{bb}, a[:nx], 0)
203 | d.Handle.Unlock()
204 | if er != nil && er != ErrHostUnreachable {
205 | select {
206 | case <-d.active:
207 | default:
208 | err = fmt.Errorf("SendEx in WriteTo error: %v", er)
209 | }
210 | return
211 | }
212 | }
213 | }
214 |
215 | const (
216 | FIN = 1 << 0
217 | SYN = 1 << 1
218 | RST = 1 << 2
219 | PSH = 1 << 3
220 | ACK = 1 << 4
221 | UGR = 1 << 5
222 | ECE = 1 << 6
223 | CWR = 1 << 7
224 | )
225 |
226 | func (d *Device) CheckIPv4(b []byte) bool {
227 | switch b[9] {
228 | case iana.ProtocolTCP:
229 | p := uint32(b[ipv4.HeaderLen])<<8 | uint32(b[ipv4.HeaderLen+1])
230 | switch d.TCP[p] {
231 | case 0:
232 | if b[ipv4.HeaderLen+13]&SYN != SYN {
233 | d.TCP[p] = 1
234 | return false
235 | }
236 |
237 | if d.IPFilter.Lookup(net.IP(b[16:20])) {
238 | d.TCP[p] = 2
239 | return true
240 | }
241 |
242 | if d.CheckTCP4(b) {
243 | d.TCP[p] = 2
244 | return true
245 | }
246 |
247 | d.TCP[p] = 1
248 | return false
249 | case 1:
250 | if b[ipv4.HeaderLen+13]&FIN == FIN {
251 | d.TCP[p] = 0
252 | }
253 |
254 | return false
255 | case 2:
256 | if b[ipv4.HeaderLen+13]&FIN == FIN {
257 | d.TCP[p] = 0
258 | }
259 |
260 | return true
261 | }
262 | case iana.ProtocolUDP:
263 | p := uint32(b[ipv4.HeaderLen])<<8 | uint32(b[ipv4.HeaderLen+1])
264 |
265 | switch d.UDP[p] {
266 | case 0:
267 | fn := func() { d.UDP[p] = 0 }
268 |
269 | if d.IPFilter.Lookup(net.IP(b[16:20])) {
270 | d.UDP[p] = 2
271 | time.AfterFunc(time.Minute, fn)
272 | return true
273 | }
274 |
275 | if d.CheckUDP4(b) {
276 | d.UDP[p] = 2
277 | time.AfterFunc(time.Minute, fn)
278 | return true
279 | }
280 |
281 | if (uint32(b[ipv4.HeaderLen+2])<<8 | uint32(b[ipv4.HeaderLen+3])) == 53 {
282 | return true
283 | }
284 |
285 | d.UDP[p] = 1
286 | time.AfterFunc(time.Minute, fn)
287 |
288 | return false
289 | case 1:
290 | return false
291 | case 2:
292 | return true
293 | }
294 | default:
295 | return d.IPFilter.Lookup(net.IP(b[16:20]))
296 | }
297 |
298 | return false
299 | }
300 |
301 | func (d *Device) CheckTCP4(b []byte) bool {
302 | rs, err := utils.GetTCPTable()
303 | if err != nil {
304 | return false
305 | }
306 |
307 | p := uint32(b[ipv4.HeaderLen]) | uint32(b[ipv4.HeaderLen+1])<<8
308 |
309 | for i := range rs {
310 | if rs[i].LocalPort == p {
311 | if *(*uint32)(unsafe.Pointer(&b[12])) == rs[i].LocalAddr {
312 | return d.AppFilter.Lookup(rs[i].OwningPid)
313 | }
314 | }
315 | }
316 |
317 | return false
318 | }
319 |
320 | func (d *Device) CheckUDP4(b []byte) bool {
321 | rs, err := utils.GetUDPTable()
322 | if err != nil {
323 | return false
324 | }
325 |
326 | p := uint32(b[ipv4.HeaderLen]) | uint32(b[ipv4.HeaderLen+1])<<8
327 |
328 | for i := range rs {
329 | if rs[i].LocalPort == p {
330 | if 0 == rs[i].LocalAddr || *(*uint32)(unsafe.Pointer(&b[12])) == rs[i].LocalAddr {
331 | return d.AppFilter.Lookup(rs[i].OwningPid)
332 | }
333 | }
334 | }
335 |
336 | return false
337 | }
338 |
339 | func (d *Device) CheckIPv6(b []byte) bool {
340 | switch b[6] {
341 | case iana.ProtocolTCP:
342 | p := uint32(b[ipv6.HeaderLen])<<8 | uint32(b[ipv6.HeaderLen+1])
343 | switch d.TCP6[p] {
344 | case 0:
345 | if b[ipv6.HeaderLen+13]&SYN != SYN {
346 | d.TCP6[p] = 1
347 | return false
348 | }
349 |
350 | if d.IPFilter.Lookup(net.IP(b[24:40])) {
351 | d.TCP6[p] = 2
352 | return true
353 | }
354 |
355 | if d.CheckTCP6(b) {
356 | d.TCP6[p] = 2
357 | return true
358 | }
359 |
360 | d.TCP6[p] = 1
361 | return false
362 | case 1:
363 | if b[ipv6.HeaderLen+13]&FIN == FIN {
364 | d.TCP6[p] = 0
365 | }
366 |
367 | return false
368 | case 2:
369 | if b[ipv6.HeaderLen+13]&FIN == FIN {
370 | d.TCP6[p] = 0
371 | }
372 |
373 | return true
374 | }
375 | case iana.ProtocolUDP:
376 | p := uint32(b[ipv6.HeaderLen])<<8 | uint32(b[ipv6.HeaderLen+1])
377 |
378 | switch d.UDP6[p] {
379 | case 0:
380 | fn := func() { d.UDP6[p] = 0 }
381 |
382 | if d.IPFilter.Lookup(net.IP(b[24:40])) {
383 | d.UDP6[p] = 2
384 | time.AfterFunc(time.Minute, fn)
385 | return true
386 | }
387 |
388 | if d.CheckUDP6(b) {
389 | d.UDP6[p] = 2
390 | time.AfterFunc(time.Minute, fn)
391 | return true
392 | }
393 |
394 | if (uint32(b[ipv6.HeaderLen+2])<<8 | uint32(b[ipv6.HeaderLen+3])) == 53 {
395 | return true
396 | }
397 |
398 | d.UDP6[p] = 1
399 | time.AfterFunc(time.Minute, fn)
400 | return false
401 | case 1:
402 | return false
403 | case 2:
404 | return true
405 | }
406 | default:
407 | return d.IPFilter.Lookup(net.IP(b[24:40]))
408 | }
409 |
410 | return false
411 | }
412 |
413 | func (d *Device) CheckTCP6(b []byte) bool {
414 | rs, err := utils.GetTCP6Table()
415 | if err != nil {
416 | return false
417 | }
418 |
419 | p := uint32(b[ipv6.HeaderLen]) | uint32(b[ipv6.HeaderLen+1])<<8
420 | a := *(*[4]uint32)(unsafe.Pointer(&b[8]))
421 |
422 | for i := range rs {
423 | if rs[i].LocalPort == p {
424 | if a[0] == rs[i].LocalAddr[0] && a[1] == rs[i].LocalAddr[1] && a[2] == rs[i].LocalAddr[2] && a[3] == rs[i].LocalAddr[3] {
425 | return d.AppFilter.Lookup(rs[i].OwningPid)
426 | }
427 | }
428 | }
429 |
430 | return false
431 | }
432 |
433 | func (d *Device) CheckUDP6(b []byte) bool {
434 | rs, err := utils.GetUDP6Table()
435 | if err != nil {
436 | return false
437 | }
438 |
439 | p := uint32(b[ipv6.HeaderLen]) | uint32(b[ipv6.HeaderLen+1])<<8
440 | a := *(*[4]uint32)(unsafe.Pointer(&b[0]))
441 |
442 | for i := range rs {
443 | if rs[i].LocalPort == p {
444 | if (0 == rs[i].LocalAddr[0] && 0 == rs[i].LocalAddr[1] && 0 == rs[i].LocalAddr[2] && 0 == rs[i].LocalAddr[3]) || (a[0] == rs[i].LocalAddr[0] && a[1] == rs[i].LocalAddr[1] && a[2] == rs[i].LocalAddr[2] && a[3] == rs[i].LocalAddr[3]) {
445 | return d.AppFilter.Lookup(rs[i].OwningPid)
446 | }
447 | }
448 | }
449 |
450 | return false
451 | }
452 |
453 | func (d *Device) writeLoop() {
454 | t := time.NewTicker(time.Millisecond)
455 | defer t.Stop()
456 |
457 | const f = uint8(0x01<<7) | uint8(0x01<<6) | uint8(0x01<<5)
458 |
459 | a := make([]Address, BatchMax)
460 | b := make([]byte, 1500*BatchMax)
461 |
462 | for i := range a {
463 | a[i] = *d.Address
464 | a[i].Flags |= f
465 | }
466 |
467 | n, m := 0, 0
468 | for {
469 | select {
470 | case <-t.C:
471 | if m > 0 {
472 | d.Handle.Lock()
473 | _, err := d.Handle.SendEx([][]byte{b[:n]}, a[:m], 0)
474 | d.Handle.Unlock()
475 | if err != nil {
476 | select {
477 | case <-d.active:
478 | default:
479 | panic(fmt.Errorf("device writeLoop error: %v", err))
480 | }
481 |
482 | return
483 | }
484 |
485 | n, m = 0, 0
486 | }
487 | case <-d.event:
488 | nr, err := d.PipeReader.Read(b[n:])
489 | if err != nil {
490 | select {
491 | case <-d.active:
492 | default:
493 | panic(fmt.Errorf("device writeLoop error: %v", err))
494 | }
495 |
496 | return
497 | }
498 |
499 | n += nr
500 | m++
501 |
502 | if m == BatchMax {
503 | d.Handle.Lock()
504 | _, err := d.Handle.SendEx([][]byte{b[:n]}, a[:m], 0)
505 | d.Handle.Unlock()
506 | if err != nil {
507 | select {
508 | case <-d.active:
509 | default:
510 | panic(fmt.Errorf("device writeLoop error: %v", err))
511 | }
512 |
513 | return
514 | }
515 |
516 | n, m = 0, 0
517 | }
518 | case <-d.active:
519 | }
520 | }
521 | }
522 |
523 | func (d *Device) Write(b []byte) (int, error) {
524 | select {
525 | case <-d.active:
526 | return 0, io.EOF
527 | case d.event <- struct{}{}:
528 | }
529 |
530 | n, err := d.PipeWriter.Write(b)
531 | if err != nil {
532 | select {
533 | case <-d.active:
534 | return 0, io.EOF
535 | default:
536 | }
537 | }
538 |
539 | return n, err
540 | }
541 |
--------------------------------------------------------------------------------
/download.go:
--------------------------------------------------------------------------------
1 | package windivert
2 |
3 | import (
4 | "archive/zip"
5 | "bytes"
6 | "fmt"
7 | "io/ioutil"
8 | "net/http"
9 | "os"
10 | "strings"
11 | )
12 |
13 | func Download() error {
14 | var (
15 | ver = "2.2.0"
16 | url = "https://github.com/basil00/Divert/releases/download/v" + ver + "/WinDivert-" + ver + "-A.zip"
17 | sys = ""
18 | dll = ""
19 | )
20 |
21 | if ^uint(0)>>63 == 1 {
22 | sys = "x64/WinDivert64.sys"
23 | dll = "x64/WinDivert.dll"
24 | } else {
25 | sys = "x86/WinDivert32.sys"
26 | dll = "x86/WinDivert.dll"
27 | }
28 |
29 | if _, err := os.Stat(WinDivertSys); err == nil {
30 | return nil
31 | }
32 |
33 | resp, err := http.Get(url)
34 | if err != nil {
35 | return err
36 | }
37 | defer resp.Body.Close()
38 |
39 | if resp.StatusCode != http.StatusOK {
40 | return fmt.Errorf("http status code is %v", resp.StatusCode)
41 | }
42 |
43 | zipFile, err := ioutil.ReadAll(resp.Body)
44 | if err != nil {
45 | return err
46 | }
47 |
48 | reader := bytes.NewReader(zipFile)
49 |
50 | zipReader, err := zip.NewReader(reader, int64(reader.Len()))
51 | if err != nil {
52 | return err
53 | }
54 |
55 | for _, file := range zipReader.File {
56 | if strings.HasSuffix(file.Name, sys) {
57 | f, err := file.Open()
58 | if err != nil {
59 | return err
60 | }
61 | defer f.Close()
62 |
63 | data, err := ioutil.ReadAll(f)
64 | if err != nil {
65 | return err
66 | }
67 |
68 | if err = ioutil.WriteFile(WinDivertSys, data, 0444); err != nil {
69 | return err
70 | }
71 | }
72 |
73 | if strings.HasSuffix(file.Name, dll) {
74 | f, err := file.Open()
75 | if err != nil {
76 | return err
77 | }
78 | defer f.Close()
79 |
80 | data, err := ioutil.ReadAll(f)
81 | if err != nil {
82 | return err
83 | }
84 |
85 | if err = ioutil.WriteFile(WinDivertDll, data, 0444); err != nil {
86 | return err
87 | }
88 | }
89 | }
90 |
91 | return nil
92 | }
93 |
--------------------------------------------------------------------------------
/driver.go:
--------------------------------------------------------------------------------
1 | package windivert
2 |
3 | import (
4 | "errors"
5 | "fmt"
6 | "os"
7 |
8 | "golang.org/x/sys/windows"
9 | "golang.org/x/sys/windows/registry"
10 | )
11 |
12 | const types = 7
13 |
14 | func CloseMutex(mutex windows.Handle) {
15 | windows.ReleaseMutex(mutex)
16 | windows.CloseHandle(mutex)
17 | }
18 |
19 | func InstallDriver() error {
20 | mutex, err := windows.CreateMutex(nil, false, windows.StringToUTF16Ptr("WinDivertDriverInstallMutex"))
21 | if err != nil {
22 | return err
23 | }
24 | defer CloseMutex(mutex)
25 |
26 | event, err := windows.WaitForSingleObject(mutex, windows.INFINITE)
27 | if err != nil {
28 | return err
29 | }
30 | switch event {
31 | case windows.WAIT_OBJECT_0, windows.WAIT_ABANDONED:
32 | default:
33 | return errors.New("wait for object error")
34 | }
35 |
36 | manager, err := windows.OpenSCManager(nil, nil, windows.SC_MANAGER_ALL_ACCESS)
37 | if err != nil {
38 | return err
39 | }
40 | defer windows.CloseServiceHandle(manager)
41 |
42 | service, err := windows.OpenService(manager, DeviceName, windows.SERVICE_ALL_ACCESS)
43 | if err == nil {
44 | windows.CloseServiceHandle(service)
45 | return nil
46 | }
47 |
48 | sys, err := GetDriverFileName()
49 | if err != nil {
50 | return err
51 | }
52 |
53 | service, err = windows.CreateService(manager, DeviceName, DeviceName, windows.SERVICE_ALL_ACCESS, windows.SERVICE_KERNEL_DRIVER, windows.SERVICE_DEMAND_START, windows.SERVICE_ERROR_NORMAL, windows.StringToUTF16Ptr(sys), nil, nil, nil, nil, nil)
54 | if err != nil {
55 | if err == windows.ERROR_SERVICE_EXISTS {
56 | return nil
57 | }
58 |
59 | service, err = windows.OpenService(manager, DeviceName, windows.SERVICE_ALL_ACCESS)
60 | if err != nil {
61 | return err
62 | }
63 | }
64 | defer windows.CloseServiceHandle(service)
65 |
66 | if err := windows.StartService(service, 0, nil); err != nil && err != windows.ERROR_SERVICE_ALREADY_RUNNING {
67 | return err
68 | }
69 |
70 | if err := windows.DeleteService(service); err != nil && err != windows.ERROR_SERVICE_MARKED_FOR_DELETE {
71 | return err
72 | }
73 |
74 | return nil
75 | }
76 |
77 | func RemoveDriver() error {
78 | status := windows.SERVICE_STATUS{}
79 |
80 | manager, err := windows.OpenSCManager(nil, nil, windows.SC_MANAGER_ALL_ACCESS)
81 | if err != nil {
82 | return err
83 | }
84 | defer windows.CloseServiceHandle(manager)
85 |
86 | service, err := windows.OpenService(manager, DeviceName, windows.SERVICE_ALL_ACCESS)
87 | if err != nil {
88 | if err == windows.ERROR_SERVICE_DOES_NOT_EXIST {
89 | return nil
90 | }
91 |
92 | return err
93 | }
94 | defer windows.CloseServiceHandle(service)
95 |
96 | if err := windows.ControlService(service, windows.SERVICE_CONTROL_STOP, &status); err != nil {
97 | if err == windows.ERROR_SERVICE_NOT_ACTIVE {
98 | return nil
99 | }
100 |
101 | return err
102 | }
103 |
104 | if err := windows.DeleteService(service); err != nil {
105 | if err == windows.ERROR_SERVICE_MARKED_FOR_DELETE {
106 | return nil
107 | }
108 |
109 | return err
110 | }
111 |
112 | return nil
113 | }
114 |
115 | func GetDriverFileName() (string, error) {
116 | key, err := registry.OpenKey(registry.LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\EventLog\\System\\WinDivert", registry.QUERY_VALUE)
117 | if err != nil {
118 | if _, err := os.Stat(WinDivertSys); err != nil {
119 | if er := Download(); er != nil {
120 | return "", fmt.Errorf("file error: %w, download error: %w", err, er)
121 | }
122 | }
123 |
124 | if err := RegisterEventSource(WinDivertSys); err != nil {
125 | return "", err
126 | }
127 |
128 | return WinDivertSys, nil
129 | }
130 | defer key.Close()
131 |
132 | val, _, err := key.GetStringValue("EventMessageFile")
133 | if err != nil {
134 | return "", err
135 | }
136 |
137 | if _, err := os.Stat(val); err != nil {
138 | if _, err := os.Stat(WinDivertSys); err != nil {
139 | if er := Download(); er != nil {
140 | return "", fmt.Errorf("file error: %w, download error: %w", err, er)
141 | }
142 | }
143 |
144 | if err := RegisterEventSource(WinDivertSys); err != nil {
145 | return "", err
146 | }
147 |
148 | return WinDivertSys, nil
149 | }
150 |
151 | return val, nil
152 | }
153 |
154 | func RegisterEventSource(sys string) error {
155 | key, _, err := registry.CreateKey(registry.LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\EventLog\\System\\WinDivert", registry.ALL_ACCESS)
156 | if err != nil {
157 | return err
158 | }
159 | defer key.Close()
160 |
161 | if err := key.SetStringValue("EventMessageFile", sys); err != nil {
162 | return err
163 | }
164 |
165 | if err := key.SetDWordValue("TypesSupported", types); err != nil {
166 | return err
167 | }
168 |
169 | return nil
170 | }
171 |
172 | // Core functions that map to WinDivert API
173 | type Driver interface {
174 | // Open opens a WinDivert handle
175 | // Maps to WinDivertOpen()
176 | Open(filter string, layer Layer, priority int16, flags uint64) error
177 |
178 | // Close closes the WinDivert handle
179 | // Maps to WinDivertClose()
180 | Close() error
181 |
182 | // Recv receives a packet
183 | // Maps to WinDivertRecv()
184 | Recv(packet []byte) (int, *Address, error)
185 |
186 | // RecvEx receives multiple packets
187 | // Maps to WinDivertRecvEx()
188 | RecvEx(packets [][]byte) (int, []*Address, error)
189 |
190 | // Send sends a packet
191 | // Maps to WinDivertSend()
192 | Send(packet []byte, addr *Address) (int, error)
193 |
194 | // SendEx sends multiple packets
195 | // Maps to WinDivertSendEx()
196 | SendEx(packets [][]byte, addrs []*Address) (int, error)
197 | }
198 |
--------------------------------------------------------------------------------
/error.go:
--------------------------------------------------------------------------------
1 | package windivert
2 |
3 | /*
4 | #include
5 | #include
6 |
7 | HANDLE getLastError() {
8 | return GetLastError();
9 | }
10 | */
11 | import "C"
12 |
13 | import (
14 | "fmt"
15 | "syscall"
16 | )
17 |
18 | // getLastError returns the last error that occurred
19 | func getLastError() error {
20 | code := C.getLastError()
21 | if code == 0 {
22 | return nil
23 | }
24 | return fmt.Errorf("windivert error: %d", uint32(code))
25 | }
26 |
27 | var (
28 | ErrNoData = syscall.WSAEWOULDBLOCK
29 | ErrHostUnreachable = syscall.WSAEHOSTUNREACH
30 | )
31 |
--------------------------------------------------------------------------------
/examples/passthru/passthru.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "os"
6 | "os/signal"
7 | "syscall"
8 |
9 | windivert "github.com/sbilly/go-windivert2"
10 | )
11 |
12 | func main() {
13 | // 打开一个 WinDivert 句柄
14 | handle, err := windivert.Open("true", windivert.LayerNetwork, 0, 0)
15 | if err != nil {
16 | fmt.Printf("Error opening WinDivert handle: %v\n", err)
17 | return
18 | }
19 | defer handle.Close()
20 |
21 | // 处理 Ctrl+C
22 | sigCh := make(chan os.Signal, 1)
23 | signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
24 |
25 | // 数据包处理循环
26 | packet := make([]byte, 1500)
27 | for {
28 | select {
29 | case <-sigCh:
30 | return
31 | default:
32 | n, addr, err := handle.Recv(packet)
33 | if err != nil {
34 | fmt.Printf("Error receiving packet: %v\n", err)
35 | continue
36 | }
37 |
38 | // 重新注入数据包
39 | _, err = handle.Send(packet[:n], addr)
40 | if err != nil {
41 | fmt.Printf("Error sending packet: %v\n", err)
42 | }
43 | }
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/sbilly/go-windivert2
2 |
3 | go 1.21
4 |
5 | require (
6 | golang.org/x/net v0.19.0
7 | golang.org/x/sys v0.15.0
8 | )
9 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | golang.org/x/net v0.19.0 h1:zTwKpTd2XuCqf8huc7Fo2iSy+4RHPd10s4KzeTnVr1c=
2 | golang.org/x/net v0.19.0/go.mod h1:CfAk/cbD4CthTvqiEl8NpboMuiuOYsAr/7NOjZJtv1U=
3 | golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc=
4 | golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
5 |
--------------------------------------------------------------------------------
/handle.go:
--------------------------------------------------------------------------------
1 | package windivert
2 |
3 | /*
4 | #include
5 | #include
6 | */
7 | import "C"
8 |
9 | // Handle 的方法实现...
10 | func (h *Handle) Lock() {
11 | h.mutex.Lock()
12 | }
13 |
14 | // 其他方法保持不变...
15 |
--------------------------------------------------------------------------------
/header.go:
--------------------------------------------------------------------------------
1 | package windivert
2 |
3 | // IPv4Header represents an IPv4 header
4 | type IPv4Header struct {
5 | HdrLength uint8 // Header length
6 | Version uint8 // Version
7 | TOS uint8 // Type of service
8 | Length uint16 // Total length
9 | Id uint16 // Identification
10 | FragOff uint16 // Fragment offset
11 | TTL uint8 // Time to live
12 | Protocol uint8 // Protocol
13 | Checksum uint16 // Checksum
14 | SrcAddr uint32 // Source address
15 | DstAddr uint32 // Destination address
16 | }
17 |
18 | // IPv6Header represents an IPv6 header
19 | type IPv6Header struct {
20 | Version uint8 // Version
21 | TrafficClass uint8 // Traffic class
22 | FlowLabel uint32 // Flow label
23 | Length uint16 // Payload length
24 | NextHdr uint8 // Next header
25 | HopLimit uint8 // Hop limit
26 | SrcAddr [16]byte // Source address
27 | DstAddr [16]byte // Destination address
28 | }
29 |
30 | // ICMPHeader represents an ICMP header
31 | type ICMPHeader struct {
32 | Type uint8 // Type
33 | Code uint8 // Code
34 | Checksum uint16 // Checksum
35 | Body uint32 // Body
36 | }
37 |
38 | // ICMPv6Header represents an ICMPv6 header
39 | type ICMPv6Header struct {
40 | Type uint8 // Type
41 | Code uint8 // Code
42 | Checksum uint16 // Checksum
43 | Body uint32 // Body
44 | }
45 |
46 | // TCPHeader represents a TCP header
47 | type TCPHeader struct {
48 | SrcPort uint16 // Source port
49 | DstPort uint16 // Destination port
50 | SeqNum uint32 // Sequence number
51 | AckNum uint32 // Acknowledgement number
52 | Reserved1 uint8 // Reserved
53 | Reserved2 uint8 // Reserved
54 | Reserved3 uint8 // Reserved
55 | Flags uint8 // Flags
56 | Window uint16 // Window
57 | Checksum uint16 // Checksum
58 | UrgPtr uint16 // Urgent pointer
59 | }
60 |
61 | // UDPHeader represents a UDP header
62 | type UDPHeader struct {
63 | SrcPort uint16 // Source port
64 | DstPort uint16 // Destination port
65 | Length uint16 // Length
66 | Checksum uint16 // Checksum
67 | }
68 |
--------------------------------------------------------------------------------
/helper.go:
--------------------------------------------------------------------------------
1 | package windivert
2 |
3 | import (
4 | "fmt"
5 | "unsafe"
6 | )
7 |
8 | /*
9 | #cgo CFLAGS: -I${SRCDIR}/include
10 | #cgo LDFLAGS: -L${SRCDIR}/lib -lwindivert
11 | #include
12 | #include
13 | */
14 | import "C"
15 |
16 | // CalcChecksums calculates checksums for the packet
17 | func CalcChecksums(packet []byte, addr *Address, flags uint64) error {
18 | if len(packet) == 0 {
19 | return fmt.Errorf("empty packet buffer")
20 | }
21 |
22 | caddr := (*C.WINDIVERT_ADDRESS)(unsafe.Pointer(addr))
23 | ret := C.WinDivertHelperCalcChecksums(
24 | unsafe.Pointer(&packet[0]),
25 | C.UINT(len(packet)),
26 | caddr,
27 | C.UINT64(flags),
28 | )
29 |
30 | if ret == 0 {
31 | return getLastError()
32 | }
33 |
34 | return nil
35 | }
36 |
37 | // ParsePacket parses a network packet
38 | func ParsePacket(packet []byte) (*PacketInfo, error) {
39 | if len(packet) == 0 {
40 | return nil, fmt.Errorf("empty packet buffer")
41 | }
42 |
43 | var info C.WINDIVERT_PACKET_INFO
44 | ret := C.WinDivertHelperParsePacket(
45 | unsafe.Pointer(&packet[0]),
46 | C.UINT(len(packet)),
47 | &info.IPv4Header,
48 | &info.IPv6Header,
49 | &info.ICMPHeader,
50 | &info.ICMPv6Header,
51 | &info.TCPHeader,
52 | &info.UDPHeader,
53 | &info.Data,
54 | &info.DataLen,
55 | )
56 |
57 | if ret == 0 {
58 | return nil, getLastError()
59 | }
60 |
61 | return (*PacketInfo)(unsafe.Pointer(&info)), nil
62 | }
63 |
64 | // FormatIPv4Address formats an IPv4 address
65 | func FormatIPv4Address(addr uint32) string {
66 | var buf [16]C.char
67 | C.WinDivertHelperFormatIPv4Address(C.UINT32(addr), &buf[0], 16)
68 | return C.GoString(&buf[0])
69 | }
70 |
71 | // FormatIPv6Address formats an IPv6 address
72 | func FormatIPv6Address(addr [4]uint32) string {
73 | var buf [46]C.char
74 | C.WinDivertHelperFormatIPv6Address((*C.UINT32)(&addr[0]), &buf[0], 46)
75 | return C.GoString(&buf[0])
76 | }
77 |
78 | // NtohIPv4Address converts a network byte order IPv4 address to host byte order
79 | func NtohIPv4Address(addr uint32) uint32 {
80 | return uint32(C.WinDivertHelperNtohIPv4Address(C.UINT32(addr)))
81 | }
82 |
83 | // NtohIPv6Address converts a network byte order IPv6 address to host byte order
84 | func NtohIPv6Address(addr [4]uint32) [4]uint32 {
85 | var result [4]uint32
86 | C.WinDivertHelperNtohIPv6Address((*C.UINT32)(&addr[0]), (*C.UINT32)(&result[0]))
87 | return result
88 | }
89 |
90 | // HtonIPv4Address converts a host byte order IPv4 address to network byte order
91 | func HtonIPv4Address(addr uint32) uint32 {
92 | return uint32(C.WinDivertHelperHtonIPv4Address(C.UINT32(addr)))
93 | }
94 |
95 | // HtonIPv6Address converts a host byte order IPv6 address to network byte order
96 | func HtonIPv6Address(addr [4]uint32) [4]uint32 {
97 | var result [4]uint32
98 | C.WinDivertHelperHtonIPv6Address((*C.UINT32)(&addr[0]), (*C.UINT32)(&result[0]))
99 | return result
100 | }
101 |
102 | // HashPacket calculates a 64bit hash value of the given packet
103 | func HashPacket(packet []byte, seed uint64) (uint64, error) {
104 | if len(packet) == 0 {
105 | return 0, fmt.Errorf("empty packet buffer")
106 | }
107 |
108 | hash := C.WinDivertHelperHashPacket(
109 | unsafe.Pointer(&packet[0]),
110 | C.UINT(len(packet)),
111 | C.UINT64(seed),
112 | )
113 |
114 | return uint64(hash), nil
115 | }
116 |
117 | // DecrementTTL decrements the TTL/HopLimit field of an IP packet
118 | func DecrementTTL(packet []byte) error {
119 | if len(packet) == 0 {
120 | return fmt.Errorf("empty packet buffer")
121 | }
122 |
123 | ret := C.WinDivertHelperDecrementTTL(
124 | unsafe.Pointer(&packet[0]),
125 | C.UINT(len(packet)),
126 | )
127 |
128 | if ret == 0 {
129 | return fmt.Errorf("TTL/HopLimit would become 0")
130 | }
131 |
132 | return nil
133 | }
134 |
135 | // CompileFilter compiles a filter string into an object representation
136 | func CompileFilter(filter string, layer Layer) (string, error) {
137 | cfilter := C.CString(filter)
138 | defer C.free(unsafe.Pointer(cfilter))
139 |
140 | var errorStr *C.char
141 | var errorPos C.UINT
142 | var objBuf [1024]C.char
143 |
144 | ret := C.WinDivertHelperCompileFilter(
145 | cfilter,
146 | C.WINDIVERT_LAYER(layer),
147 | &objBuf[0],
148 | C.UINT(len(objBuf)),
149 | &errorStr,
150 | &errorPos,
151 | )
152 |
153 | if ret == 0 {
154 | return "", fmt.Errorf("filter compilation failed at position %d: %s",
155 | uint(errorPos), C.GoString(errorStr))
156 | }
157 |
158 | return C.GoString(&objBuf[0]), nil
159 | }
160 |
161 | // EvalFilter evaluates a packet against a filter string
162 | func EvalFilter(filter string, packet []byte, addr *Address) (bool, error) {
163 | if len(packet) == 0 {
164 | return false, fmt.Errorf("empty packet buffer")
165 | }
166 |
167 | cfilter := C.CString(filter)
168 | defer C.free(unsafe.Pointer(cfilter))
169 |
170 | caddr := (*C.WINDIVERT_ADDRESS)(unsafe.Pointer(addr))
171 | ret := C.WinDivertHelperEvalFilter(
172 | cfilter,
173 | unsafe.Pointer(&packet[0]),
174 | C.UINT(len(packet)),
175 | caddr,
176 | )
177 |
178 | return ret != 0, nil
179 | }
180 |
181 | // FormatFilter formats a filter string
182 | func FormatFilter(filter string, layer Layer) (string, error) {
183 | cfilter := C.CString(filter)
184 | defer C.free(unsafe.Pointer(cfilter))
185 |
186 | var buf [1024]C.char
187 | ret := C.WinDivertHelperFormatFilter(
188 | cfilter,
189 | C.WINDIVERT_LAYER(layer),
190 | &buf[0],
191 | C.UINT(len(buf)),
192 | )
193 |
194 | if ret == 0 {
195 | return "", getLastError()
196 | }
197 |
198 | return C.GoString(&buf[0]), nil
199 | }
200 |
201 | // Htons converts a 16-bit number from host to network byte order
202 | func Htons(x uint16) uint16 {
203 | return uint16(C.WinDivertHelperHtons(C.UINT16(x)))
204 | }
205 |
206 | // Htonl converts a 32-bit number from host to network byte order
207 | func Htonl(x uint32) uint32 {
208 | return uint32(C.WinDivertHelperHtonl(C.UINT32(x)))
209 | }
210 |
211 | // Htonll converts a 64-bit number from host to network byte order
212 | func Htonll(x uint64) uint64 {
213 | return uint64(C.WinDivertHelperHtonll(C.UINT64(x)))
214 | }
215 |
--------------------------------------------------------------------------------
/interface.go:
--------------------------------------------------------------------------------
1 | package windivert
2 |
3 | import (
4 | "fmt"
5 | "net"
6 | "sync"
7 | "time"
8 | )
9 |
10 | func DialIPv4(wg *sync.WaitGroup) {
11 | defer wg.Done()
12 |
13 | conn, err := net.DialTimeout("tcp4", "8.8.8.8:53", time.Second)
14 | if err != nil {
15 | return
16 | }
17 |
18 | conn.Close()
19 | }
20 |
21 | func DialIPv6(wg *sync.WaitGroup) {
22 | defer wg.Done()
23 |
24 | conn, err := net.DialTimeout("tcp6", "[2001:4860:4860::8888]:53", time.Second)
25 | if err != nil {
26 | return
27 | }
28 |
29 | conn.Close()
30 | }
31 |
32 | func GetInterfaceIndex() (uint32, uint32, error) {
33 | var filter = "not loopback and outbound and (ip.DstAddr = 8.8.8.8 or ipv6.DstAddr = 2001:4860:4860::8888) and tcp.DstPort = 53"
34 | hd, err := Open(filter, LayerNetwork, PriorityDefault, FlagSniff)
35 | if err != nil {
36 | return 0, 0, fmt.Errorf("open interface handle error: %v", err)
37 | }
38 | defer hd.Close()
39 |
40 | wg := &sync.WaitGroup{}
41 |
42 | wg.Add(1)
43 | go DialIPv4(wg)
44 |
45 | wg.Add(1)
46 | go DialIPv6(wg)
47 |
48 | a := new(Address)
49 | b := make([]byte, 1500)
50 |
51 | if _, err := hd.Recv(b, a); err != nil {
52 | return 0, 0, err
53 | }
54 |
55 | if err := hd.Shutdown(ShutdownBoth); err != nil {
56 | return 0, 0, fmt.Errorf("shutdown interface handle error: %v", err)
57 | }
58 |
59 | if err := hd.Close(); err != nil {
60 | return 0, 0, fmt.Errorf("close interface handle error: %v", err)
61 | }
62 |
63 | wg.Wait()
64 |
65 | nw := a.Network()
66 | return nw.InterfaceIndex, nw.SubInterfaceIndex, nil
67 | }
68 |
--------------------------------------------------------------------------------
/internal/iana/const.go:
--------------------------------------------------------------------------------
1 | // go generate gen.go
2 | // Code generated by the command above; DO NOT EDIT.
3 |
4 | // Package iana provides protocol number resources managed by the Internet Assigned Numbers Authority (IANA).
5 | package iana
6 |
7 | // import "golang.org/x/net/internal/iana"
8 |
9 | // Differentiated Services Field Codepoints (DSCP), Updated: 2019-06-19
10 | const (
11 | DiffServCS0 = 0x00 // CS0
12 | DiffServCS1 = 0x20 // CS1
13 | DiffServCS2 = 0x40 // CS2
14 | DiffServCS3 = 0x60 // CS3
15 | DiffServCS4 = 0x80 // CS4
16 | DiffServCS5 = 0xa0 // CS5
17 | DiffServCS6 = 0xc0 // CS6
18 | DiffServCS7 = 0xe0 // CS7
19 | DiffServAF11 = 0x28 // AF11
20 | DiffServAF12 = 0x30 // AF12
21 | DiffServAF13 = 0x38 // AF13
22 | DiffServAF21 = 0x48 // AF21
23 | DiffServAF22 = 0x50 // AF22
24 | DiffServAF23 = 0x58 // AF23
25 | DiffServAF31 = 0x68 // AF31
26 | DiffServAF32 = 0x70 // AF32
27 | DiffServAF33 = 0x78 // AF33
28 | DiffServAF41 = 0x88 // AF41
29 | DiffServAF42 = 0x90 // AF42
30 | DiffServAF43 = 0x98 // AF43
31 | DiffServEF = 0xb8 // EF
32 | DiffServVOICEADMIT = 0xb0 // VOICE-ADMIT
33 | NotECNTransport = 0x00 // Not-ECT (Not ECN-Capable Transport)
34 | ECNTransport1 = 0x01 // ECT(1) (ECN-Capable Transport(1))
35 | ECNTransport0 = 0x02 // ECT(0) (ECN-Capable Transport(0))
36 | CongestionExperienced = 0x03 // CE (Congestion Experienced)
37 | )
38 |
39 | // Protocol Numbers, Updated: 2020-01-31
40 | const (
41 | ProtocolIP = 0 // IPv4 encapsulation, pseudo protocol number
42 | ProtocolHOPOPT = 0 // IPv6 Hop-by-Hop Option
43 | ProtocolICMP = 1 // Internet Control Message
44 | ProtocolIGMP = 2 // Internet Group Management
45 | ProtocolGGP = 3 // Gateway-to-Gateway
46 | ProtocolIPv4 = 4 // IPv4 encapsulation
47 | ProtocolST = 5 // Stream
48 | ProtocolTCP = 6 // Transmission Control
49 | ProtocolCBT = 7 // CBT
50 | ProtocolEGP = 8 // Exterior Gateway Protocol
51 | ProtocolIGP = 9 // any private interior gateway (used by Cisco for their IGRP)
52 | ProtocolBBNRCCMON = 10 // BBN RCC Monitoring
53 | ProtocolNVPII = 11 // Network Voice Protocol
54 | ProtocolPUP = 12 // PUP
55 | ProtocolEMCON = 14 // EMCON
56 | ProtocolXNET = 15 // Cross Net Debugger
57 | ProtocolCHAOS = 16 // Chaos
58 | ProtocolUDP = 17 // User Datagram
59 | ProtocolMUX = 18 // Multiplexing
60 | ProtocolDCNMEAS = 19 // DCN Measurement Subsystems
61 | ProtocolHMP = 20 // Host Monitoring
62 | ProtocolPRM = 21 // Packet Radio Measurement
63 | ProtocolXNSIDP = 22 // XEROX NS IDP
64 | ProtocolTRUNK1 = 23 // Trunk-1
65 | ProtocolTRUNK2 = 24 // Trunk-2
66 | ProtocolLEAF1 = 25 // Leaf-1
67 | ProtocolLEAF2 = 26 // Leaf-2
68 | ProtocolRDP = 27 // Reliable Data Protocol
69 | ProtocolIRTP = 28 // Internet Reliable Transaction
70 | ProtocolISOTP4 = 29 // ISO Transport Protocol Class 4
71 | ProtocolNETBLT = 30 // Bulk Data Transfer Protocol
72 | ProtocolMFENSP = 31 // MFE Network Services Protocol
73 | ProtocolMERITINP = 32 // MERIT Internodal Protocol
74 | ProtocolDCCP = 33 // Datagram Congestion Control Protocol
75 | Protocol3PC = 34 // Third Party Connect Protocol
76 | ProtocolIDPR = 35 // Inter-Domain Policy Routing Protocol
77 | ProtocolXTP = 36 // XTP
78 | ProtocolDDP = 37 // Datagram Delivery Protocol
79 | ProtocolIDPRCMTP = 38 // IDPR Control Message Transport Proto
80 | ProtocolTPPP = 39 // TP++ Transport Protocol
81 | ProtocolIL = 40 // IL Transport Protocol
82 | ProtocolIPv6 = 41 // IPv6 encapsulation
83 | ProtocolSDRP = 42 // Source Demand Routing Protocol
84 | ProtocolIPv6Route = 43 // Routing Header for IPv6
85 | ProtocolIPv6Frag = 44 // Fragment Header for IPv6
86 | ProtocolIDRP = 45 // Inter-Domain Routing Protocol
87 | ProtocolRSVP = 46 // Reservation Protocol
88 | ProtocolGRE = 47 // Generic Routing Encapsulation
89 | ProtocolDSR = 48 // Dynamic Source Routing Protocol
90 | ProtocolBNA = 49 // BNA
91 | ProtocolESP = 50 // Encap Security Payload
92 | ProtocolAH = 51 // Authentication Header
93 | ProtocolINLSP = 52 // Integrated Net Layer Security TUBA
94 | ProtocolNARP = 54 // NBMA Address Resolution Protocol
95 | ProtocolMOBILE = 55 // IP Mobility
96 | ProtocolTLSP = 56 // Transport Layer Security Protocol using Kryptonet key management
97 | ProtocolSKIP = 57 // SKIP
98 | ProtocolIPv6ICMP = 58 // ICMP for IPv6
99 | ProtocolIPv6NoNxt = 59 // No Next Header for IPv6
100 | ProtocolIPv6Opts = 60 // Destination Options for IPv6
101 | ProtocolCFTP = 62 // CFTP
102 | ProtocolSATEXPAK = 64 // SATNET and Backroom EXPAK
103 | ProtocolKRYPTOLAN = 65 // Kryptolan
104 | ProtocolRVD = 66 // MIT Remote Virtual Disk Protocol
105 | ProtocolIPPC = 67 // Internet Pluribus Packet Core
106 | ProtocolSATMON = 69 // SATNET Monitoring
107 | ProtocolVISA = 70 // VISA Protocol
108 | ProtocolIPCV = 71 // Internet Packet Core Utility
109 | ProtocolCPNX = 72 // Computer Protocol Network Executive
110 | ProtocolCPHB = 73 // Computer Protocol Heart Beat
111 | ProtocolWSN = 74 // Wang Span Network
112 | ProtocolPVP = 75 // Packet Video Protocol
113 | ProtocolBRSATMON = 76 // Backroom SATNET Monitoring
114 | ProtocolSUNND = 77 // SUN ND PROTOCOL-Temporary
115 | ProtocolWBMON = 78 // WIDEBAND Monitoring
116 | ProtocolWBEXPAK = 79 // WIDEBAND EXPAK
117 | ProtocolISOIP = 80 // ISO Internet Protocol
118 | ProtocolVMTP = 81 // VMTP
119 | ProtocolSECUREVMTP = 82 // SECURE-VMTP
120 | ProtocolVINES = 83 // VINES
121 | ProtocolTTP = 84 // Transaction Transport Protocol
122 | ProtocolIPTM = 84 // Internet Protocol Traffic Manager
123 | ProtocolNSFNETIGP = 85 // NSFNET-IGP
124 | ProtocolDGP = 86 // Dissimilar Gateway Protocol
125 | ProtocolTCF = 87 // TCF
126 | ProtocolEIGRP = 88 // EIGRP
127 | ProtocolOSPFIGP = 89 // OSPFIGP
128 | ProtocolSpriteRPC = 90 // Sprite RPC Protocol
129 | ProtocolLARP = 91 // Locus Address Resolution Protocol
130 | ProtocolMTP = 92 // Multicast Transport Protocol
131 | ProtocolAX25 = 93 // AX.25 Frames
132 | ProtocolIPIP = 94 // IP-within-IP Encapsulation Protocol
133 | ProtocolSCCSP = 96 // Semaphore Communications Sec. Pro.
134 | ProtocolETHERIP = 97 // Ethernet-within-IP Encapsulation
135 | ProtocolENCAP = 98 // Encapsulation Header
136 | ProtocolGMTP = 100 // GMTP
137 | ProtocolIFMP = 101 // Ipsilon Flow Management Protocol
138 | ProtocolPNNI = 102 // PNNI over IP
139 | ProtocolPIM = 103 // Protocol Independent Multicast
140 | ProtocolARIS = 104 // ARIS
141 | ProtocolSCPS = 105 // SCPS
142 | ProtocolQNX = 106 // QNX
143 | ProtocolAN = 107 // Active Networks
144 | ProtocolIPComp = 108 // IP Payload Compression Protocol
145 | ProtocolSNP = 109 // Sitara Networks Protocol
146 | ProtocolCompaqPeer = 110 // Compaq Peer Protocol
147 | ProtocolIPXinIP = 111 // IPX in IP
148 | ProtocolVRRP = 112 // Virtual Router Redundancy Protocol
149 | ProtocolPGM = 113 // PGM Reliable Transport Protocol
150 | ProtocolL2TP = 115 // Layer Two Tunneling Protocol
151 | ProtocolDDX = 116 // D-II Data Exchange (DDX)
152 | ProtocolIATP = 117 // Interactive Agent Transfer Protocol
153 | ProtocolSTP = 118 // Schedule Transfer Protocol
154 | ProtocolSRP = 119 // SpectraLink Radio Protocol
155 | ProtocolUTI = 120 // UTI
156 | ProtocolSMP = 121 // Simple Message Protocol
157 | ProtocolPTP = 123 // Performance Transparency Protocol
158 | ProtocolISIS = 124 // ISIS over IPv4
159 | ProtocolFIRE = 125 // FIRE
160 | ProtocolCRTP = 126 // Combat Radio Transport Protocol
161 | ProtocolCRUDP = 127 // Combat Radio User Datagram
162 | ProtocolSSCOPMCE = 128 // SSCOPMCE
163 | ProtocolIPLT = 129 // IPLT
164 | ProtocolSPS = 130 // Secure Packet Shield
165 | ProtocolPIPE = 131 // Private IP Encapsulation within IP
166 | ProtocolSCTP = 132 // Stream Control Transmission Protocol
167 | ProtocolFC = 133 // Fibre Channel
168 | ProtocolRSVPE2EIGNORE = 134 // RSVP-E2E-IGNORE
169 | ProtocolMobilityHeader = 135 // Mobility Header
170 | ProtocolUDPLite = 136 // UDPLite
171 | ProtocolMPLSinIP = 137 // MPLS-in-IP
172 | ProtocolMANET = 138 // MANET Protocols
173 | ProtocolHIP = 139 // Host Identity Protocol
174 | ProtocolShim6 = 140 // Shim6 Protocol
175 | ProtocolWESP = 141 // Wrapped Encapsulating Security Payload
176 | ProtocolROHC = 142 // Robust Header Compression
177 | ProtocolEthernet = 143 // Ethernet (TEMPORARY - registered 2020-01-31, expires 2021-01-31)
178 | ProtocolReserved = 255 // Reserved
179 | )
180 |
181 | // Address Family Numbers, Updated: 2020-05-12
182 | const (
183 | AddrFamilyIPv4 = 1 // IP (IP version 4)
184 | AddrFamilyIPv6 = 2 // IP6 (IP version 6)
185 | AddrFamilyNSAP = 3 // NSAP
186 | AddrFamilyHDLC = 4 // HDLC (8-bit multidrop)
187 | AddrFamilyBBN1822 = 5 // BBN 1822
188 | AddrFamily802 = 6 // 802 (includes all 802 media plus Ethernet "canonical format")
189 | AddrFamilyE163 = 7 // E.163
190 | AddrFamilyE164 = 8 // E.164 (SMDS, Frame Relay, ATM)
191 | AddrFamilyF69 = 9 // F.69 (Telex)
192 | AddrFamilyX121 = 10 // X.121 (X.25, Frame Relay)
193 | AddrFamilyIPX = 11 // IPX
194 | AddrFamilyAppletalk = 12 // Appletalk
195 | AddrFamilyDecnetIV = 13 // Decnet IV
196 | AddrFamilyBanyanVines = 14 // Banyan Vines
197 | AddrFamilyE164withSubaddress = 15 // E.164 with NSAP format subaddress
198 | AddrFamilyDNS = 16 // DNS (Domain Name System)
199 | AddrFamilyDistinguishedName = 17 // Distinguished Name
200 | AddrFamilyASNumber = 18 // AS Number
201 | AddrFamilyXTPoverIPv4 = 19 // XTP over IP version 4
202 | AddrFamilyXTPoverIPv6 = 20 // XTP over IP version 6
203 | AddrFamilyXTPnativemodeXTP = 21 // XTP native mode XTP
204 | AddrFamilyFibreChannelWorldWidePortName = 22 // Fibre Channel World-Wide Port Name
205 | AddrFamilyFibreChannelWorldWideNodeName = 23 // Fibre Channel World-Wide Node Name
206 | AddrFamilyGWID = 24 // GWID
207 | AddrFamilyL2VPN = 25 // AFI for L2VPN information
208 | AddrFamilyMPLSTPSectionEndpointID = 26 // MPLS-TP Section Endpoint Identifier
209 | AddrFamilyMPLSTPLSPEndpointID = 27 // MPLS-TP LSP Endpoint Identifier
210 | AddrFamilyMPLSTPPseudowireEndpointID = 28 // MPLS-TP Pseudowire Endpoint Identifier
211 | AddrFamilyMTIPv4 = 29 // MT IP: Multi-Topology IP version 4
212 | AddrFamilyMTIPv6 = 30 // MT IPv6: Multi-Topology IP version 6
213 | AddrFamilyEIGRPCommonServiceFamily = 16384 // EIGRP Common Service Family
214 | AddrFamilyEIGRPIPv4ServiceFamily = 16385 // EIGRP IPv4 Service Family
215 | AddrFamilyEIGRPIPv6ServiceFamily = 16386 // EIGRP IPv6 Service Family
216 | AddrFamilyLISPCanonicalAddressFormat = 16387 // LISP Canonical Address Format (LCAF)
217 | AddrFamilyBGPLS = 16388 // BGP-LS
218 | AddrFamily48bitMAC = 16389 // 48-bit MAC
219 | AddrFamily64bitMAC = 16390 // 64-bit MAC
220 | AddrFamilyOUI = 16391 // OUI
221 | AddrFamilyMACFinal24bits = 16392 // MAC/24
222 | AddrFamilyMACFinal40bits = 16393 // MAC/40
223 | AddrFamilyIPv6Initial64bits = 16394 // IPv6/64
224 | AddrFamilyRBridgePortID = 16395 // RBridge Port ID
225 | AddrFamilyTRILLNickname = 16396 // TRILL Nickname
226 | AddrFamilyUniversallyUniqueID = 16397 // Universally Unique Identifier (UUID)
227 | AddrFamilyRoutingPolicyAFI = 16398 // Routing Policy AFI
228 | )
229 |
--------------------------------------------------------------------------------
/internal/iana/gen.go:
--------------------------------------------------------------------------------
1 | // Copyright 2013 The Go Authors. All rights reserved.
2 | // Use of this source code is governed by a BSD-style
3 | // license that can be found in the LICENSE file.
4 |
5 | //go:build ignore
6 | // +build ignore
7 |
8 | //go:generate go run gen.go
9 |
10 | // This program generates internet protocol constants and tables by
11 | // reading IANA protocol registries.
12 | package main
13 |
14 | import (
15 | "bytes"
16 | "encoding/xml"
17 | "fmt"
18 | "go/format"
19 | "io"
20 | "io/ioutil"
21 | "net/http"
22 | "os"
23 | "strconv"
24 | "strings"
25 | )
26 |
27 | var registries = []struct {
28 | url string
29 | parse func(io.Writer, io.Reader) error
30 | }{
31 | {
32 | "https://www.iana.org/assignments/dscp-registry/dscp-registry.xml",
33 | parseDSCPRegistry,
34 | },
35 | {
36 | "https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xml",
37 | parseProtocolNumbers,
38 | },
39 | {
40 | "https://www.iana.org/assignments/address-family-numbers/address-family-numbers.xml",
41 | parseAddrFamilyNumbers,
42 | },
43 | }
44 |
45 | func main() {
46 | var bb bytes.Buffer
47 | fmt.Fprintf(&bb, "// go generate gen.go\n")
48 | fmt.Fprintf(&bb, "// Code generated by the command above; DO NOT EDIT.\n\n")
49 | fmt.Fprintf(&bb, "// Package iana provides protocol number resources managed by the Internet Assigned Numbers Authority (IANA).\n")
50 | fmt.Fprintf(&bb, `package iana // import "golang.org/x/net/internal/iana"`+"\n\n")
51 | for _, r := range registries {
52 | resp, err := http.Get(r.url)
53 | if err != nil {
54 | fmt.Fprintln(os.Stderr, err)
55 | os.Exit(1)
56 | }
57 | defer resp.Body.Close()
58 | if resp.StatusCode != http.StatusOK {
59 | fmt.Fprintf(os.Stderr, "got HTTP status code %v for %v\n", resp.StatusCode, r.url)
60 | os.Exit(1)
61 | }
62 | if err := r.parse(&bb, resp.Body); err != nil {
63 | fmt.Fprintln(os.Stderr, err)
64 | os.Exit(1)
65 | }
66 | fmt.Fprintf(&bb, "\n")
67 | }
68 | b, err := format.Source(bb.Bytes())
69 | if err != nil {
70 | fmt.Fprintln(os.Stderr, err)
71 | os.Exit(1)
72 | }
73 | if err := ioutil.WriteFile("const.go", b, 0644); err != nil {
74 | fmt.Fprintln(os.Stderr, err)
75 | os.Exit(1)
76 | }
77 | }
78 |
79 | func parseDSCPRegistry(w io.Writer, r io.Reader) error {
80 | dec := xml.NewDecoder(r)
81 | var dr dscpRegistry
82 | if err := dec.Decode(&dr); err != nil {
83 | return err
84 | }
85 | fmt.Fprintf(w, "// %s, Updated: %s\n", dr.Title, dr.Updated)
86 | fmt.Fprintf(w, "const (\n")
87 | for _, dr := range dr.escapeDSCP() {
88 | fmt.Fprintf(w, "DiffServ%s = %#02x", dr.Name, dr.Value)
89 | fmt.Fprintf(w, "// %s\n", dr.OrigName)
90 | }
91 | for _, er := range dr.escapeECN() {
92 | fmt.Fprintf(w, "%s = %#02x", er.Descr, er.Value)
93 | fmt.Fprintf(w, "// %s\n", er.OrigDescr)
94 | }
95 | fmt.Fprintf(w, ")\n")
96 | return nil
97 | }
98 |
99 | type dscpRegistry struct {
100 | XMLName xml.Name `xml:"registry"`
101 | Title string `xml:"title"`
102 | Updated string `xml:"updated"`
103 | Note string `xml:"note"`
104 | Registries []struct {
105 | Title string `xml:"title"`
106 | Registries []struct {
107 | Title string `xml:"title"`
108 | Records []struct {
109 | Name string `xml:"name"`
110 | Space string `xml:"space"`
111 | } `xml:"record"`
112 | } `xml:"registry"`
113 | Records []struct {
114 | Value string `xml:"value"`
115 | Descr string `xml:"description"`
116 | } `xml:"record"`
117 | } `xml:"registry"`
118 | }
119 |
120 | type canonDSCPRecord struct {
121 | OrigName string
122 | Name string
123 | Value int
124 | }
125 |
126 | func (drr *dscpRegistry) escapeDSCP() []canonDSCPRecord {
127 | var drs []canonDSCPRecord
128 | for _, preg := range drr.Registries {
129 | if !strings.Contains(preg.Title, "Differentiated Services Field Codepoints") {
130 | continue
131 | }
132 | for _, reg := range preg.Registries {
133 | if !strings.Contains(reg.Title, "Pool 1 Codepoints") {
134 | continue
135 | }
136 | drs = make([]canonDSCPRecord, len(reg.Records))
137 | sr := strings.NewReplacer(
138 | "+", "",
139 | "-", "",
140 | "/", "",
141 | ".", "",
142 | " ", "",
143 | )
144 | for i, dr := range reg.Records {
145 | s := strings.TrimSpace(dr.Name)
146 | drs[i].OrigName = s
147 | drs[i].Name = sr.Replace(s)
148 | n, err := strconv.ParseUint(dr.Space, 2, 8)
149 | if err != nil {
150 | continue
151 | }
152 | drs[i].Value = int(n) << 2
153 | }
154 | }
155 | }
156 | return drs
157 | }
158 |
159 | type canonECNRecord struct {
160 | OrigDescr string
161 | Descr string
162 | Value int
163 | }
164 |
165 | func (drr *dscpRegistry) escapeECN() []canonECNRecord {
166 | var ers []canonECNRecord
167 | for _, reg := range drr.Registries {
168 | if !strings.Contains(reg.Title, "ECN Field") {
169 | continue
170 | }
171 | ers = make([]canonECNRecord, len(reg.Records))
172 | sr := strings.NewReplacer(
173 | "Capable", "",
174 | "Not-ECT", "",
175 | "ECT(1)", "",
176 | "ECT(0)", "",
177 | "CE", "",
178 | "(", "",
179 | ")", "",
180 | "+", "",
181 | "-", "",
182 | "/", "",
183 | ".", "",
184 | " ", "",
185 | )
186 | for i, er := range reg.Records {
187 | s := strings.TrimSpace(er.Descr)
188 | ers[i].OrigDescr = s
189 | ss := strings.Split(s, " ")
190 | if len(ss) > 1 {
191 | ers[i].Descr = strings.Join(ss[1:], " ")
192 | } else {
193 | ers[i].Descr = ss[0]
194 | }
195 | ers[i].Descr = sr.Replace(er.Descr)
196 | n, err := strconv.ParseUint(er.Value, 2, 8)
197 | if err != nil {
198 | continue
199 | }
200 | ers[i].Value = int(n)
201 | }
202 | }
203 | return ers
204 | }
205 |
206 | func parseProtocolNumbers(w io.Writer, r io.Reader) error {
207 | dec := xml.NewDecoder(r)
208 | var pn protocolNumbers
209 | if err := dec.Decode(&pn); err != nil {
210 | return err
211 | }
212 | prs := pn.escape()
213 | prs = append([]canonProtocolRecord{{
214 | Name: "IP",
215 | Descr: "IPv4 encapsulation, pseudo protocol number",
216 | Value: 0,
217 | }}, prs...)
218 | fmt.Fprintf(w, "// %s, Updated: %s\n", pn.Title, pn.Updated)
219 | fmt.Fprintf(w, "const (\n")
220 | for _, pr := range prs {
221 | if pr.Name == "" {
222 | continue
223 | }
224 | fmt.Fprintf(w, "Protocol%s = %d", pr.Name, pr.Value)
225 | s := pr.Descr
226 | if s == "" {
227 | s = pr.OrigName
228 | }
229 | fmt.Fprintf(w, "// %s\n", s)
230 | }
231 | fmt.Fprintf(w, ")\n")
232 | return nil
233 | }
234 |
235 | type protocolNumbers struct {
236 | XMLName xml.Name `xml:"registry"`
237 | Title string `xml:"title"`
238 | Updated string `xml:"updated"`
239 | RegTitle string `xml:"registry>title"`
240 | Note string `xml:"registry>note"`
241 | Records []struct {
242 | Value string `xml:"value"`
243 | Name string `xml:"name"`
244 | Descr string `xml:"description"`
245 | } `xml:"registry>record"`
246 | }
247 |
248 | type canonProtocolRecord struct {
249 | OrigName string
250 | Name string
251 | Descr string
252 | Value int
253 | }
254 |
255 | func (pn *protocolNumbers) escape() []canonProtocolRecord {
256 | prs := make([]canonProtocolRecord, len(pn.Records))
257 | sr := strings.NewReplacer(
258 | "-in-", "in",
259 | "-within-", "within",
260 | "-over-", "over",
261 | "+", "P",
262 | "-", "",
263 | "/", "",
264 | ".", "",
265 | " ", "",
266 | )
267 | for i, pr := range pn.Records {
268 | if strings.Contains(pr.Name, "Deprecated") ||
269 | strings.Contains(pr.Name, "deprecated") {
270 | continue
271 | }
272 | prs[i].OrigName = pr.Name
273 | s := strings.TrimSpace(pr.Name)
274 | switch pr.Name {
275 | case "ISIS over IPv4":
276 | prs[i].Name = "ISIS"
277 | case "manet":
278 | prs[i].Name = "MANET"
279 | default:
280 | prs[i].Name = sr.Replace(s)
281 | }
282 | ss := strings.Split(pr.Descr, "\n")
283 | for i := range ss {
284 | ss[i] = strings.TrimSpace(ss[i])
285 | }
286 | if len(ss) > 1 {
287 | prs[i].Descr = strings.Join(ss, " ")
288 | } else {
289 | prs[i].Descr = ss[0]
290 | }
291 | prs[i].Value, _ = strconv.Atoi(pr.Value)
292 | }
293 | return prs
294 | }
295 |
296 | func parseAddrFamilyNumbers(w io.Writer, r io.Reader) error {
297 | dec := xml.NewDecoder(r)
298 | var afn addrFamilylNumbers
299 | if err := dec.Decode(&afn); err != nil {
300 | return err
301 | }
302 | afrs := afn.escape()
303 | fmt.Fprintf(w, "// %s, Updated: %s\n", afn.Title, afn.Updated)
304 | fmt.Fprintf(w, "const (\n")
305 | for _, afr := range afrs {
306 | if afr.Name == "" {
307 | continue
308 | }
309 | fmt.Fprintf(w, "AddrFamily%s = %d", afr.Name, afr.Value)
310 | fmt.Fprintf(w, "// %s\n", afr.Descr)
311 | }
312 | fmt.Fprintf(w, ")\n")
313 | return nil
314 | }
315 |
316 | type addrFamilylNumbers struct {
317 | XMLName xml.Name `xml:"registry"`
318 | Title string `xml:"title"`
319 | Updated string `xml:"updated"`
320 | RegTitle string `xml:"registry>title"`
321 | Note string `xml:"registry>note"`
322 | Records []struct {
323 | Value string `xml:"value"`
324 | Descr string `xml:"description"`
325 | } `xml:"registry>record"`
326 | }
327 |
328 | type canonAddrFamilyRecord struct {
329 | Name string
330 | Descr string
331 | Value int
332 | }
333 |
334 | func (afn *addrFamilylNumbers) escape() []canonAddrFamilyRecord {
335 | afrs := make([]canonAddrFamilyRecord, len(afn.Records))
336 | sr := strings.NewReplacer(
337 | "IP version 4", "IPv4",
338 | "IP version 6", "IPv6",
339 | "Identifier", "ID",
340 | "-", "",
341 | "-", "",
342 | "/", "",
343 | ".", "",
344 | " ", "",
345 | )
346 | for i, afr := range afn.Records {
347 | if strings.Contains(afr.Descr, "Unassigned") ||
348 | strings.Contains(afr.Descr, "Reserved") {
349 | continue
350 | }
351 | afrs[i].Descr = afr.Descr
352 | s := strings.TrimSpace(afr.Descr)
353 | switch s {
354 | case "IP (IP version 4)":
355 | afrs[i].Name = "IPv4"
356 | case "IP6 (IP version 6)":
357 | afrs[i].Name = "IPv6"
358 | case "AFI for L2VPN information":
359 | afrs[i].Name = "L2VPN"
360 | case "E.164 with NSAP format subaddress":
361 | afrs[i].Name = "E164withSubaddress"
362 | case "MT IP: Multi-Topology IP version 4":
363 | afrs[i].Name = "MTIPv4"
364 | case "MAC/24":
365 | afrs[i].Name = "MACFinal24bits"
366 | case "MAC/40":
367 | afrs[i].Name = "MACFinal40bits"
368 | case "IPv6/64":
369 | afrs[i].Name = "IPv6Initial64bits"
370 | default:
371 | n := strings.Index(s, "(")
372 | if n > 0 {
373 | s = s[:n]
374 | }
375 | n = strings.Index(s, ":")
376 | if n > 0 {
377 | s = s[:n]
378 | }
379 | afrs[i].Name = sr.Replace(s)
380 | }
381 | afrs[i].Value, _ = strconv.Atoi(afr.Value)
382 | }
383 | return afrs
384 | }
385 |
--------------------------------------------------------------------------------
/internal/utils/addr.go:
--------------------------------------------------------------------------------
1 | package utils
2 |
3 | import (
4 | "encoding/binary"
5 | "errors"
6 | "io"
7 | "net"
8 | "strconv"
9 | )
10 |
11 | type Addr []byte
12 |
13 | const MaxAddrLen = 1 + 1 + 255 + 2
14 |
15 | const (
16 | AddrTypeIPv4 = 1
17 | AddrTypeDomain = 3
18 | AddrTypeIPv6 = 4
19 | )
20 |
21 | var ErrInvalidAddrType = errors.New("invalid address type")
22 |
23 | func (addr Addr) Network() string {
24 | return "socks"
25 | }
26 |
27 | func (addr Addr) String() string {
28 | switch addr[0] {
29 | case AddrTypeIPv4:
30 | return net.JoinHostPort(net.IP(addr[1:1+net.IPv4len]).String(), strconv.Itoa(int(binary.BigEndian.Uint16(addr[1+net.IPv4len:]))))
31 | case AddrTypeDomain:
32 | return net.JoinHostPort(string(addr[2:2+addr[1]]), strconv.Itoa(int(binary.BigEndian.Uint16(addr[2+addr[1]:]))))
33 | case AddrTypeIPv6:
34 | return net.JoinHostPort(net.IP(addr[1:1+net.IPv6len]).String(), strconv.Itoa(int(binary.BigEndian.Uint16(addr[1+net.IPv6len:]))))
35 | default:
36 | return ""
37 | }
38 | }
39 |
40 | func ReadAddr(conn net.Conn) (Addr, error) {
41 | return ReadAddrBuffer(conn, make([]byte, MaxAddrLen))
42 | }
43 | func ReadAddrBuffer(conn net.Conn, addr []byte) (Addr, error) {
44 | _, err := io.ReadFull(conn, addr[:2])
45 | if err != nil {
46 | return nil, err
47 | }
48 |
49 | switch addr[0] {
50 | case AddrTypeIPv4:
51 | n := 1 + net.IPv4len + 2
52 | _, err := io.ReadFull(conn, addr[2:n])
53 | if err != nil {
54 | return nil, err
55 | }
56 |
57 | return addr[:n], nil
58 | case AddrTypeDomain:
59 | n := 1 + 1 + int(addr[1]) + 2
60 | _, err := io.ReadFull(conn, addr[2:n])
61 | if err != nil {
62 | return nil, err
63 | }
64 |
65 | return addr[:n], nil
66 | case AddrTypeIPv6:
67 | n := 1 + net.IPv6len + 2
68 | _, err := io.ReadFull(conn, addr[2:n])
69 | if err != nil {
70 | return nil, err
71 | }
72 |
73 | return addr[:n], nil
74 | default:
75 | return nil, ErrInvalidAddrType
76 | }
77 | }
78 |
79 | var ErrInvalidAddrLen = errors.New("invalid address length")
80 |
81 | func ParseAddr(addr []byte) (Addr, error) {
82 | if len(addr) < 1+1+1+2 {
83 | return nil, ErrInvalidAddrLen
84 | }
85 |
86 | switch addr[0] {
87 | case AddrTypeIPv4:
88 | n := 1 + net.IPv4len + 2
89 | if len(addr) < n {
90 | return nil, ErrInvalidAddrLen
91 | }
92 |
93 | return addr[:n], nil
94 | case AddrTypeDomain:
95 | n := 1 + 1 + int(addr[1]) + 2
96 | if len(addr) < n {
97 | return nil, ErrInvalidAddrLen
98 | }
99 |
100 | return addr[:n], nil
101 | case AddrTypeIPv6:
102 | n := 1 + net.IPv6len + 2
103 | if len(addr) < n {
104 | return nil, ErrInvalidAddrLen
105 | }
106 |
107 | return addr[:n], nil
108 | default:
109 | return nil, ErrInvalidAddrType
110 | }
111 | }
112 |
113 | func ResolveTCPAddr(addr Addr) (*net.TCPAddr, error) {
114 | switch addr[0] {
115 | case AddrTypeIPv4:
116 | return &net.TCPAddr{IP: net.IP(addr[1 : 1+net.IPv4len]), Port: int(binary.BigEndian.Uint16(addr[1+net.IPv4len:]))}, nil
117 | case AddrTypeDomain:
118 | return net.ResolveTCPAddr("tcp", addr.String())
119 | case AddrTypeIPv6:
120 | return &net.TCPAddr{IP: net.IP(addr[1 : 1+net.IPv6len]), Port: int(binary.BigEndian.Uint16(addr[1+net.IPv6len:]))}, nil
121 | default:
122 | return nil, ErrInvalidAddrType
123 | }
124 | }
125 |
126 | func ResolveUDPAddr(addr Addr) (*net.UDPAddr, error) {
127 | switch addr[0] {
128 | case AddrTypeIPv4:
129 | return &net.UDPAddr{IP: net.IP(addr[1 : 1+net.IPv4len]), Port: int(binary.BigEndian.Uint16(addr[1+net.IPv4len:]))}, nil
130 | case AddrTypeDomain:
131 | return net.ResolveUDPAddr("udp", addr.String())
132 | case AddrTypeIPv6:
133 | return &net.UDPAddr{IP: net.IP(addr[1 : 1+net.IPv6len]), Port: int(binary.BigEndian.Uint16(addr[1+net.IPv6len:]))}, nil
134 | default:
135 | return nil, ErrInvalidAddrType
136 | }
137 | }
138 |
139 | func ResolveAddr(addr net.Addr) (Addr, error) {
140 | if a, ok := addr.(Addr); ok {
141 | return a, nil
142 | }
143 |
144 | return ResolveAddrBuffer(addr, make([]byte, MaxAddrLen))
145 | }
146 | func ResolveAddrBuffer(addr net.Addr, b []byte) (Addr, error) {
147 | if a, ok := addr.(*net.TCPAddr); ok {
148 | if ip := a.IP.To4(); ip != nil {
149 | b[0] = AddrTypeIPv4
150 | copy(b[1:], ip)
151 | b[1+net.IPv4len], b[1+net.IPv4len+1] = byte(a.Port>>8), byte(a.Port)
152 |
153 | return b[:1+net.IPv4len+2], nil
154 | } else {
155 | ip = a.IP.To16()
156 |
157 | b[0] = AddrTypeIPv6
158 | copy(b[1:], ip)
159 | b[1+net.IPv6len], b[1+net.IPv6len+1] = byte(a.Port>>8), byte(a.Port)
160 |
161 | return b[:1+net.IPv6len+2], nil
162 | }
163 | }
164 |
165 | if a, ok := addr.(*net.UDPAddr); ok {
166 | if ip := a.IP.To4(); ip != nil {
167 | b[0] = AddrTypeIPv4
168 | copy(b[1:], ip)
169 | b[1+net.IPv4len], b[1+net.IPv4len+1] = byte(a.Port>>8), byte(a.Port)
170 |
171 | return b[:1+net.IPv4len+2], nil
172 | } else {
173 | ip = a.IP.To16()
174 |
175 | b[0] = AddrTypeIPv6
176 | copy(b[1:], ip)
177 | b[1+net.IPv6len], b[1+net.IPv6len+1] = byte(a.Port>>8), byte(a.Port)
178 |
179 | return b[:1+net.IPv6len+2], nil
180 | }
181 | }
182 |
183 | if a, ok := addr.(Addr); ok {
184 | return a, nil
185 | }
186 |
187 | return nil, ErrInvalidAddrType
188 | }
189 |
--------------------------------------------------------------------------------
/internal/utils/appfilter.go:
--------------------------------------------------------------------------------
1 | package utils
2 |
3 | import "sync"
4 |
5 | // AppFilter represents an application filter
6 | type AppFilter struct {
7 | sync.RWMutex
8 | pids map[uint32]struct{}
9 | }
10 |
11 | // NewAppFilter creates a new application filter
12 | func NewAppFilter() *AppFilter {
13 | return &AppFilter{
14 | pids: make(map[uint32]struct{}),
15 | }
16 | }
17 |
18 | // Add adds a process ID to the filter
19 | func (f *AppFilter) Add(pid uint32) {
20 | f.Lock()
21 | defer f.Unlock()
22 | f.pids[pid] = struct{}{}
23 | }
24 |
25 | // Remove removes a process ID from the filter
26 | func (f *AppFilter) Remove(pid uint32) {
27 | f.Lock()
28 | defer f.Unlock()
29 | delete(f.pids, pid)
30 | }
31 |
32 | // Lookup checks if a process ID exists in the filter
33 | func (f *AppFilter) Lookup(pid uint32) bool {
34 | f.RLock()
35 | defer f.RUnlock()
36 | _, ok := f.pids[pid]
37 | return ok
38 | }
39 |
--------------------------------------------------------------------------------
/internal/utils/ipfilter.go:
--------------------------------------------------------------------------------
1 | package utils
2 |
3 | import (
4 | "net"
5 | "sync"
6 | )
7 |
8 | // IPFilter represents an IP filter
9 | type IPFilter struct {
10 | sync.RWMutex
11 | tree *IPTree
12 | }
13 |
14 | // NewIPFilter creates a new IP filter
15 | func NewIPFilter() *IPFilter {
16 | return &IPFilter{
17 | tree: NewIPTree(),
18 | }
19 | }
20 |
21 | // Add adds an IP address to the filter
22 | func (f *IPFilter) Add(ip net.IP) {
23 | f.Lock()
24 | defer f.Unlock()
25 | f.tree.Insert(ip)
26 | }
27 |
28 | // Lookup checks if an IP address exists in the filter
29 | func (f *IPFilter) Lookup(ip net.IP) bool {
30 | f.RLock()
31 | defer f.RUnlock()
32 | return f.tree.Lookup(ip)
33 | }
34 |
--------------------------------------------------------------------------------
/internal/utils/iphelper_windows.go:
--------------------------------------------------------------------------------
1 | //go:build windows
2 | // +build windows
3 |
4 | package utils
5 |
6 | import (
7 | "syscall"
8 | "unsafe"
9 | )
10 |
11 | var (
12 | modiphlpapi = syscall.NewLazyDLL("iphlpapi.dll")
13 |
14 | procGetTcpTable2 = modiphlpapi.NewProc("GetTcpTable2")
15 | procGetUdpTable = modiphlpapi.NewProc("GetUdpTable")
16 | procGetTcp6Table = modiphlpapi.NewProc("GetTcp6Table")
17 | procGetUdp6Table = modiphlpapi.NewProc("GetUdp6Table")
18 | )
19 |
20 | // TCPRow represents a TCP connection entry
21 | type TCPRow struct {
22 | State uint32
23 | LocalAddr uint32
24 | LocalPort uint32
25 | RemoteAddr uint32
26 | RemotePort uint32
27 | OwningPid uint32
28 | }
29 |
30 | // TCP6Row represents a TCP IPv6 connection entry
31 | type TCP6Row struct {
32 | LocalAddr [4]uint32
33 | LocalPort uint32
34 | RemoteAddr [4]uint32
35 | RemotePort uint32
36 | State uint32
37 | OwningPid uint32
38 | }
39 |
40 | // UDPRow represents a UDP connection entry
41 | type UDPRow struct {
42 | LocalAddr uint32
43 | LocalPort uint32
44 | OwningPid uint32
45 | }
46 |
47 | // UDP6Row represents a UDP IPv6 connection entry
48 | type UDP6Row struct {
49 | LocalAddr [4]uint32
50 | LocalPort uint32
51 | OwningPid uint32
52 | }
53 |
54 | // GetTCPTable retrieves the TCP connection table
55 | func GetTCPTable() ([]TCPRow, error) {
56 | var size uint32
57 | var tcpTable []byte
58 |
59 | // Get the size of the table
60 | r1, _, err := procGetTcpTable2.Call(0, uintptr(unsafe.Pointer(&size)), 1)
61 | if r1 != 0 && err != syscall.ERROR_INSUFFICIENT_BUFFER {
62 | return nil, err
63 | }
64 |
65 | tcpTable = make([]byte, size)
66 | r1, _, err = procGetTcpTable2.Call(
67 | uintptr(unsafe.Pointer(&tcpTable[0])),
68 | uintptr(unsafe.Pointer(&size)),
69 | 1,
70 | )
71 | if r1 != 0 {
72 | return nil, err
73 | }
74 |
75 | count := *(*uint32)(unsafe.Pointer(&tcpTable[0]))
76 | rows := make([]TCPRow, count)
77 |
78 | for i := uint32(0); i < count; i++ {
79 | offset := 4 + i*uint32(unsafe.Sizeof(TCPRow{}))
80 | row := (*TCPRow)(unsafe.Pointer(&tcpTable[offset]))
81 | rows[i] = *row
82 | }
83 |
84 | return rows, nil
85 | }
86 |
87 | // GetUDPTable retrieves the UDP connection table
88 | func GetUDPTable() ([]UDPRow, error) {
89 | var size uint32
90 | var udpTable []byte
91 |
92 | // Get the size of the table
93 | r1, _, err := procGetUdpTable.Call(0, uintptr(unsafe.Pointer(&size)), 1)
94 | if r1 != 0 && err != syscall.ERROR_INSUFFICIENT_BUFFER {
95 | return nil, err
96 | }
97 |
98 | udpTable = make([]byte, size)
99 | r1, _, err = procGetUdpTable.Call(
100 | uintptr(unsafe.Pointer(&udpTable[0])),
101 | uintptr(unsafe.Pointer(&size)),
102 | 1,
103 | )
104 | if r1 != 0 {
105 | return nil, err
106 | }
107 |
108 | count := *(*uint32)(unsafe.Pointer(&udpTable[0]))
109 | rows := make([]UDPRow, count)
110 |
111 | for i := uint32(0); i < count; i++ {
112 | offset := 4 + i*uint32(unsafe.Sizeof(UDPRow{}))
113 | row := (*UDPRow)(unsafe.Pointer(&udpTable[offset]))
114 | rows[i] = *row
115 | }
116 |
117 | return rows, nil
118 | }
119 |
120 | // GetTCP6Table retrieves the TCP IPv6 connection table
121 | func GetTCP6Table() ([]TCP6Row, error) {
122 | var size uint32
123 | var tcp6Table []byte
124 |
125 | // Get the size of the table
126 | r1, _, err := procGetTcp6Table.Call(0, uintptr(unsafe.Pointer(&size)), 1)
127 | if r1 != 0 && err != syscall.ERROR_INSUFFICIENT_BUFFER {
128 | return nil, err
129 | }
130 |
131 | tcp6Table = make([]byte, size)
132 | r1, _, err = procGetTcp6Table.Call(
133 | uintptr(unsafe.Pointer(&tcp6Table[0])),
134 | uintptr(unsafe.Pointer(&size)),
135 | 1,
136 | )
137 | if r1 != 0 {
138 | return nil, err
139 | }
140 |
141 | count := *(*uint32)(unsafe.Pointer(&tcp6Table[0]))
142 | rows := make([]TCP6Row, count)
143 |
144 | for i := uint32(0); i < count; i++ {
145 | offset := 4 + i*uint32(unsafe.Sizeof(TCP6Row{}))
146 | row := (*TCP6Row)(unsafe.Pointer(&tcp6Table[offset]))
147 | rows[i] = *row
148 | }
149 |
150 | return rows, nil
151 | }
152 |
153 | // GetUDP6Table retrieves the UDP IPv6 connection table
154 | func GetUDP6Table() ([]UDP6Row, error) {
155 | var size uint32
156 | var udp6Table []byte
157 |
158 | // Get the size of the table
159 | r1, _, err := procGetUdp6Table.Call(0, uintptr(unsafe.Pointer(&size)), 1)
160 | if r1 != 0 && err != syscall.ERROR_INSUFFICIENT_BUFFER {
161 | return nil, err
162 | }
163 |
164 | udp6Table = make([]byte, size)
165 | r1, _, err = procGetUdp6Table.Call(
166 | uintptr(unsafe.Pointer(&udp6Table[0])),
167 | uintptr(unsafe.Pointer(&size)),
168 | 1,
169 | )
170 | if r1 != 0 {
171 | return nil, err
172 | }
173 |
174 | count := *(*uint32)(unsafe.Pointer(&udp6Table[0]))
175 | rows := make([]UDP6Row, count)
176 |
177 | for i := uint32(0); i < count; i++ {
178 | offset := 4 + i*uint32(unsafe.Sizeof(UDP6Row{}))
179 | row := (*UDP6Row)(unsafe.Pointer(&udp6Table[offset]))
180 | rows[i] = *row
181 | }
182 |
183 | return rows, nil
184 | }
185 |
--------------------------------------------------------------------------------
/internal/utils/iptree.go:
--------------------------------------------------------------------------------
1 | package utils
2 |
3 | // IPTree is a simple IP tree implementation for IP lookup
4 | type IPTree struct {
5 | root *ipNode
6 | }
7 |
8 | type ipNode struct {
9 | left *ipNode
10 | right *ipNode
11 | isLeaf bool
12 | }
13 |
14 | // NewIPTree creates a new IP tree
15 | func NewIPTree() *IPTree {
16 | return &IPTree{
17 | root: &ipNode{},
18 | }
19 | }
20 |
21 | // Insert inserts an IP address into the tree
22 | func (t *IPTree) Insert(ip []byte) {
23 | current := t.root
24 | for _, b := range ip {
25 | for i := 7; i >= 0; i-- {
26 | bit := (b >> uint(i)) & 1
27 | if bit == 0 {
28 | if current.left == nil {
29 | current.left = &ipNode{}
30 | }
31 | current = current.left
32 | } else {
33 | if current.right == nil {
34 | current.right = &ipNode{}
35 | }
36 | current = current.right
37 | }
38 | }
39 | }
40 | current.isLeaf = true
41 | }
42 |
43 | // Lookup checks if an IP address exists in the tree
44 | func (t *IPTree) Lookup(ip []byte) bool {
45 | current := t.root
46 | for _, b := range ip {
47 | for i := 7; i >= 0; i-- {
48 | if current == nil {
49 | return false
50 | }
51 | if current.isLeaf {
52 | return true
53 | }
54 | bit := (b >> uint(i)) & 1
55 | if bit == 0 {
56 | current = current.left
57 | } else {
58 | current = current.right
59 | }
60 | }
61 | }
62 | return current != nil && current.isLeaf
63 | }
64 |
--------------------------------------------------------------------------------
/internal/utils/iptree/iptree.go:
--------------------------------------------------------------------------------
1 | // Package iptree implements radix tree data structure for IPv4 and IPv6 networks.
2 | // https://github.com/infobloxopen/go-trees/tree/master/iptree
3 | package iptree
4 |
5 | import (
6 | "fmt"
7 | "net"
8 | )
9 |
10 | const (
11 | iPv4Bits = net.IPv4len * 8
12 | iPv6Bits = net.IPv6len * 8
13 | )
14 |
15 | var (
16 | iPv4MaxMask = net.CIDRMask(iPv4Bits, iPv4Bits)
17 | iPv6MaxMask = net.CIDRMask(iPv6Bits, iPv6Bits)
18 | )
19 |
20 | // Tree is a radix tree for IPv4 and IPv6 networks.
21 | type Tree struct {
22 | root32 *Node32
23 | root64 *Node64
24 | }
25 |
26 | // Pair represents a key-value pair returned by Enumerate method.
27 | type Pair struct {
28 | Key *net.IPNet
29 | Value interface{}
30 | }
31 |
32 | type subTree64 *Node64
33 |
34 | // NewTree creates empty tree.
35 | func NewTree() *Tree {
36 | return &Tree{}
37 | }
38 |
39 | // InsertNet inserts value using given network as a key. The method returns new tree (old one remains unaffected).
40 | func (t *Tree) InsertNet(n *net.IPNet, value interface{}) *Tree {
41 | if n == nil {
42 | return t
43 | }
44 |
45 | if key, bits := iPv4NetToUint32(n); bits >= 0 {
46 | var (
47 | r32 *Node32
48 | r64 *Node64
49 | )
50 |
51 | if t != nil {
52 | r32 = t.root32
53 | r64 = t.root64
54 | }
55 |
56 | return &Tree{root32: r32.Insert(key, bits, value), root64: r64}
57 | }
58 |
59 | if MSKey, MSBits, LSKey, LSBits := iPv6NetToUint64Pair(n); MSBits >= 0 {
60 | var (
61 | r32 *Node32
62 | r64 *Node64
63 | )
64 |
65 | if t != nil {
66 | r32 = t.root32
67 | r64 = t.root64
68 | }
69 |
70 | if MSBits < Key64BitSize {
71 | return &Tree{root32: r32, root64: r64.Insert(MSKey, MSBits, value)}
72 | }
73 |
74 | var r *Node64
75 | if v, ok := r64.ExactMatch(MSKey, MSBits); ok {
76 | s, ok := v.(subTree64)
77 | if !ok {
78 | err := fmt.Errorf("invalid IPv6 tree: expected subTree64 value at 0x%016x, %d but got %T (%#v)",
79 | MSKey, MSBits, v, v)
80 | panic(err)
81 | }
82 |
83 | r = (*Node64)(s)
84 | }
85 |
86 | r = r.Insert(LSKey, LSBits, value)
87 | return &Tree{root32: r32, root64: r64.Insert(MSKey, MSBits, subTree64(r))}
88 | }
89 |
90 | return t
91 | }
92 |
93 | // InplaceInsertNet inserts (or replaces) value using given network as a key in current tree.
94 | func (t *Tree) InplaceInsertNet(n *net.IPNet, value interface{}) {
95 | if n == nil {
96 | return
97 | }
98 |
99 | if key, bits := iPv4NetToUint32(n); bits >= 0 {
100 | t.root32 = t.root32.InplaceInsert(key, bits, value)
101 | } else if MSKey, MSBits, LSKey, LSBits := iPv6NetToUint64Pair(n); MSBits >= 0 {
102 | if MSBits < Key64BitSize {
103 | t.root64 = t.root64.InplaceInsert(MSKey, MSBits, value)
104 | } else {
105 | if v, ok := t.root64.ExactMatch(MSKey, MSBits); ok {
106 | s, ok := v.(subTree64)
107 | if !ok {
108 | err := fmt.Errorf("invalid IPv6 tree: expected subTree64 value at 0x%016x, %d but got %T (%#v)",
109 | MSKey, MSBits, v, v)
110 | panic(err)
111 | }
112 |
113 | r := (*Node64)(s)
114 | newR := r.InplaceInsert(LSKey, LSBits, value)
115 | if newR != r {
116 | t.root64 = t.root64.InplaceInsert(MSKey, MSBits, subTree64(newR))
117 | }
118 | } else {
119 | var r *Node64
120 | r = r.InplaceInsert(LSKey, LSBits, value)
121 | t.root64 = t.root64.InplaceInsert(MSKey, MSBits, subTree64(r))
122 | }
123 | }
124 | }
125 | }
126 |
127 | // InsertIP inserts value using given IP address as a key. The method returns new tree (old one remains unaffected).
128 | func (t *Tree) InsertIP(ip net.IP, value interface{}) *Tree {
129 | return t.InsertNet(newIPNetFromIP(ip), value)
130 | }
131 |
132 | // InplaceInsertIP inserts (or replaces) value using given IP address as a key in current tree.
133 | func (t *Tree) InplaceInsertIP(ip net.IP, value interface{}) {
134 | t.InplaceInsertNet(newIPNetFromIP(ip), value)
135 | }
136 |
137 | // Enumerate returns channel which is populated by key-value pairs of tree content.
138 | func (t *Tree) Enumerate() chan Pair {
139 | ch := make(chan Pair)
140 |
141 | go func() {
142 | defer close(ch)
143 |
144 | if t == nil {
145 | return
146 | }
147 |
148 | t.enumerate(ch)
149 | }()
150 |
151 | return ch
152 | }
153 |
154 | // GetByNet gets value for network which is equal to or contains given network.
155 | func (t *Tree) GetByNet(n *net.IPNet) (interface{}, bool) {
156 | if t == nil || n == nil {
157 | return nil, false
158 | }
159 |
160 | if key, bits := iPv4NetToUint32(n); bits >= 0 {
161 | return t.root32.Match(key, bits)
162 | }
163 |
164 | if MSKey, MSBits, LSKey, LSBits := iPv6NetToUint64Pair(n); MSBits >= 0 {
165 | v, ok := t.root64.Match(MSKey, MSBits)
166 | if !ok || MSBits < Key64BitSize {
167 | return v, ok
168 | }
169 |
170 | s, ok := v.(subTree64)
171 | if !ok {
172 | return v, true
173 | }
174 |
175 | v, ok = (*Node64)(s).Match(LSKey, LSBits)
176 | if ok {
177 | return v, ok
178 | }
179 |
180 | return t.root64.Match(MSKey, Key64BitSize-1)
181 | }
182 |
183 | return nil, false
184 | }
185 |
186 | // GetByIP gets value for network which is equal to or contains given IP address.
187 | func (t *Tree) GetByIP(ip net.IP) (interface{}, bool) {
188 | return t.GetByNet(newIPNetFromIP(ip))
189 | }
190 |
191 | // DeleteByNet removes subtree which is contained by given network. The method returns new tree (old one remains unaffected) and flag indicating if deletion happens indeed.
192 | func (t *Tree) DeleteByNet(n *net.IPNet) (*Tree, bool) {
193 | if t == nil || n == nil {
194 | return t, false
195 | }
196 |
197 | if key, bits := iPv4NetToUint32(n); bits >= 0 {
198 | r, ok := t.root32.Delete(key, bits)
199 | if ok {
200 | return &Tree{root32: r, root64: t.root64}, true
201 | }
202 | } else if MSKey, MSBits, LSKey, LSBits := iPv6NetToUint64Pair(n); MSBits >= 0 {
203 | r64 := t.root64
204 | if MSBits < Key64BitSize {
205 | r64, ok := r64.Delete(MSKey, MSBits)
206 | if ok {
207 | return &Tree{root32: t.root32, root64: r64}, true
208 | }
209 | } else if v, ok := r64.ExactMatch(MSKey, MSBits); ok {
210 | s, ok := v.(subTree64)
211 | if !ok {
212 | err := fmt.Errorf("invalid IPv6 tree: expected subTree64 value at 0x%016x, %d but got %T (%#v)",
213 | MSKey, MSBits, v, v)
214 | panic(err)
215 | }
216 |
217 | r, ok := (*Node64)(s).Delete(LSKey, LSBits)
218 | if ok {
219 | if r == nil {
220 | r64, _ = r64.Delete(MSKey, MSBits)
221 | } else {
222 | r64 = r64.Insert(MSKey, MSBits, subTree64(r))
223 | }
224 |
225 | return &Tree{root32: t.root32, root64: r64}, true
226 | }
227 | }
228 | }
229 |
230 | return t, false
231 | }
232 |
233 | // DeleteByIP removes node by given IP address. The method returns new tree (old one remains unaffected) and flag indicating if deletion happens indeed.
234 | func (t *Tree) DeleteByIP(ip net.IP) (*Tree, bool) {
235 | return t.DeleteByNet(newIPNetFromIP(ip))
236 | }
237 |
238 | func (t *Tree) enumerate(ch chan Pair) {
239 | for n := range t.root32.Enumerate() {
240 | mask := net.CIDRMask(int(n.Bits), iPv4Bits)
241 | ch <- Pair{
242 | Key: &net.IPNet{
243 | IP: unpackUint32ToIP(n.Key).Mask(mask),
244 | Mask: mask},
245 | Value: n.Value}
246 | }
247 |
248 | for n := range t.root64.Enumerate() {
249 | MSIP := append(unpackUint64ToIP(n.Key), make(net.IP, 8)...)
250 | if s, ok := n.Value.(subTree64); ok {
251 | for n := range (*Node64)(s).Enumerate() {
252 | LSIP := unpackUint64ToIP(n.Key)
253 | mask := net.CIDRMask(Key64BitSize+int(n.Bits), iPv6Bits)
254 | ch <- Pair{
255 | Key: &net.IPNet{
256 | IP: append(MSIP[0:8], LSIP...).Mask(mask),
257 | Mask: mask},
258 | Value: n.Value}
259 | }
260 | } else {
261 | mask := net.CIDRMask(int(n.Bits), iPv6Bits)
262 | ch <- Pair{
263 | Key: &net.IPNet{
264 | IP: MSIP.Mask(mask),
265 | Mask: mask},
266 | Value: n.Value}
267 | }
268 | }
269 | }
270 |
271 | func iPv4NetToUint32(n *net.IPNet) (uint32, int) {
272 | if len(n.IP) != net.IPv4len {
273 | return 0, -1
274 | }
275 |
276 | ones, bits := n.Mask.Size()
277 | if bits != iPv4Bits {
278 | return 0, -1
279 | }
280 |
281 | return packIPToUint32(n.IP), ones
282 | }
283 |
284 | func packIPToUint32(x net.IP) uint32 {
285 | return (uint32(x[0]) << 24) | (uint32(x[1]) << 16) | (uint32(x[2]) << 8) | uint32(x[3])
286 | }
287 |
288 | func unpackUint32ToIP(x uint32) net.IP {
289 | return net.IP{byte(x >> 24 & 0xff), byte(x >> 16 & 0xff), byte(x >> 8 & 0xff), byte(x & 0xff)}
290 | }
291 |
292 | func iPv6NetToUint64Pair(n *net.IPNet) (uint64, int, uint64, int) {
293 | if len(n.IP) != net.IPv6len {
294 | return 0, -1, 0, -1
295 | }
296 |
297 | ones, bits := n.Mask.Size()
298 | if bits != iPv6Bits {
299 | return 0, -1, 0, -1
300 | }
301 |
302 | MSBits := Key64BitSize
303 | LSBits := 0
304 | if ones > Key64BitSize {
305 | LSBits = ones - Key64BitSize
306 | } else {
307 | MSBits = ones
308 | }
309 |
310 | return packIPToUint64(n.IP), MSBits, packIPToUint64(n.IP[8:]), LSBits
311 | }
312 |
313 | func packIPToUint64(x net.IP) uint64 {
314 | return (uint64(x[0]) << 56) | (uint64(x[1]) << 48) | (uint64(x[2]) << 40) | (uint64(x[3]) << 32) |
315 | (uint64(x[4]) << 24) | (uint64(x[5]) << 16) | (uint64(x[6]) << 8) | uint64(x[7])
316 | }
317 |
318 | func unpackUint64ToIP(x uint64) net.IP {
319 | return net.IP{
320 | byte(x >> 56 & 0xff),
321 | byte(x >> 48 & 0xff),
322 | byte(x >> 40 & 0xff),
323 | byte(x >> 32 & 0xff),
324 | byte(x >> 24 & 0xff),
325 | byte(x >> 16 & 0xff),
326 | byte(x >> 8 & 0xff),
327 | byte(x & 0xff)}
328 | }
329 |
330 | func newIPNetFromIP(ip net.IP) *net.IPNet {
331 | if ip4 := ip.To4(); ip4 != nil {
332 | return &net.IPNet{IP: ip4, Mask: iPv4MaxMask}
333 | }
334 |
335 | if ip6 := ip.To16(); ip6 != nil {
336 | return &net.IPNet{IP: ip6, Mask: iPv6MaxMask}
337 | }
338 |
339 | return nil
340 | }
341 |
--------------------------------------------------------------------------------
/internal/utils/iptree/node32.go:
--------------------------------------------------------------------------------
1 | // Package numtree implements radix tree data structure for 32 and 64-bit unsigned integets. Copy-on-write is used for any tree modification so old root doesn't see any change happens with tree.
2 | // https://github.com/infobloxopen/go-trees/tree/master/numtree
3 | package iptree
4 |
5 | import (
6 | "fmt"
7 | "math/bits"
8 | )
9 |
10 | // Key32BitSize is an alias for bitsize of 32-bit radix tree's key.
11 | const Key32BitSize = 32
12 |
13 | var (
14 | masks32 = []uint32{
15 | 0x00000000, 0x80000000, 0xc0000000, 0xe0000000,
16 | 0xf0000000, 0xf8000000, 0xfc000000, 0xfe000000,
17 | 0xff000000, 0xff800000, 0xffc00000, 0xffe00000,
18 | 0xfff00000, 0xfff80000, 0xfffc0000, 0xfffe0000,
19 | 0xffff0000, 0xffff8000, 0xffffc000, 0xffffe000,
20 | 0xfffff000, 0xfffff800, 0xfffffc00, 0xfffffe00,
21 | 0xffffff00, 0xffffff80, 0xffffffc0, 0xffffffe0,
22 | 0xfffffff0, 0xfffffff8, 0xfffffffc, 0xfffffffe,
23 | 0xffffffff}
24 | )
25 |
26 | // Node32 is an element of radix tree with 32-bit unsigned integer as a key.
27 | type Node32 struct {
28 | // Key stores key for current node.
29 | Key uint32
30 | // Bits is a number of significant bits in Key.
31 | Bits uint8
32 | // Leaf indicates if the node is leaf node and contains any data in Value.
33 | Leaf bool
34 | // Value contains data associated with key.
35 | Value interface{}
36 |
37 | chld [2]*Node32
38 | }
39 |
40 | // Dot dumps tree to Graphviz .dot format
41 | func (n *Node32) Dot() string {
42 | body := ""
43 |
44 | // Iterate all nodes using breadth-first search algorithm.
45 | i := 0
46 | queue := []*Node32{n}
47 | for len(queue) > 0 {
48 | c := queue[0]
49 | body += fmt.Sprintf("N%d %s\n", i, c.dotString())
50 | if c != nil && (c.chld[0] != nil || c.chld[1] != nil) {
51 | // Children for current node if any always go to the end of the queue
52 | // so we can know their indices using current queue length.
53 | body += fmt.Sprintf("N%d -> { N%d N%d }\n", i, i+len(queue), i+len(queue)+1)
54 | queue = append(append(queue, c.chld[0]), c.chld[1])
55 | }
56 |
57 | queue = queue[1:]
58 | i++
59 | }
60 |
61 | return "digraph d {\n" + body + "}\n"
62 | }
63 |
64 | // Insert puts new leaf to radix tree and returns pointer to new root. The method uses copy on write strategy so old root doesn't see the change.
65 | func (n *Node32) Insert(key uint32, bits int, value interface{}) *Node32 {
66 | // Adjust bits.
67 | if bits < 0 {
68 | bits = 0
69 | } else if bits > Key32BitSize {
70 | bits = Key32BitSize
71 | }
72 |
73 | return n.insert(newNode32(key, uint8(bits), true, value))
74 | }
75 |
76 | // InplaceInsert puts new leaf to radix tree (or replaces value in existing one). The method inserts data directly to current tree so make sure you have exclusive access to it.
77 | func (n *Node32) InplaceInsert(key uint32, bits int, value interface{}) *Node32 {
78 | // Adjust bits.
79 | if bits < 0 {
80 | bits = 0
81 | } else if bits > Key32BitSize {
82 | bits = Key32BitSize
83 | }
84 |
85 | return n.inplaceInsert(key, uint8(bits), value)
86 | }
87 |
88 | // Enumerate returns channel which is populated by nodes with data in order of their keys.
89 | func (n *Node32) Enumerate() chan *Node32 {
90 | ch := make(chan *Node32)
91 |
92 | go func() {
93 | defer close(ch)
94 |
95 | // If tree is empty -
96 | if n == nil {
97 | // return nothing.
98 | return
99 | }
100 |
101 | n.enumerate(ch)
102 | }()
103 |
104 | return ch
105 | }
106 |
107 | // Match locates node which key is equal to or "contains" the key passed as argument.
108 | func (n *Node32) Match(key uint32, bits int) (interface{}, bool) {
109 | // If tree is empty -
110 | if n == nil {
111 | // report nothing.
112 | return n, false
113 | }
114 |
115 | // Adjust bits.
116 | if bits < 0 {
117 | bits = 0
118 | } else if bits > Key32BitSize {
119 | bits = Key32BitSize
120 | }
121 |
122 | r := n.match(key, uint8(bits))
123 | if r == nil {
124 | return nil, false
125 | }
126 |
127 | return r.Value, true
128 | }
129 |
130 | // ExactMatch locates node which exactly matches given key.
131 | func (n *Node32) ExactMatch(key uint32, bits int) (interface{}, bool) {
132 | // If tree is empty -
133 | if n == nil {
134 | // report nothing.
135 | return n, false
136 | }
137 |
138 | // Adjust bits.
139 | if bits < 0 {
140 | bits = 0
141 | } else if bits > Key32BitSize {
142 | bits = Key32BitSize
143 | }
144 |
145 | r := n.exactMatch(key, uint8(bits))
146 | if r == nil {
147 | return nil, false
148 | }
149 |
150 | return r.Value, true
151 | }
152 |
153 | // Delete removes subtree which is contained by given key. The method uses copy on write strategy.
154 | func (n *Node32) Delete(key uint32, bits int) (*Node32, bool) {
155 | // If tree is empty -
156 | if n == nil {
157 | // report nothing.
158 | return n, false
159 | }
160 |
161 | // Adjust bits.
162 | if bits < 0 {
163 | bits = 0
164 | } else if bits > Key32BitSize {
165 | bits = Key32BitSize
166 | }
167 |
168 | return n.del(key, uint8(bits))
169 | }
170 |
171 | func (n *Node32) dotString() string {
172 | if n == nil {
173 | return "[label=\"nil\"]"
174 | }
175 |
176 | if n.Leaf {
177 | v := fmt.Sprintf("%q", fmt.Sprintf("%#v", n.Value))
178 | return fmt.Sprintf("[label=\"k: %08x, b: %d, v: \\\"%s\\\"\"]", n.Key, n.Bits, v[1:len(v)-1])
179 | }
180 |
181 | return fmt.Sprintf("[label=\"k: %08x, b: %d\"]", n.Key, n.Bits)
182 | }
183 |
184 | func (n *Node32) insert(c *Node32) *Node32 {
185 | if n == nil {
186 | return c
187 | }
188 |
189 | // Find number of common most significant bits (NCSB):
190 | // 1. xor operation puts zeroes at common bits;
191 | // 2. or masks put ones so that zeroes can't go after smaller number of significant bits (NSB)
192 | // 3. count of leading zeroes gives number of common bits
193 | bits := uint8(bits.LeadingZeros32((n.Key ^ c.Key) | ^masks32[n.Bits] | ^masks32[c.Bits]))
194 |
195 | // There are three cases possible:
196 | // - NCSB less than number of significant bits (NSB) of current tree node:
197 | if bits < n.Bits {
198 | // (branch for current tree node is determined by a bit right after the last common bit)
199 | branch := (n.Key >> (Key32BitSize - 1 - bits)) & 1
200 |
201 | // - NCSB equals to NSB of candidate node:
202 | if bits == c.Bits {
203 | // make new root from the candidate and put current node to one of its branch;
204 | c.chld[branch] = n
205 | return c
206 | }
207 |
208 | // - NCSB less than NSB of candidate node (it can't be greater because bits after NSB don't count):
209 | // make new root (non-leaf node)
210 | m := newNode32(c.Key&masks32[bits], bits, false, nil)
211 | // with current tree node at one of branches
212 | m.chld[branch] = n
213 | // and the candidate at the other.
214 | m.chld[1-branch] = c
215 |
216 | return m
217 | }
218 |
219 | // - keys are equal (NCSB not less than NSB of current tree node and both numbers are equal):
220 | if c.Bits == n.Bits {
221 | // replace current node with the candidate.
222 | c.chld = n.chld
223 | return c
224 | }
225 |
226 | // - current tree node contains candidate node:
227 | // make new root as a copy of current tree node;
228 | m := newNode32(n.Key, n.Bits, n.Leaf, n.Value)
229 | m.chld = n.chld
230 |
231 | // (branch for the candidate is determined by a bit right after the last common bit)
232 | branch := (c.Key >> (Key32BitSize - 1 - bits)) & 1
233 | // insert it to correct branch.
234 | m.chld[branch] = m.chld[branch].insert(c)
235 |
236 | return m
237 | }
238 |
239 | func (n *Node32) inplaceInsert(key uint32, sbits uint8, value interface{}) *Node32 {
240 | var (
241 | p *Node32
242 | branch uint32
243 | )
244 |
245 | r := n
246 |
247 | for n != nil {
248 | cbits := uint8(bits.LeadingZeros32((n.Key ^ key) | ^masks32[n.Bits] | ^masks32[sbits]))
249 | if cbits < n.Bits {
250 | pBranch := branch
251 | branch = (n.Key >> (Key32BitSize - 1 - cbits)) & 1
252 |
253 | var m *Node32
254 |
255 | if cbits == sbits {
256 | m = newNode32(key, sbits, true, value)
257 | m.chld[branch] = n
258 | } else {
259 | m = newNode32(key&masks32[cbits], cbits, false, nil)
260 | m.chld[1-branch] = newNode32(key, sbits, true, value)
261 | }
262 |
263 | m.chld[branch] = n
264 | if p == nil {
265 | r = m
266 | } else {
267 | p.chld[pBranch] = m
268 | }
269 |
270 | return r
271 | }
272 |
273 | if sbits == n.Bits {
274 | n.Key = key
275 | n.Leaf = true
276 | n.Value = value
277 | return r
278 | }
279 |
280 | p = n
281 | branch = (key >> (Key32BitSize - 1 - cbits)) & 1
282 | n = n.chld[branch]
283 | }
284 |
285 | n = newNode32(key, sbits, true, value)
286 | if p == nil {
287 | return n
288 | }
289 |
290 | p.chld[branch] = n
291 | return r
292 | }
293 |
294 | func (n *Node32) enumerate(ch chan *Node32) {
295 | // Implemented by depth-first search.
296 | if n.Leaf {
297 | ch <- n
298 | }
299 |
300 | if n.chld[0] != nil {
301 | n.chld[0].enumerate(ch)
302 | }
303 |
304 | if n.chld[1] != nil {
305 | n.chld[1].enumerate(ch)
306 | }
307 | }
308 |
309 | func (n *Node32) match(key uint32, bits uint8) *Node32 {
310 | // If can't be contained in current root node -
311 | if n.Bits > bits {
312 | // report nothing.
313 | return nil
314 | }
315 |
316 | // If NSB of current tree node is the same as key has -
317 | if n.Bits == bits {
318 | // return current node only if it contains data (leaf node) and masked keys are equal.
319 | if n.Leaf && (n.Key^key)&masks32[n.Bits] == 0 {
320 | return n
321 | }
322 |
323 | return nil
324 | }
325 |
326 | // If key can be contained by current tree node -
327 | if (n.Key^key)&masks32[n.Bits] != 0 {
328 | // but it isn't report nothing.
329 | return nil
330 | }
331 |
332 | // Otherwise jump to branch by key bit right after NSB of current tree node
333 | c := n.chld[(key>>(Key32BitSize-1-n.Bits))&1]
334 | if c != nil {
335 | // and check if child on the branch has anything.
336 | r := c.match(key, bits)
337 | if r != nil {
338 | return r
339 | }
340 | }
341 |
342 | // If nothing matches check if current node contains any data.
343 | if n.Leaf {
344 | return n
345 | }
346 |
347 | return nil
348 | }
349 |
350 | func (n *Node32) exactMatch(key uint32, bits uint8) *Node32 {
351 | // If can't be contained in current root node -
352 | if n.Bits > bits {
353 | // report nothing.
354 | return nil
355 | }
356 |
357 | // If NSB of current tree node is the same as key has -
358 | if n.Bits == bits {
359 | // return current node only if it contains data (leaf node) and masked keys are equal.
360 | if n.Leaf && (n.Key^key)&masks32[n.Bits] == 0 {
361 | return n
362 | }
363 |
364 | return nil
365 | }
366 |
367 | // If key can be contained by current tree node -
368 | if (n.Key^key)&masks32[n.Bits] != 0 {
369 | // but it isn't report nothing.
370 | return nil
371 | }
372 |
373 | // Otherwise jump to branch by key bit right after NSB of current tree node
374 | c := n.chld[(key>>(Key32BitSize-1-n.Bits))&1]
375 | if c != nil {
376 | // and check if child on the branch has anything.
377 | r := c.exactMatch(key, bits)
378 | if r != nil {
379 | return r
380 | }
381 | }
382 |
383 | return nil
384 | }
385 |
386 | func (n *Node32) del(key uint32, bits uint8) (*Node32, bool) {
387 | // If key can contain current tree node -
388 | if bits <= n.Bits {
389 | // report empty new tree and put deletion mark if it contains indeed.
390 | if (n.Key^key)&masks32[bits] == 0 {
391 | return nil, true
392 | }
393 |
394 | return n, false
395 | }
396 |
397 | // If key can be contained by current tree node -
398 | if (n.Key^key)&masks32[n.Bits] != 0 {
399 | // but it isn't report nothing.
400 | return n, false
401 | }
402 |
403 | // Otherwise jump to branch by key bit right after NSB of current tree node
404 | branch := (key >> (Key32BitSize - 1 - n.Bits)) & 1
405 | c := n.chld[branch]
406 | if c == nil {
407 | // report nothing if the branch is empty.
408 | return n, false
409 | }
410 |
411 | // Try to remove from subtree
412 | c, ok := c.del(key, bits)
413 | if !ok {
414 | // and report nothing if nothing has been deleted.
415 | return n, false
416 | }
417 |
418 | // If child of non-leaf node has been completely deleted -
419 | if c == nil && !n.Leaf {
420 | // drop the node.
421 | return n.chld[1-branch], true
422 | }
423 |
424 | // If deletion happens inside the branch then copy current node.
425 | m := newNode32(n.Key, n.Bits, n.Leaf, n.Value)
426 | m.chld = n.chld
427 |
428 | // Replace changed child with new one and return new root with deletion mark set.
429 | m.chld[branch] = c
430 | return m, true
431 | }
432 |
433 | func newNode32(key uint32, bits uint8, leaf bool, value interface{}) *Node32 {
434 | return &Node32{
435 | Key: key,
436 | Bits: bits,
437 | Leaf: leaf,
438 | Value: value}
439 | }
440 |
--------------------------------------------------------------------------------
/internal/utils/iptree/node64.go:
--------------------------------------------------------------------------------
1 | // Package numtree implements radix tree data structure for 32 and 64-bit unsigned integets. Copy-on-write is used for any tree modification so old root doesn't see any change happens with tree.
2 | // https://github.com/infobloxopen/go-trees/tree/master/numtree
3 | package iptree
4 |
5 | import (
6 | "fmt"
7 | "math/bits"
8 | )
9 |
10 | // Key64BitSize is an alias for bitsize of 64-bit radix tree's key.
11 | const Key64BitSize = 64
12 |
13 | var (
14 | masks64 = []uint64{
15 | 0x0000000000000000, 0x8000000000000000, 0xc000000000000000, 0xe000000000000000,
16 | 0xf000000000000000, 0xf800000000000000, 0xfc00000000000000, 0xfe00000000000000,
17 | 0xff00000000000000, 0xff80000000000000, 0xffc0000000000000, 0xffe0000000000000,
18 | 0xfff0000000000000, 0xfff8000000000000, 0xfffc000000000000, 0xfffe000000000000,
19 | 0xffff000000000000, 0xffff800000000000, 0xffffc00000000000, 0xffffe00000000000,
20 | 0xfffff00000000000, 0xfffff80000000000, 0xfffffc0000000000, 0xfffffe0000000000,
21 | 0xffffff0000000000, 0xffffff8000000000, 0xffffffc000000000, 0xffffffe000000000,
22 | 0xfffffff000000000, 0xfffffff800000000, 0xfffffffc00000000, 0xfffffffe00000000,
23 | 0xffffffff00000000, 0xffffffff80000000, 0xffffffffc0000000, 0xffffffffe0000000,
24 | 0xfffffffff0000000, 0xfffffffff8000000, 0xfffffffffc000000, 0xfffffffffe000000,
25 | 0xffffffffff000000, 0xffffffffff800000, 0xffffffffffc00000, 0xffffffffffe00000,
26 | 0xfffffffffff00000, 0xfffffffffff80000, 0xfffffffffffc0000, 0xfffffffffffe0000,
27 | 0xffffffffffff0000, 0xffffffffffff8000, 0xffffffffffffc000, 0xffffffffffffe000,
28 | 0xfffffffffffff000, 0xfffffffffffff800, 0xfffffffffffffc00, 0xfffffffffffffe00,
29 | 0xffffffffffffff00, 0xffffffffffffff80, 0xffffffffffffffc0, 0xffffffffffffffe0,
30 | 0xfffffffffffffff0, 0xfffffffffffffff8, 0xfffffffffffffffc, 0xfffffffffffffffe,
31 | 0xffffffffffffffff}
32 | )
33 |
34 | // Node64 is an element of radix tree with 64-bit unsigned integer as a key.
35 | type Node64 struct {
36 | // Key stores key for current node.
37 | Key uint64
38 | // Bits is a number of significant bits in Key.
39 | Bits uint8
40 | // Leaf indicates if the node is leaf node and contains any data in Value.
41 | Leaf bool
42 | // Value contains data associated with key.
43 | Value interface{}
44 |
45 | chld [2]*Node64
46 | }
47 |
48 | // Dot dumps tree to Graphviz .dot format
49 | func (n *Node64) Dot() string {
50 | body := ""
51 |
52 | i := 0
53 | queue := []*Node64{n}
54 | for len(queue) > 0 {
55 | c := queue[0]
56 | body += fmt.Sprintf("N%d %s\n", i, c.dotString())
57 |
58 | if c != nil && (c.chld[0] != nil || c.chld[1] != nil) {
59 | body += fmt.Sprintf("N%d -> { N%d N%d }\n", i, i+len(queue), i+len(queue)+1)
60 | queue = append(append(queue, c.chld[0]), c.chld[1])
61 | }
62 |
63 | queue = queue[1:]
64 | i++
65 | }
66 |
67 | return "digraph d {\n" + body + "}\n"
68 | }
69 |
70 | // Insert puts new leaf to radix tree and returns pointer to new root. The method uses copy on write strategy so old root doesn't see the change.
71 | func (n *Node64) Insert(key uint64, bits int, value interface{}) *Node64 {
72 | if bits < 0 {
73 | bits = 0
74 | } else if bits > Key64BitSize {
75 | bits = Key64BitSize
76 | }
77 |
78 | return n.insert(newNode64(key, uint8(bits), true, value))
79 | }
80 |
81 | // InplaceInsert puts new leaf to radix tree (or replaces value in existing one). The method inserts data directly to current tree so make sure you have exclusive access to it.
82 | func (n *Node64) InplaceInsert(key uint64, bits int, value interface{}) *Node64 {
83 | // Adjust bits.
84 | if bits < 0 {
85 | bits = 0
86 | } else if bits > Key64BitSize {
87 | bits = Key64BitSize
88 | }
89 |
90 | return n.inplaceInsert(key, uint8(bits), value)
91 | }
92 |
93 | // Enumerate returns channel which is populated by nodes in order of their keys.
94 | func (n *Node64) Enumerate() chan *Node64 {
95 | ch := make(chan *Node64)
96 |
97 | go func() {
98 | defer close(ch)
99 |
100 | if n == nil {
101 | return
102 | }
103 |
104 | n.enumerate(ch)
105 | }()
106 |
107 | return ch
108 | }
109 |
110 | // Match locates node which key is equal to or "contains" the key passed as argument.
111 | func (n *Node64) Match(key uint64, bits int) (interface{}, bool) {
112 | if n == nil {
113 | return n, false
114 | }
115 |
116 | if bits < 0 {
117 | bits = 0
118 | } else if bits > Key64BitSize {
119 | bits = Key64BitSize
120 | }
121 |
122 | r := n.match(key, uint8(bits))
123 | if r == nil {
124 | return nil, false
125 | }
126 |
127 | return r.Value, true
128 | }
129 |
130 | // ExactMatch locates node which exactly matches given key.
131 | func (n *Node64) ExactMatch(key uint64, bits int) (interface{}, bool) {
132 | if n == nil {
133 | return n, false
134 | }
135 |
136 | if bits < 0 {
137 | bits = 0
138 | } else if bits > Key64BitSize {
139 | bits = Key64BitSize
140 | }
141 |
142 | r := n.exactMatch(key, uint8(bits))
143 | if r == nil {
144 | return nil, false
145 | }
146 |
147 | return r.Value, true
148 | }
149 |
150 | // Delete removes subtree which is contained by given key. The method uses copy on write strategy.
151 | func (n *Node64) Delete(key uint64, bits int) (*Node64, bool) {
152 | if n == nil {
153 | return n, false
154 | }
155 |
156 | if bits < 0 {
157 | bits = 0
158 | } else if bits > Key64BitSize {
159 | bits = Key64BitSize
160 | }
161 |
162 | return n.del(key, uint8(bits))
163 | }
164 |
165 | func (n *Node64) dotString() string {
166 | if n == nil {
167 | return "[label=\"nil\"]"
168 | }
169 |
170 | if n.Leaf {
171 | v := fmt.Sprintf("%q", fmt.Sprintf("%#v", n.Value))
172 | return fmt.Sprintf("[label=\"k: %016x, b: %d, v: \\\"%s\\\"\"]", n.Key, n.Bits, v[1:len(v)-1])
173 | }
174 |
175 | return fmt.Sprintf("[label=\"k: %016x, b: %d\"]", n.Key, n.Bits)
176 | }
177 |
178 | func (n *Node64) insert(c *Node64) *Node64 {
179 | if n == nil {
180 | return c
181 | }
182 |
183 | bits := uint8(bits.LeadingZeros64((n.Key ^ c.Key) | ^masks64[n.Bits] | ^masks64[c.Bits]))
184 | if bits < n.Bits {
185 | branch := (n.Key >> (Key64BitSize - 1 - bits)) & 1
186 | if bits == c.Bits {
187 | c.chld[branch] = n
188 | return c
189 | }
190 |
191 | m := newNode64(c.Key&masks64[bits], bits, false, nil)
192 | m.chld[branch] = n
193 | m.chld[1-branch] = c
194 |
195 | return m
196 | }
197 |
198 | if c.Bits == n.Bits {
199 | c.chld = n.chld
200 | return c
201 | }
202 |
203 | m := newNode64(n.Key, n.Bits, n.Leaf, n.Value)
204 | m.chld = n.chld
205 |
206 | branch := (c.Key >> (Key64BitSize - 1 - bits)) & 1
207 | m.chld[branch] = m.chld[branch].insert(c)
208 |
209 | return m
210 | }
211 |
212 | func (n *Node64) inplaceInsert(key uint64, sbits uint8, value interface{}) *Node64 {
213 | var (
214 | p *Node64
215 | branch uint64
216 | )
217 |
218 | r := n
219 |
220 | for n != nil {
221 | cbits := uint8(bits.LeadingZeros64((n.Key ^ key) | ^masks64[n.Bits] | ^masks64[sbits]))
222 | if cbits < n.Bits {
223 | pBranch := branch
224 | branch = (n.Key >> (Key64BitSize - 1 - cbits)) & 1
225 |
226 | var m *Node64
227 |
228 | if cbits == sbits {
229 | m = newNode64(key, sbits, true, value)
230 | m.chld[branch] = n
231 | } else {
232 | m = newNode64(key&masks64[cbits], cbits, false, nil)
233 | m.chld[1-branch] = newNode64(key, sbits, true, value)
234 | }
235 |
236 | m.chld[branch] = n
237 | if p == nil {
238 | r = m
239 | } else {
240 | p.chld[pBranch] = m
241 | }
242 |
243 | return r
244 | }
245 |
246 | if sbits == n.Bits {
247 | n.Key = key
248 | n.Leaf = true
249 | n.Value = value
250 | return r
251 | }
252 |
253 | p = n
254 | branch = (key >> (Key64BitSize - 1 - cbits)) & 1
255 | n = n.chld[branch]
256 | }
257 |
258 | n = newNode64(key, sbits, true, value)
259 | if p == nil {
260 | return n
261 | }
262 |
263 | p.chld[branch] = n
264 | return r
265 | }
266 |
267 | func (n *Node64) enumerate(ch chan *Node64) {
268 | if n.Leaf {
269 | ch <- n
270 | }
271 |
272 | if n.chld[0] != nil {
273 | n.chld[0].enumerate(ch)
274 | }
275 |
276 | if n.chld[1] != nil {
277 | n.chld[1].enumerate(ch)
278 | }
279 | }
280 |
281 | func (n *Node64) match(key uint64, bits uint8) *Node64 {
282 | if n.Bits > bits {
283 | return nil
284 | }
285 |
286 | if n.Bits == bits {
287 | if n.Leaf && (n.Key^key)&masks64[n.Bits] == 0 {
288 | return n
289 | }
290 |
291 | return nil
292 | }
293 |
294 | if (n.Key^key)&masks64[n.Bits] != 0 {
295 | return nil
296 | }
297 |
298 | c := n.chld[(key>>(Key64BitSize-1-n.Bits))&1]
299 | if c != nil {
300 | r := c.match(key, bits)
301 | if r != nil {
302 | return r
303 | }
304 | }
305 |
306 | if n.Leaf {
307 | return n
308 | }
309 |
310 | return nil
311 | }
312 |
313 | func (n *Node64) exactMatch(key uint64, bits uint8) *Node64 {
314 | if n.Bits > bits {
315 | return nil
316 | }
317 |
318 | if n.Bits == bits {
319 | if n.Leaf && (n.Key^key)&masks64[n.Bits] == 0 {
320 | return n
321 | }
322 |
323 | return nil
324 | }
325 |
326 | if (n.Key^key)&masks64[n.Bits] != 0 {
327 | return nil
328 | }
329 |
330 | c := n.chld[(key>>(Key64BitSize-1-n.Bits))&1]
331 | if c != nil {
332 | r := c.exactMatch(key, bits)
333 | if r != nil {
334 | return r
335 | }
336 | }
337 |
338 | return nil
339 | }
340 |
341 | func (n *Node64) del(key uint64, bits uint8) (*Node64, bool) {
342 | if bits <= n.Bits {
343 | if (n.Key^key)&masks64[bits] == 0 {
344 | return nil, true
345 | }
346 |
347 | return n, false
348 | }
349 |
350 | if (n.Key^key)&masks64[n.Bits] != 0 {
351 | return n, false
352 | }
353 |
354 | branch := (key >> (Key64BitSize - 1 - n.Bits)) & 1
355 | c := n.chld[branch]
356 | if c == nil {
357 | return n, false
358 | }
359 |
360 | c, ok := c.del(key, bits)
361 | if !ok {
362 | return n, false
363 | }
364 |
365 | if c == nil && !n.Leaf {
366 | return n.chld[1-branch], true
367 | }
368 |
369 | m := newNode64(n.Key, n.Bits, n.Leaf, n.Value)
370 | m.chld = n.chld
371 |
372 | m.chld[branch] = c
373 | return m, true
374 | }
375 |
376 | func newNode64(key uint64, bits uint8, leaf bool, value interface{}) *Node64 {
377 | return &Node64{
378 | Key: key,
379 | Bits: bits,
380 | Leaf: leaf,
381 | Value: value}
382 | }
383 |
--------------------------------------------------------------------------------
/internal/utils/resolver.go:
--------------------------------------------------------------------------------
1 | package utils
2 |
3 | import (
4 | "bytes"
5 | "context"
6 | "crypto/tls"
7 | "encoding/base64"
8 | "encoding/binary"
9 | "errors"
10 | "fmt"
11 | "io"
12 | "net"
13 | "net/http"
14 | "net/url"
15 | "time"
16 | )
17 |
18 | type Dialer struct {
19 | net.Dialer
20 | server string
21 | Config *tls.Config
22 | }
23 |
24 | func (d *Dialer) Dial(network, addr string) (net.Conn, error) {
25 | conn, err := d.Dialer.Dial("tcp", d.server)
26 | if nc, ok := conn.(*net.TCPConn); ok {
27 | nc.SetKeepAlive(true)
28 | }
29 | return conn, err
30 | }
31 |
32 | func (d *Dialer) DialContext(ctx context.Context, network, addr string) (net.Conn, error) {
33 | conn, err := d.Dialer.DialContext(ctx, "tcp", d.server)
34 | if nc, ok := conn.(*net.TCPConn); ok {
35 | nc.SetKeepAlive(true)
36 | }
37 | return conn, err
38 | }
39 |
40 | func (d *Dialer) DialTLS(network, addr string) (net.Conn, error) {
41 | conn, err := d.Dialer.Dial("tcp", d.server)
42 | if err != nil {
43 | return nil, err
44 | }
45 | if nc, ok := conn.(*net.TCPConn); ok {
46 | nc.SetKeepAlive(true)
47 | }
48 | return tls.Client(conn, d.Config), err
49 | }
50 |
51 | func (d *Dialer) DialTLSContext(ctx context.Context, network, addr string) (net.Conn, error) {
52 | conn, err := d.Dialer.DialContext(ctx, "tcp", d.server)
53 | if err != nil {
54 | return nil, err
55 | }
56 | if nc, ok := conn.(*net.TCPConn); ok {
57 | nc.SetKeepAlive(true)
58 | }
59 | return tls.Client(conn, d.Config), nil
60 | }
61 |
62 | type Resolver interface {
63 | Resolve([]byte, int) (int, error)
64 | DialContext(ctx context.Context, network, address string) (net.Conn, error)
65 | }
66 |
67 | func NewResolver(s string) (Resolver, error) {
68 | u, err := url.Parse(s)
69 | if err != nil {
70 | return nil, fmt.Errorf("parse url %v error: %v", s, err)
71 | }
72 |
73 | switch u.Scheme {
74 | case "udp":
75 | addr, err := net.ResolveUDPAddr("udp", net.JoinHostPort(u.Host, "53"))
76 | if err != nil {
77 | return nil, err
78 | }
79 |
80 | resolver := &UDPResolver{
81 | Addr: addr.String(),
82 | Timeout: time.Second * 3,
83 | }
84 | return resolver, nil
85 | case "tcp":
86 | addr, err := net.ResolveTCPAddr("tcp", net.JoinHostPort(u.Host, "53"))
87 | if err != nil {
88 | return nil, err
89 | }
90 |
91 | resolver := &TCPResolver{
92 | Addr: addr.String(),
93 | Timeout: time.Second * 3,
94 | }
95 | return resolver, nil
96 | case "tls":
97 | addr, err := net.ResolveTCPAddr("tcp", net.JoinHostPort(u.Host, "853"))
98 | if err != nil {
99 | return nil, err
100 | }
101 |
102 | resolver := &TLSResolver{
103 | Conf: &tls.Config{
104 | ServerName: u.Host,
105 | ClientSessionCache: tls.NewLRUClientSessionCache(32),
106 | InsecureSkipVerify: false,
107 | },
108 | Addr: addr.String(),
109 | Timeout: time.Second * 3,
110 | }
111 | return resolver, nil
112 | case "https":
113 | addr, err := net.ResolveTCPAddr("tcp", net.JoinHostPort(u.Host, "443"))
114 | if err != nil {
115 | return nil, err
116 | }
117 |
118 | resolver := &HTTPSResolverPost{
119 | Dialer: Dialer{
120 | Dialer: net.Dialer{},
121 | server: addr.String(),
122 | Config: &tls.Config{
123 | ServerName: u.Host,
124 | ClientSessionCache: tls.NewLRUClientSessionCache(32),
125 | InsecureSkipVerify: false,
126 | },
127 | },
128 | BaseUrl: s,
129 | Timeout: time.Second * 3,
130 | Client: http.Client{
131 | Timeout: time.Second * 3,
132 | },
133 | }
134 | resolver.Client.Transport = &http.Transport{
135 | Dial: resolver.Dialer.Dial,
136 | DialContext: resolver.Dialer.DialContext,
137 | TLSClientConfig: resolver.Dialer.Config,
138 | DialTLS: resolver.Dialer.DialTLS,
139 | DialTLSContext: resolver.Dialer.DialTLSContext,
140 | ForceAttemptHTTP2: true,
141 | }
142 | return resolver, nil
143 | default:
144 | return nil, fmt.Errorf("not a valid dns protocol")
145 | }
146 | }
147 |
148 | type UDPResolver struct {
149 | Dialer net.Dialer
150 | Addr string
151 | Timeout time.Duration
152 | }
153 |
154 | func (r *UDPResolver) Resolve(b []byte, n int) (int, error) {
155 | conn, err := net.Dial("udp", r.Addr)
156 | if err != nil {
157 | return 0, err
158 | }
159 | defer conn.Close()
160 |
161 | _, err = conn.Write(b[2 : 2+n])
162 | if err != nil {
163 | return 0, err
164 | }
165 |
166 | conn.SetReadDeadline(time.Now().Add(r.Timeout))
167 | return conn.Read(b[2:])
168 | }
169 |
170 | func (r *UDPResolver) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
171 | return r.Dialer.DialContext(ctx, "udp", r.Addr)
172 | }
173 |
174 | type TCPResolver struct {
175 | Dialer net.Dialer
176 | Addr string
177 | Timeout time.Duration
178 | }
179 |
180 | func (r *TCPResolver) Resolve(b []byte, n int) (l int, err error) {
181 | binary.BigEndian.PutUint16(b[:2], uint16(n))
182 |
183 | conn, err := net.Dial("tcp", r.Addr)
184 | if err != nil {
185 | return
186 | }
187 | conn.(*net.TCPConn).SetKeepAlive(true)
188 | defer conn.Close()
189 |
190 | _, err = conn.Write(b[:2+n])
191 | if err != nil {
192 | return
193 | }
194 |
195 | conn.SetReadDeadline(time.Now().Add(r.Timeout))
196 | _, err = io.ReadFull(conn, b[:2])
197 | if err != nil {
198 | return
199 | }
200 |
201 | l = int(binary.BigEndian.Uint16(b[:2]))
202 | if l > len(b)-2 {
203 | err = io.ErrShortBuffer
204 | return
205 | }
206 |
207 | _, err = io.ReadFull(conn, b[2:2+l])
208 | return
209 | }
210 |
211 | func (r *TCPResolver) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
212 | conn, err := r.Dialer.DialContext(ctx, "tcp", r.Addr)
213 | if nc, ok := conn.(*net.TCPConn); ok {
214 | nc.SetKeepAlive(true)
215 | }
216 | return conn, err
217 | }
218 |
219 | type TLSResolver struct {
220 | Dialer net.Dialer
221 | Conf *tls.Config
222 | Addr string
223 | Timeout time.Duration
224 | }
225 |
226 | func (r *TLSResolver) Resolve(b []byte, n int) (l int, err error) {
227 | binary.BigEndian.PutUint16(b[:2], uint16(n))
228 |
229 | conn, err := net.Dial("tcp", r.Addr)
230 | if err != nil {
231 | return
232 | }
233 | conn.(*net.TCPConn).SetKeepAlive(true)
234 | conn = tls.Client(conn, r.Conf)
235 | defer conn.Close()
236 |
237 | _, err = conn.Write(b[:2+n])
238 | if err != nil {
239 | return
240 | }
241 |
242 | conn.SetReadDeadline(time.Now().Add(r.Timeout))
243 | _, err = io.ReadFull(conn, b[:2])
244 | if err != nil {
245 | return
246 | }
247 |
248 | l = int(binary.BigEndian.Uint16(b[:2]))
249 | if l > len(b)-2 {
250 | err = io.ErrShortBuffer
251 | return
252 | }
253 |
254 | _, err = io.ReadFull(conn, b[2:2+l])
255 | return
256 | }
257 |
258 | func (r *TLSResolver) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
259 | conn, err := r.Dialer.DialContext(ctx, "tcp", r.Addr)
260 | if nc, ok := conn.(*net.TCPConn); ok {
261 | nc.SetKeepAlive(true)
262 | conn = tls.Client(conn, r.Conf)
263 | }
264 | return conn, err
265 | }
266 |
267 | type Buffer []byte
268 |
269 | func (b Buffer) ReadFrom(r io.Reader) (n int64, err error) {
270 | for {
271 | nr, er := r.Read(b[n:])
272 | if nr > 0 {
273 | n += int64(nr)
274 | }
275 | if er != nil {
276 | if errors.Is(er, io.EOF) {
277 | break
278 | }
279 | err = er
280 | break
281 | }
282 | if int(n) == len(b) {
283 | err = io.ErrShortBuffer
284 | break
285 | }
286 | }
287 | return
288 | }
289 |
290 | type Conn struct{}
291 |
292 | func (c Conn) Close() error { return nil }
293 | func (c Conn) LocalAddr() net.Addr { return nil }
294 | func (c Conn) RemoteAddr() net.Addr { return nil }
295 | func (c Conn) SetDeadline(t time.Time) error { return nil }
296 | func (c Conn) SetReadDeadline(t time.Time) error { return nil }
297 | func (c Conn) SetWriteDeadline(t time.Time) error { return nil }
298 |
299 | type PacketConnPost struct {
300 | Conn
301 | r *HTTPSResolverPost
302 | rc io.ReadCloser
303 | }
304 |
305 | func (c *PacketConnPost) Write(b []byte) (int, error) {
306 | req, err := http.NewRequest(http.MethodPost, c.r.BaseUrl, bytes.NewBuffer(b))
307 | if err != nil {
308 | return 0, err
309 | }
310 | req.Header.Add("accept", "application/dns-message")
311 | req.Header.Add("content-type", "application/dns-message")
312 |
313 | res, err := c.r.Do(req)
314 | if err != nil {
315 | return 0, err
316 | }
317 | if res.StatusCode != http.StatusOK {
318 | res.Body.Close()
319 | return 0, fmt.Errorf("bad http response code: %v", res.StatusCode)
320 | }
321 |
322 | c.rc = res.Body
323 | return len(b), err
324 | }
325 |
326 | func (c *PacketConnPost) WriteTo(b []byte, addr net.Addr) (int, error) {
327 | return c.Write(b)
328 | }
329 |
330 | func (c *PacketConnPost) Read(b []byte) (int, error) {
331 | n, err := Buffer(b).ReadFrom(c.rc)
332 | c.rc.Close()
333 | return int(n), err
334 | }
335 |
336 | func (c *PacketConnPost) ReadFrom(b []byte) (int, net.Addr, error) {
337 | n, err := c.Read(b)
338 | return n, nil, err
339 | }
340 |
341 | type HTTPSResolverPost struct {
342 | Dialer Dialer
343 | BaseUrl string
344 | Timeout time.Duration
345 | http.Client
346 | }
347 |
348 | func (r *HTTPSResolverPost) Resolve(b []byte, n int) (int, error) {
349 | req, err := http.NewRequest(http.MethodPost, r.BaseUrl, bytes.NewBuffer(b[2:2+n]))
350 | if err != nil {
351 | return 0, err
352 | }
353 | req.Header.Add("accept", "application/dns-message")
354 | req.Header.Add("content-type", "application/dns-message")
355 |
356 | res, err := r.Do(req)
357 | if err != nil {
358 | return 0, err
359 | }
360 | defer res.Body.Close()
361 |
362 | if res.StatusCode != http.StatusOK {
363 | return 0, fmt.Errorf("bad http response code: %v", res.StatusCode)
364 | }
365 |
366 | nr, err := Buffer(b[2:]).ReadFrom(res.Body)
367 | return int(nr), err
368 | }
369 |
370 | func (r *HTTPSResolverPost) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
371 | return &PacketConnPost{r: r}, nil
372 | }
373 |
374 | type PacketConnGet struct {
375 | Conn
376 | r *HTTPSResolverGet
377 | rc io.ReadCloser
378 | }
379 |
380 | func (c *PacketConnGet) Write(b []byte) (int, error) {
381 | req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("%s?%s=%s", c.r.BaseUrl, "dns", base64.RawURLEncoding.EncodeToString(b)), nil)
382 | if err != nil {
383 | return 0, err
384 | }
385 | req.Header.Add("accept", "application/dns-message")
386 | req.Header.Add("content-type", "application/dns-message")
387 |
388 | res, err := c.r.Do(req)
389 | if err != nil {
390 | return 0, err
391 | }
392 | if res.StatusCode != http.StatusOK {
393 | res.Body.Close()
394 | return 0, fmt.Errorf("bad http response code: %v", res.StatusCode)
395 | }
396 | c.rc = res.Body
397 | return len(b), err
398 | }
399 |
400 | func (c *PacketConnGet) WriteTo(b []byte, addr net.Addr) (int, error) {
401 | return c.Write(b)
402 | }
403 |
404 | func (c *PacketConnGet) Read(b []byte) (int, error) {
405 | n, err := Buffer(b).ReadFrom(c.rc)
406 | c.rc.Close()
407 | return int(n), err
408 | }
409 |
410 | func (c *PacketConnGet) ReadFrom(b []byte) (int, net.Addr, error) {
411 | n, err := c.Read(b)
412 | return n, nil, err
413 | }
414 |
415 | type HTTPSResolverGet struct {
416 | Dialer Dialer
417 | BaseUrl string
418 | Timeout time.Duration
419 | http.Client
420 | }
421 |
422 | func (r *HTTPSResolverGet) Resolve(b []byte, n int) (int, error) {
423 | req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("%s?%s=%s", r.BaseUrl, "dns", base64.RawURLEncoding.EncodeToString(b[2:2+n])), nil)
424 | if err != nil {
425 | return 0, err
426 | }
427 | req.Header.Add("accept", "application/dns-message")
428 | req.Header.Add("content-type", "application/dns-message")
429 |
430 | res, err := r.Do(req)
431 | if err != nil {
432 | return 0, err
433 | }
434 | defer res.Body.Close()
435 |
436 | if res.StatusCode != http.StatusOK {
437 | return 0, fmt.Errorf("bad http response code: %v", res.StatusCode)
438 | }
439 |
440 | nr, err := Buffer(b[2:]).ReadFrom(res.Body)
441 | return int(nr), err
442 | }
443 |
444 | func (r *HTTPSResolverGet) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
445 | return &PacketConnGet{r: r}, nil
446 | }
447 |
--------------------------------------------------------------------------------
/internal/utils/suffixtree.go:
--------------------------------------------------------------------------------
1 | package utils
2 |
3 | import (
4 | "strings"
5 | "sync"
6 | )
7 |
8 | type DomainTree struct {
9 | *node
10 | sep string
11 | sync.RWMutex
12 | }
13 | type node struct {
14 | value interface{}
15 | branch map[string]*node
16 | }
17 |
18 | func NewDomainTree(sep string) *DomainTree {
19 | return &DomainTree{
20 | node: &node{
21 | value: struct{}{},
22 | branch: map[string]*node{},
23 | },
24 | sep: sep,
25 | RWMutex: sync.RWMutex{},
26 | }
27 | }
28 |
29 | func (t *DomainTree) Store(k string, v interface{}) {
30 | t.Lock()
31 | defer t.Unlock()
32 | t.store(strings.Split(strings.TrimSuffix(k, t.sep), t.sep), v)
33 | }
34 | func (t *DomainTree) UnsafeStore(k string, v interface{}) {
35 | t.store(strings.Split(strings.TrimSuffix(k, t.sep), t.sep), v)
36 | }
37 | func (n *node) store(ks []string, v interface{}) {
38 | l := len(ks)
39 | switch l {
40 | case 0:
41 | return
42 | case 1:
43 | k := ks[l-1]
44 |
45 | if k == "*" || k == "**" {
46 | n.value = v
47 | }
48 |
49 | b, ok := n.branch[k]
50 | if ok {
51 | b.value = v
52 | return
53 | }
54 |
55 | n.branch[k] = &node{
56 | value: v,
57 | branch: map[string]*node{},
58 | }
59 | default:
60 | k := ks[l-1]
61 |
62 | b, ok := n.branch[k]
63 | if !ok {
64 | b = &node{
65 | value: struct{}{},
66 | branch: map[string]*node{},
67 | }
68 | n.branch[k] = b
69 | }
70 |
71 | b.store(ks[:l-1], v)
72 | }
73 | }
74 |
75 | func (t *DomainTree) Load(k string) interface{} {
76 | t.RLock()
77 | defer t.RUnlock()
78 | return t.load(strings.Split(strings.TrimSuffix(k, t.sep), t.sep))
79 | }
80 | func (t *DomainTree) UnsafeLoad(k string) interface{} {
81 | return t.load(strings.Split(strings.TrimSuffix(k, t.sep), t.sep))
82 | }
83 | func (n *node) load(ks []string) interface{} {
84 | l := len(ks)
85 | switch l {
86 | case 0:
87 | return struct{}{}
88 | case 1:
89 | b, ok := n.branch[ks[l-1]]
90 | if ok {
91 | return b.value
92 | }
93 |
94 | b, ok = n.branch["*"]
95 | if ok {
96 | return b.value
97 | }
98 |
99 | b, ok = n.branch["**"]
100 | if ok {
101 | return b.value
102 | }
103 |
104 | return struct{}{}
105 | default:
106 | b, ok := n.branch[ks[l-1]]
107 | if ok {
108 | s := b.load(ks[:l-1])
109 | if s != struct{}{} {
110 | return s
111 | }
112 | }
113 |
114 | b, ok = n.branch["*"]
115 | if ok {
116 | s := b.load(ks[:l-1])
117 | if s != struct{}{} {
118 | return s
119 | }
120 | }
121 |
122 | b, ok = n.branch["**"]
123 | if ok {
124 | return b.value
125 | }
126 |
127 | return struct{}{}
128 | }
129 | }
130 |
131 | func (t *DomainTree) Reset() {
132 | t.Lock()
133 | defer t.Unlock()
134 | t.reset()
135 | }
136 | func (t *DomainTree) UnsafeReset() {
137 | t.reset()
138 | }
139 | func (n *node) reset() {
140 | n.value = nil
141 | for k, v := range n.branch {
142 | v.reset()
143 | delete(n.branch, k)
144 | }
145 | }
146 |
--------------------------------------------------------------------------------
/packet.go:
--------------------------------------------------------------------------------
1 | package windivert
2 |
3 | /*
4 | #include
5 | #include
6 | */
7 | import "C"
8 |
9 | import (
10 | "fmt"
11 | "unsafe"
12 | )
13 |
14 | // PacketInfo contains parsed packet information
15 | type PacketInfo struct {
16 | IPv4Header *IPv4Header
17 | IPv6Header *IPv6Header
18 | ICMPHeader *ICMPHeader
19 | ICMPv6Header *ICMPv6Header
20 | TCPHeader *TCPHeader
21 | UDPHeader *UDPHeader
22 | Data []byte
23 | }
24 |
25 | // IPv4Header represents an IPv4 header (WINDIVERT_IPHDR)
26 | type IPv4Header struct {
27 | HdrLength uint8 // Header length
28 | Version uint8 // Version
29 | TOS uint8 // Type of service
30 | Length uint16 // Total length
31 | Id uint16 // Identification
32 | FragOff uint16 // Fragment offset
33 | TTL uint8 // Time to live
34 | Protocol uint8 // Protocol
35 | Checksum uint16 // Checksum
36 | SrcAddr uint32 // Source address
37 | DstAddr uint32 // Destination address
38 | }
39 |
40 | // IPv6Header represents an IPv6 header (WINDIVERT_IPV6HDR)
41 | type IPv6Header struct {
42 | Version uint8 // Version
43 | TrafficClass uint8 // Traffic class
44 | FlowLabel uint32 // Flow label
45 | Length uint16 // Payload length
46 | NextHdr uint8 // Next header
47 | HopLimit uint8 // Hop limit
48 | SrcAddr [16]byte // Source address
49 | DstAddr [16]byte // Destination address
50 | }
51 |
52 | // ICMPHeader represents an ICMP header (WINDIVERT_ICMPHDR)
53 | type ICMPHeader struct {
54 | Type uint8 // Type
55 | Code uint8 // Code
56 | Checksum uint16 // Checksum
57 | Body uint32 // Body
58 | }
59 |
60 | // ICMPv6Header represents an ICMPv6 header (WINDIVERT_ICMPV6HDR)
61 | type ICMPv6Header struct {
62 | Type uint8 // Type
63 | Code uint8 // Code
64 | Checksum uint16 // Checksum
65 | Body uint32 // Body
66 | }
67 |
68 | // TCPHeader represents a TCP header (WINDIVERT_TCPHDR)
69 | type TCPHeader struct {
70 | SrcPort uint16 // Source port
71 | DstPort uint16 // Destination port
72 | SeqNum uint32 // Sequence number
73 | AckNum uint32 // Acknowledgement number
74 | Reserved1 uint8 // Reserved
75 | Reserved2 uint8 // Reserved
76 | Reserved3 uint8 // Reserved
77 | Flags uint8 // Flags
78 | Window uint16 // Window
79 | Checksum uint16 // Checksum
80 | UrgPtr uint16 // Urgent pointer
81 | }
82 |
83 | // UDPHeader represents a UDP header (WINDIVERT_UDPHDR)
84 | type UDPHeader struct {
85 | SrcPort uint16 // Source port
86 | DstPort uint16 // Destination port
87 | Length uint16 // Length
88 | Checksum uint16 // Checksum
89 | }
90 |
91 | // Helper functions for parsing addresses
92 | func ParseIPv4Address(str string) (uint32, error) {
93 | cstr := C.CString(str)
94 | defer C.free(unsafe.Pointer(cstr))
95 |
96 | var addr C.UINT32
97 | if ret := C.WinDivertHelperParseIPv4Address(cstr, &addr); ret == 0 {
98 | return 0, fmt.Errorf("failed to parse IPv4 address")
99 | }
100 | return uint32(addr), nil
101 | }
102 |
103 | func ParseIPv6Address(str string) ([4]uint32, error) {
104 | cstr := C.CString(str)
105 | defer C.free(unsafe.Pointer(cstr))
106 |
107 | var addr [4]C.UINT32
108 | if ret := C.WinDivertHelperParseIPv6Address(cstr, &addr[0]); ret == 0 {
109 | return [4]uint32{}, fmt.Errorf("failed to parse IPv6 address")
110 | }
111 | return *(*[4]uint32)(unsafe.Pointer(&addr)), nil
112 | }
113 |
--------------------------------------------------------------------------------
/types.go:
--------------------------------------------------------------------------------
1 | package windivert
2 |
3 | /*
4 | #include
5 | #include
6 | */
7 | import "C"
8 |
9 | import (
10 | "sync"
11 | "unsafe"
12 | )
13 |
14 | // Handle represents a WinDivert handle
15 | type Handle struct {
16 | handle C.HANDLE
17 | mutex sync.Mutex
18 | }
19 |
20 | // Lock locks the handle
21 | func (h *Handle) Lock() {
22 | h.mutex.Lock()
23 | }
24 |
25 | // Unlock unlocks the handle
26 | func (h *Handle) Unlock() {
27 | h.mutex.Unlock()
28 | }
29 |
30 | // Close closes the WinDivert handle
31 | func (h *Handle) Close() error {
32 | if h.handle != C.INVALID_HANDLE_VALUE {
33 | if C.WinDivertClose(h.handle) == 0 {
34 | return getLastError()
35 | }
36 | h.handle = C.INVALID_HANDLE_VALUE
37 | }
38 | return nil
39 | }
40 |
41 | // Open opens a WinDivert handle
42 | func Open(filter string, layer Layer, priority int16, flags uint64) (*Handle, error) {
43 | cfilter := C.CString(filter)
44 | defer C.free(unsafe.Pointer(cfilter))
45 |
46 | handle := C.WinDivertOpen(cfilter, C.WINDIVERT_LAYER(layer), C.INT16(priority), C.UINT64(flags))
47 | if handle == C.INVALID_HANDLE_VALUE {
48 | return nil, getLastError()
49 | }
50 |
51 | return &Handle{handle: handle}, nil
52 | }
53 |
--------------------------------------------------------------------------------
/vars.go:
--------------------------------------------------------------------------------
1 | package windivert
2 |
3 | import "golang.org/x/sys/windows"
4 |
5 | var (
6 | // WinDivert is the DLL instance
7 | WinDivert = (*windows.DLL)(nil)
8 | // WinDivertOpen is the WinDivertOpen procedure
9 | WinDivertOpen = (*windows.Proc)(nil)
10 | // WinDivertSys is the path to WinDivert sys file
11 | WinDivertSys = ""
12 | // WinDivertDll is the path to WinDivert dll file
13 | WinDivertDll = ""
14 | // DeviceName is the WinDivert device name
15 | DeviceName = windows.StringToUTF16Ptr("WinDivert")
16 | )
17 |
--------------------------------------------------------------------------------
/windivert.go:
--------------------------------------------------------------------------------
1 | package windivert
2 |
3 | /*
4 | #include
5 | #include
6 |
7 | HANDLE getLastError() {
8 | return GetLastError();
9 | }
10 | */
11 | import "C"
12 |
13 | import (
14 | "fmt"
15 | "path/filepath"
16 | "strconv"
17 | "strings"
18 | "unsafe"
19 |
20 | "golang.org/x/sys/windows"
21 | )
22 |
23 | // CtlCode represents a control code
24 | type CtlCode uint32
25 |
26 | // IoCtl represents an IO control structure
27 | type IoCtl struct {
28 | Code CtlCode
29 | Pkt uint64
30 | Addr uint64
31 | Param uint32
32 | Length uint32
33 | }
34 |
35 | // recv represents a receive operation
36 | type recv struct {
37 | Addr uint64
38 | AddrLenPtr uint64
39 | }
40 |
41 | // send represents a send operation
42 | type send struct {
43 | Addr uint64
44 | AddrLen uint64
45 | }
46 |
47 | var (
48 | // WinDivert is the DLL instance
49 | WinDivert = (*windows.DLL)(nil)
50 | // WinDivertOpen is the WinDivertOpen procedure
51 | WinDivertOpen = (*windows.Proc)(nil)
52 | // WinDivertSys is the path to WinDivert sys file
53 | WinDivertSys = ""
54 | // WinDivertDll is the path to WinDivert dll file
55 | WinDivertDll = ""
56 | // DeviceName is the WinDivert device name
57 | DeviceName = windows.StringToUTF16Ptr("WinDivert")
58 | )
59 |
60 | func init() {
61 | if err := checkForWow64(); err != nil {
62 | panic(err)
63 | }
64 |
65 | system32, err := windows.GetSystemDirectory()
66 | if err != nil {
67 | panic(err)
68 | }
69 | WinDivertSys = filepath.Join(system32, "WinDivert"+strconv.Itoa(32<<(^uint(0)>>63))+".sys")
70 | WinDivertDll = filepath.Join(system32, "WinDivert.dll")
71 |
72 | if err := InstallDriver(); err != nil {
73 | panic(err)
74 | }
75 |
76 | WinDivert = windows.MustLoadDLL("WinDivert.dll")
77 | WinDivertOpen = WinDivert.MustFindProc("WinDivertOpen")
78 |
79 | var vers = map[string]struct{}{
80 | "2.0": struct{}{},
81 | "2.1": struct{}{},
82 | "2.2": struct{}{},
83 | }
84 |
85 | hd, err := Open("false", LayerNetwork, PriorityDefault, FlagDefault)
86 | if err != nil {
87 | panic(err)
88 | }
89 | defer hd.Close()
90 |
91 | major, err := hd.GetParam(VersionMajor)
92 | if err != nil {
93 | panic(err)
94 | }
95 |
96 | minor, err := hd.GetParam(VersionMinor)
97 | if err != nil {
98 | panic(err)
99 | }
100 |
101 | if err := hd.Shutdown(ShutdownBoth); err != nil {
102 | panic(err)
103 | }
104 |
105 | ver := strings.Join([]string{strconv.Itoa(int(major)), strconv.Itoa(int(minor))}, ".")
106 | if _, ok := vers[ver]; !ok {
107 | s := ""
108 | for k, _ := range vers {
109 | s += k
110 | }
111 | panic(fmt.Errorf("unsupported version %v of windivert, only support %v", ver, s))
112 | }
113 | }
114 |
115 | func checkForWow64() error {
116 | var b bool
117 | err := windows.IsWow64Process(windows.CurrentProcess(), &b)
118 | if err != nil {
119 | return fmt.Errorf("Unable to determine whether the process is running under WOW64: %v", err)
120 | }
121 | if b {
122 | return fmt.Errorf("You must use the 64-bit version of WireGuard on this computer.")
123 | }
124 | return nil
125 | }
126 |
127 | func IoControlEx(h windows.Handle, code CtlCode, ioctl unsafe.Pointer, buf *byte, bufLen uint32, overlapped *windows.Overlapped) (iolen uint32, err error) {
128 | err = windows.DeviceIoControl(h, uint32(code), (*byte)(ioctl), uint32(unsafe.Sizeof(IoCtl{})), buf, bufLen, &iolen, overlapped)
129 | if err != windows.ERROR_IO_PENDING {
130 | return
131 | }
132 |
133 | err = windows.GetOverlappedResult(h, overlapped, &iolen, true)
134 |
135 | return
136 | }
137 |
138 | func IoControl(h windows.Handle, code CtlCode, ioctl unsafe.Pointer, buf *byte, bufLen uint32) (iolen uint32, err error) {
139 | event, _ := windows.CreateEvent(nil, 0, 0, nil)
140 |
141 | overlapped := windows.Overlapped{
142 | HEvent: event,
143 | }
144 |
145 | iolen, err = IoControlEx(h, code, ioctl, buf, bufLen, &overlapped)
146 |
147 | windows.CloseHandle(event)
148 | return
149 | }
150 |
151 | // RecvEx receives multiple packets
152 | func (h *Handle) RecvEx(packets [][]byte, addrs []Address, flags uint64) (uint, uint, error) {
153 | if len(packets) == 0 || len(addrs) == 0 {
154 | return 0, 0, fmt.Errorf("empty packets or addresses buffer")
155 | }
156 |
157 | h.mutex.Lock()
158 | defer h.mutex.Unlock()
159 |
160 | var readLen C.UINT
161 | var addrLen C.UINT
162 |
163 | ret := C.WinDivertRecvEx(
164 | h.handle,
165 | unsafe.Pointer(&packets[0][0]),
166 | C.UINT(len(packets[0])*len(packets)),
167 | &readLen,
168 | C.UINT64(flags),
169 | (*C.WINDIVERT_ADDRESS)(unsafe.Pointer(&addrs[0])),
170 | &addrLen,
171 | nil,
172 | )
173 |
174 | if ret == 0 {
175 | return 0, 0, getLastError()
176 | }
177 |
178 | return uint(readLen), uint(addrLen), nil
179 | }
180 |
181 | // SendEx sends multiple packets
182 | func (h *Handle) SendEx(packets [][]byte, addrs []Address, flags uint64) (uint, error) {
183 | if len(packets) == 0 || len(addrs) == 0 {
184 | return 0, fmt.Errorf("empty packets or addresses buffer")
185 | }
186 |
187 | h.mutex.Lock()
188 | defer h.mutex.Unlock()
189 |
190 | var writeLen C.UINT
191 |
192 | ret := C.WinDivertSendEx(
193 | h.handle,
194 | unsafe.Pointer(&packets[0][0]),
195 | C.UINT(len(packets[0])*len(packets)),
196 | &writeLen,
197 | C.UINT64(flags),
198 | (*C.WINDIVERT_ADDRESS)(unsafe.Pointer(&addrs[0])),
199 | C.UINT(len(addrs)),
200 | nil,
201 | )
202 |
203 | if ret == 0 {
204 | return 0, getLastError()
205 | }
206 |
207 | return uint(writeLen), nil
208 | }
209 |
210 | // Recv receives a single packet
211 | func (h *Handle) Recv(packet []byte, addr *Address) (uint, error) {
212 | nr, _, err := h.RecvEx([][]byte{packet}, []Address{*addr}, 0)
213 | if err != nil {
214 | return 0, err
215 | }
216 | return nr, nil
217 | }
218 |
219 | // SetParam sets a WinDivert parameter
220 | func (h *Handle) SetParam(param Param, value uint64) error {
221 | h.mutex.Lock()
222 | defer h.mutex.Unlock()
223 |
224 | ret := C.WinDivertSetParam(h.handle, C.WINDIVERT_PARAM(param), C.UINT64(value))
225 | if ret == 0 {
226 | return getLastError()
227 | }
228 | return nil
229 | }
230 |
231 | // Shutdown shuts down a WinDivert handle
232 | func (h *Handle) Shutdown(how ShutdownType) error {
233 | h.mutex.Lock()
234 | defer h.mutex.Unlock()
235 |
236 | ret := C.WinDivertShutdown(h.handle, C.WINDIVERT_SHUTDOWN(how))
237 | if ret == 0 {
238 | return getLastError()
239 | }
240 | return nil
241 | }
242 |
--------------------------------------------------------------------------------
/windivert_device.go:
--------------------------------------------------------------------------------
1 | package windivert
2 |
3 | const (
4 | METHOD_BUFFERED = 0
5 | METHOD_IN_DIRECT = 1
6 | METHOD_OUT_DIRECT = 2
7 | METHOD_NEITHER = 3
8 | )
9 |
10 | const (
11 | FILE_READ_DATA = 1
12 | FILE_WRITE_DATA = 2
13 | )
14 |
15 | const (
16 | FILE_DEVICE_NETWORK = 0x00000012
17 | FILE_DEVICE_NETWORK_BROWSER = 0x00000013
18 | FILE_DEVICE_NETWORK_FILE_SYSTEM = 0x00000014
19 | FILE_DEVICE_NETWORK_REDIRECTOR = 0x00000028
20 | )
21 |
22 | func CTL_CODE(DeviceType, Function, Method, Access uint32) CtlCode {
23 | return CtlCode(((DeviceType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method))
24 | }
25 |
26 | var (
27 | IoCtlInitialize = CTL_CODE(FILE_DEVICE_NETWORK, 0x921, METHOD_OUT_DIRECT, FILE_READ_DATA|FILE_WRITE_DATA)
28 | IoCtlStartup = CTL_CODE(FILE_DEVICE_NETWORK, 0x922, METHOD_IN_DIRECT, FILE_READ_DATA|FILE_WRITE_DATA)
29 | IoCtlRecv = CTL_CODE(FILE_DEVICE_NETWORK, 0x923, METHOD_OUT_DIRECT, FILE_READ_DATA)
30 | IoCtlSend = CTL_CODE(FILE_DEVICE_NETWORK, 0x924, METHOD_IN_DIRECT, FILE_READ_DATA|FILE_WRITE_DATA)
31 | IoCtlSetParam = CTL_CODE(FILE_DEVICE_NETWORK, 0x925, METHOD_IN_DIRECT, FILE_READ_DATA|FILE_WRITE_DATA)
32 | IoCtlGetParam = CTL_CODE(FILE_DEVICE_NETWORK, 0x926, METHOD_OUT_DIRECT, FILE_READ_DATA)
33 | IoCtlShutdown = CTL_CODE(FILE_DEVICE_NETWORK, 0x927, METHOD_IN_DIRECT, FILE_READ_DATA|FILE_WRITE_DATA)
34 | )
35 |
36 | func (code CtlCode) String() string {
37 | switch code {
38 | case IoCtlInitialize:
39 | return "IOCTL_WINDIVERT_INITIALIZE"
40 | case IoCtlStartup:
41 | return "IOCTL_WINDIVERT_STARTUP"
42 | case IoCtlRecv:
43 | return "IOCTL_WINDIVERT_RECV"
44 | case IoCtlSend:
45 | return "IOCTL_WINDIVERT_SEND"
46 | case IoCtlSetParam:
47 | return "IOCTL_WINDIVERT_SET_PARAM"
48 | case IoCtlGetParam:
49 | return "IOCTL_WINDIVERT_GET_PARAM"
50 | case IoCtlShutdown:
51 | return "IOCTL_WINDIVERT_SHUTDOWN"
52 | default:
53 | return ""
54 | }
55 | }
56 |
57 | type initialize struct {
58 | Layer uint32
59 | Priority uint32
60 | Flags uint64
61 | }
62 |
63 | type startup struct {
64 | Flags uint64
65 | _ uint64
66 | }
67 |
68 | type shutdown struct {
69 | How uint32
70 | _ uint32
71 | _ uint64
72 | }
73 |
74 | type getParam struct {
75 | Param uint32
76 | _ uint32
77 | Value uint64
78 | }
79 |
80 | type setParam struct {
81 | Value uint64
82 | Param uint32
83 | _ uint32
84 | }
85 |
--------------------------------------------------------------------------------