├── .gitignore
├── LICENSE
├── Makefile
├── README.md
├── examples
├── dump-table-raw
│ └── dump-table-raw.go
├── dump-table-rules
│ └── dump-table-rules.go
└── lock
│ └── lock.go
├── libip4tc
├── libip4tc.go
└── libip4tc_test.go
├── libip6tc
├── libip6tc.go
└── libip6tc_test.go
├── libiptc.go
├── update-version.sh
├── xtables-lock.c
└── xtables-lock.h
/.gitignore:
--------------------------------------------------------------------------------
1 | examples/dump-table-raw/dump-table-raw
2 | examples/dump-table-rules/dump-table-rules
3 | examples/lock/lock
4 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 2, June 1991
3 |
4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6 | Everyone is permitted to copy and distribute verbatim copies
7 | of this license document, but changing it is not allowed.
8 |
9 | Preamble
10 |
11 | The licenses for most software are designed to take away your
12 | freedom to share and change it. By contrast, the GNU General Public
13 | License is intended to guarantee your freedom to share and change free
14 | software--to make sure the software is free for all its users. This
15 | General Public License applies to most of the Free Software
16 | Foundation's software and to any other program whose authors commit to
17 | using it. (Some other Free Software Foundation software is covered by
18 | the GNU Lesser General Public License instead.) You can apply it to
19 | your programs, too.
20 |
21 | When we speak of free software, we are referring to freedom, not
22 | price. Our General Public Licenses are designed to make sure that you
23 | have the freedom to distribute copies of free software (and charge for
24 | this service if you wish), that you receive source code or can get it
25 | if you want it, that you can change the software or use pieces of it
26 | in new free programs; and that you know you can do these things.
27 |
28 | To protect your rights, we need to make restrictions that forbid
29 | anyone to deny you these rights or to ask you to surrender the rights.
30 | These restrictions translate to certain responsibilities for you if you
31 | distribute copies of the software, or if you modify it.
32 |
33 | For example, if you distribute copies of such a program, whether
34 | gratis or for a fee, you must give the recipients all the rights that
35 | you have. You must make sure that they, too, receive or can get the
36 | source code. And you must show them these terms so they know their
37 | rights.
38 |
39 | We protect your rights with two steps: (1) copyright the software, and
40 | (2) offer you this license which gives you legal permission to copy,
41 | distribute and/or modify the software.
42 |
43 | Also, for each author's protection and ours, we want to make certain
44 | that everyone understands that there is no warranty for this free
45 | software. If the software is modified by someone else and passed on, we
46 | want its recipients to know that what they have is not the original, so
47 | that any problems introduced by others will not reflect on the original
48 | authors' reputations.
49 |
50 | Finally, any free program is threatened constantly by software
51 | patents. We wish to avoid the danger that redistributors of a free
52 | program will individually obtain patent licenses, in effect making the
53 | program proprietary. To prevent this, we have made it clear that any
54 | patent must be licensed for everyone's free use or not licensed at all.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | GNU GENERAL PUBLIC LICENSE
60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61 |
62 | 0. This License applies to any program or other work which contains
63 | a notice placed by the copyright holder saying it may be distributed
64 | under the terms of this General Public License. The "Program", below,
65 | refers to any such program or work, and a "work based on the Program"
66 | means either the Program or any derivative work under copyright law:
67 | that is to say, a work containing the Program or a portion of it,
68 | either verbatim or with modifications and/or translated into another
69 | language. (Hereinafter, translation is included without limitation in
70 | the term "modification".) Each licensee is addressed as "you".
71 |
72 | Activities other than copying, distribution and modification are not
73 | covered by this License; they are outside its scope. The act of
74 | running the Program is not restricted, and the output from the Program
75 | is covered only if its contents constitute a work based on the
76 | Program (independent of having been made by running the Program).
77 | Whether that is true depends on what the Program does.
78 |
79 | 1. You may copy and distribute verbatim copies of the Program's
80 | source code as you receive it, in any medium, provided that you
81 | conspicuously and appropriately publish on each copy an appropriate
82 | copyright notice and disclaimer of warranty; keep intact all the
83 | notices that refer to this License and to the absence of any warranty;
84 | and give any other recipients of the Program a copy of this License
85 | along with the Program.
86 |
87 | You may charge a fee for the physical act of transferring a copy, and
88 | you may at your option offer warranty protection in exchange for a fee.
89 |
90 | 2. You may modify your copy or copies of the Program or any portion
91 | of it, thus forming a work based on the Program, and copy and
92 | distribute such modifications or work under the terms of Section 1
93 | above, provided that you also meet all of these conditions:
94 |
95 | a) You must cause the modified files to carry prominent notices
96 | stating that you changed the files and the date of any change.
97 |
98 | b) You must cause any work that you distribute or publish, that in
99 | whole or in part contains or is derived from the Program or any
100 | part thereof, to be licensed as a whole at no charge to all third
101 | parties under the terms of this License.
102 |
103 | c) If the modified program normally reads commands interactively
104 | when run, you must cause it, when started running for such
105 | interactive use in the most ordinary way, to print or display an
106 | announcement including an appropriate copyright notice and a
107 | notice that there is no warranty (or else, saying that you provide
108 | a warranty) and that users may redistribute the program under
109 | these conditions, and telling the user how to view a copy of this
110 | License. (Exception: if the Program itself is interactive but
111 | does not normally print such an announcement, your work based on
112 | the Program is not required to print an announcement.)
113 |
114 | These requirements apply to the modified work as a whole. If
115 | identifiable sections of that work are not derived from the Program,
116 | and can be reasonably considered independent and separate works in
117 | themselves, then this License, and its terms, do not apply to those
118 | sections when you distribute them as separate works. But when you
119 | distribute the same sections as part of a whole which is a work based
120 | on the Program, the distribution of the whole must be on the terms of
121 | this License, whose permissions for other licensees extend to the
122 | entire whole, and thus to each and every part regardless of who wrote it.
123 |
124 | Thus, it is not the intent of this section to claim rights or contest
125 | your rights to work written entirely by you; rather, the intent is to
126 | exercise the right to control the distribution of derivative or
127 | collective works based on the Program.
128 |
129 | In addition, mere aggregation of another work not based on the Program
130 | with the Program (or with a work based on the Program) on a volume of
131 | a storage or distribution medium does not bring the other work under
132 | the scope of this License.
133 |
134 | 3. You may copy and distribute the Program (or a work based on it,
135 | under Section 2) in object code or executable form under the terms of
136 | Sections 1 and 2 above provided that you also do one of the following:
137 |
138 | a) Accompany it with the complete corresponding machine-readable
139 | source code, which must be distributed under the terms of Sections
140 | 1 and 2 above on a medium customarily used for software interchange; or,
141 |
142 | b) Accompany it with a written offer, valid for at least three
143 | years, to give any third party, for a charge no more than your
144 | cost of physically performing source distribution, a complete
145 | machine-readable copy of the corresponding source code, to be
146 | distributed under the terms of Sections 1 and 2 above on a medium
147 | customarily used for software interchange; or,
148 |
149 | c) Accompany it with the information you received as to the offer
150 | to distribute corresponding source code. (This alternative is
151 | allowed only for noncommercial distribution and only if you
152 | received the program in object code or executable form with such
153 | an offer, in accord with Subsection b above.)
154 |
155 | The source code for a work means the preferred form of the work for
156 | making modifications to it. For an executable work, complete source
157 | code means all the source code for all modules it contains, plus any
158 | associated interface definition files, plus the scripts used to
159 | control compilation and installation of the executable. However, as a
160 | special exception, the source code distributed need not include
161 | anything that is normally distributed (in either source or binary
162 | form) with the major components (compiler, kernel, and so on) of the
163 | operating system on which the executable runs, unless that component
164 | itself accompanies the executable.
165 |
166 | If distribution of executable or object code is made by offering
167 | access to copy from a designated place, then offering equivalent
168 | access to copy the source code from the same place counts as
169 | distribution of the source code, even though third parties are not
170 | compelled to copy the source along with the object code.
171 |
172 | 4. You may not copy, modify, sublicense, or distribute the Program
173 | except as expressly provided under this License. Any attempt
174 | otherwise to copy, modify, sublicense or distribute the Program is
175 | void, and will automatically terminate your rights under this License.
176 | However, parties who have received copies, or rights, from you under
177 | this License will not have their licenses terminated so long as such
178 | parties remain in full compliance.
179 |
180 | 5. You are not required to accept this License, since you have not
181 | signed it. However, nothing else grants you permission to modify or
182 | distribute the Program or its derivative works. These actions are
183 | prohibited by law if you do not accept this License. Therefore, by
184 | modifying or distributing the Program (or any work based on the
185 | Program), you indicate your acceptance of this License to do so, and
186 | all its terms and conditions for copying, distributing or modifying
187 | the Program or works based on it.
188 |
189 | 6. Each time you redistribute the Program (or any work based on the
190 | Program), the recipient automatically receives a license from the
191 | original licensor to copy, distribute or modify the Program subject to
192 | these terms and conditions. You may not impose any further
193 | restrictions on the recipients' exercise of the rights granted herein.
194 | You are not responsible for enforcing compliance by third parties to
195 | this License.
196 |
197 | 7. If, as a consequence of a court judgment or allegation of patent
198 | infringement or for any other reason (not limited to patent issues),
199 | conditions are imposed on you (whether by court order, agreement or
200 | otherwise) that contradict the conditions of this License, they do not
201 | excuse you from the conditions of this License. If you cannot
202 | distribute so as to satisfy simultaneously your obligations under this
203 | License and any other pertinent obligations, then as a consequence you
204 | may not distribute the Program at all. For example, if a patent
205 | license would not permit royalty-free redistribution of the Program by
206 | all those who receive copies directly or indirectly through you, then
207 | the only way you could satisfy both it and this License would be to
208 | refrain entirely from distribution of the Program.
209 |
210 | If any portion of this section is held invalid or unenforceable under
211 | any particular circumstance, the balance of the section is intended to
212 | apply and the section as a whole is intended to apply in other
213 | circumstances.
214 |
215 | It is not the purpose of this section to induce you to infringe any
216 | patents or other property right claims or to contest validity of any
217 | such claims; this section has the sole purpose of protecting the
218 | integrity of the free software distribution system, which is
219 | implemented by public license practices. Many people have made
220 | generous contributions to the wide range of software distributed
221 | through that system in reliance on consistent application of that
222 | system; it is up to the author/donor to decide if he or she is willing
223 | to distribute software through any other system and a licensee cannot
224 | impose that choice.
225 |
226 | This section is intended to make thoroughly clear what is believed to
227 | be a consequence of the rest of this License.
228 |
229 | 8. If the distribution and/or use of the Program is restricted in
230 | certain countries either by patents or by copyrighted interfaces, the
231 | original copyright holder who places the Program under this License
232 | may add an explicit geographical distribution limitation excluding
233 | those countries, so that distribution is permitted only in or among
234 | countries not thus excluded. In such case, this License incorporates
235 | the limitation as if written in the body of this License.
236 |
237 | 9. The Free Software Foundation may publish revised and/or new versions
238 | of the General Public License from time to time. Such new versions will
239 | be similar in spirit to the present version, but may differ in detail to
240 | address new problems or concerns.
241 |
242 | Each version is given a distinguishing version number. If the Program
243 | specifies a version number of this License which applies to it and "any
244 | later version", you have the option of following the terms and conditions
245 | either of that version or of any later version published by the Free
246 | Software Foundation. If the Program does not specify a version number of
247 | this License, you may choose any version ever published by the Free Software
248 | Foundation.
249 |
250 | 10. If you wish to incorporate parts of the Program into other free
251 | programs whose distribution conditions are different, write to the author
252 | to ask for permission. For software which is copyrighted by the Free
253 | Software Foundation, write to the Free Software Foundation; we sometimes
254 | make exceptions for this. Our decision will be guided by the two goals
255 | of preserving the free status of all derivatives of our free software and
256 | of promoting the sharing and reuse of software generally.
257 |
258 | NO WARRANTY
259 |
260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268 | REPAIR OR CORRECTION.
269 |
270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278 | POSSIBILITY OF SUCH DAMAGES.
279 |
280 | END OF TERMS AND CONDITIONS
281 |
282 | How to Apply These Terms to Your New Programs
283 |
284 | If you develop a new program, and you want it to be of the greatest
285 | possible use to the public, the best way to achieve this is to make it
286 | free software which everyone can redistribute and change under these terms.
287 |
288 | To do so, attach the following notices to the program. It is safest
289 | to attach them to the start of each source file to most effectively
290 | convey the exclusion of warranty; and each file should have at least
291 | the "copyright" line and a pointer to where the full notice is found.
292 |
293 | {description}
294 | Copyright (C) {year} {fullname}
295 |
296 | This program is free software; you can redistribute it and/or modify
297 | it under the terms of the GNU General Public License as published by
298 | the Free Software Foundation; either version 2 of the License, or
299 | (at your option) any later version.
300 |
301 | This program is distributed in the hope that it will be useful,
302 | but WITHOUT ANY WARRANTY; without even the implied warranty of
303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304 | GNU General Public License for more details.
305 |
306 | You should have received a copy of the GNU General Public License along
307 | with this program; if not, write to the Free Software Foundation, Inc.,
308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
309 |
310 | Also add information on how to contact you by electronic and paper mail.
311 |
312 | If the program is interactive, make it output a short notice like this
313 | when it starts in an interactive mode:
314 |
315 | Gnomovision version 69, Copyright (C) year name of author
316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
317 | This is free software, and you are welcome to redistribute it
318 | under certain conditions; type `show c' for details.
319 |
320 | The hypothetical commands `show w' and `show c' should show the appropriate
321 | parts of the General Public License. Of course, the commands you use may
322 | be called something other than `show w' and `show c'; they could even be
323 | mouse-clicks or menu items--whatever suits your program.
324 |
325 | You should also get your employer (if you work as a programmer) or your
326 | school, if any, to sign a "copyright disclaimer" for the program, if
327 | necessary. Here is a sample; alter the names:
328 |
329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program
330 | `Gnomovision' (which makes passes at compilers) written by James Hacker.
331 |
332 | {signature of Ty Coon}, 1 April 1989
333 | Ty Coon, President of Vice
334 |
335 | This General Public License does not permit incorporating your program into
336 | proprietary programs. If your program is a subroutine library, you may
337 | consider it more useful to permit linking proprietary applications with the
338 | library. If this is what you want to do, use the GNU Lesser General
339 | Public License instead of this License.
340 |
341 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | SRCFILES := *.go libip4tc/*.go libip6tc/*.go
2 |
3 | all: build examples
4 |
5 | build:
6 | go build
7 | cd libip4tc && go build
8 | cd libip6tc && go build
9 |
10 | test:
11 | go test
12 |
13 | examples: examples/dump-table-raw/dump-table-raw examples/dump-table-rules/dump-table-rules examples/lock/lock
14 |
15 | examples/dump-table-raw/dump-table-raw: examples/dump-table-raw/dump-table-raw.go $(SRCFILES)
16 | cd examples/dump-table-raw && go build
17 |
18 | examples/dump-table-rules/dump-table-rules: examples/dump-table-rules/dump-table-rules.go $(SRCFILES)
19 | cd examples/dump-table-rules && go build
20 |
21 | examples/lock/lock: examples/lock/lock.go $(SRCFILES)
22 | cd examples/lock && go build
23 |
24 | clean:
25 | rm -f examples/dump-table-raw/dump-table-raw examples/dump-table-rules/dump-table-rules examples/lock/lock
26 |
27 | .PHONY: all build test examples clean
28 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # libiptc Go bindings
2 |
3 | [libiptc](http://www.tldp.org/HOWTO/Querying-libiptc-HOWTO/whatis.html) bindings for Go language.
4 | Object-oriented design, support for IPv6 (libip6tc) and same wait locking mechanism as iptables/ip6tables official binaries.
5 |
6 | This project currently contains Go bindings to libip4tc/libip6tc dynamic link libraries, most headers/commenst are from original [iptables](http://www.netfilter.org/) C headers.
7 |
8 | Please note that there is no public/stable C/C++ API for libiptc, quoting from official [Netfilter FAQs](http://www.netfilter.org/documentation/FAQ/netfilter-faq-4.html#ss4.5):
9 |
10 | > 4.5 Is there an C/C++ API for adding/removing rules?
11 | >
12 | > The answer unfortunately is: No.
13 | >
14 | > Now you might think 'but what about libiptc?'. As has been pointed out numerous times on the mailinglist(s), libiptc was _NEVER_ meant to be used as a public interface. We don't guarantee a stable interface, and it is planned to remove it in the next incarnation of linux packet filtering. libiptc is way too low-layer to be used reasonably anyway.
15 | >
16 | > We are well aware that there is a fundamental lack for such an API, and we are working on improving that situation. Until then, it is recommended to either use system() or open a pipe into stdin of iptables-restore. The latter will give you a way better performance.
17 | >
18 |
19 | # How to use
20 |
21 | Install the dependency with `go get` or your dependency system of choice.
22 | ```
23 | go get github.com/gdm85/go-libiptc
24 | ```
25 |
26 | You can use xtables locking features by importing `github.com/gdm85/go-libiptc` and IPv4/IPv6 features by importing either `github.com/gdm85/go-libiptc/ipv4` or `github.com/gdm85/go-libiptc/ipv6`.
27 |
28 | Once the package is imported and being used, the OS thread is locked to a specific background goroutine and all calls are performed serially through such goroutine.
29 |
30 | # Building
31 |
32 | In order to build this package it is necessary for it to reside within a proper GOPATH and that iptables headers are globally available on the system; on Debian/Ubuntu systems these are provided by `iptables-dev` package, otherwise you can refer to the official upstream iptables git repository: `git://git.netfilter.org/iptables.git`.
33 |
34 | To build everything (except tests):
35 | ```
36 | make
37 | ```
38 |
39 | To build the package it will suffice a:
40 | ```
41 | make build
42 | ```
43 |
44 | To run tests (with proper root privileges):
45 | ```
46 | make test
47 | ```
48 |
49 | To build the examples:
50 | ```
51 | make examples
52 | ```
53 |
54 | # TODO
55 |
56 | * ~~separate libip6tc package that uses '#cgo LDFLAGS: -lip6tc'~~
57 | * unit tests coverage
58 | * finally, some analysis of memory leakage
59 |
60 | # Useful resources
61 |
62 | * http://www.bani.com.br/2012/05/programmatically-managing-iptables-rules-in-c-iptc/
63 |
64 | # License
65 |
66 | Licensed under [GNU/GPL v2](LICENSE).
67 |
--------------------------------------------------------------------------------
/examples/dump-table-raw/dump-table-raw.go:
--------------------------------------------------------------------------------
1 | /*
2 | * go-libiptc v0.3.1 - libiptc bindings for Go language
3 | * Copyright (C) 2015 gdm85 - https://github.com/gdm85/go-libiptc/
4 |
5 | This program is free software; you can redistribute it and/or
6 | modify it under the terms of the GNU General Public License
7 | as published by the Free Software Foundation; either version 2
8 | of the License, or (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU General Public License for more details.
14 |
15 | You should have received a copy of the GNU General Public License
16 | along with this program; if not, write to the Free Software
17 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 | */
19 |
20 | package main
21 |
22 | import (
23 | "fmt"
24 | "os"
25 |
26 | common "github.com/gdm85/go-libiptc"
27 | "github.com/gdm85/go-libiptc/libip4tc"
28 | "github.com/gdm85/go-libiptc/libip6tc"
29 | )
30 |
31 | func showSyntax() {
32 | fmt.Fprintf(os.Stderr, "Usage: dump-table-raw [-4|-6] \n")
33 | os.Exit(1)
34 | }
35 |
36 | func main() {
37 | if len(os.Args) != 3 {
38 | showSyntax()
39 | }
40 |
41 | var useIpv6 bool
42 | switch os.Args[1] {
43 | case `-4`:
44 | case `-6`:
45 | useIpv6 = true
46 | default:
47 | showSyntax()
48 | }
49 |
50 | acquired, err := common.XtablesLock(false, 0)
51 | if err != nil {
52 | panic(err)
53 | }
54 | if !acquired {
55 | fmt.Fprintf(os.Stderr, "dump-table-raw: could not acquire xtables lock!\n")
56 | os.Exit(1)
57 | }
58 | defer func() {
59 | _, err := common.XtablesUnlock()
60 | if err != nil {
61 | panic(err)
62 | }
63 | }()
64 |
65 | tableName := os.Args[2]
66 |
67 | if !useIpv6 {
68 | table, err := libip4tc.TableInit(tableName)
69 | if err != nil {
70 | fmt.Fprintf(os.Stderr, "dump-table-raw: %s\n", err)
71 | os.Exit(3)
72 | }
73 | defer table.Free()
74 |
75 | // use the native/undocumented DumpEntries() anyways
76 | table.DumpEntries()
77 | } else {
78 | table, err := libip6tc.TableInit(tableName)
79 | if err != nil {
80 | fmt.Fprintf(os.Stderr, "dump-table-raw: %s\n", err)
81 | os.Exit(3)
82 | }
83 | defer table.Free()
84 |
85 | // use the native/undocumented DumpEntries() anyways
86 | table.DumpEntries()
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/examples/dump-table-rules/dump-table-rules.go:
--------------------------------------------------------------------------------
1 | /*
2 | * go-libiptc v0.3.1 - libiptc bindings for Go language
3 | * Copyright (C) 2015 gdm85 - https://github.com/gdm85/go-libiptc/
4 |
5 | This program is free software; you can redistribute it and/or
6 | modify it under the terms of the GNU General Public License
7 | as published by the Free Software Foundation; either version 2
8 | of the License, or (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU General Public License for more details.
14 |
15 | You should have received a copy of the GNU General Public License
16 | along with this program; if not, write to the Free Software
17 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 | */
19 |
20 | package main
21 |
22 | import (
23 | "fmt"
24 | "os"
25 |
26 | common "github.com/gdm85/go-libiptc"
27 | "github.com/gdm85/go-libiptc/libip4tc"
28 | "github.com/gdm85/go-libiptc/libip6tc"
29 | )
30 |
31 | func showSyntax() {
32 | fmt.Fprintf(os.Stderr, "Usage: dump-table-rules [-4|-6] \n")
33 | os.Exit(1)
34 | }
35 |
36 | func main() {
37 | if len(os.Args) != 3 {
38 | showSyntax()
39 | }
40 |
41 | var useIpv6 bool
42 | switch os.Args[1] {
43 | case `-4`:
44 | case `-6`:
45 | useIpv6 = true
46 | default:
47 | showSyntax()
48 | }
49 |
50 | acquired, err := common.XtablesLock(false, 0)
51 | if err != nil {
52 | panic(err)
53 | }
54 | if !acquired {
55 | fmt.Fprintf(os.Stderr, "dump-table-rules: could not acquire xtables lock!\n")
56 | os.Exit(1)
57 | }
58 | defer func() {
59 | _, err := common.XtablesUnlock()
60 | if err != nil {
61 | panic(err)
62 | }
63 | }()
64 |
65 | tableName := os.Args[2]
66 |
67 | if !useIpv6 {
68 | table, err := libip4tc.TableInit(tableName)
69 | if err != nil {
70 | fmt.Fprintf(os.Stderr, "dump-table-rules: %s\n", err)
71 | os.Exit(3)
72 | }
73 | defer table.Free()
74 |
75 | // traverse trough chains
76 | chain, err := table.FirstChain()
77 | if err != nil {
78 | fmt.Fprintf(os.Stderr, "dump-table-rules: %s\n", err)
79 | os.Exit(3)
80 | }
81 | for chain != "" {
82 | // use Go-native rules conversion
83 | e, err := table.FirstRule(chain)
84 | if err != nil {
85 | fmt.Fprintf(os.Stderr, "dump-table-rules: %s\n", err)
86 | os.Exit(3)
87 | }
88 | for !e.IsEmpty() {
89 | fmt.Println(chain+":", table.IptEntry2Rule(&e).String())
90 | e, err = table.NextRule(e)
91 | if err != nil {
92 | fmt.Fprintf(os.Stderr, "dump-table-rules: %s\n", err)
93 | os.Exit(3)
94 | }
95 | }
96 |
97 | chain, err = table.NextChain()
98 | if err != nil {
99 | fmt.Fprintf(os.Stderr, "dump-table-rules: %s\n", err)
100 | os.Exit(3)
101 | }
102 | }
103 | } else {
104 | table, err := libip6tc.TableInit(tableName)
105 | if err != nil {
106 | fmt.Fprintf(os.Stderr, "dump-table-rules: %s\n", err)
107 | os.Exit(3)
108 | }
109 | defer table.Free()
110 |
111 | // traverse trough chains
112 | chain, err := table.FirstChain()
113 | if err != nil {
114 | fmt.Fprintf(os.Stderr, "dump-table-rules: %s\n", err)
115 | os.Exit(3)
116 | }
117 | for chain != "" {
118 | // use Go-native rules conversion
119 | e, err := table.FirstRule(chain)
120 | if err != nil {
121 | fmt.Fprintf(os.Stderr, "dump-table-rules: %s\n", err)
122 | os.Exit(3)
123 | }
124 | for !e.IsEmpty() {
125 | fmt.Println(chain+":", table.IptEntry2Rule(&e).String())
126 | e, err = table.NextRule(e)
127 | if err != nil {
128 | fmt.Fprintf(os.Stderr, "dump-table-rules: %s\n", err)
129 | os.Exit(3)
130 | }
131 | }
132 |
133 | chain, err = table.NextChain()
134 | if err != nil {
135 | fmt.Fprintf(os.Stderr, "dump-table-rules: %s\n", err)
136 | os.Exit(3)
137 | }
138 | }
139 | }
140 | }
141 |
--------------------------------------------------------------------------------
/examples/lock/lock.go:
--------------------------------------------------------------------------------
1 | /*
2 | * go-libiptc v0.3.1 - libiptc bindings for Go language
3 | * Copyright (C) 2015 gdm85 - https://github.com/gdm85/go-libiptc/
4 |
5 | This program is free software; you can redistribute it and/or
6 | modify it under the terms of the GNU General Public License
7 | as published by the Free Software Foundation; either version 2
8 | of the License, or (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU General Public License for more details.
14 |
15 | You should have received a copy of the GNU General Public License
16 | along with this program; if not, write to the Free Software
17 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 | */
19 |
20 | package main
21 |
22 | import (
23 | "fmt"
24 | "os"
25 | "time"
26 |
27 | "github.com/gdm85/go-libiptc"
28 | )
29 |
30 | func main() {
31 | fmt.Println("acquiring xtables lock immediately...")
32 | acquired, err := libiptc.XtablesLock(false, 0)
33 | if err != nil {
34 | panic(err)
35 | }
36 | if !acquired {
37 | fmt.Fprintf(os.Stderr, "Could not acquire xtables lock!\n")
38 | os.Exit(1)
39 | }
40 | defer func() {
41 | _, err := libiptc.XtablesUnlock()
42 | if err != nil {
43 | panic(err)
44 | }
45 | }()
46 |
47 | fmt.Printf("I have acquired a lock for 5 seconds, try any 'iptables --wait' command\n")
48 | time.Sleep(5 * time.Second)
49 | }
50 |
--------------------------------------------------------------------------------
/libip4tc/libip4tc.go:
--------------------------------------------------------------------------------
1 | /*
2 | * go-libiptc v0.3.1 - libiptc bindings for Go language
3 | * Copyright (C) 2015~2016 gdm85 - https://github.com/gdm85/go-libiptc/
4 |
5 | This program is free software; you can redistribute it and/or
6 | modify it under the terms of the GNU General Public License
7 | as published by the Free Software Foundation; either version 2
8 | of the License, or (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU General Public License for more details.
14 |
15 | You should have received a copy of the GNU General Public License
16 | along with this program; if not, write to the Free Software
17 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 | */
19 |
20 | package libip4tc
21 |
22 | // #cgo LDFLAGS: -lip4tc
23 | // #include
24 | // #include
25 | import "C"
26 |
27 | import (
28 | "net"
29 | "runtime"
30 | "unsafe"
31 |
32 | common "github.com/gdm85/go-libiptc"
33 | )
34 |
35 | func cuint2ip(cAaddr, cMask C.in_addr_t) *net.IPNet {
36 | addr := uint32(cAaddr)
37 | ip := new(net.IPNet)
38 | ip.IP = net.IPv4(byte(addr&0xff),
39 | byte((addr>>8)&0xff),
40 | byte((addr>>16)&0xff),
41 | byte((addr>>24)&0xff))
42 | mask := uint32(cMask)
43 | ip.Mask = net.IPv4Mask(byte(mask&0xff),
44 | byte((mask>>8)&0xff),
45 | byte((mask>>16)&0xff),
46 | byte((mask>>24)&0xff),
47 | )
48 | return ip
49 | }
50 |
51 | type IptEntry struct {
52 | handle *C.struct_ipt_entry
53 | }
54 |
55 | func (h IptEntry) IsEmpty() bool {
56 | return h.handle == nil
57 | }
58 |
59 | type XtcHandle struct {
60 | handle *C.struct_xtc_handle
61 | }
62 |
63 | func (h XtcHandle) IptEntry2Rule(e *IptEntry) *common.Rule {
64 | entry := e.handle
65 | rule := new(common.Rule)
66 | rule.Pcnt = uint64(entry.counters.pcnt)
67 | rule.Bcnt = uint64(entry.counters.bcnt)
68 | rule.InDev = C.GoString(&entry.ip.iniface[0])
69 | rule.OutDev = C.GoString(&entry.ip.outiface[0])
70 | if entry.ip.invflags&C.IPT_INV_VIA_IN != 0 {
71 | rule.Not.InDev = true
72 | }
73 | if entry.ip.invflags&C.IPT_INV_VIA_OUT != 0 {
74 | rule.Not.OutDev = true
75 | }
76 |
77 | rule.Src = cuint2ip(entry.ip.src.s_addr, entry.ip.smsk.s_addr)
78 | if entry.ip.invflags&C.IPT_INV_SRCIP != 0 {
79 | rule.Not.Src = true
80 | }
81 |
82 | rule.Dest = cuint2ip(entry.ip.dst.s_addr, entry.ip.dmsk.s_addr)
83 | if entry.ip.invflags&C.IPT_INV_DSTIP != 0 {
84 | rule.Not.Dest = true
85 | }
86 |
87 | target := C.iptc_get_target(entry, h.handle)
88 | if target != nil {
89 | rule.Target = C.GoString(target)
90 | }
91 | return rule
92 | }
93 |
94 | func getNativeError() string {
95 | return C.GoString(C.iptc_strerror(C.int(common.GetErrno())))
96 | }
97 |
98 | func (h *XtcHandle) Free() error {
99 | return common.RelayCall(func() bool {
100 | if h.handle != nil {
101 | C.iptc_free(h.handle)
102 | h.handle = nil
103 | }
104 | return true
105 | }, "iptc_free", getNativeError)
106 | }
107 |
108 | func TableInit(tableName string) (result XtcHandle, osErr error) {
109 | osErr = common.RelayCall(func() bool {
110 | cStr := C.CString(tableName)
111 | defer C.free(unsafe.Pointer(cStr))
112 |
113 | h := C.iptc_init(cStr)
114 | result = XtcHandle{h}
115 |
116 | return h != nil
117 | }, "iptc_init", getNativeError)
118 |
119 | // set the finalizer before returning the usable result
120 | runtime.SetFinalizer(&result, (*XtcHandle).Free)
121 |
122 | return
123 | }
124 |
125 | func (h XtcHandle) IsChain(chain string) (result bool, osErr error) {
126 | osErr = common.RelayCall(func() bool {
127 | cStr := C.CString(chain)
128 | defer C.free(unsafe.Pointer(cStr))
129 |
130 | r := C.iptc_is_chain(cStr, h.handle)
131 | if r == 1 {
132 | result = true
133 | return result
134 | } else if r == 0 {
135 | result = false
136 | return result
137 | }
138 | panic("invalid return value")
139 | }, "iptc_is_chain", getNativeError)
140 | return
141 | }
142 |
143 | func (h XtcHandle) IsBuiltin(chain string) (result bool, osErr error) {
144 | osErr = common.RelayCall(func() bool {
145 | cStr := C.CString(chain)
146 | defer C.free(unsafe.Pointer(cStr))
147 |
148 | r := C.iptc_builtin(cStr, h.handle)
149 | if r == 1 {
150 | result = true
151 | return result
152 | } else if r == 0 {
153 | result = false
154 | return result
155 | }
156 | panic("invalid return value")
157 | }, "iptc_builtin", getNativeError)
158 | return
159 | }
160 |
161 | /* Iterator functions to run through the chains. Returns NULL at end. */
162 | func (h XtcHandle) FirstChain() (result string, osErr error) {
163 | osErr = common.RelayCall(func() bool {
164 | cStr := C.iptc_first_chain(h.handle)
165 | if cStr == nil {
166 | result = ""
167 | return common.GetErrno() == 0
168 | }
169 |
170 | result = C.GoString(cStr)
171 | return true
172 | }, "iptc_first_chain", getNativeError)
173 | return
174 | }
175 |
176 | func (h XtcHandle) NextChain() (result string, osErr error) {
177 | osErr = common.RelayCall(func() bool {
178 | cStr := C.iptc_next_chain(h.handle)
179 | if cStr == nil {
180 | result = ""
181 | return common.GetErrno() == 0
182 | }
183 |
184 | result = C.GoString(cStr)
185 | return true
186 | }, "iptc_next_chain", getNativeError)
187 | return
188 | }
189 |
190 | /* Get first rule in the given chain: NULL for empty chain. */
191 | func (h XtcHandle) FirstRule(chain string) (result IptEntry, osErr error) {
192 | osErr = common.RelayCall(func() bool {
193 | cStr := C.CString(chain)
194 | defer C.free(unsafe.Pointer(cStr))
195 |
196 | result.handle = C.iptc_first_rule(cStr, h.handle)
197 |
198 | if result.handle == nil && common.GetErrno() != 0 {
199 | // there's some error
200 | return false
201 | }
202 |
203 | return true
204 | }, "iptc_first_rule", getNativeError)
205 | return
206 | }
207 |
208 | /* Returns NULL when rules run out. */
209 | func (h XtcHandle) NextRule(previous IptEntry) (result IptEntry, osErr error) {
210 | osErr = common.RelayCall(func() bool {
211 | result.handle = C.iptc_next_rule(previous.handle, h.handle)
212 |
213 | if result.handle == nil && common.GetErrno() != 0 {
214 | // there's some error
215 | return false
216 | }
217 |
218 | return true
219 | }, "iptc_next_rule", getNativeError)
220 | return
221 | }
222 |
223 | /* Returns a pointer to the target name of this entry. */
224 | func (h XtcHandle) GetTarget(entry IptEntry) (result string, osErr error) {
225 | osErr = common.RelayCall(func() bool {
226 | cStr := C.iptc_get_target(entry.handle, h.handle)
227 | if cStr == nil {
228 | result = ""
229 | return false
230 | }
231 |
232 | result = C.GoString(cStr)
233 | return true
234 | }, "iptc_get_target", getNativeError)
235 | return
236 | }
237 |
238 | /* Get the policy of a given built-in chain */
239 | func (h XtcHandle) GetPolicy(chain string) (policy string, counters common.XtCounters, osErr error) {
240 | osErr = common.RelayCall(func() bool {
241 | cStr := C.CString(chain)
242 | defer C.free(unsafe.Pointer(cStr))
243 |
244 | var c _Ctype_struct_xt_counters
245 | cStr = C.iptc_get_policy(cStr, &c, h.handle)
246 | if cStr == nil {
247 | // no chains
248 | policy = ""
249 | return false
250 | }
251 |
252 | policy = C.GoString(cStr)
253 | counters.Bcnt = uint64(c.bcnt)
254 | counters.Pcnt = uint64(c.pcnt)
255 | return true
256 | }, "iptc_get_policy", getNativeError)
257 | return
258 | }
259 |
260 | /* These functions return TRUE for OK or 0 and set errno. If errno ==
261 | 0, it means there was a version error (ie. upgrade libiptc). */
262 | /* Rule numbers start at 1 for the first rule. */
263 |
264 | /* Insert the entry `e' in chain `chain' into position `rulenum'. */
265 | func (h XtcHandle) InsertEntry(chain common.XtChainLabel, entry IptEntry, ruleNum uint) error {
266 | return common.RelayCall(func() bool {
267 | cStr := C.CString(string(chain))
268 | defer C.free(unsafe.Pointer(cStr))
269 |
270 | r := C.iptc_insert_entry(cStr, entry.handle, C.uint(ruleNum), h.handle)
271 | if r == 1 {
272 | return true
273 | } else if r == 0 {
274 | // has error
275 | return false
276 | }
277 |
278 | panic("invalid return value")
279 | }, "iptc_insert_entry", getNativeError)
280 | }
281 |
282 | /* Append entry `e' to chain `chain'. Equivalent to insert with
283 | rulenum = length of chain. */
284 | func (h XtcHandle) AppendEntry(chain common.XtChainLabel, entry IptEntry) error {
285 | return common.RelayCall(func() bool {
286 | cStr := C.CString(string(chain))
287 | defer C.free(unsafe.Pointer(cStr))
288 |
289 | r := C.iptc_append_entry(cStr, entry.handle, h.handle)
290 | if r == 1 {
291 | return true
292 | } else if r == 0 {
293 | // has error
294 | return false
295 | }
296 |
297 | panic("invalid return value")
298 | }, "iptc_append_entry", getNativeError)
299 | }
300 |
301 | /* Check whether a matching rule exists */
302 | func (h XtcHandle) CheckEntry(chain common.XtChainLabel, origfw IptEntry, matchMask []byte) (result bool, osErr error) {
303 | osErr = common.RelayCall(func() bool {
304 | cStr := C.CString(string(chain))
305 | defer C.free(unsafe.Pointer(cStr))
306 | cMask := (*C.uchar)(unsafe.Pointer(&matchMask[0]))
307 |
308 | r := C.iptc_check_entry(cStr, origfw.handle, cMask, h.handle)
309 | if r == 1 {
310 | result = true
311 | return result
312 | } else if r == 0 {
313 | result = false
314 | return result
315 | }
316 |
317 | panic("invalid return value")
318 | }, "iptc_check_entry", getNativeError)
319 | return
320 | }
321 |
322 | /* Delete the first rule in `chain' which matches `e', subject to
323 | matchmask (array of length == origfw) */
324 | func (h XtcHandle) DeleteEntry(chain common.XtChainLabel, origfw IptEntry, matchMask []byte) (result bool, osErr error) {
325 | osErr = common.RelayCall(func() bool {
326 | cStr := C.CString(string(chain))
327 | defer C.free(unsafe.Pointer(cStr))
328 | cMask := (*C.uchar)(unsafe.Pointer(&matchMask[0]))
329 |
330 | r := C.iptc_delete_entry(cStr, origfw.handle, cMask, h.handle)
331 | if r == 1 {
332 | result = true
333 | return result
334 | } else if r == 0 {
335 | result = false
336 | return result
337 | }
338 |
339 | panic("invalid return value")
340 | }, "iptc_delete_entry", getNativeError)
341 | return
342 | }
343 |
344 | /* Delete the rule in position `rulenum' in `chain'. */
345 | func (h XtcHandle) DeleteNumEntry(chain common.XtChainLabel, ruleNum uint) (result bool, osErr error) {
346 | osErr = common.RelayCall(func() bool {
347 | cStr := C.CString(string(chain))
348 | defer C.free(unsafe.Pointer(cStr))
349 |
350 | r := C.iptc_delete_num_entry(cStr, C.uint(ruleNum), h.handle)
351 | if r == 1 {
352 | result = true
353 | return result
354 | } else if r == 0 {
355 | result = false
356 | return result
357 | }
358 |
359 | panic("invalid return value")
360 | }, "iptc_delete_num_entry", getNativeError)
361 | return
362 | }
363 |
364 | /* Flushes the entries in the given chain (ie. empties chain). */
365 | func (h XtcHandle) FlushEntries(chain common.XtChainLabel) (result bool, osErr error) {
366 | osErr = common.RelayCall(func() bool {
367 | cStr := C.CString(string(chain))
368 | defer C.free(unsafe.Pointer(cStr))
369 |
370 | r := C.iptc_flush_entries(cStr, h.handle)
371 | if r == 1 {
372 | result = true
373 | return result
374 | } else if r == 0 {
375 | result = false
376 | return result
377 | }
378 |
379 | panic("invalid return value")
380 | }, "iptc_flush_entries", getNativeError)
381 | return
382 | }
383 |
384 | /* Zeroes the counters in a chain. */
385 | func (h XtcHandle) ZeroEntries(chain common.XtChainLabel) (result bool, osErr error) {
386 | osErr = common.RelayCall(func() bool {
387 | cStr := C.CString(string(chain))
388 | defer C.free(unsafe.Pointer(cStr))
389 |
390 | r := C.iptc_zero_entries(cStr, h.handle)
391 | if r == 1 {
392 | result = true
393 | return result
394 | } else if r == 0 {
395 | result = false
396 | return result
397 | }
398 |
399 | panic("invalid return value")
400 | }, "iptc_zero_entries", getNativeError)
401 | return
402 | }
403 |
404 | /* Creates a new chain. */
405 | func (h XtcHandle) CreateChain(chain common.XtChainLabel) (result bool, osErr error) {
406 | osErr = common.RelayCall(func() bool {
407 | cStr := C.CString(string(chain))
408 | defer C.free(unsafe.Pointer(cStr))
409 |
410 | r := C.iptc_create_chain(cStr, h.handle)
411 | if r == 1 {
412 | result = true
413 | return result
414 | } else if r == 0 {
415 | result = false
416 | return result
417 | }
418 |
419 | panic("invalid return value")
420 | }, "iptc_create_chain", getNativeError)
421 | return
422 | }
423 |
424 | /* Deletes a chain. */
425 | func (h XtcHandle) DeleteChain(chain common.XtChainLabel) (result bool, osErr error) {
426 | osErr = common.RelayCall(func() bool {
427 | cStr := C.CString(string(chain))
428 | defer C.free(unsafe.Pointer(cStr))
429 |
430 | r := C.iptc_delete_chain(cStr, h.handle)
431 | if r == 1 {
432 | result = true
433 | return result
434 | } else if r == 0 {
435 | result = false
436 | return result
437 | }
438 |
439 | panic("invalid return value")
440 | }, "iptc_delete_chain", getNativeError)
441 | return
442 | }
443 |
444 | /* Renames a chain. */
445 | func (h XtcHandle) RenameChain(oldName, newName common.XtChainLabel) (result bool, osErr error) {
446 | osErr = common.RelayCall(func() bool {
447 | cOldName := C.CString(string(oldName))
448 | defer C.free(unsafe.Pointer(cOldName))
449 | cNewName := C.CString(string(newName))
450 | defer C.free(unsafe.Pointer(cNewName))
451 |
452 | r := C.iptc_rename_chain(cOldName, cNewName, h.handle)
453 | if r == 1 {
454 | result = true
455 | return result
456 | } else if r == 0 {
457 | result = false
458 | return result
459 | }
460 |
461 | panic("invalid return value")
462 | }, "iptc_rename_chain", getNativeError)
463 | return
464 | }
465 |
466 | /* Sets the policy and (optionally) counters on a built-in chain. */
467 | func (h XtcHandle) SetPolicy(chain, policy common.XtChainLabel, counters *common.XtCounters) (result bool, osErr error) {
468 | osErr = common.RelayCall(func() bool {
469 | cChain := C.CString(string(chain))
470 | defer C.free(unsafe.Pointer(cChain))
471 | cPolicy := C.CString(string(policy))
472 | defer C.free(unsafe.Pointer(cPolicy))
473 |
474 | var c *_Ctype_struct_xt_counters
475 | if counters != nil {
476 | c = &_Ctype_struct_xt_counters{}
477 | c.bcnt = C.__u64(counters.Bcnt)
478 | c.pcnt = C.__u64(counters.Pcnt)
479 | }
480 |
481 | r := C.iptc_set_policy(cChain, cPolicy, c, h.handle)
482 | if r == 1 {
483 | result = true
484 | return result
485 | } else if r == 0 {
486 | result = false
487 | return result
488 | }
489 |
490 | panic("invalid return value")
491 | }, "iptc_set_policy", getNativeError)
492 | return
493 | }
494 |
495 | /* Get the number of references to this chain */
496 | func (h XtcHandle) GetReferences(chain common.XtChainLabel) (result uint, osErr error) {
497 | osErr = common.RelayCall(func() bool {
498 | cStr := C.CString(string(chain))
499 | defer C.free(unsafe.Pointer(cStr))
500 |
501 | var i C.uint
502 |
503 | r := C.iptc_get_references(&i, cStr, h.handle)
504 | if r == 1 {
505 | // has a valid result
506 | result = uint(i)
507 | return true
508 | } else if r == 0 {
509 | // has an error
510 | return false
511 | }
512 |
513 | panic("invalid return value")
514 | }, "iptc_get_references", getNativeError)
515 | return
516 | }
517 |
518 | /* read packet and byte counters for a specific rule */
519 | func (h XtcHandle) ReadCounter(chain common.XtChainLabel, ruleNum uint) (result common.XtCounters, osErr error) {
520 | osErr = common.RelayCall(func() bool {
521 | cStr := C.CString(string(chain))
522 | defer C.free(unsafe.Pointer(cStr))
523 |
524 | counters_handle := C.iptc_read_counter(cStr, C.uint(ruleNum), h.handle)
525 | if counters_handle == nil {
526 | // has an error
527 | return false
528 | }
529 |
530 | result.Bcnt = uint64(counters_handle.bcnt)
531 | result.Pcnt = uint64(counters_handle.pcnt)
532 | return true
533 | }, "iptc_read_counter", getNativeError)
534 | return
535 | }
536 |
537 | /* zero packet and byte counters for a specific rule */
538 | func (h XtcHandle) ZeroCounter(chain common.XtChainLabel, ruleNum uint) (result bool, osErr error) {
539 | osErr = common.RelayCall(func() bool {
540 | cStr := C.CString(string(chain))
541 | defer C.free(unsafe.Pointer(cStr))
542 |
543 | r := C.iptc_zero_counter(cStr, C.uint(ruleNum), h.handle)
544 | if r == 1 {
545 | result = true
546 | return result
547 | } else if r == 0 {
548 | result = false
549 | return result
550 | }
551 |
552 | panic("invalid return value")
553 | }, "iptc_read_counter", getNativeError)
554 | return
555 | }
556 |
557 | // SetCounter sets packet and byte counters for a specific rule.
558 | func (h XtcHandle) SetCounter(chain common.XtChainLabel, ruleNum uint, counters common.XtCounters) (result bool, osErr error) {
559 | osErr = common.RelayCall(func() bool {
560 | cStr := C.CString(string(chain))
561 | defer C.free(unsafe.Pointer(cStr))
562 |
563 | var c _Ctype_struct_xt_counters
564 | c.bcnt = C.__u64(counters.Bcnt)
565 | c.pcnt = C.__u64(counters.Pcnt)
566 |
567 | r := C.iptc_set_counter(cStr, C.uint(ruleNum), &c, h.handle)
568 | if r == 1 {
569 | result = true
570 | return result
571 | } else if r == 0 {
572 | result = false
573 | return result
574 | }
575 |
576 | panic("invalid return value")
577 | }, "iptc_set_counter", getNativeError)
578 | return
579 | }
580 |
581 | // Commit makes the actual changes.
582 | func (h XtcHandle) Commit() error {
583 | return common.RelayCall(func() bool {
584 | r := C.iptc_commit(h.handle)
585 | if r == 1 {
586 | return true
587 | } else if r == 0 {
588 | return false
589 | }
590 |
591 | panic("unexpected return value")
592 | }, "iptc_commit", getNativeError)
593 | }
594 |
595 | // DumpEntries will use an internal undocumented function to dump all table entries to stdout.
596 | func (h XtcHandle) DumpEntries() error {
597 | return common.RelayCall(func() bool {
598 | C.dump_entries(h.handle)
599 | return false
600 | }, "dump_entries", getNativeError)
601 | }
602 |
--------------------------------------------------------------------------------
/libip4tc/libip4tc_test.go:
--------------------------------------------------------------------------------
1 | /*
2 | * go-libiptc v0.3.1 - libiptc bindings for Go language
3 | * Copyright (C) 2015~2016 gdm85 - https://github.com/gdm85/go-libiptc/
4 |
5 | This program is free software; you can redistribute it and/or
6 | modify it under the terms of the GNU General Public License
7 | as published by the Free Software Foundation; either version 2
8 | of the License, or (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU General Public License for more details.
14 |
15 | You should have received a copy of the GNU General Public License
16 | along with this program; if not, write to the Free Software
17 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 | */
19 |
20 | package libip4tc
21 |
22 | import (
23 | "testing"
24 |
25 | common "github.com/gdm85/go-libiptc"
26 | )
27 |
28 | func TestXtablesLock(t *testing.T) {
29 | acquired, err := common.XtablesLock(false, 0)
30 | if err != nil {
31 | t.Error(err)
32 | t.FailNow()
33 | }
34 | if !acquired {
35 | t.FailNow()
36 | }
37 |
38 | released, err := common.XtablesUnlock()
39 | if err != nil {
40 | t.Error(err)
41 | t.FailNow()
42 | }
43 |
44 | released, err = common.XtablesUnlock()
45 | if err == nil || released {
46 | t.Error("unlocking twice succeeded!")
47 | t.FailNow()
48 | }
49 | }
50 |
51 | func TestInit(t *testing.T) {
52 | acquired, err := common.XtablesLock(false, 0)
53 | if err != nil {
54 | t.Fatal(err)
55 | }
56 | if !acquired {
57 | t.FailNow()
58 | }
59 | defer func() {
60 | _, err := common.XtablesUnlock()
61 | if err != nil {
62 | panic(err)
63 | }
64 | }()
65 |
66 | handle, err := TableInit("filter")
67 | if err != nil {
68 | t.Fatal(err)
69 | }
70 |
71 | err = handle.Free()
72 | if err != nil {
73 | t.Fatal(err)
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/libip6tc/libip6tc.go:
--------------------------------------------------------------------------------
1 | /*
2 | * go-libiptc v0.3.1 - libiptc bindings for Go language
3 | * Copyright (C) 2015~2016 gdm85 - https://github.com/gdm85/go-libiptc/
4 |
5 | This program is free software; you can redistribute it and/or
6 | modify it under the terms of the GNU General Public License
7 | as published by the Free Software Foundation; either version 2
8 | of the License, or (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU General Public License for more details.
14 |
15 | You should have received a copy of the GNU General Public License
16 | along with this program; if not, write to the Free Software
17 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 | */
19 |
20 | package libip6tc
21 |
22 | import (
23 | // #cgo LDFLAGS: -lip6tc
24 | // #include
25 | // #include
26 | "C"
27 | "net"
28 | "runtime"
29 | "unsafe"
30 |
31 | common "github.com/gdm85/go-libiptc"
32 | )
33 |
34 | func cin6addr2ip(cAaddr, cMask C.struct_in6_addr) *net.IPNet {
35 | ip := new(net.IPNet)
36 |
37 | ip.IP = make(net.IP, 16)
38 | copy(ip.IP, cAaddr.__in6_u[:])
39 | ip.Mask = make(net.IPMask, 16)
40 | copy(ip.Mask, cMask.__in6_u[:])
41 |
42 | return ip
43 | }
44 |
45 | type IptEntry struct {
46 | handle *C.struct_ip6t_entry
47 | }
48 |
49 | func (h IptEntry) IsEmpty() bool {
50 | return h.handle == nil
51 | }
52 |
53 | type XtcHandle struct {
54 | handle *C.struct_xtc_handle
55 | }
56 |
57 | func (h XtcHandle) IptEntry2Rule(e *IptEntry) *common.Rule {
58 | entry := e.handle
59 | rule := new(common.Rule)
60 | rule.Pcnt = uint64(entry.counters.pcnt)
61 | rule.Bcnt = uint64(entry.counters.bcnt)
62 | rule.InDev = C.GoString(&entry.ipv6.iniface[0])
63 | rule.OutDev = C.GoString(&entry.ipv6.outiface[0])
64 | if entry.ipv6.invflags&C.IP6T_INV_VIA_IN != 0 {
65 | rule.Not.InDev = true
66 | }
67 | if entry.ipv6.invflags&C.IP6T_INV_VIA_OUT != 0 {
68 | rule.Not.OutDev = true
69 | }
70 |
71 | rule.Src = cin6addr2ip(entry.ipv6.src, entry.ipv6.smsk)
72 | if entry.ipv6.invflags&C.IP6T_INV_SRCIP != 0 {
73 | rule.Not.Src = true
74 | }
75 |
76 | rule.Dest = cin6addr2ip(entry.ipv6.dst, entry.ipv6.dmsk)
77 | if entry.ipv6.invflags&C.IP6T_INV_DSTIP != 0 {
78 | rule.Not.Dest = true
79 | }
80 |
81 | target := C.ip6tc_get_target(entry, h.handle)
82 | if target != nil {
83 | rule.Target = C.GoString(target)
84 | }
85 | return rule
86 | }
87 |
88 | func getNativeError() string {
89 | return C.GoString(C.ip6tc_strerror(C.int(common.GetErrno())))
90 | }
91 |
92 | func (h *XtcHandle) Free() error {
93 | return common.RelayCall(func() bool {
94 | if h.handle != nil {
95 | C.ip6tc_free(h.handle)
96 | h.handle = nil
97 | }
98 | return true
99 | }, "ip6tc_free", getNativeError)
100 | }
101 |
102 | func TableInit(tableName string) (result XtcHandle, osErr error) {
103 | osErr = common.RelayCall(func() bool {
104 | cStr := C.CString(tableName)
105 | defer C.free(unsafe.Pointer(cStr))
106 |
107 | h := C.ip6tc_init(cStr)
108 | result = XtcHandle{h}
109 |
110 | return h != nil
111 | }, "ip6tc_init", getNativeError)
112 |
113 | // set the finalizer before returning the usable result
114 | runtime.SetFinalizer(&result, (*XtcHandle).Free)
115 |
116 | return
117 | }
118 |
119 | func (h XtcHandle) IsChain(chain string) (result bool, osErr error) {
120 | osErr = common.RelayCall(func() bool {
121 | cStr := C.CString(chain)
122 | defer C.free(unsafe.Pointer(cStr))
123 |
124 | r := C.ip6tc_is_chain(cStr, h.handle)
125 | if r == 1 {
126 | result = true
127 | return result
128 | } else if r == 0 {
129 | result = false
130 | return result
131 | }
132 | panic("invalid return value")
133 | }, "ip6tc_is_chain", getNativeError)
134 | return
135 | }
136 |
137 | func (h XtcHandle) IsBuiltin(chain string) (result bool, osErr error) {
138 | osErr = common.RelayCall(func() bool {
139 | cStr := C.CString(chain)
140 | defer C.free(unsafe.Pointer(cStr))
141 |
142 | r := C.ip6tc_builtin(cStr, h.handle)
143 | if r == 1 {
144 | result = true
145 | return result
146 | } else if r == 0 {
147 | result = false
148 | return result
149 | }
150 | panic("invalid return value")
151 | }, "ip6tc_builtin", getNativeError)
152 | return
153 | }
154 |
155 | /* Iterator functions to run through the chains. Returns NULL at end. */
156 | func (h XtcHandle) FirstChain() (result string, osErr error) {
157 | osErr = common.RelayCall(func() bool {
158 | cStr := C.ip6tc_first_chain(h.handle)
159 | if cStr == nil {
160 | result = ""
161 | return common.GetErrno() == 0
162 | }
163 |
164 | result = C.GoString(cStr)
165 | return true
166 | }, "ip6tc_first_chain", getNativeError)
167 | return
168 | }
169 |
170 | func (h XtcHandle) NextChain() (result string, osErr error) {
171 | osErr = common.RelayCall(func() bool {
172 | cStr := C.ip6tc_next_chain(h.handle)
173 | if cStr == nil {
174 | result = ""
175 | return common.GetErrno() == 0
176 | }
177 |
178 | result = C.GoString(cStr)
179 | return true
180 | }, "ip6tc_next_chain", getNativeError)
181 | return
182 | }
183 |
184 | /* Get first rule in the given chain: NULL for empty chain. */
185 | func (h XtcHandle) FirstRule(chain string) (result IptEntry, osErr error) {
186 | osErr = common.RelayCall(func() bool {
187 | cStr := C.CString(chain)
188 | defer C.free(unsafe.Pointer(cStr))
189 |
190 | result.handle = C.ip6tc_first_rule(cStr, h.handle)
191 |
192 | if result.handle == nil && common.GetErrno() != 0 {
193 | // there's some error
194 | return false
195 | }
196 |
197 | return true
198 | }, "ip6tc_first_rule", getNativeError)
199 | return
200 | }
201 |
202 | /* Returns NULL when rules run out. */
203 | func (h XtcHandle) NextRule(previous IptEntry) (result IptEntry, osErr error) {
204 | osErr = common.RelayCall(func() bool {
205 | result.handle = C.ip6tc_next_rule(previous.handle, h.handle)
206 |
207 | if result.handle == nil && common.GetErrno() != 0 {
208 | // there's some error
209 | return false
210 | }
211 |
212 | return true
213 | }, "ip6tc_next_rule", getNativeError)
214 | return
215 | }
216 |
217 | /* Returns a pointer to the target name of this entry. */
218 | func (h XtcHandle) GetTarget(entry IptEntry) (result string, osErr error) {
219 | osErr = common.RelayCall(func() bool {
220 | cStr := C.ip6tc_get_target(entry.handle, h.handle)
221 | if cStr == nil {
222 | result = ""
223 | return false
224 | }
225 |
226 | result = C.GoString(cStr)
227 | return true
228 | }, "ip6tc_get_target", getNativeError)
229 | return
230 | }
231 |
232 | // GetPolicy gets the policy of a given built-in chain.
233 | func (h XtcHandle) GetPolicy(chain string) (policy string, counters common.XtCounters, osErr error) {
234 | osErr = common.RelayCall(func() bool {
235 | cStr := C.CString(chain)
236 | defer C.free(unsafe.Pointer(cStr))
237 |
238 | var c _Ctype_struct_xt_counters
239 | cStr = C.ip6tc_get_policy(cStr, &c, h.handle)
240 | if cStr == nil {
241 | // no chains
242 | policy = ""
243 | return false
244 | }
245 |
246 | policy = C.GoString(cStr)
247 | counters.Bcnt = uint64(c.bcnt)
248 | counters.Pcnt = uint64(c.pcnt)
249 | return true
250 | }, "ip6tc_get_policy", getNativeError)
251 | return
252 | }
253 |
254 | /* These functions return TRUE for OK or 0 and set errno. If errno ==
255 | 0, it means there was a version error (ie. upgrade libiptc). */
256 | /* Rule numbers start at 1 for the first rule. */
257 |
258 | /* Insert the entry `e' in chain `chain' into position `rulenum'. */
259 | func (h XtcHandle) InsertEntry(chain common.XtChainLabel, entry IptEntry, ruleNum uint) error {
260 | return common.RelayCall(func() bool {
261 | cStr := C.CString(string(chain))
262 | defer C.free(unsafe.Pointer(cStr))
263 |
264 | r := C.ip6tc_insert_entry(cStr, entry.handle, C.uint(ruleNum), h.handle)
265 | if r == 1 {
266 | return true
267 | } else if r == 0 {
268 | // has error
269 | return false
270 | }
271 |
272 | panic("invalid return value")
273 | }, "ip6tc_insert_entry", getNativeError)
274 | }
275 |
276 | /* Append entry `e' to chain `chain'. Equivalent to insert with
277 | rulenum = length of chain. */
278 | func (h XtcHandle) AppendEntry(chain common.XtChainLabel, entry IptEntry) error {
279 | return common.RelayCall(func() bool {
280 | cStr := C.CString(string(chain))
281 | defer C.free(unsafe.Pointer(cStr))
282 |
283 | r := C.ip6tc_append_entry(cStr, entry.handle, h.handle)
284 | if r == 1 {
285 | return true
286 | } else if r == 0 {
287 | // has error
288 | return false
289 | }
290 |
291 | panic("invalid return value")
292 | }, "ip6tc_append_entry", getNativeError)
293 | }
294 |
295 | /* Check whether a matching rule exists */
296 | func (h XtcHandle) CheckEntry(chain common.XtChainLabel, origfw IptEntry, matchMask []byte) (result bool, osErr error) {
297 | osErr = common.RelayCall(func() bool {
298 | cStr := C.CString(string(chain))
299 | defer C.free(unsafe.Pointer(cStr))
300 | cMask := (*C.uchar)(unsafe.Pointer(&matchMask[0]))
301 |
302 | r := C.ip6tc_check_entry(cStr, origfw.handle, cMask, h.handle)
303 | if r == 1 {
304 | result = true
305 | return result
306 | } else if r == 0 {
307 | result = false
308 | return result
309 | }
310 |
311 | panic("invalid return value")
312 | }, "ip6tc_check_entry", getNativeError)
313 | return
314 | }
315 |
316 | /* Delete the first rule in `chain' which matches `e', subject to
317 | matchmask (array of length == origfw) */
318 | func (h XtcHandle) DeleteEntry(chain common.XtChainLabel, origfw IptEntry, matchMask []byte) (result bool, osErr error) {
319 | osErr = common.RelayCall(func() bool {
320 | cStr := C.CString(string(chain))
321 | defer C.free(unsafe.Pointer(cStr))
322 | cMask := (*C.uchar)(unsafe.Pointer(&matchMask[0]))
323 |
324 | r := C.ip6tc_delete_entry(cStr, origfw.handle, cMask, h.handle)
325 | if r == 1 {
326 | result = true
327 | return result
328 | } else if r == 0 {
329 | result = false
330 | return result
331 | }
332 |
333 | panic("invalid return value")
334 | }, "ip6tc_delete_entry", getNativeError)
335 | return
336 | }
337 |
338 | /* Delete the rule in position `rulenum' in `chain'. */
339 | func (h XtcHandle) DeleteNumEntry(chain common.XtChainLabel, ruleNum uint) (result bool, osErr error) {
340 | osErr = common.RelayCall(func() bool {
341 | cStr := C.CString(string(chain))
342 | defer C.free(unsafe.Pointer(cStr))
343 |
344 | r := C.ip6tc_delete_num_entry(cStr, C.uint(ruleNum), h.handle)
345 | if r == 1 {
346 | result = true
347 | return result
348 | } else if r == 0 {
349 | result = false
350 | return result
351 | }
352 |
353 | panic("invalid return value")
354 | }, "ip6tc_delete_num_entry", getNativeError)
355 | return
356 | }
357 |
358 | /* Flushes the entries in the given chain (ie. empties chain). */
359 | func (h XtcHandle) FlushEntries(chain common.XtChainLabel) (result bool, osErr error) {
360 | osErr = common.RelayCall(func() bool {
361 | cStr := C.CString(string(chain))
362 | defer C.free(unsafe.Pointer(cStr))
363 |
364 | r := C.ip6tc_flush_entries(cStr, h.handle)
365 | if r == 1 {
366 | result = true
367 | return result
368 | } else if r == 0 {
369 | result = false
370 | return result
371 | }
372 |
373 | panic("invalid return value")
374 | }, "ip6tc_flush_entries", getNativeError)
375 | return
376 | }
377 |
378 | /* Zeroes the counters in a chain. */
379 | func (h XtcHandle) ZeroEntries(chain common.XtChainLabel) (result bool, osErr error) {
380 | osErr = common.RelayCall(func() bool {
381 | cStr := C.CString(string(chain))
382 | defer C.free(unsafe.Pointer(cStr))
383 |
384 | r := C.ip6tc_zero_entries(cStr, h.handle)
385 | if r == 1 {
386 | result = true
387 | return result
388 | } else if r == 0 {
389 | result = false
390 | return result
391 | }
392 |
393 | panic("invalid return value")
394 | }, "ip6tc_zero_entries", getNativeError)
395 | return
396 | }
397 |
398 | /* Creates a new chain. */
399 | func (h XtcHandle) CreateChain(chain common.XtChainLabel) (result bool, osErr error) {
400 | osErr = common.RelayCall(func() bool {
401 | cStr := C.CString(string(chain))
402 | defer C.free(unsafe.Pointer(cStr))
403 |
404 | r := C.ip6tc_create_chain(cStr, h.handle)
405 | if r == 1 {
406 | result = true
407 | return result
408 | } else if r == 0 {
409 | result = false
410 | return result
411 | }
412 |
413 | panic("invalid return value")
414 | }, "ip6tc_create_chain", getNativeError)
415 | return
416 | }
417 |
418 | /* Deletes a chain. */
419 | func (h XtcHandle) DeleteChain(chain common.XtChainLabel) (result bool, osErr error) {
420 | osErr = common.RelayCall(func() bool {
421 | cStr := C.CString(string(chain))
422 | defer C.free(unsafe.Pointer(cStr))
423 |
424 | r := C.ip6tc_delete_chain(cStr, h.handle)
425 | if r == 1 {
426 | result = true
427 | return result
428 | } else if r == 0 {
429 | result = false
430 | return result
431 | }
432 |
433 | panic("invalid return value")
434 | }, "ip6tc_delete_chain", getNativeError)
435 | return
436 | }
437 |
438 | /* Renames a chain. */
439 | func (h XtcHandle) RenameChain(oldName, newName common.XtChainLabel) (result bool, osErr error) {
440 | osErr = common.RelayCall(func() bool {
441 | cOldName := C.CString(string(oldName))
442 | defer C.free(unsafe.Pointer(cOldName))
443 | cNewName := C.CString(string(newName))
444 | defer C.free(unsafe.Pointer(cNewName))
445 |
446 | r := C.ip6tc_rename_chain(cOldName, cNewName, h.handle)
447 | if r == 1 {
448 | result = true
449 | return result
450 | } else if r == 0 {
451 | result = false
452 | return result
453 | }
454 |
455 | panic("invalid return value")
456 | }, "ip6tc_rename_chain", getNativeError)
457 | return
458 | }
459 |
460 | /* Sets the policy and (optionally) counters on a built-in chain. */
461 | func (h XtcHandle) SetPolicy(chain, policy common.XtChainLabel, counters *common.XtCounters) (result bool, osErr error) {
462 | osErr = common.RelayCall(func() bool {
463 | cChain := C.CString(string(chain))
464 | defer C.free(unsafe.Pointer(cChain))
465 | cPolicy := C.CString(string(policy))
466 | defer C.free(unsafe.Pointer(cPolicy))
467 |
468 | var c *_Ctype_struct_xt_counters
469 | if counters != nil {
470 | c = &_Ctype_struct_xt_counters{}
471 | c.bcnt = C.__u64(counters.Bcnt)
472 | c.pcnt = C.__u64(counters.Pcnt)
473 | }
474 |
475 | r := C.ip6tc_set_policy(cChain, cPolicy, c, h.handle)
476 | if r == 1 {
477 | result = true
478 | return result
479 | } else if r == 0 {
480 | result = false
481 | return result
482 | }
483 |
484 | panic("invalid return value")
485 | }, "ip6tc_set_policy", getNativeError)
486 | return
487 | }
488 |
489 | /* Get the number of references to this chain */
490 | func (h XtcHandle) GetReferences(chain common.XtChainLabel) (result uint, osErr error) {
491 | osErr = common.RelayCall(func() bool {
492 | cStr := C.CString(string(chain))
493 | defer C.free(unsafe.Pointer(cStr))
494 |
495 | var i C.uint
496 |
497 | r := C.ip6tc_get_references(&i, cStr, h.handle)
498 | if r == 1 {
499 | // has a valid result
500 | result = uint(i)
501 | return true
502 | } else if r == 0 {
503 | // has an error
504 | return false
505 | }
506 |
507 | panic("invalid return value")
508 | }, "ip6tc_get_references", getNativeError)
509 | return
510 | }
511 |
512 | /* read packet and byte counters for a specific rule */
513 | func (h XtcHandle) ReadCounter(chain common.XtChainLabel, ruleNum uint) (result common.XtCounters, osErr error) {
514 | osErr = common.RelayCall(func() bool {
515 | cStr := C.CString(string(chain))
516 | defer C.free(unsafe.Pointer(cStr))
517 |
518 | counters_handle := C.ip6tc_read_counter(cStr, C.uint(ruleNum), h.handle)
519 | if counters_handle == nil {
520 | // has an error
521 | return false
522 | }
523 |
524 | result.Bcnt = uint64(counters_handle.bcnt)
525 | result.Pcnt = uint64(counters_handle.pcnt)
526 | return true
527 | }, "ip6tc_read_counter", getNativeError)
528 | return
529 | }
530 |
531 | /* zero packet and byte counters for a specific rule */
532 | func (h XtcHandle) ZeroCounter(chain common.XtChainLabel, ruleNum uint) (result bool, osErr error) {
533 | osErr = common.RelayCall(func() bool {
534 | cStr := C.CString(string(chain))
535 | defer C.free(unsafe.Pointer(cStr))
536 |
537 | r := C.ip6tc_zero_counter(cStr, C.uint(ruleNum), h.handle)
538 | if r == 1 {
539 | result = true
540 | return result
541 | } else if r == 0 {
542 | result = false
543 | return result
544 | }
545 |
546 | panic("invalid return value")
547 | }, "ip6tc_read_counter", getNativeError)
548 | return
549 | }
550 |
551 | // SetCounter sets packet and byte counters for a specific rule.
552 | func (h XtcHandle) SetCounter(chain common.XtChainLabel, ruleNum uint, counters common.XtCounters) (result bool, osErr error) {
553 | osErr = common.RelayCall(func() bool {
554 | cStr := C.CString(string(chain))
555 | defer C.free(unsafe.Pointer(cStr))
556 |
557 | var c _Ctype_struct_xt_counters
558 | c.bcnt = C.__u64(counters.Bcnt)
559 | c.pcnt = C.__u64(counters.Pcnt)
560 |
561 | r := C.ip6tc_set_counter(cStr, C.uint(ruleNum), &c, h.handle)
562 | if r == 1 {
563 | result = true
564 | return result
565 | } else if r == 0 {
566 | result = false
567 | return result
568 | }
569 |
570 | panic("invalid return value")
571 | }, "ip6tc_set_counter", getNativeError)
572 | return
573 | }
574 |
575 | // Commit makes the actual changes.
576 | func (h XtcHandle) Commit() error {
577 | return common.RelayCall(func() bool {
578 | r := C.ip6tc_commit(h.handle)
579 | if r == 1 {
580 | return true
581 | } else if r == 0 {
582 | return false
583 | }
584 |
585 | panic("unexpected return value")
586 | }, "ip6tc_commit", getNativeError)
587 | }
588 |
589 | // DumpEntries will use an internal undocumented function to dump all table entries to stdout.
590 | func (h XtcHandle) DumpEntries() error {
591 | return common.RelayCall(func() bool {
592 | C.dump_entries6(h.handle)
593 | return false
594 | }, "dump_entries6", getNativeError)
595 | }
596 |
--------------------------------------------------------------------------------
/libip6tc/libip6tc_test.go:
--------------------------------------------------------------------------------
1 | /*
2 | * go-libiptc v0.3.1 - libiptc bindings for Go language
3 | * Copyright (C) 2015~2016 gdm85 - https://github.com/gdm85/go-libiptc/
4 |
5 | This program is free software; you can redistribute it and/or
6 | modify it under the terms of the GNU General Public License
7 | as published by the Free Software Foundation; either version 2
8 | of the License, or (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU General Public License for more details.
14 |
15 | You should have received a copy of the GNU General Public License
16 | along with this program; if not, write to the Free Software
17 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 | */
19 |
20 | package libip6tc
21 |
22 | import (
23 | "testing"
24 |
25 | common "github.com/gdm85/go-libiptc"
26 | )
27 |
28 | func TestInit(t *testing.T) {
29 | acquired, err := common.XtablesLock(false, 0)
30 | if err != nil {
31 | t.Error(err)
32 | t.FailNow()
33 | }
34 | if !acquired {
35 | t.FailNow()
36 | }
37 | defer func() {
38 | _, err := common.XtablesUnlock()
39 | if err != nil {
40 | panic(err)
41 | }
42 | }()
43 |
44 | handle, err := TableInit("filter")
45 | if err != nil {
46 | t.Error(err)
47 | t.FailNow()
48 | }
49 |
50 | err = handle.Free()
51 | if err != nil {
52 | t.Error(err)
53 | t.FailNow()
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/libiptc.go:
--------------------------------------------------------------------------------
1 | /*
2 | * go-libiptc v0.3.1 - libiptc bindings for Go language
3 | * Copyright (C) 2015~2016 gdm85 - https://github.com/gdm85/go-libiptc/
4 |
5 | This program is free software; you can redistribute it and/or
6 | modify it under the terms of the GNU General Public License
7 | as published by the Free Software Foundation; either version 2
8 | of the License, or (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU General Public License for more details.
14 |
15 | You should have received a copy of the GNU General Public License
16 | along with this program; if not, write to the Free Software
17 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 | */
19 |
20 | package libiptc
21 |
22 | import (
23 | // #cgo LDFLAGS: -liptc
24 | // #include "xtables-lock.h"
25 | "C"
26 | "fmt"
27 | "net"
28 | "runtime"
29 | )
30 |
31 | // XtChainLabel is a chain label.
32 | type XtChainLabel string
33 |
34 | const (
35 | // the constants are copied from #define declarations in libiptc.h
36 | IPTC_LABEL_ACCEPT = "ACCEPT"
37 | IPTC_LABEL_DROP = "DROP"
38 | IPTC_LABEL_QUEUE = "QUEUE"
39 | IPTC_LABEL_RETURN = "RETURN"
40 | )
41 |
42 | // XtCounters contains packet and byte counters.
43 | type XtCounters struct {
44 | // Pcnt is the packet counter.
45 | Pcnt uint64
46 | // Bcnt is the byte counter.
47 | Bcnt uint64
48 | }
49 |
50 | // Not is a shortand for rule negation description.
51 | type Not bool
52 |
53 | // String returns '!' for a negated rule.
54 | func (n Not) String() string {
55 | if n {
56 | return "!"
57 | }
58 | return " "
59 | }
60 |
61 | // Rule is a complete iptables rule descriptor.
62 | type Rule struct {
63 | Src *net.IPNet
64 | Dest *net.IPNet
65 | InDev string
66 | OutDev string
67 | Not struct {
68 | Src Not
69 | Dest Not
70 | InDev Not
71 | OutDev Not
72 | }
73 | Target string
74 | XtCounters
75 | }
76 |
77 | // String returns a human-readable description of a rule.
78 | func (r Rule) String() string {
79 | return fmt.Sprintf("in: %s%s, out: %s%s, %s%s -> %s%s -> %s: %d packets, %d bytes",
80 | r.Not.InDev, r.InDev,
81 | r.Not.OutDev, r.OutDev,
82 | r.Not.Src, r.Src,
83 | r.Not.Dest, r.Dest,
84 | r.Target,
85 | r.Pcnt, r.Bcnt)
86 | }
87 |
88 | // RelayedFunc is a function that returns false if there is an 'errno' to query about. Used internally to perform all lib*iptc calls serially.
89 | type RelayedFunc func() bool
90 |
91 | // ErrorFunc generates an error based on a libip*tc_strerror call. Used internally to report about errors.
92 | type ErrorFunc func() string
93 |
94 | // RelayedCall
95 | type RelayedCall struct {
96 | // Context is the C function being called.
97 | Context string
98 | // Func is the function that performs the wrapper around the C function call that does the conversion of input/output parameters.
99 | Func RelayedFunc
100 | // Error is the specific ErrorFunc needed to extract an error after the C call.
101 | Error ErrorFunc
102 | }
103 |
104 | var (
105 | callResult = make(chan error)
106 | queueOfCalls = make(chan RelayedCall)
107 | )
108 |
109 | func init() {
110 | // start a main loop that will process (serially) all incoming libiptc/libip6tc calls
111 | go func() {
112 | runtime.LockOSThread()
113 |
114 | for {
115 | call := <-queueOfCalls
116 |
117 | // as extra good measure, reset errno before C-land calls
118 | C.reset_errno()
119 |
120 | // libiptc logic is called here
121 | success := call.Func()
122 |
123 | var err error
124 | if !success {
125 | err = fmt.Errorf("%s: %s", call.Context, call.Error())
126 | }
127 |
128 | // this will also signal completion of the call
129 | callResult <- err
130 | }
131 | }()
132 | }
133 |
134 | // this is used just for the errors set in xtables-lock.c:
135 | // * ENOLCK - lock was not being held at all
136 | // * EALREADY - trying to acquire lock twice
137 | // * any error set by a failed bind() call
138 | // * ETIMEOUT - could not acquire lock in specified timeout
139 | // * any error set by a failed socket() call
140 | func getNativeError() string {
141 | return C.GoString(C.strerror(C.get_errno()))
142 | }
143 |
144 | // XtablesLock acquires the same lock that a call to `iptables --wait` would.
145 | func XtablesLock(wait bool, maxSeconds uint) (result bool, osErr error) {
146 | osErr = RelayCall(func() bool {
147 | r := C.xtables_lock(true, C.uint(maxSeconds))
148 | if r == 0 {
149 | result = true
150 | return result
151 | } else if r == 1 {
152 | result = false
153 | return result
154 | }
155 | panic("invalid return value")
156 | }, "xtables_lock", getNativeError)
157 | return
158 | }
159 |
160 | // XtablesUnlock releases an iptables lock previously acquired with XtablesLock().
161 | func XtablesUnlock() (result bool, osErr error) {
162 | osErr = RelayCall(func() bool {
163 | r := C.xtables_unlock()
164 | if r == 0 {
165 | result = true
166 | return result
167 | } else if r == 1 {
168 | result = false
169 | return result
170 | }
171 | panic("invalid return value")
172 | }, "xtables_unlock", getNativeError)
173 | return
174 | }
175 |
176 | // GetErrno returns the OS-level errno value. It is used internally to properly report about errors.
177 | func GetErrno() int {
178 | return int(C.get_errno())
179 | }
180 |
181 | // RelayCall will perform the C call on a OS-locked goroutine, serially.
182 | func RelayCall(f RelayedFunc, context string, e ErrorFunc) error {
183 | queueOfCalls <- RelayedCall{Func: f, Context: context, Error: e}
184 | return <-callResult
185 | }
186 |
--------------------------------------------------------------------------------
/update-version.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | if [ ! $# -eq 1 ]; then
4 | echo "Usage: update-version.sh 0.3.1" 1>&2
5 | exit 1
6 | fi
7 |
8 | VER="$1"
9 |
10 | sed -i "s~go-libiptc v[^ ]*~go-libiptc v${VER}~g" $(find . -type f -name '*.go' -o -name '*.c' -o -name '*.h')
11 |
--------------------------------------------------------------------------------
/xtables-lock.c:
--------------------------------------------------------------------------------
1 | /*
2 | * go-libiptc v0.3.1 - libiptc bindings for Go language
3 | * Copyright (C) 2015~2016 gdm85 - https://github.com/gdm85/go-libiptc/
4 |
5 | This program is free software; you can redistribute it and/or
6 | modify it under the terms of the GNU General Public License
7 | as published by the Free Software Foundation; either version 2
8 | of the License, or (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU General Public License for more details.
14 |
15 | You should have received a copy of the GNU General Public License
16 | along with this program; if not, write to the Free Software
17 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 | */
19 |
20 | #include
21 | #include
22 | #include
23 | #include
24 | #include
25 | #include
26 | #include
27 | #include
28 | #include
29 | #include
30 | #include
31 | #include
32 | #include
33 |
34 | #include "xtables-lock.h"
35 |
36 | #define XT_SOCKET_NAME "xtables"
37 | #define XT_SOCKET_LEN 8
38 |
39 | int xtables_socket = -1;
40 |
41 | // it's not possible to read or write errno directly in Go
42 | void reset_errno() {
43 | errno = 0;
44 | }
45 |
46 | // some functions inconsistently report about an erroneous condition through their result,
47 | // thus error checking is peeked with this helper function
48 | // see also: https://www.securecoding.cert.org/confluence/pages/viewpage.action?pageId=6619179
49 | // NOTE: there is a PR upstream about improving error handling in iptables
50 | int get_errno() {
51 | return errno;
52 | }
53 |
54 | int xtables_unlock() {
55 | // lock was not being held at all
56 | if (xtables_socket < 0) {
57 | errno = ENOLCK;
58 | return 1;
59 | }
60 |
61 | if (close(xtables_socket) != 0)
62 | return 1;
63 |
64 | xtables_socket = -1;
65 | return 0;
66 | }
67 |
68 | // <0 - lock failed, 0 - success, 1 - failure
69 | int xtables_lock(bool wait, uint max_seconds_wait)
70 | {
71 | // trying to acquire lock twice
72 | if (xtables_socket >= 0) {
73 | errno = EALREADY;
74 | return 1;
75 | }
76 |
77 | int i = 0, ret;
78 | struct sockaddr_un xt_addr;
79 |
80 | memset(&xt_addr, 0, sizeof(xt_addr));
81 | xt_addr.sun_family = AF_UNIX;
82 | strcpy(xt_addr.sun_path+1, XT_SOCKET_NAME);
83 | xtables_socket = socket(AF_UNIX, SOCK_STREAM, 0);
84 | /* If we can't even create a socket, fall back to prior (lockless) behavior */
85 | if (xtables_socket < 0) {
86 | // errno is expected to have been set by previous socket() call
87 | return xtables_socket;
88 | }
89 |
90 | uint waited_seconds = 0;
91 | while (waited_seconds <= max_seconds_wait) {
92 | ret = bind(xtables_socket, (struct sockaddr*)&xt_addr,
93 | offsetof(struct sockaddr_un, sun_path)+XT_SOCKET_LEN);
94 |
95 | // successfully acquired lock (via socket)
96 | // NOTE: the socket is released with xtables_unlock(), or anyway when process exits
97 | if (ret == 0)
98 | return 0;
99 |
100 | // fail immediately
101 | if (wait == false) {
102 | // errno has been set by the bind() call
103 | return 1;
104 | }
105 |
106 | // time to wait
107 | sleep(1);
108 | ++waited_seconds;
109 | }
110 |
111 | // timeout
112 | errno = ETIMEDOUT;
113 | return 1;
114 | }
115 |
--------------------------------------------------------------------------------
/xtables-lock.h:
--------------------------------------------------------------------------------
1 | /*
2 | * go-libiptc v0.3.1 - libiptc bindings for Go language
3 | * Copyright (C) 2015~2016 gdm85 - https://github.com/gdm85/go-libiptc/
4 |
5 | This program is free software; you can redistribute it and/or
6 | modify it under the terms of the GNU General Public License
7 | as published by the Free Software Foundation; either version 2
8 | of the License, or (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU General Public License for more details.
14 |
15 | You should have received a copy of the GNU General Public License
16 | along with this program; if not, write to the Free Software
17 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 | */
19 |
20 | // these headers needs to be here so that Go will import the externs
21 | #include
22 | #include
23 | #include
24 |
25 | int get_errno();
26 | void reset_errno();
27 |
28 | int xtables_lock(bool wait, uint max_seconds_wait);
29 | int xtables_unlock();
30 |
--------------------------------------------------------------------------------