├── .gitignore ├── .travis.yml ├── CHANGELOG.md ├── LICENSE ├── Makefile ├── README.md ├── c_src ├── .gitignore ├── Makefile └── netlink_drv.c ├── include └── netlink.hrl ├── priv └── .gitignore ├── rebar.config ├── rebar.lock ├── src ├── .gitignore ├── netl_codec.erl ├── netl_codec.hrl ├── netlink.app.src ├── netlink.erl ├── netlink.hrl ├── netlink.inc ├── netlink_app.erl ├── netlink_codec.erl ├── netlink_drv.erl ├── netlink_gen.erl ├── netlink_stat.erl └── netlink_sup.erl └── tetrapak ├── build_drv.erl └── config.ini /.gitignore: -------------------------------------------------------------------------------- 1 | /_build 2 | /.tool-versions 3 | /deps 4 | /.rebar 5 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | language: erlang 3 | script: 4 | - wget -c https://github.com/erlang/rebar3/releases/download/3.6.2/rebar3 5 | - chmod +x rebar3 6 | - REBAR3=./rebar3 make ci 7 | otp_release: 8 | - 21.1 9 | - 20.3 10 | - 20.2 11 | - 20.1 12 | - 20.0 13 | - 19.3 14 | - 19.2 15 | - 19.1 16 | - 18.3 17 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## [v1.1.0](https://github.com/Feuerlabs/netlink/tree/v1.1.0) (2018-11-02) 4 | [Full Changelog](https://github.com/Feuerlabs/netlink/compare/1.0...v1.1.0) 5 | 6 | - Add basic readme 7 | - Set up Travis CI 8 | - Pad stats if needed, allow export_all without complain 9 | - change dict() to term() (for OTP 18) [\#5](https://github.com/Feuerlabs/netlink/pull/5) 10 | - Don't use lager directly for logging [\#8](https://github.com/Feuerlabs/netlink/pull/8) 11 | - Add rebar3 support & OTP 21 compatibility [\#9](https://github.com/Feuerlabs/netlink/pull/9) 12 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | REBAR3 ?= rebar3 2 | 3 | .PHONY: all clean compile xref ci 4 | 5 | all: compile xref 6 | 7 | ci: compile xref 8 | 9 | compile: 10 | $(REBAR3) compile 11 | 12 | clean: 13 | $(REBAR3) clean 14 | 15 | clean-all: clean 16 | rm -rf _build 17 | 18 | xref: 19 | $(REBAR3) xref 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Travis][travis badge]][travis] 2 | [![Hex.pm Version][hex version badge]][hex] 3 | [![Hex.pm License][hex license badge]][hex] 4 | [![Erlang Versions][erlang version badge]][travis] 5 | [![Build Tool][build tool]][hex] 6 | 7 | This is a [Netlink][wikipedia] socket implementation in Erlang. 8 | 9 | **NOTE:** Only supported on Linux, because [Netlink][wikipedia] is Linux-only. 10 | 11 | [travis]: https://travis-ci.org/Feuerlabs/netlink 12 | [travis badge]: https://img.shields.io/travis/Feuerlabs/netlink/master.svg?style=flat-square 13 | [hex]: https://hex.pm/packages/netlink 14 | [hex version badge]: https://img.shields.io/hexpm/v/netlink.svg?style=flat-square 15 | [hex license badge]: https://img.shields.io/hexpm/l/netlink.svg?style=flat-square 16 | [erlang version badge]: https://img.shields.io/badge/erlang-18--21-blue.svg?style=flat-square 17 | [build tool]: https://img.shields.io/badge/build%20tool-rebar3-orange.svg?style=flat-square 18 | [wikipedia]: https://en.wikipedia.org/wiki/Netlink 19 | -------------------------------------------------------------------------------- /c_src/.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | *.o 3 | -------------------------------------------------------------------------------- /c_src/Makefile: -------------------------------------------------------------------------------- 1 | # Based on c_src.mk from erlang.mk by Loic Hoguin 2 | 3 | CURDIR := $(shell pwd) 4 | BASEDIR := $(abspath $(CURDIR)/..) 5 | 6 | PROJECT := netlink_drv 7 | 8 | ERTS_INCLUDE_DIR ?= $(shell erl -noshell -s init stop -eval "io:format(\"~s/erts-~s/include/\", [code:root_dir(), erlang:system_info(version)]).") 9 | ERL_INTERFACE_INCLUDE_DIR ?= $(shell erl -noshell -s init stop -eval "io:format(\"~s\", [code:lib_dir(erl_interface, include)]).") 10 | ERL_INTERFACE_LIB_DIR ?= $(shell erl -noshell -s init stop -eval "io:format(\"~s\", [code:lib_dir(erl_interface, lib)]).") 11 | 12 | C_SRC_DIR = $(CURDIR) 13 | C_SRC_OUTPUT ?= $(CURDIR)/../priv/$(PROJECT).so 14 | 15 | # System type and C compiler/flags. 16 | 17 | UNAME_SYS := $(shell uname -s) 18 | ifeq ($(UNAME_SYS), Darwin) 19 | CC ?= cc 20 | CFLAGS ?= -O3 -std=c99 -arch x86_64 -finline-functions -Wall -Wmissing-prototypes 21 | CXXFLAGS ?= -O3 -arch x86_64 -finline-functions -Wall 22 | LDFLAGS ?= -arch x86_64 -flat_namespace -undefined suppress 23 | else ifeq ($(UNAME_SYS), FreeBSD) 24 | CC ?= cc 25 | CFLAGS ?= -O3 -std=c99 -finline-functions -Wall -Wmissing-prototypes 26 | CXXFLAGS ?= -O3 -finline-functions -Wall 27 | else ifeq ($(UNAME_SYS), Linux) 28 | CC ?= gcc 29 | CFLAGS ?= -O3 -std=c99 -finline-functions -Wall -Wmissing-prototypes 30 | CXXFLAGS ?= -O3 -finline-functions -Wall 31 | endif 32 | 33 | CFLAGS += -fPIC -I $(ERTS_INCLUDE_DIR) -I $(ERL_INTERFACE_INCLUDE_DIR) 34 | CXXFLAGS += -fPIC -I $(ERTS_INCLUDE_DIR) -I $(ERL_INTERFACE_INCLUDE_DIR) 35 | 36 | LDLIBS += -L $(ERL_INTERFACE_LIB_DIR) -lerl_interface -lei 37 | LDFLAGS += -shared 38 | 39 | # Verbosity. 40 | 41 | c_verbose_0 = @echo " C " $(?F); 42 | c_verbose = $(c_verbose_$(V)) 43 | 44 | cpp_verbose_0 = @echo " CPP " $(?F); 45 | cpp_verbose = $(cpp_verbose_$(V)) 46 | 47 | link_verbose_0 = @echo " LD " $(@F); 48 | link_verbose = $(link_verbose_$(V)) 49 | 50 | SOURCES := $(shell find $(C_SRC_DIR) -type f \( -name "*.c" -o -name "*.C" -o -name "*.cc" -o -name "*.cpp" \)) 51 | OBJECTS = $(addsuffix .o, $(basename $(SOURCES))) 52 | 53 | COMPILE_C = $(c_verbose) $(CC) $(CFLAGS) $(CPPFLAGS) -c 54 | COMPILE_CPP = $(cpp_verbose) $(CXX) $(CXXFLAGS) $(CPPFLAGS) -c 55 | 56 | $(C_SRC_OUTPUT): $(OBJECTS) 57 | @mkdir -p $(BASEDIR)/priv/ 58 | $(link_verbose) $(CC) $(OBJECTS) $(LDFLAGS) $(LDLIBS) -o $(C_SRC_OUTPUT) 59 | 60 | %.o: %.c 61 | $(COMPILE_C) $(OUTPUT_OPTION) $< 62 | 63 | %.o: %.cc 64 | $(COMPILE_CPP) $(OUTPUT_OPTION) $< 65 | 66 | %.o: %.C 67 | $(COMPILE_CPP) $(OUTPUT_OPTION) $< 68 | 69 | %.o: %.cpp 70 | $(COMPILE_CPP) $(OUTPUT_OPTION) $< 71 | 72 | clean: 73 | @rm -f $(C_SRC_OUTPUT) $(OBJECTS) 74 | -------------------------------------------------------------------------------- /c_src/netlink_drv.c: -------------------------------------------------------------------------------- 1 | /****** BEGIN COPYRIGHT ******************************************************* 2 | * 3 | * Copyright (C) 2012 Feuerlabs, Inc. All rights reserved. 4 | * 5 | * This Source Code Form is subject to the terms of the Mozilla Public 6 | * License, v. 2.0. If a copy of the MPL was not distributed with this 7 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. 8 | * 9 | ****** END COPYRIGHT ********************************************************/ 10 | // 11 | // Netlink driver 12 | // 13 | 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | 26 | #include "erl_driver.h" 27 | 28 | #define ATOM(NAME) am_ ## NAME 29 | #define INIT_ATOM(NAME) am_ ## NAME = driver_mk_atom(#NAME) 30 | 31 | // Hack to handle R15 driver used with pre R15 driver 32 | #if ERL_DRV_EXTENDED_MAJOR_VERSION == 1 33 | typedef int ErlDrvSizeT; 34 | typedef int ErlDrvSSizeT; 35 | #endif 36 | 37 | #if (ERL_DRV_EXTENDED_MAJOR_VERSION > 2) || ((ERL_DRV_EXTENDED_MAJOR_VERSION == 2) && (ERL_DRV_EXTENDED_MINOR_VERSION >= 1)) 38 | #define SEND_TERM(ctx, to, message, len) erl_drv_send_term((ctx)->dport,(to),(message),(len)) 39 | #else 40 | #define SEND_TERM(ctx, to, message, len) driver_send_term((ctx)->port,(to),(message),(len)) 41 | #endif 42 | 43 | #ifndef SOL_NETLINK 44 | #define SOL_NETLINK 270 45 | #endif 46 | 47 | #define PORT_CONTROL_BINARY 48 | 49 | #define INT_EVENT(ptr) ((int)((long)(ptr))) 50 | 51 | typedef struct _nl_ctx_t { 52 | ErlDrvPort port; 53 | ErlDrvTermData dport; 54 | ErlDrvTermData owner; 55 | ErlDrvEvent fd; // netlink socket 56 | int protocol; // netlink protocol 57 | int active; 58 | int is_selecting; 59 | int is_sending; 60 | void* nlbuf; 61 | size_t nlbuf_len; 62 | } nl_ctx_t; 63 | 64 | #define CMD_ADD_MEMBERSHIP 1 65 | #define CMD_DROP_MEMBERSHIP 2 66 | #define CMD_ACTIVE 3 67 | #define CMD_DEBUG 4 68 | #define CMD_SET_RCVBUF 5 69 | #define CMD_SET_SNDBUF 6 70 | #define CMD_GET_RCVBUF 7 71 | #define CMD_GET_SNDBUF 8 72 | #define CMD_GET_SIZEOF 9 73 | 74 | 75 | #define CTL_OK 0 76 | #define CTL_INT 1 77 | #define CTL_PAIR 2 78 | #define CTL_BIN 3 79 | #define CTL_LIST 4 80 | #define CTL_ERR 255 81 | #define CTL_STRERR 254 82 | 83 | #define MIN_NL_BUFSIZE (32*1024) 84 | #define MAX_NL_BUFSIZE (512*1024) 85 | 86 | #define MAX_VSIZE 16 87 | 88 | ErlDrvTermData am_ok; 89 | ErlDrvTermData am_error; 90 | ErlDrvTermData am_undefined; 91 | ErlDrvTermData am_true; 92 | ErlDrvTermData am_false; 93 | ErlDrvTermData am_nl_data; 94 | 95 | #define push_atom(atm) do { \ 96 | message[i++] = ERL_DRV_ATOM; \ 97 | message[i++] = (atm); \ 98 | } while(0) 99 | 100 | #define push_port(prt) do { \ 101 | message[i++] = ERL_DRV_PORT; \ 102 | message[i++] = (prt); \ 103 | } while(0) 104 | 105 | #define push_pid(pid) do { \ 106 | message[i++] = ERL_DRV_PID; \ 107 | message[i++] = (pid); \ 108 | } while(0) 109 | 110 | #define push_bin(buf,len) do { \ 111 | message[i++] = ERL_DRV_BUF2BINARY; \ 112 | message[i++] = (ErlDrvTermData)(buf); \ 113 | message[i++] = (ErlDrvTermData)(len); \ 114 | } while(0) 115 | 116 | #define push_nil() do { \ 117 | message[i++] = ERL_DRV_NIL; \ 118 | } while(0) 119 | 120 | #define push_string(str) do { \ 121 | message[i++] = ERL_DRV_STRING; \ 122 | message[i++] = (ErlDrvTermData) (str); \ 123 | message[i++] = strlen(str); \ 124 | } while(0) 125 | 126 | #define push_int(val) do { \ 127 | message[i++] = ERL_DRV_INT; \ 128 | message[i++] = (val); \ 129 | } while(0) 130 | 131 | #define push_tuple(n) do { \ 132 | message[i++] = ERL_DRV_TUPLE; \ 133 | message[i++] = (n); \ 134 | } while(0) 135 | 136 | #define push_list(n) do { \ 137 | message[i++] = ERL_DRV_LIST; \ 138 | message[i++] = (n); \ 139 | } while(0) 140 | 141 | 142 | ErlDrvEntry nl_drv_entry; 143 | 144 | static inline uint32_t get_uint32(uint8_t* ptr) 145 | { 146 | uint32_t value = (ptr[0]<<24) | (ptr[1]<<16) | (ptr[2]<<8) | (ptr[3]<<0); 147 | return value; 148 | } 149 | 150 | static inline int32_t get_int32(uint8_t* ptr) 151 | { 152 | uint32_t value = (ptr[0]<<24) | (ptr[1]<<16) | (ptr[2]<<8) | (ptr[3]<<0); 153 | return (int32_t) value; 154 | } 155 | 156 | static inline uint16_t get_uint16(uint8_t* ptr) 157 | { 158 | uint16_t value = (ptr[0]<<8) | (ptr[1]<<0); 159 | return value; 160 | } 161 | 162 | static inline uint8_t get_uint8(uint8_t* ptr) 163 | { 164 | return ptr[0]; 165 | } 166 | 167 | static inline int8_t get_int8(uint8_t* ptr) 168 | { 169 | return (int8_t) ptr[0]; 170 | } 171 | 172 | static inline void put_uint16(uint8_t* ptr, uint16_t v) 173 | { 174 | ptr[0] = v>>8; 175 | ptr[1] = v; 176 | } 177 | 178 | static inline void put_uint32(uint8_t* ptr, uint32_t v) 179 | { 180 | ptr[0] = v>>24; 181 | ptr[1] = v>>16; 182 | ptr[2] = v>>8; 183 | ptr[3] = v; 184 | } 185 | 186 | static int nl_drv_init(void); 187 | static void nl_drv_finish(void); 188 | static void nl_drv_stop(ErlDrvData); 189 | static void nl_drv_output(ErlDrvData,char*,ErlDrvSizeT); 190 | #if 0 191 | static void nl_drv_outputv(ErlDrvData, ErlIOVec*); 192 | #endif 193 | static void nl_drv_ready_input(ErlDrvData, ErlDrvEvent); 194 | static void nl_drv_ready_output(ErlDrvData data, ErlDrvEvent event); 195 | static ErlDrvData nl_drv_start(ErlDrvPort, char* command); 196 | static ErlDrvSSizeT nl_drv_ctl(ErlDrvData,unsigned int,char*,ErlDrvSizeT,char**,ErlDrvSizeT); 197 | static void nl_drv_timeout(ErlDrvData); 198 | static void nl_drv_stop_select(ErlDrvEvent event, void* arg); 199 | 200 | #define DLOG_DEBUG 7 201 | #define DLOG_INFO 6 202 | #define DLOG_NOTICE 5 203 | #define DLOG_WARNING 4 204 | #define DLOG_ERROR 3 205 | #define DLOG_CRITICAL 2 206 | #define DLOG_ALERT 1 207 | #define DLOG_EMERGENCY 0 208 | #define DLOG_NONE -1 209 | 210 | #ifndef DLOG_DEFAULT 211 | #define DLOG_DEFAULT DLOG_NONE 212 | #endif 213 | 214 | #define DLOG(level,file,line,args...) do { \ 215 | if (((level) == DLOG_EMERGENCY) || \ 216 | ((debug_level >= 0) && ((level) <= debug_level))) { \ 217 | emit_log((level),(file),(line),args); \ 218 | } \ 219 | } while(0) 220 | 221 | #define DEBUGF(args...) DLOG(DLOG_DEBUG,__FILE__,__LINE__,args) 222 | #define INFOF(args...) DLOG(DLOG_INFO,__FILE__,__LINE__,args) 223 | #define NOTICEF(args...) DLOG(DLOG_NOTICE,__FILE__,__LINE__,args) 224 | #define WARNINGF(args...) DLOG(DLOG_WARNING,__FILE__,__LINE__,args) 225 | #define ERRORF(args...) DLOG(DLOG_ERROR,__FILE__,__LINE__,args) 226 | #define CRITICALF(args...) DLOG(DLOG_CRITICAL,__FILE__,__LINE__,args) 227 | #define ALERTF(args...) DLOG(DLOG_ALERT,__FILE__,__LINE__,args) 228 | #define EMERGENCYF(args...) DLOG(DLOG_EMERGENCY,__FILE__,__LINE__,args) 229 | 230 | static int debug_level = DLOG_DEFAULT; 231 | 232 | static void emit_log(int level, char* file, int line, ...) 233 | { 234 | va_list ap; 235 | char* fmt; 236 | 237 | if ((level == DLOG_EMERGENCY) || 238 | ((debug_level >= 0) && (level <= debug_level))) { 239 | int save_errno = errno; 240 | va_start(ap, line); 241 | fmt = va_arg(ap, char*); 242 | fprintf(stderr, "%s:%d: ", file, line); 243 | vfprintf(stderr, fmt, ap); 244 | fprintf(stderr, "\r\n"); 245 | va_end(ap); 246 | errno = save_errno; 247 | } 248 | } 249 | 250 | /* general control reply function */ 251 | static ErlDrvSSizeT ctl_reply(int rep, void* buf, ErlDrvSizeT len, 252 | char** rbuf, ErlDrvSizeT rsize) 253 | { 254 | char* ptr; 255 | 256 | if ((len+1) > rsize) { 257 | #ifdef PORT_CONTROL_BINARY 258 | ErlDrvBinary* bin = driver_alloc_binary(len+1); 259 | if (bin == NULL) 260 | return -1; 261 | ptr = bin->orig_bytes; 262 | *rbuf = (char*) bin; 263 | #else 264 | if ((ptr = driver_alloc(len+1)) == NULL) 265 | return -1; 266 | *rbuf = ptr; 267 | #endif 268 | } 269 | else 270 | ptr = *rbuf; 271 | *ptr++ = rep; 272 | memcpy(ptr, buf, len); 273 | return len+1; 274 | } 275 | 276 | static void* nl_realloc_buffer(nl_ctx_t* ctx, size_t len) 277 | { 278 | if (ctx->nlbuf_len < len) { 279 | ctx->nlbuf = driver_realloc(ctx->nlbuf, NLMSG_SPACE(len)); 280 | ctx->nlbuf_len = len; 281 | } 282 | return ctx->nlbuf; 283 | } 284 | 285 | static int nl_drv_init(void) 286 | { 287 | INIT_ATOM(ok); 288 | INIT_ATOM(error); 289 | INIT_ATOM(undefined); 290 | INIT_ATOM(true); 291 | INIT_ATOM(false); 292 | INIT_ATOM(nl_data); 293 | return 0; 294 | } 295 | 296 | static void nl_drv_finish(void) 297 | { 298 | } 299 | 300 | static void nl_drv_stop(ErlDrvData d) 301 | { 302 | nl_ctx_t* ctx = (nl_ctx_t*) d; 303 | 304 | if (ctx) { 305 | if (ctx->is_selecting) 306 | driver_select(ctx->port, ctx->fd, ERL_DRV_READ, 0); 307 | if (ctx->is_sending) 308 | driver_select(ctx->port, ctx->fd, ERL_DRV_WRITE, 0); 309 | driver_select(ctx->port, ctx->fd, ERL_DRV_USE, 0); 310 | driver_free(ctx); 311 | } 312 | } 313 | 314 | static void nl_drv_output(ErlDrvData d, char* buf,ErlDrvSizeT len) 315 | { 316 | nl_ctx_t* ctx = (nl_ctx_t*) d; 317 | int n; 318 | struct nlmsghdr* nlh = (struct nlmsghdr*) buf; 319 | 320 | if (!NLMSG_OK(nlh, len)) { 321 | DEBUGF("netlink_drv: data not OK"); 322 | } 323 | else { 324 | DEBUGF("netlink_drv: output len=%d, type=%d, seq=%d, pid=%d", 325 | nlh->nlmsg_len, nlh->nlmsg_type, nlh->nlmsg_seq, nlh->nlmsg_pid); 326 | if ((n = driver_sizeq(ctx->port)) > 0) { 327 | driver_enq(ctx->port, buf, len); 328 | DEBUGF("netlink_drv_output: put on queue pending=%d", n+len); 329 | } 330 | else { // try send directly 331 | struct sockaddr_nl dest_addr; 332 | struct iovec iov; 333 | struct msghdr msg; 334 | 335 | memset(&msg, 0, sizeof(msg)); 336 | memset(&dest_addr, 0, sizeof(dest_addr)); 337 | 338 | dest_addr.nl_family = AF_NETLINK; 339 | dest_addr.nl_pid = 0; // to kernel 340 | dest_addr.nl_groups = 0; // unicast 341 | 342 | iov.iov_base = (void*) buf; 343 | iov.iov_len = len; 344 | 345 | msg.msg_name = (void*) &dest_addr; 346 | msg.msg_namelen = sizeof(dest_addr); 347 | msg.msg_iov = &iov; 348 | msg.msg_iovlen = 1; 349 | 350 | n = sendmsg(INT_EVENT(ctx->fd), &msg, 0); 351 | if (n < 0) { 352 | ERRORF("write error=%s", strerror(errno)); 353 | if ((errno == EAGAIN) || (errno = ENOBUFS)) { 354 | DEBUGF("netlink_drv: put on queue", n); 355 | driver_enq(ctx->port, buf, len); 356 | driver_select(ctx->port, ctx->fd, ERL_DRV_WRITE, 1); 357 | ctx->is_sending = 1; 358 | } 359 | } 360 | } 361 | } 362 | } 363 | 364 | 365 | // netlink socket triggered process data 366 | static void nl_drv_ready_input(ErlDrvData d, ErlDrvEvent event) 367 | { 368 | nl_ctx_t* ctx = (nl_ctx_t*) d; 369 | struct sockaddr_nl src_addr; 370 | struct iovec iov; 371 | struct msghdr msg; 372 | struct nlmsghdr* nlh; 373 | int n; 374 | int part = 0; 375 | int recv_count = 10; 376 | 377 | DEBUGF("nl_drv_ready_input"); 378 | 379 | again: 380 | if (!--recv_count) 381 | return; 382 | memset(&iov, 0, sizeof(iov)); 383 | memset(&msg, 0, sizeof(msg)); 384 | memset(&src_addr, 0, sizeof(src_addr)); 385 | 386 | nlh = nl_realloc_buffer(ctx, MIN_NL_BUFSIZE); 387 | 388 | iov.iov_base = (void*) nlh; 389 | iov.iov_len = ctx->nlbuf_len; 390 | msg.msg_name = (void*) &src_addr; 391 | msg.msg_namelen = sizeof(src_addr); 392 | msg.msg_iov = &iov; 393 | msg.msg_iovlen = 1; 394 | 395 | if ((n = recvmsg(INT_EVENT(ctx->fd), &msg, 0)) < 0) { 396 | if (errno == EAGAIN) 397 | return; 398 | // send error to erlang ? 399 | WARNINGF("nl_drv_read_input: read error=%s", strerror(errno)); 400 | } 401 | else if (n == 0) { 402 | WARNINGF("nl_drv_read_input: read eof?"); 403 | } 404 | else { 405 | ErlDrvTermData message[16]; 406 | 407 | while(NLMSG_OK(nlh, n)) { 408 | int i = 0; 409 | // {nl_data, , } 410 | push_atom(ATOM(nl_data)); 411 | push_port(ctx->dport); 412 | push_bin((char*)nlh, nlh->nlmsg_len); 413 | push_tuple(3); 414 | DEBUGF("nl_drv_read_input: part = %d", part); 415 | part++; 416 | if (ctx->active) { 417 | SEND_TERM(ctx, ctx->owner, message, i); 418 | if (ctx->active > 0) { 419 | ctx->active--; 420 | if (ctx->active == 0) { 421 | ctx->is_selecting = 0; 422 | driver_select(ctx->port, ctx->fd, ERL_DRV_READ, 0); 423 | } 424 | } 425 | } 426 | nlh = NLMSG_NEXT(nlh, n); 427 | } 428 | goto again; 429 | } 430 | } 431 | 432 | static void nl_drv_ready_output(ErlDrvData d, ErlDrvEvent event) 433 | { 434 | nl_ctx_t* ctx = (nl_ctx_t*) d; 435 | struct sockaddr_nl dest_addr; 436 | int vsize; 437 | SysIOVec* iovp; 438 | struct msghdr msg; 439 | int n; 440 | 441 | DEBUGF("nl_drv_ready_output called"); 442 | 443 | if (ctx->fd != event) { 444 | DEBUGF("nl_drv_ready_output bad event"); 445 | return; 446 | } 447 | 448 | if ((iovp = driver_peekq(ctx->port, &vsize)) == NULL) { 449 | driver_select(ctx->port, ctx->fd, ERL_DRV_WRITE, 0); 450 | ctx->is_sending = 0; 451 | return; 452 | } 453 | vsize = vsize > MAX_VSIZE ? MAX_VSIZE : vsize; 454 | 455 | memset(&msg, 0, sizeof(msg)); 456 | memset(&dest_addr, 0, sizeof(dest_addr)); 457 | 458 | dest_addr.nl_family = AF_NETLINK; 459 | dest_addr.nl_pid = 0; // to kernel 460 | dest_addr.nl_groups = 0; // unicast 461 | 462 | msg.msg_name = (void*) &dest_addr; 463 | msg.msg_namelen = sizeof(dest_addr); 464 | msg.msg_iov = (struct iovec*) iovp; 465 | msg.msg_iovlen = vsize; 466 | 467 | DEBUGF("nl_drv_ready_output: try send vsize=%d", vsize); 468 | n = sendmsg(INT_EVENT(ctx->fd), &msg, 0); 469 | if (n < 0) { 470 | if ((errno == EAGAIN) || (errno == ENOBUFS)) 471 | return; 472 | ERRORF("write error=%s", strerror(errno)); 473 | return; 474 | } 475 | DEBUGF("nl_drv_ready_output: sent %d bytes", n); 476 | if (driver_deq(ctx->port, n) == 0) { 477 | driver_select(ctx->port, ctx->fd, ERL_DRV_WRITE, 0); 478 | ctx->is_sending = 0; 479 | } 480 | } 481 | 482 | static ErlDrvSSizeT nl_drv_ctl(ErlDrvData d,unsigned int cmd,char* buf0, 483 | ErlDrvSizeT len,char** rbuf,ErlDrvSizeT rsize) 484 | { 485 | uint8_t* buf = (uint8_t*) buf0; 486 | nl_ctx_t* ctx = (nl_ctx_t*) d; 487 | 488 | DEBUGF("nl_drv_ctl cmd=%d", cmd); 489 | 490 | switch(cmd) { 491 | case CMD_ADD_MEMBERSHIP: { 492 | int opt; 493 | if (len != 4) 494 | goto badarg; 495 | opt = get_int32(buf); 496 | if (setsockopt(INT_EVENT(ctx->fd), SOL_NETLINK, 497 | NETLINK_ADD_MEMBERSHIP, 498 | (void*) &opt, sizeof(opt)) < 0) 499 | goto error; 500 | goto ok; 501 | } 502 | case CMD_DROP_MEMBERSHIP: { 503 | int opt; 504 | if (len != 4) 505 | goto badarg; 506 | opt = get_int32(buf); 507 | 508 | if (setsockopt(INT_EVENT(ctx->fd), SOL_NETLINK, 509 | NETLINK_DROP_MEMBERSHIP, 510 | (void*) &opt, sizeof(opt)) < 0) 511 | goto error; 512 | goto ok; 513 | } 514 | 515 | case CMD_SET_RCVBUF: { 516 | int opt; 517 | if (len != 4) 518 | goto badarg; 519 | opt = get_int32(buf); 520 | if (setsockopt(INT_EVENT(ctx->fd), SOL_SOCKET, 521 | SO_RCVBUF, 522 | (void*) &opt, sizeof(opt)) < 0) 523 | goto error; 524 | if (opt > 0) { 525 | // make sure i/o buffer match 526 | nl_realloc_buffer(ctx, (size_t)opt); 527 | } 528 | goto ok; 529 | } 530 | 531 | case CMD_SET_SNDBUF: { 532 | int opt; 533 | if (len != 4) 534 | goto badarg; 535 | opt = get_int32(buf); 536 | if (setsockopt(INT_EVENT(ctx->fd), SOL_SOCKET, 537 | SO_SNDBUF, 538 | (void*) &opt, sizeof(opt)) < 0) 539 | goto error; 540 | if (opt > 0) { 541 | // make sure i/o buffer match 542 | nl_realloc_buffer(ctx, (size_t)opt); 543 | } 544 | goto ok; 545 | } 546 | 547 | case CMD_GET_RCVBUF: { 548 | int opt; 549 | socklen_t optlen; 550 | if (len != 0) 551 | goto badarg; 552 | optlen = sizeof(opt); 553 | opt = get_int32(buf); 554 | if (getsockopt(INT_EVENT(ctx->fd), SOL_SOCKET, 555 | SO_RCVBUF, 556 | (void*) &opt, &optlen) < 0) 557 | goto error; 558 | return ctl_reply(CTL_INT, &opt, sizeof(opt), rbuf, rsize); 559 | } 560 | 561 | case CMD_GET_SNDBUF: { 562 | int opt; 563 | socklen_t optlen; 564 | if (len != 0) 565 | goto badarg; 566 | optlen = sizeof(opt); 567 | opt = get_int32(buf); 568 | if (getsockopt(INT_EVENT(ctx->fd), SOL_SOCKET, 569 | SO_SNDBUF, 570 | (void*) &opt, &optlen) < 0) 571 | goto error; 572 | return ctl_reply(CTL_INT, &opt, sizeof(opt), rbuf, rsize); 573 | } 574 | 575 | case CMD_GET_SIZEOF: { 576 | uint8_t sizes[6]; 577 | 578 | sizes[0] = (uint8_t) sizeof(char); 579 | sizes[1] = (uint8_t) sizeof(short); 580 | sizes[2] = (uint8_t) sizeof(int); 581 | sizes[3] = (uint8_t) sizeof(long); 582 | sizes[4] = (uint8_t) sizeof(long long); 583 | sizes[5] = (uint8_t) sizeof(void*); 584 | return ctl_reply(CTL_LIST, sizes, 6, rbuf, rsize); 585 | } 586 | 587 | case CMD_ACTIVE: { 588 | int active; 589 | 590 | if (len != 4) 591 | goto badarg; 592 | active = get_int32(buf); 593 | if (active) { 594 | if (!ctx->is_selecting) 595 | driver_select(ctx->port, ctx->fd, ERL_DRV_READ, 1); 596 | ctx->is_selecting = 1; 597 | ctx->active = active; 598 | } 599 | else { 600 | if (ctx->is_selecting) 601 | driver_select(ctx->port, ctx->fd, ERL_DRV_READ, 0); 602 | ctx->is_selecting = 0; 603 | ctx->active = 0; 604 | } 605 | goto ok; 606 | break; 607 | } 608 | case CMD_DEBUG: { 609 | if (len != 4) 610 | goto badarg; 611 | debug_level = get_int32(buf); 612 | goto ok; 613 | } 614 | 615 | default: 616 | return -1; 617 | } 618 | 619 | ok: 620 | return ctl_reply(CTL_OK, NULL, 0, rbuf, rsize); 621 | badarg: 622 | errno = EINVAL; 623 | error: { 624 | char* err_str = erl_errno_id(errno); 625 | return ctl_reply(CTL_ERR, err_str, strlen(err_str), rbuf, rsize); 626 | } 627 | } 628 | 629 | 630 | static void nl_drv_timeout(ErlDrvData d) 631 | { 632 | (void) d; 633 | fprintf(stderr, "nl_drv_timeout called!!!\r\n"); 634 | } 635 | 636 | static void nl_drv_stop_select(ErlDrvEvent event, void* arg) 637 | { 638 | (void) arg; 639 | DEBUGF("eth_drv: stop_select event=%d", INT_EVENT(event)); 640 | close(INT_EVENT(event)); 641 | } 642 | 643 | 644 | static ErlDrvData nl_drv_start(ErlDrvPort port, char* command) 645 | { 646 | (void) command; 647 | nl_ctx_t* ctx; 648 | int flags; 649 | int fd; 650 | int protocol; 651 | char* ptr; 652 | char* arg; 653 | struct sockaddr_nl addr; 654 | 655 | ptr = command; 656 | while(*ptr && (*ptr != ' ')) ptr++; // skip command 657 | while(*ptr && (*ptr == ' ')) ptr++; // and blanks 658 | arg = ptr; 659 | while(*ptr && (*ptr >= '0') && (*ptr <= '9')) ptr++; 660 | if ((arg == ptr) || (*ptr != '\0')) { 661 | errno = EINVAL; 662 | return ERL_DRV_ERROR_ERRNO; 663 | } 664 | protocol = atoi(arg); 665 | 666 | if ((fd = socket(PF_NETLINK, SOCK_RAW, protocol)) < 0) 667 | return ERL_DRV_ERROR_ERRNO; 668 | 669 | memset(&addr, 0, sizeof(addr)); 670 | addr.nl_family = AF_NETLINK; 671 | addr.nl_groups = 0; // start with no groups 672 | addr.nl_pid = getpid(); // bind using this pid? 673 | 674 | if (bind(fd, (struct sockaddr* ) &addr, sizeof(addr)) < 0) 675 | return ERL_DRV_ERROR_ERRNO; 676 | 677 | flags = fcntl(fd, F_GETFL, 0); 678 | fcntl(fd, F_SETFL, flags | O_NONBLOCK); 679 | 680 | if (!(ctx = driver_alloc(sizeof(nl_ctx_t)))) 681 | return ERL_DRV_ERROR_ERRNO; 682 | memset(ctx, 0, sizeof(nl_ctx_t)); 683 | ctx->port = port; 684 | ctx->dport = driver_mk_port(port); 685 | ctx->owner = driver_caller(port); 686 | ctx->protocol = protocol; 687 | ctx->fd = (ErlDrvEvent)((long)fd); 688 | 689 | nl_realloc_buffer(ctx, MIN_NL_BUFSIZE); // create i/o buffer 690 | 691 | #ifdef PORT_CONTROL_BINARY 692 | set_port_control_flags(port, PORT_CONTROL_FLAG_BINARY); 693 | #endif 694 | 695 | return (ErlDrvData) ctx; 696 | } 697 | 698 | DRIVER_INIT(nl_drv) 699 | { 700 | ErlDrvEntry* ptr = &nl_drv_entry; 701 | 702 | ptr->driver_name = "netlink_drv"; 703 | ptr->init = nl_drv_init; 704 | ptr->start = nl_drv_start; 705 | ptr->stop = nl_drv_stop; 706 | ptr->output = nl_drv_output; 707 | ptr->ready_input = nl_drv_ready_input; 708 | ptr->ready_output = nl_drv_ready_output; 709 | ptr->finish = nl_drv_finish; 710 | ptr->control = nl_drv_ctl; 711 | ptr->timeout = nl_drv_timeout; 712 | #if 0 713 | ptr->outputv = nl_drv_outputv; 714 | #endif 715 | ptr->ready_async = 0; 716 | ptr->flush = 0; 717 | ptr->call = 0; 718 | ptr->extended_marker = ERL_DRV_EXTENDED_MARKER; 719 | ptr->major_version = ERL_DRV_EXTENDED_MAJOR_VERSION; 720 | ptr->minor_version = ERL_DRV_EXTENDED_MINOR_VERSION; 721 | ptr->driver_flags = ERL_DRV_FLAG_USE_PORT_LOCKING; 722 | ptr->process_exit = 0; 723 | ptr->stop_select = nl_drv_stop_select; 724 | 725 | return (ErlDrvEntry*) ptr; 726 | } 727 | -------------------------------------------------------------------------------- /include/netlink.hrl: -------------------------------------------------------------------------------- 1 | 2 | -ifndef(__NETLINK_HRL__). 3 | -define(__NETLINK_HRL__, true). 4 | 5 | 6 | -record(rtnl_link_stats, { 7 | rx_packets, %% total packets received 8 | tx_packets, %% total packets transmitted 9 | rx_bytes, %% total bytes received 10 | tx_bytes, %% total bytes transmitted 11 | rx_errors, %% bad packets received 12 | tx_errors, %% packet transmit problems 13 | rx_dropped, %% no space in linux buffers 14 | tx_dropped, %% no space available in linux 15 | multicast, %% multicast packets received 16 | collisions, 17 | 18 | %% detailed rx_errors: 19 | rx_length_errors, 20 | rx_over_errors, %% receiver ring buff overflow 21 | rx_crc_errors, %% recved pkt with crc error 22 | rx_frame_errors, %% recv'd frame alignment error 23 | rx_fifo_errors, %% recv'r fifo overrun 24 | rx_missed_errors, %% receiver missed packet 25 | 26 | %% detailed tx_errors 27 | tx_aborted_errors, 28 | tx_carrier_errors, 29 | tx_fifo_errors, 30 | tx_heartbeat_errors, 31 | tx_window_errors, 32 | 33 | %% for cslip etc 34 | rx_compressed, 35 | tx_compressed 36 | }). 37 | 38 | -endif. 39 | -------------------------------------------------------------------------------- /priv/.gitignore: -------------------------------------------------------------------------------- 1 | *.so 2 | -------------------------------------------------------------------------------- /rebar.config: -------------------------------------------------------------------------------- 1 | %% -*- erlang -*- 2 | {deps, 3 | [ 4 | {hut, "1.3.0"} 5 | ]}. 6 | 7 | {erl_opts, [debug_info, fail_on_warning, nowarn_export_all]}. 8 | 9 | {pre_hooks, 10 | [ 11 | {"(linux)", compile, "make -C c_src OUTPUT_OPTION=\"-DDLOG_DEFAULT=DLOG_INFO\""} 12 | ]}. 13 | 14 | {post_hooks, 15 | [ 16 | {"(linux)", clean, "make -C c_src clean"} 17 | ]}. 18 | 19 | {xref_checks, 20 | [ 21 | undefined_function_calls, undefined_functions, locals_not_used, 22 | deprecated_function_calls, deprecated_functions 23 | ]}. 24 | -------------------------------------------------------------------------------- /rebar.lock: -------------------------------------------------------------------------------- 1 | {"1.1.0", 2 | [{<<"hut">>,{pkg,<<"hut">>,<<"1.3.0">>},0}]}. 3 | [ 4 | {pkg_hash,[ 5 | {<<"hut">>, <<"71F2F054E657C03F959CF1ACC43F436EA87580696528CA2A55C8AFB1B06C85E7">>}]} 6 | ]. 7 | -------------------------------------------------------------------------------- /src/.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | -------------------------------------------------------------------------------- /src/netl_codec.hrl: -------------------------------------------------------------------------------- 1 | -define(AF_ATMPVC, 8). 2 | -define(AF_ATMSVC, 20). 3 | -define(ARPHRD_CHAOS, 5). 4 | -define(ARPHRD_RAWHDLC, 518). 5 | -define(RTM_DELADDR, 21). 6 | -define(RTM_GETADDR, 22). 7 | -define(ARPHRD_IEEE802, 6). 8 | -define(AF_SNA, 22). 9 | -define(NLMSG_NOOP, 1). 10 | -define(PROTO_ICMP, 1). 11 | -define(PROTO_IGMP, 2). 12 | -define(PROTO_IPIP, 4). 13 | -define(PROTO_UDP, 17). 14 | -define(PROTO_IDP, 22). 15 | -define(PROTO_MTP, 92). 16 | -define(PROTO_COMP, 108). 17 | -define(ARPHRD_ETHER , 1). 18 | -define(ARPHRD_CISCO, 513). 19 | -define(IPCTNL_MSG_CT_GET_CTRZERO, 3). 20 | -define(AF_CAN, 29). 21 | -define(ARPHRD_CAN, 280). 22 | -define(AF_NETROM, 6). 23 | -define(ARPHRD_NETROM, 0). 24 | -define(ARPHRD_METRICOM, 23). 25 | -define(RTM_NEWNEIGHTBL, 64). 26 | -define(RTM_GETNEIGHTBL, 66). 27 | -define(RTM_SETNEIGHTBL, 67). 28 | -define(ARPHRD_TUNNEL, 768). 29 | -define(ARPHRD_FCPL, 786). 30 | -define(RTM_DELLINK, 17). 31 | -define(RTM_GETLINK, 18). 32 | -define(AF_APPLETALK, 5). 33 | -define(ARPHRD_APPLETLK, 8). 34 | -define(ARPHRD_LOOPBACK, 772). 35 | -define(AF_NETBEUI, 13). 36 | -define(ARPHRD_FDDI, 774). 37 | -define(RTM_NEWNEIGH, 28). 38 | -define(RTM_DELNEIGH, 29). 39 | -define(RTM_GETNEIGH, 30). 40 | -define(RTM_NEWPREFIX, 52). 41 | -define(AF_IPX, 4). 42 | -define(AF_ASH, 18). 43 | -define(AF_PPPOX, 24). 44 | -define(AF_BLUETOOTH, 31). 45 | -define(ARPHRD_ASH, 781). 46 | -define(PROTO_ROUTING, 43). 47 | -define(PROTO_RAW, 255). 48 | -define(ARPHRD_PIMREG, 779). 49 | -define(PROTO_IPV6, 41). 50 | -define(ARPHRD_SLIP6, 258). 51 | -define(ARPHRD_CSLIP6, 259). 52 | -define(ARPHRD_TUNNEL6, 769). 53 | -define(ARPHRD_BIF, 775). 54 | -define(RTM_GETROUTE, 26). 55 | -define(RTM_DELRULE, 33). 56 | -define(RTM_GETRULE, 34). 57 | -define(AF_AX25, 3). 58 | -define(AF_BRIDGE, 7). 59 | -define(AF_X25, 9). 60 | -define(AF_ROSE, 11). 61 | -define(AF_ROUTE, 16). 62 | -define(PROTO_GRE, 47). 63 | -define(PROTO_UDPLITE, 136). 64 | -define(ARPHRD_X25, 271). 65 | -define(ARPHRD_HWX25, 272). 66 | -define(ARPHRD_NONE, 65534). 67 | -define(RTM_GETMULTICAST, 58). 68 | -define(RTM_GETANYCAST, 62). 69 | -define(RTM_NEWNDUSEROPT, 68). 70 | -define(AF_IEEE802154, 36). 71 | -define(PROTO_FRAGMENT, 44). 72 | -define(ARPHRD_EUI64, 27). 73 | -define(ARPHRD_INFINIBAND, 32). 74 | -define(ARPHRD_ADAPT, 264). 75 | -define(RTM_NEWQDISC, 36). 76 | -define(RTM_DELQDISC, 37). 77 | -define(RTM_NEWTCLASS, 40). 78 | -define(RTM_DELTCLASS, 41). 79 | -define(RTM_GETTCLASS, 42). 80 | -define(AF_UNSPEC, 0). 81 | -define(AF_RDS, 21). 82 | -define(AF_RXRPC, 33). 83 | -define(PROTO_DSTOPTS, 60). 84 | -define(ARPHRD_HDLC, 513). 85 | -define(NLMSG_ERROR, 2). 86 | -define(RTM_NEWADDR, 20). 87 | -define(RTM_NEWTFILTER, 44). 88 | -define(ARPHRD_LAPB, 516). 89 | -define(ARPHRD_IEEE802_TR, 800). 90 | -define(ARPHRD_IRDA, 783). 91 | -define(ARPHRD_IEEE80211, 801). 92 | -define(PROTO_IP, 0). 93 | -define(PROTO_TCP, 6). 94 | -define(PROTO_EGP, 8). 95 | -define(PROTO_PUP, 12). 96 | -define(PROTO_RSVP, 46). 97 | -define(PROTO_ESP, 50). 98 | -define(PROTO_ENCAP, 98). 99 | -define(PROTO_SCTP, 132). 100 | -define(ARPHRD_SLIP, 256). 101 | -define(ARPHRD_PPP, 512). 102 | -define(ARPHRD_SKIP, 771). 103 | -define(ARPHRD_IPDDP, 777). 104 | -define(ARPHRD_IEEE80211_RADIOTAP, 803). 105 | -define(NLMSG_OVERRUN, 4). 106 | -define(RTM_NEWACTION, 48). 107 | -define(RTM_DELACTION, 49). 108 | -define(RTM_GETACTION, 50). 109 | -define(AF_ISDN, 34). 110 | -define(PROTO_PIM, 103). 111 | -define(ARPHRD_ATM, 19). 112 | -define(ARPHRD_IEEE80211_PRISM, 802). 113 | -define(RTM_NEWADDRLABEL, 72). 114 | -define(RTM_DELADDRLABEL, 73). 115 | -define(RTM_GETADDRLABEL, 74). 116 | -define(AF_LOCAL, 1). 117 | -define(ARPHRD_FCAL, 785). 118 | -define(RTM_NEWLINK, 16). 119 | -define(RTM_SETLINK, 19). 120 | -define(AF_NETLINK, 16). 121 | -define(ARPHRD_LOCALTLK, 773). 122 | -define(AF_SECURITY, 14). 123 | -define(AF_KEY, 15). 124 | -define(ARPHRD_DLCI, 15). 125 | -define(ARPHRD_HIPPI, 780). 126 | -define(AF_UNIX, 1). 127 | -define(PROTO_AH, 51). 128 | -define(IPCTNL_MSG_CT_NEW, 0). 129 | -define(IPCTNL_MSG_EXP_NEW, 0). 130 | -define(AF_INET6, 10). 131 | -define(AF_IUCV, 32). 132 | -define(PROTO_ICMPV6, 58). 133 | -define(ARPHRD_CAIF, 822). 134 | -define(NLMSG_DONE, 3). 135 | -define(RTM_NEWROUTE, 24). 136 | -define(RTM_DELROUTE, 25). 137 | -define(RTM_NEWRULE, 32). 138 | -define(AF_FILE, 1). 139 | -define(AF_WANPIPE, 25). 140 | -define(PROTO_NONE, 59). 141 | -define(ARPHRD_AX25, 3). 142 | -define(ARPHRD_ROSE, 270). 143 | -define(ARPHRD_IPGRE, 778). 144 | -define(ARPHRD_PHONET_PIPE, 821). 145 | -define(IPCTNL_MSG_CT_DELETE, 2). 146 | -define(IPCTNL_MSG_EXP_DELETE, 2). 147 | -define(AF_INET, 2). 148 | -define(AF_DECNET, 12). 149 | -define(AF_PACKET, 17). 150 | -define(AF_ECONET, 19). 151 | -define(AF_PHONET, 35). 152 | -define(ARPHRD_PRONET, 4). 153 | -define(ARPHRD_ARCNET, 7). 154 | -define(ARPHRD_IEEE1394, 24). 155 | -define(ARPHRD_RSRVD, 260). 156 | -define(ARPHRD_FRAD, 770). 157 | -define(ARPHRD_SIT, 776). 158 | -define(ARPHRD_ECONET, 782). 159 | -define(ARPHRD_IEEE802154, 804). 160 | -define(ARPHRD_PHONET, 820). 161 | -define(ARPHRD_VOID, 65535). 162 | -define(IPCTNL_MSG_CT_GET, 1). 163 | -define(IPCTNL_MSG_EXP_GET, 1). 164 | -define(RTM_GETQDISC, 38). 165 | -define(AF_LLC, 26). 166 | -define(AF_TIPC, 30). 167 | -define(ARPHRD_FCFABRIC, 787). 168 | -define(RTM_DELTFILTER, 45). 169 | -define(RTM_GETTFILTER, 46). 170 | -define(RTM_GETDCB, 78). 171 | -define(RTM_SETDCB, 79). 172 | -define(ARPHRD_EETHER, 2). 173 | -define(AF_IRDA, 23). 174 | -define(PROTO_TP, 29). 175 | -define(PROTO_DCCP, 33). 176 | -define(ARPHRD_CSLIP, 257). 177 | -define(ARPHRD_DDCMP, 517). 178 | -define(ARPHRD_FCPP, 784). 179 | -record(overrun, {status}). 180 | -record(newlink, {family,arphrd,index,flags,change,attributes}). 181 | -record(dellink, {family,arphrd,index,flags,change,attributes}). 182 | -record(getlink, {family,arphrd,index,flags,change,attributes}). 183 | -record(newneigh, {family,index,state,flags,nmd_type,attributes}). 184 | -record(delneigh, {family,index,state,flags,nmd_type,attributes}). 185 | -record(getneigh, {family,index,state,flags,nmd_type,attributes}). 186 | -record(ifaddrmsg, {family,prefixlen,flags,scope,index,attributes}). 187 | -record(ifinfomsg, {family,arphrd,index,flags,change,attributes}). 188 | -record(rtmsg, {family,dstlen,srclen,tos,table,protocol,scope,rtm_type,flags,attributes}). 189 | -record(ndmsg, {family,index,state,flags,nmd_type,attributes}). 190 | -record(newroute, {family,dstlen,srclen,tos,table,protocol,scope,rtm_type,flags,attributes}). 191 | -record(delroute, {family,dstlen,srclen,tos,table,protocol,scope,rtm_type,flags,attributes}). 192 | -record(getroute, {family,dstlen,srclen,tos,table,protocol,scope,rtm_type,flags,attributes}). 193 | -record(done, {status}). 194 | -record(nlmsghdr, {len,type,flags,seq,pid}). 195 | -record(newaddr, {family,prefixlen,flags,scope,index,attributes}). 196 | -record(deladdr, {family,prefixlen,flags,scope,index,attributes}). 197 | -record(getaddr, {family,prefixlen,flags,scope,index,attributes}). 198 | -record(error, {errno,msg,data}). 199 | -record(if_map, {memstart,memend,baseaddr,irq,dma,port}). 200 | -record(noop, {}). 201 | -------------------------------------------------------------------------------- /src/netlink.app.src: -------------------------------------------------------------------------------- 1 | %% -*- erlang -*- 2 | {application, netlink, 3 | [ 4 | {description, "Netlink socket implementation."}, 5 | {vsn, "1.1.0"}, 6 | {registered, []}, 7 | {applications, 8 | [ 9 | kernel, 10 | stdlib, 11 | hut 12 | ]}, 13 | {included_applications, 14 | [ 15 | ]}, 16 | {mod, {netlink_app, []}}, 17 | {env, []}, 18 | {maintainers, ["Tony Rogvall", "Ulf Wiger", "Tino Breddin"]}, 19 | {licenses, ["MPL-2.0"]}, 20 | {links, [{"Github", "https://github.com/Feuerlabs/netlink"}]} 21 | ]}. 22 | -------------------------------------------------------------------------------- /src/netlink.erl: -------------------------------------------------------------------------------- 1 | %%%---- BEGIN COPYRIGHT ------------------------------------------------------- 2 | %%% 3 | %%% Copyright (C) 2012 Feuerlabs, Inc. All rights reserved. 4 | %%% 5 | %%% This Source Code Form is subject to the terms of the Mozilla Public 6 | %%% License, v. 2.0. If a copy of the MPL was not distributed with this 7 | %%% file, You can obtain one at http://mozilla.org/MPL/2.0/. 8 | %%% 9 | %%%---- END COPYRIGHT --------------------------------------------------------- 10 | %%%------------------------------------------------------------------- 11 | %%% @author Tony Rogvall 12 | %%% @doc 13 | %%% Netlink state monitor 14 | %%% @end 15 | %%% Created : 11 Jun 2012 by Tony Rogvall 16 | %%%------------------------------------------------------------------- 17 | -module(netlink). 18 | 19 | -behaviour(gen_server). 20 | 21 | %% API 22 | -export([start_link/0, start_link/1]). 23 | -export([start/0, stop/0]). 24 | 25 | %% gen_server callbacks 26 | -export([init/1, handle_call/3, handle_cast/2, handle_info/2, 27 | terminate/2, code_change/3]). 28 | -export([i/0, list/1]). 29 | -export([subscribe/1, subscribe/2, subscribe/3]). 30 | -export([unsubscribe/1]). 31 | -export([invalidate/2]). 32 | -export([get_root/2, get_match/3, get/4]). 33 | 34 | -include_lib("hut/include/hut.hrl"). 35 | 36 | -include("netlink.hrl"). 37 | -include("netl_codec.hrl"). 38 | 39 | -define(SERVER, ?MODULE). 40 | 41 | -type if_addr_field() :: address | local | broadcast | anycast | multicast. 42 | 43 | -type if_link_field() :: name | index | mtu | txqlen | flags | 44 | operstate | qdisc | address | broadcast. 45 | 46 | -type uint8_t() :: 0..16#ff. 47 | -type uint16_t() :: 0..16#ffff. 48 | 49 | -type ipv4_addr() :: {uint8_t(),uint8_t(),uint8_t(),uint8_t()}. 50 | -type ipv6_addr() :: {uint16_t(),uint16_t(),uint16_t(),uint16_t(), 51 | uint16_t(),uint16_t(),uint16_t(),uint16_t()}. 52 | 53 | -type if_addr() :: ipv4_addr() | ipv6_addr(). 54 | 55 | -type if_field() :: if_link_field() | if_addr_field() | 56 | {link,if_link_field()} | {addr,if_addr_field()}. 57 | 58 | -type if_name() :: string(). 59 | 60 | 61 | -record(link, 62 | { 63 | name :: if_name(), %% interface name 64 | index :: non_neg_integer(), %% interface index 65 | attr :: term() %% attributes {atom(),term} 66 | }). 67 | 68 | -record(addr, 69 | { 70 | addr :: if_addr(), %% the address 71 | name :: if_name(), %% interface label 72 | index :: non_neg_integer(), %% interface index 73 | attr :: term() %% attributes 74 | }). 75 | 76 | -record(subscription, 77 | { 78 | pid :: pid(), %% subscriber 79 | mon :: reference(), %% monitor 80 | name :: string(), %% name 81 | fields=all :: all | addr | link | [if_field()] 82 | }). 83 | 84 | -define(MIN_RCVBUF, (128*1024)). 85 | -define(MIN_SNDBUF, (32*1024)). 86 | 87 | -define(REQUEST_TMO, 2000). 88 | 89 | -record(request, 90 | { 91 | tmr, %% timer reference 92 | call, %% call request 93 | from, %% caller 94 | reply=ok, %% reply to send when done 95 | seq=0 %% sequence to expect in reply 96 | }). 97 | 98 | -record(state, 99 | { 100 | port, 101 | link_list = [] :: [#link {}], 102 | addr_list = [] :: [#addr {}], 103 | sub_list = [] :: [#subscription {}], 104 | request :: undefined | #request{}, 105 | request_queue = [] :: [#request{}], 106 | o_seq = 0, 107 | i_seq = 0, 108 | ospid 109 | }). 110 | 111 | %%%=================================================================== 112 | %%% API 113 | %%%=================================================================== 114 | 115 | start() -> 116 | application:start(netlink). 117 | 118 | i() -> 119 | gen_server:call(?SERVER, {list,[]}). 120 | 121 | stop() -> 122 | gen_server:call(?SERVER, stop). 123 | 124 | list(Match) -> 125 | gen_server:call(?SERVER, {list,Match}). 126 | 127 | %% @doc 128 | %% Subscribe to interface changes, notifications will be 129 | %% sent in {netlink,reference(),if_name(),if_field(),OldValue,NewValue} 130 | %% @end 131 | 132 | -spec subscribe(Name::string()) -> 133 | {ok,reference()}. 134 | 135 | subscribe(Name) -> 136 | subscribe(Name,all,[]). 137 | 138 | -spec subscribe(Name::string(),Fields::all|[if_field()]) -> 139 | {ok,reference()}. 140 | 141 | subscribe(Name,Fields) -> 142 | subscribe(Name,Fields, []). 143 | 144 | -spec subscribe(Name::string(),Fields::all|[if_field()],Otions::[atom()]) -> 145 | {ok,reference()}. 146 | subscribe(Name,Fields,Options) -> 147 | gen_server:call(?SERVER, {subscribe, self(),Name,Options,Fields}). 148 | 149 | unsubscribe(Ref) -> 150 | gen_server:call(?SERVER, {unsubscribe,Ref}). 151 | 152 | %% clear all attributes for interface Name 153 | invalidate(Name,Fields) -> 154 | gen_server:call(?SERVER, {invalidate,Name,Fields}). 155 | 156 | get_root(What,Fam) -> 157 | get(What,Fam,[root,match,request],[]). 158 | 159 | get_match(What,Fam,GetAttrs) -> 160 | get(What,Fam,[match,request],GetAttrs). 161 | 162 | get(What,Fam,GetFlags,GetAttrs) -> 163 | gen_server:call(?SERVER, {get,What,Fam,GetFlags,GetAttrs}). 164 | 165 | %%-------------------------------------------------------------------- 166 | %% @doc 167 | %% Starts the server 168 | %% 169 | %% @spec start_link() -> {ok, Pid} | ignore | {error, Error} 170 | %% @end 171 | %%-------------------------------------------------------------------- 172 | start_link() -> 173 | start_link([]). 174 | start_link(Opts) -> 175 | gen_server:start_link({local, ?SERVER}, ?MODULE, [Opts], []). 176 | 177 | %%%=================================================================== 178 | %%% gen_server callbacks 179 | %%%=================================================================== 180 | 181 | %%-------------------------------------------------------------------- 182 | %% @private 183 | %% @doc 184 | %% Initializes the server 185 | %% 186 | %% @spec init(Args) -> {ok, State} | 187 | %% {ok, State, Timeout} | 188 | %% ignore | 189 | %% {stop, Reason} 190 | %% @end 191 | %%-------------------------------------------------------------------- 192 | init([Opts]) -> 193 | OsPid = list_to_integer(os:getpid()), 194 | I_Seq = O_Seq = 1234, %% element(2,now()), 195 | State = #state{ ospid = OsPid, 196 | o_seq = O_Seq, 197 | i_seq = I_Seq }, 198 | 199 | case os:type() of 200 | {unix, linux} -> 201 | init_drv(Opts, State); 202 | _ -> 203 | {ok, State} 204 | end. 205 | 206 | init_drv(Opts, State) -> 207 | Port = netlink_drv:open(?NETLINK_ROUTE), 208 | 209 | netlink_drv:debug(Port, proplists:get_value(debug,Opts,none)), 210 | 211 | {ok,Rcvbuf} = update_rcvbuf(Port, ?MIN_RCVBUF), 212 | {ok,Sndbuf} = update_sndbuf(Port, ?MIN_SNDBUF), 213 | 214 | ?log(info, "Rcvbuf: ~w, Sndbuf: ~w", [Rcvbuf, Sndbuf]), 215 | 216 | {ok,Sizes} = netlink_drv:get_sizeof(Port), 217 | ?log(info, "Sizes: ~w", [Sizes]), 218 | 219 | ok = netlink_drv:add_membership(Port, ?RTNLGRP_LINK), 220 | ok = netlink_drv:add_membership(Port, ?RTNLGRP_IPV4_IFADDR), 221 | ok = netlink_drv:add_membership(Port, ?RTNLGRP_IPV6_IFADDR), 222 | 223 | netlink_drv:activate(Port), 224 | %% init sequence to fill the cache 225 | T0 = erlang:start_timer(200, self(), request_timeout), 226 | R0 = #request { tmr = T0, 227 | call = noop, 228 | from = {self(),make_ref()} 229 | }, 230 | R1 = #request { tmr = {relative, ?REQUEST_TMO}, 231 | call = {get,link,unspec, 232 | [root,match,request], 233 | []}, 234 | from = {self(),make_ref()} 235 | }, 236 | R2 = #request { tmr = {relative, 1000}, 237 | call = noop, 238 | from = {self(),make_ref()} 239 | }, 240 | R3 = #request { tmr = {relative,?REQUEST_TMO}, 241 | call = {get,addr,unspec, 242 | [root,match,request], 243 | []}, 244 | from = {self(),make_ref()} 245 | }, 246 | {ok, State#state{ port=Port, 247 | request = R0, 248 | request_queue = [R1,R2,R3] 249 | }}. 250 | 251 | %%-------------------------------------------------------------------- 252 | %% @private 253 | %% @doc 254 | %% Handling call messages 255 | %% 256 | %% @spec handle_call(Request, From, State) -> 257 | %% {reply, Reply, State} | 258 | %% {reply, Reply, State, Timeout} | 259 | %% {noreply, State} | 260 | %% {noreply, State, Timeout} | 261 | %% {stop, Reason, Reply, State} | 262 | %% {stop, Reason, State} 263 | %% @end 264 | %%-------------------------------------------------------------------- 265 | handle_call({list,Match}, _From, State) -> 266 | lists:foreach( 267 | fun(L) -> 268 | %% select addresses that belong to link L 269 | Ys = [Y || Y <- State#state.addr_list, 270 | Y#addr.index =:= L#link.index], 271 | FYs = [format_addr(Y) || Y <- Ys ], 272 | case match(L#link.attr,dict:new(),Match) of 273 | true -> 274 | io:format("link {~s~s}\n", 275 | [FYs,format_link(L)]); 276 | false -> 277 | ok 278 | end 279 | end, State#state.link_list), 280 | {reply, ok, State}; 281 | handle_call({subscribe, Pid, Name, Options, Fs}, _From, State) -> 282 | Mon = erlang:monitor(process, Pid), 283 | S = #subscription { pid=Pid, mon=Mon, name=Name, fields=Fs }, 284 | SList = [S | State#state.sub_list], 285 | case proplists:get_bool(flush, Options) of 286 | false -> 287 | {reply, {ok,Mon}, State#state { sub_list = SList }}; 288 | true -> 289 | lists:foreach( 290 | fun(L) -> 291 | As = dict:to_list(L#link.attr), 292 | update_attrs(L#link.name, link, As, dict:new(), [S]) 293 | end, State#state.link_list), 294 | lists:foreach( 295 | fun(Y) -> 296 | As = dict:to_list(Y#addr.attr), 297 | update_attrs(Y#addr.name, addr, As, dict:new(), [S]) 298 | end, State#state.addr_list), 299 | {reply, {ok,Mon}, State#state { sub_list = SList }} 300 | end; 301 | handle_call({unsubscribe,Ref}, _From, State) -> 302 | case lists:keytake(Ref, #subscription.mon, State#state.sub_list) of 303 | false -> 304 | {reply,ok,State}; 305 | {value,_S,SubList} -> 306 | erlang:demonitor(Ref), 307 | {reply,ok,State#state { sub_list=SubList }} 308 | end; 309 | handle_call({invalidate,Name,Fields},_From,State) -> 310 | case lists:keytake(Name, #link.name, State#state.link_list) of 311 | false -> {reply, {error,enoent}, State}; 312 | {value,L,Ls} -> 313 | Attr = lists:foldl( 314 | fun(F,D) when is_atom(F) -> 315 | dict:erase(F, D) 316 | end, L#link.attr, Fields), 317 | L1 = L#link { attr = Attr }, 318 | {reply, ok, State#state { link_list = [L1|Ls] } } 319 | end; 320 | 321 | handle_call(Req={get,_What,_Fam,_Flags,_Attrs}, From, State) -> 322 | ?log(debug, "handle_call: GET: ~p", [Req]), 323 | State1 = enq_request(Req, From, State), 324 | State2 = dispatch_command(State1), 325 | {noreply, State2}; 326 | handle_call(stop, _From, State) -> 327 | {stop, normal, ok, State}; 328 | handle_call(_Request, _From, State) -> 329 | Reply = ok, 330 | {reply, Reply, State}. 331 | 332 | %%-------------------------------------------------------------------- 333 | %% @private 334 | %% @doc 335 | %% Handling cast messages 336 | %% 337 | %% @spec handle_cast(Msg, State) -> {noreply, State} | 338 | %% {noreply, State, Timeout} | 339 | %% {stop, Reason, State} 340 | %% @end 341 | %%-------------------------------------------------------------------- 342 | handle_cast(_Msg, State) -> 343 | {noreply, State}. 344 | 345 | %%-------------------------------------------------------------------- 346 | %% @private 347 | %% @doc 348 | %% Handling all non call/cast messages 349 | %% 350 | %% @spec handle_info(Info, State) -> {noreply, State} | 351 | %% {noreply, State, Timeout} | 352 | %% {stop, Reason, State} 353 | %% @end 354 | %%-------------------------------------------------------------------- 355 | 356 | handle_info(_Info={nl_data,Port,Data},State) when Port =:= State#state.port -> 357 | try netlink_codec:decode(Data,[]) of 358 | MsgList -> 359 | %% FIXME: the messages should be delivered one by one from 360 | %% the driver so the decoding could simplified. 361 | State1 = 362 | lists:foldl( 363 | fun(Msg,StateI) -> 364 | ?log(debug, "handle_info: msg=~p", [Msg]), 365 | _Hdr = Msg#nlmsg.hdr, 366 | MsgData = Msg#nlmsg.data, 367 | handle_nlmsg(MsgData, StateI) 368 | end, State, MsgList), 369 | {noreply, State1} 370 | catch 371 | ?EXCEPTION(error, _Reason, Stacktrace) -> 372 | ?log(error, "netlink: handle_info: Crash: ~p", 373 | [?GET_STACK(Stacktrace)]), 374 | {noreply, State} 375 | end; 376 | 377 | handle_info({'DOWN',Ref,process,Pid,Reason}, State) -> 378 | case lists:keytake(Ref, #subscription.mon, State#state.sub_list) of 379 | false -> 380 | {noreply,State}; 381 | {value,_S,SubList} -> 382 | ?log(debug, "subscription from pid ~p deleted reason=~p", 383 | [Pid, Reason]), 384 | {noreply,State#state { sub_list=SubList }} 385 | end; 386 | handle_info({timeout,Tmr,request_timeout}, State) -> 387 | R = State#state.request, 388 | if R#request.tmr =:= Tmr -> 389 | ?log(debug, "Timeout: ref current", []), 390 | gen_server:reply(R#request.from, {error,timeout}), 391 | State1 = State#state { request = undefined }, 392 | {noreply, dispatch_command(State1)}; 393 | true -> 394 | case lists:keytake(Tmr, #request.tmr, State#state.request_queue) of 395 | false -> 396 | ?log(debug, "Timeout: ref not found", []), 397 | {noreply, State}; 398 | {value,#request { from = From},Q} -> 399 | ?log(debug, "Timeout: ref in queue", []), 400 | gen_server:reply(From, {error,timeout}), 401 | State1 = State#state { request_queue = Q }, 402 | {noreply,dispatch_command(State1)} 403 | end 404 | end; 405 | handle_info({Tag, Reply}, State) when is_reference(Tag) -> 406 | ?log(debug, "INFO: SELF Reply=~p", [Reply]), 407 | {noreply, State}; 408 | handle_info(_Info, State) -> 409 | ?log(debug, "INFO: ~p", [_Info]), 410 | {noreply, State}. 411 | 412 | %%-------------------------------------------------------------------- 413 | %% @private 414 | %% @doc 415 | %% This function is called by a gen_server when it is about to 416 | %% terminate. It should be the opposite of Module:init/1 and do any 417 | %% necessary cleaning up. When it returns, the gen_server terminates 418 | %% with Reason. The return value is ignored. 419 | %% 420 | %% @spec terminate(Reason, State) -> void() 421 | %% @end 422 | %%-------------------------------------------------------------------- 423 | terminate(_Reason, _State) -> 424 | ok. 425 | 426 | %%-------------------------------------------------------------------- 427 | %% @private 428 | %% @doc 429 | %% Convert process state when code is changed 430 | %% 431 | %% @spec code_change(OldVsn, State, Extra) -> {ok, NewState} 432 | %% @end 433 | %%-------------------------------------------------------------------- 434 | code_change(_OldVsn, State, _Extra) -> 435 | {ok, State}. 436 | 437 | %%%=================================================================== 438 | %%% Internal functions 439 | %%%=================================================================== 440 | 441 | enq_request(Call, From, State) -> 442 | Tmr = erlang:start_timer(?REQUEST_TMO, self(), request_timeout), 443 | R = #request { tmr = Tmr, 444 | call = Call, 445 | from = From 446 | }, 447 | Q = State#state.request_queue ++ [R], 448 | State#state { request_queue = Q }. 449 | 450 | dispatch_command(State) when State#state.request =:= undefined -> 451 | case State#state.request_queue of 452 | [R=#request { call = {get,What,Fam,Flags,Attrs} } | Q ] -> 453 | R1 = update_timer(R), 454 | State1 = State#state { request_queue = Q, request = R1 }, 455 | ?log(debug, "dispatch_command: ~p", [R1]), 456 | get_command(What,Fam,Flags,Attrs,State1); 457 | [R=#request { call = noop } | Q ] -> 458 | R1 = update_timer(R), 459 | State1 = State#state { request_queue = Q, request = R1 }, 460 | ?log(debug, "dispatch_command: ~p", [R1]), 461 | State1; %% let it timeout 462 | [] -> 463 | State 464 | end; 465 | dispatch_command(State) -> 466 | State. 467 | 468 | update_timer(R = #request { tmr = {relative,Tmo} }) 469 | when is_integer(Tmo), Tmo >= 0 -> 470 | Tmr = erlang:start_timer(Tmo, self(), request_timeout), 471 | R#request { tmr = Tmr }; 472 | update_timer(R = #request { tmr = Tmr }) when is_reference(Tmr) -> 473 | R. 474 | 475 | update_sndbuf(Port, Min) -> 476 | case netlink_drv:get_sndbuf(Port) of 477 | {ok,Size} when Size >= Min -> 478 | {ok,Size}; 479 | {ok,_Size} -> 480 | netlink_drv:set_sndbuf(Port, Min), 481 | netlink_drv:get_sndbuf(Port); 482 | Err -> Err 483 | end. 484 | 485 | 486 | update_rcvbuf(Port, Min) -> 487 | case netlink_drv:get_rcvbuf(Port) of 488 | {ok,Size} when Size >= Min -> 489 | {ok,Size}; 490 | {ok,_Size} -> 491 | netlink_drv:set_rcvbuf(Port, Min), 492 | netlink_drv:get_rcvbuf(Port); 493 | Err -> Err 494 | end. 495 | 496 | get_command(link,Fam,Flags,Attrs,State) -> 497 | Seq = State#state.o_seq, 498 | Get = #getlink{family=Fam,arphrd=ether,index=0, 499 | flags=[], change=[], attributes=Attrs}, 500 | Hdr = #nlmsghdr { type = getlink, 501 | flags = Flags, 502 | seq = Seq, 503 | pid = State#state.ospid }, 504 | Request = netlink_codec:encode(Hdr,Get), 505 | netlink_drv:send(State#state.port, Request), 506 | State#state { o_seq = (Seq+1) band 16#ffffffff }; 507 | get_command(addr,Fam,Flags,Attrs,State) -> 508 | Seq = State#state.o_seq, 509 | Get = #getaddr{family=Fam,prefixlen=0,flags=[],scope=0, 510 | index=0,attributes=Attrs}, 511 | Hdr = #nlmsghdr { type=getaddr, 512 | flags=Flags, 513 | seq=Seq, 514 | pid=State#state.ospid }, 515 | Request = netlink_codec:encode(Hdr,Get), 516 | netlink_drv:send(State#state.port, Request), 517 | State#state { o_seq = (Seq+1) band 16#ffffffff}. 518 | 519 | handle_nlmsg(RTM=#newlink{family=_Fam,index=Index,flags=Fs,change=Cs, 520 | attributes=As}, State) -> 521 | ?log(debug, "RTM = ~p", [RTM]), 522 | Name = proplists:get_value(ifname, As, ""), 523 | As1 = [{index,Index},{flags,Fs},{change,Cs}|As], 524 | case lists:keytake(Index, #link.index, State#state.link_list) of 525 | false -> 526 | Attr = update_attrs(Name, link, As1, dict:new(), State#state.sub_list), 527 | L = #link { index = Index, name = Name, attr = Attr }, 528 | Ls = [L|State#state.link_list], 529 | State#state { link_list = Ls }; 530 | {value,L,Ls} -> 531 | Attr = update_attrs(Name, link, As1, L#link.attr, State#state.sub_list), 532 | L1 = L#link { name = Name, attr = Attr }, 533 | State#state { link_list = [L1|Ls] } 534 | end; 535 | handle_nlmsg(RTM=#dellink{family=_Fam,index=Index,flags=_Fs,change=_Cs, 536 | attributes=As}, State) -> 537 | ?log(debug, "RTM = ~p\n", [RTM]), 538 | Name = proplists:get_value(ifname, As, ""), 539 | %% does this delete the link? 540 | case lists:keytake(Index, #link.index, State#state.link_list) of 541 | false -> 542 | ?log(warning, "Warning link index=~w not found", [Index]), 543 | State; 544 | {value,L,Ls} -> 545 | As1 = dict:to_list(L#link.attr), 546 | update_attrs(Name, link, As1, undefined, State#state.sub_list), 547 | State#state { link_list = Ls } 548 | end; 549 | handle_nlmsg(RTM=#newaddr { family=Fam, prefixlen=Prefixlen, 550 | flags=Flags, scope=Scope, 551 | index=Index, attributes=As }, 552 | State) -> 553 | ?log(debug, "RTM = ~p", [RTM]), 554 | Addr = proplists:get_value(address, As, {}), 555 | Name = proplists:get_value(label, As, ""), 556 | As1 = [{family,Fam},{prefixlen,Prefixlen},{flags,Flags}, 557 | {scope,Scope},{index,Index} | As], 558 | case lists:keymember(Index, #link.index, State#state.link_list) of 559 | false -> 560 | ?log(warning, "link index ~p does not exist", [Index]); 561 | true -> 562 | ok 563 | end, 564 | case lists:keytake(Addr, #addr.addr, State#state.addr_list) of 565 | false -> 566 | Attrs = update_attrs(Name,addr,As1,dict:new(),State#state.sub_list), 567 | Y = #addr { addr=Addr, name = Name, index=Index, attr=Attrs }, 568 | Ys = [Y|State#state.addr_list], 569 | State#state { addr_list = Ys }; 570 | {value,Y,Ys} -> 571 | Attr = update_attrs(Name,addr,As1,Y#addr.attr,State#state.sub_list), 572 | Y1 = Y#addr { index=Index, name=Name, attr = Attr }, 573 | State#state { addr_list = [Y1|Ys] } 574 | end; 575 | 576 | handle_nlmsg(RTM=#deladdr { family=_Fam, index=_Index, attributes=As }, 577 | State) -> 578 | ?log(debug, "RTM = ~p", [RTM]), 579 | Addr = proplists:get_value(address, As, {}), 580 | Name = proplists:get_value(label, As, ""), 581 | case lists:keytake(Addr, #addr.addr, State#state.addr_list) of 582 | false -> 583 | ?log(warning, "Warning addr=~w not found", [Addr]), 584 | State; 585 | {value,Y,Ys} -> 586 | As1 = dict:to_list(Y#addr.attr), 587 | update_attrs(Name, addr, As1, undefined, State#state.sub_list), 588 | State#state { addr_list = Ys } 589 | end; 590 | handle_nlmsg(#done { }, State) -> 591 | case State#state.request of 592 | undefined -> 593 | dispatch_command(State); 594 | #request { tmr = Tmr, from = From, reply = Reply } -> 595 | ?log(debug, "handle_nlmsg: DONE: ~p", 596 | [State#state.request]), 597 | erlang:cancel_timer(Tmr), 598 | gen_server:reply(From, Reply), 599 | State1 = State#state { request = undefined }, 600 | dispatch_command(State1) 601 | end; 602 | handle_nlmsg(Err=#error { errno=Err }, State) -> 603 | ?log(debug, "handle_nlmsg: ERROR: ~p", [State#state.request]), 604 | case State#state.request of 605 | undefined -> 606 | dispatch_command(State); 607 | #request { tmr = Tmr, from = From } -> 608 | ?log(debug, "handle_nlmsg: DONE: ~p", 609 | [State#state.request]), 610 | erlang:cancel_timer(Tmr), 611 | %% fixme: convert errno to posix error (netlink.inc?) 612 | gen_server:reply(From, {error,Err}), 613 | State1 = State#state { request = undefined }, 614 | dispatch_command(State1) 615 | end; 616 | 617 | handle_nlmsg(RTM, State) -> 618 | ?log(debug, "netlink: handle_nlmsg, ignore ~p", [RTM]), 619 | State. 620 | 621 | %% update attributes form interface "Name" 622 | %% From to To Type is either link | addr 623 | update_attrs(Name,Type,As,undefined,Subs) -> 624 | lists:foreach( 625 | fun({K,Vold}) -> 626 | send_event(Name,Type,K,Vold,undefined,Subs) 627 | end, As), 628 | undefined; 629 | update_attrs(Name,Type,As,To,Subs) -> 630 | lists:foldl( 631 | fun({K,Vnew},D) -> 632 | case dict:find(K,D) of 633 | error -> 634 | send_event(Name,Type,K,undefined,Vnew,Subs), 635 | dict:store(K,Vnew,D); 636 | {ok,Vnew} -> D; %% already exist 637 | {ok,Vold} -> 638 | send_event(Name,Type,K,Vold,Vnew,Subs), 639 | dict:store(K,Vnew,D) 640 | end 641 | end, To, As). 642 | 643 | 644 | send_event(Name,Type,Field,Old,New,[S|SList]) when 645 | S#subscription.name =:= Name; S#subscription.name =:= "" -> 646 | case S#subscription.fields =:= all orelse 647 | S#subscription.fields =:= Type orelse 648 | lists:member(Field,S#subscription.fields) orelse 649 | lists:member({Type,Field},S#subscription.fields) of 650 | true -> 651 | S#subscription.pid ! {netlink,S#subscription.mon, 652 | Name,Field,Old,New}, 653 | send_event(Name,Type,Field,Old,New,SList); 654 | false -> 655 | send_event(Name,Type,Field,Old,New,SList) 656 | end; 657 | send_event(Name,Type,Field,Old,New,[_|SList]) -> 658 | send_event(Name,Type,Field,Old,New,SList); 659 | send_event(_Name,_Type,_Field,_Old,_New,[]) -> 660 | ok. 661 | 662 | 663 | match(Y,L,[{Field,Value}|Match]) when is_atom(Field) -> 664 | case find2(Field,Y,L) of 665 | {ok,Value} -> match(Y, L, Match); 666 | _ -> false 667 | end; 668 | match(Y,L,[{Op,Field,Value}|Match]) when is_atom(Op),is_atom(Field) -> 669 | case find2(Y,L,Field) of 670 | {ok,FValue} -> 671 | case compare(Op,FValue,Value) of 672 | true -> match(Y,L,Match); 673 | false -> false 674 | end; 675 | error -> 676 | false 677 | end; 678 | match(_Y, _L, []) -> 679 | true. 680 | 681 | find2(Key,D1,D2) -> 682 | case dict:find(Key,D1) of 683 | error -> 684 | dict:find(Key,D2); 685 | Res -> Res 686 | end. 687 | 688 | 689 | format_link(L) -> 690 | dict:fold( 691 | fun(af_spec,_V,A) -> A; 692 | (map,_V,A) -> A; 693 | (stats,_V,A) -> A; 694 | (stats64,_V,A) -> A; 695 | (change,_V,A) -> A; 696 | (K,V,A) -> 697 | [["\n ",name_to_list(K), " ",value_to_list(K,V),";"]|A] 698 | end, [], L#link.attr). 699 | 700 | format_addr(Y) -> 701 | ["\n", " addr {", 702 | dict:fold( 703 | fun(cacheinfo,_V,A) -> A; 704 | (K,V,A) -> 705 | [[" ",name_to_list(K), " ",value_to_list(K,V),";"]|A] 706 | end, [], Y#addr.attr), "}"]. 707 | 708 | name_to_list(K) when is_atom(K) -> 709 | atom_to_list(K); 710 | name_to_list(K) when is_integer(K) -> 711 | integer_to_list(K). 712 | 713 | 714 | value_to_list(local,V) -> format_a(V); 715 | value_to_list(address,V) -> format_a(V); 716 | value_to_list(broadcast,V) -> format_a(V); 717 | value_to_list(multicast,V) -> format_a(V); 718 | value_to_list(anycast,V) -> format_a(V); 719 | value_to_list(_, V) -> io_lib:format("~p", [V]). 720 | 721 | format_a(undefined) -> ""; 722 | format_a(A) when is_tuple(A), tuple_size(A) =:= 6 -> 723 | io_lib:format("~2.16.0b:~2.16.0b:~2.16.0b:~2.16.0b:~2.16.0b:~2.16.0b", 724 | tuple_to_list(A)); 725 | format_a(A) when is_tuple(A), tuple_size(A) =:= 4 -> 726 | inet_parse:ntoa(A); 727 | format_a(A) when is_tuple(A), tuple_size(A) =:= 8 -> 728 | inet_parse:ntoa(A). 729 | 730 | compare('==',A,B) -> A == B; 731 | compare('=:=',A,B) -> A =:= B; 732 | compare('<' ,A,B) -> A < B; 733 | compare('=<' ,A,B) -> A =< B; 734 | compare('>' ,A,B) -> A > B; 735 | compare('>=' ,A,B) -> A >= B; 736 | compare('/=' ,A,B) -> A /= B; 737 | compare('=/=' ,A,B) -> A =/= B; 738 | compare(_,_,_) -> false. 739 | -------------------------------------------------------------------------------- /src/netlink.hrl: -------------------------------------------------------------------------------- 1 | 2 | %% netlink protocols 3 | -define(NETLINK_ROUTE, 0). %% Routing/device hook 4 | -define(NETLINK_UNUSED, 1). %% Unused number 5 | -define(NETLINK_USERSOCK, 2). %% Reserved for user mode socket protocols 6 | -define(NETLINK_FIREWALL, 3). %% Unused number, formerly ip_queue 7 | -define(NETLINK_SOCK_DIAG, 4). %% socket monitoring 8 | -define(NETLINK_NFLOG, 5). %% netfilter/iptables ULOG */ 9 | -define(NETLINK_XFRM, 6). %% ipsec */ 10 | -define(NETLINK_SELINUX, 7). %% SELinux event notifications */ 11 | -define(NETLINK_ISCSI, 8). %% Open-iSCSI */ 12 | -define(NETLINK_AUDIT, 9). %% auditing */ 13 | -define(NETLINK_FIB_LOOKUP, 10). 14 | -define(NETLINK_CONNECTOR, 11). 15 | -define(NETLINK_NETFILTER, 12). %% netfilter subsystem 16 | -define(NETLINK_IP6_FW, 13). 17 | -define(NETLINK_DNRTMSG, 14). %% DECnet routing messages 18 | -define(NETLINK_KOBJECT_UEVENT, 15). %% Kernel messages to userspace 19 | -define(NETLINK_GENERIC, 16). 20 | %% leave room for NETLINK_DM (DM Events) 21 | -define(NETLINK_SCSITRANSPORT, 18). %% SCSI Transports 22 | -define(NETLINK_ECRYPTFS, 19). 23 | -define(NETLINK_RDMA, 20). 24 | -define(NETLINK_CRYPTO, 21). %% Crypto layer */ 25 | -define(NETLINK_INET_DIAG, ?NETLINK_SOCK_DIAG). 26 | 27 | -define(NFNLGRP_NONE, 0). 28 | -define(NFNLGRP_CONNTRACK_NEW, 1). 29 | -define(NFNLGRP_CONNTRACK_UPDATE, 2). 30 | -define(NFNLGRP_CONNTRACK_DESTROY, 3). 31 | -define(NFNLGRP_CONNTRACK_EXP_NEW, 4). 32 | -define(NFNLGRP_CONNTRACK_EXP_UPDATE, 5). 33 | -define(NFNLGRP_CONNTRACK_EXP_DESTROY, 6). 34 | 35 | -define(RTNLGRP_NONE, 0). 36 | -define(RTNLGRP_LINK, 1). 37 | -define(RTNLGRP_NOTIFY, 2). 38 | -define(RTNLGRP_NEIGH, 3). 39 | -define(RTNLGRP_TC, 4). 40 | -define(RTNLGRP_IPV4_IFADDR, 5). 41 | -define(RTNLGRP_IPV4_MROUTE, 6). 42 | -define(RTNLGRP_IPV4_ROUTE, 7). 43 | -define(RTNLGRP_IPV4_RULE, 8). 44 | -define(RTNLGRP_IPV6_IFADDR, 9). 45 | -define(RTNLGRP_IPV6_MROUTE, 10). 46 | -define(RTNLGRP_IPV6_ROUTE, 11). 47 | -define(RTNLGRP_IPV6_IFINFO, 12). 48 | -define(RTNLGRP_DECnet_IFADDR, 13). 49 | -define(RTNLGRP_NOP2, 14). 50 | -define(RTNLGRP_DECnet_ROUTE, 15). 51 | -define(RTNLGRP_DECnet_RULE, 16). 52 | -define(RTNLGRP_NOP4, 17). 53 | -define(RTNLGRP_IPV6_PREFIX, 18). 54 | -define(RTNLGRP_IPV6_RULE, 19). 55 | -define(RTNLGRP_ND_USEROPT, 20). 56 | -define(RTNLGRP_PHONET_IFADDR, 21). 57 | -define(RTNLGRP_PHONET_ROUTE, 22). 58 | -define(RTNLGRL_DCB, 23). 59 | 60 | -record(nlmsg, 61 | { 62 | hdr, 63 | data 64 | }). 65 | 66 | -ifdef(OTP_RELEASE). %% this implies 21 or higher 67 | -define(EXCEPTION(Class, Reason, Stacktrace), Class:Reason:Stacktrace). 68 | -define(GET_STACK(Stacktrace), Stacktrace). 69 | -else. 70 | -define(EXCEPTION(Class, Reason, _), Class:Reason). 71 | -define(GET_STACK(_), erlang:get_stacktrace()). 72 | -endif. 73 | -------------------------------------------------------------------------------- /src/netlink.inc: -------------------------------------------------------------------------------- 1 | %% -*- erlang -*- 2 | %% 3 | %% nlink data definitions 4 | %% 5 | {define, 'NLMSG_NOOP', 1}. 6 | {define, 'NLMSG_ERROR', 2}. 7 | {define, 'NLMSG_DONE', 3}. 8 | {define, 'NLMSG_OVERRUN', 4}. 9 | 10 | {define, 'RTM_NEWLINK', 16}. 11 | {define, 'RTM_DELLINK', 17}. 12 | {define, 'RTM_GETLINK', 18}. 13 | {define, 'RTM_SETLINK', 19}. 14 | {define, 'RTM_NEWADDR', 20}. 15 | {define, 'RTM_DELADDR', 21}. 16 | {define, 'RTM_GETADDR', 22}. 17 | {define, 'RTM_NEWROUTE', 24}. 18 | {define, 'RTM_DELROUTE', 25}. 19 | {define, 'RTM_GETROUTE', 26}. 20 | {define, 'RTM_NEWNEIGH', 28}. 21 | {define, 'RTM_DELNEIGH', 29}. 22 | {define, 'RTM_GETNEIGH', 30}. 23 | {define, 'RTM_NEWRULE', 32}. 24 | {define, 'RTM_DELRULE', 33}. 25 | {define, 'RTM_GETRULE', 34}. 26 | {define, 'RTM_NEWQDISC', 36}. 27 | {define, 'RTM_DELQDISC', 37}. 28 | {define, 'RTM_GETQDISC', 38}. 29 | {define, 'RTM_NEWTCLASS', 40}. 30 | {define, 'RTM_DELTCLASS', 41}. 31 | {define, 'RTM_GETTCLASS', 42}. 32 | {define, 'RTM_NEWTFILTER', 44}. 33 | {define, 'RTM_DELTFILTER', 45}. 34 | {define, 'RTM_GETTFILTER', 46}. 35 | {define, 'RTM_NEWACTION', 48}. 36 | {define, 'RTM_DELACTION', 49}. 37 | {define, 'RTM_GETACTION', 50}. 38 | {define, 'RTM_NEWPREFIX', 52}. 39 | {define, 'RTM_GETMULTICAST', 58}. 40 | {define, 'RTM_GETANYCAST', 62}. 41 | {define, 'RTM_NEWNEIGHTBL', 64}. 42 | {define, 'RTM_GETNEIGHTBL', 66}. 43 | {define, 'RTM_SETNEIGHTBL', 67}. 44 | {define, 'RTM_NEWNDUSEROPT', 68}. 45 | {define, 'RTM_NEWADDRLABEL', 72}. 46 | {define, 'RTM_DELADDRLABEL', 73}. 47 | {define, 'RTM_GETADDRLABEL', 74}. 48 | {define, 'RTM_GETDCB', 78}. 49 | {define, 'RTM_SETDCB', 79}. 50 | 51 | {define, 'AF_UNSPEC', 0}. 52 | {define, 'AF_LOCAL', 1}. 53 | {define, 'AF_UNIX', 1}. 54 | {define, 'AF_FILE', 1}. 55 | {define, 'AF_INET', 2}. 56 | {define, 'AF_AX25', 3}. 57 | {define, 'AF_IPX', 4}. 58 | {define, 'AF_APPLETALK', 5}. 59 | {define, 'AF_NETROM', 6}. 60 | {define, 'AF_BRIDGE', 7}. 61 | {define, 'AF_ATMPVC', 8}. 62 | {define, 'AF_X25', 9}. 63 | {define, 'AF_INET6', 10}. 64 | {define, 'AF_ROSE', 11}. 65 | {define, 'AF_DECNET', 12}. 66 | {define, 'AF_NETBEUI', 13}. 67 | {define, 'AF_SECURITY', 14}. 68 | {define, 'AF_KEY', 15}. 69 | {define, 'AF_NETLINK', 16}. 70 | {define, 'AF_ROUTE', 16}. 71 | {define, 'AF_PACKET', 17}. 72 | {define, 'AF_ASH', 18}. 73 | {define, 'AF_ECONET', 19}. 74 | {define, 'AF_ATMSVC', 20}. 75 | {define, 'AF_RDS', 21}. 76 | {define, 'AF_SNA', 22}. 77 | {define, 'AF_IRDA', 23}. 78 | {define, 'AF_PPPOX', 24}. 79 | {define, 'AF_WANPIPE', 25}. 80 | {define, 'AF_LLC', 26}. 81 | {define, 'AF_CAN', 29}. 82 | {define, 'AF_TIPC', 30}. 83 | {define, 'AF_BLUETOOTH', 31}. 84 | {define, 'AF_IUCV', 32}. 85 | {define, 'AF_RXRPC', 33}. 86 | {define, 'AF_ISDN', 34}. 87 | {define, 'AF_PHONET', 35}. 88 | {define, 'AF_IEEE802154', 36}. 89 | 90 | {define, 'PROTO_IP', 0}. 91 | {define, 'PROTO_ICMP', 1}. 92 | {define, 'PROTO_IGMP', 2}. 93 | {define, 'PROTO_IPIP', 4}. 94 | {define, 'PROTO_TCP', 6}. 95 | {define, 'PROTO_EGP', 8}. 96 | {define, 'PROTO_PUP', 12}. 97 | {define, 'PROTO_UDP', 17}. 98 | {define, 'PROTO_IDP', 22}. 99 | {define, 'PROTO_TP', 29}. 100 | {define, 'PROTO_DCCP', 33}. 101 | {define, 'PROTO_IPV6', 41}. 102 | {define, 'PROTO_ROUTING', 43}. 103 | {define, 'PROTO_FRAGMENT', 44}. 104 | {define, 'PROTO_RSVP', 46}. 105 | {define, 'PROTO_GRE', 47}. 106 | {define, 'PROTO_ESP', 50}. 107 | {define, 'PROTO_AH', 51}. 108 | {define, 'PROTO_ICMPV6', 58}. 109 | {define, 'PROTO_NONE', 59}. 110 | {define, 'PROTO_DSTOPTS', 60}. 111 | {define, 'PROTO_MTP', 92}. 112 | {define, 'PROTO_ENCAP', 98}. 113 | {define, 'PROTO_PIM', 103}. 114 | {define, 'PROTO_COMP', 108}. 115 | {define, 'PROTO_SCTP', 132}. 116 | {define, 'PROTO_UDPLITE', 136}. 117 | {define, 'PROTO_RAW', 255}. 118 | 119 | {define, 'ARPHRD_NETROM', 0}. %% from KA9Q: NET/ROM pseudo 120 | {define, 'ARPHRD_ETHER ', 1}. %% Ethernet 10Mbps 121 | {define, 'ARPHRD_EETHER', 2}. %% Experimental Ethernet 122 | {define, 'ARPHRD_AX25', 3}. %% AX.25 Level 2 123 | {define, 'ARPHRD_PRONET', 4}. %% PROnet token ring 124 | {define, 'ARPHRD_CHAOS', 5}. %% Chaosnet 125 | {define, 'ARPHRD_IEEE802',6}. %% IEEE 802.2 Ethernet/TR/TB 126 | {define, 'ARPHRD_ARCNET', 7}. %% ARCnet 127 | {define, 'ARPHRD_APPLETLK', 8}. %% APPLEtalk 128 | {define, 'ARPHRD_DLCI', 15}. %% Frame Relay DLCI 129 | {define, 'ARPHRD_ATM', 19}. %% ATM 130 | {define, 'ARPHRD_METRICOM', 23}. %% Metricom STRIP (new IANA id) 131 | {define, 'ARPHRD_IEEE1394', 24}. %% IEEE 1394 IPv4 - RFC 2734 132 | {define, 'ARPHRD_EUI64', 27}. %% EUI-64 133 | {define, 'ARPHRD_INFINIBAND', 32}. %% InfiniBand 134 | %% Dummy types for non ARP hardware 135 | {define, 'ARPHRD_SLIP', 256}. 136 | {define, 'ARPHRD_CSLIP', 257}. 137 | {define, 'ARPHRD_SLIP6', 258}. 138 | {define, 'ARPHRD_CSLIP6', 259}. 139 | {define, 'ARPHRD_RSRVD', 260}. %% Notional KISS type 140 | {define, 'ARPHRD_ADAPT', 264}. 141 | {define, 'ARPHRD_ROSE', 270}. 142 | {define, 'ARPHRD_X25', 271}. %% CCITT X.25 143 | {define, 'ARPHRD_HWX25', 272}. %% Boards with X.25 in firmware 144 | {define, 'ARPHRD_CAN', 280}. %% Controller Area Network 145 | {define, 'ARPHRD_PPP', 512}. 146 | {define, 'ARPHRD_CISCO', 513}. %% Cisco HDLC 147 | {define, 'ARPHRD_HDLC', 513}. 148 | {define, 'ARPHRD_LAPB', 516}. %% LAPB 149 | {define, 'ARPHRD_DDCMP', 517}. %% Digitals DDCMP protocol 150 | {define, 'ARPHRD_RAWHDLC', 518}. %% Raw HDLC 151 | {define, 'ARPHRD_TUNNEL', 768}. %% IPIP tunnel 152 | {define, 'ARPHRD_TUNNEL6', 769}. %% IP6IP6 tunnel 153 | {define, 'ARPHRD_FRAD', 770}. %% Frame Relay Access Device 154 | {define, 'ARPHRD_SKIP', 771}. %% SKIP vif 155 | {define, 'ARPHRD_LOOPBACK', 772}. %% Loopback device 156 | {define, 'ARPHRD_LOCALTLK', 773}. %% Localtalk device 157 | {define, 'ARPHRD_FDDI', 774}. %% Fiber Distributed Data Interface 158 | {define, 'ARPHRD_BIF', 775}. %% AP1000 BIF 159 | {define, 'ARPHRD_SIT', 776}. %% sit0 device - IPv6-in-IPv4 160 | {define, 'ARPHRD_IPDDP', 777}. %% IP over DDP tunneller 161 | {define, 'ARPHRD_IPGRE', 778}. %% GRE over IP 162 | {define, 'ARPHRD_PIMREG', 779}. %% PIMSM register interface 163 | {define, 'ARPHRD_HIPPI', 780}. %% High Performance Parallel Interface 164 | {define, 'ARPHRD_ASH', 781}. %% Nexus 64Mbps Ash 165 | {define, 'ARPHRD_ECONET', 782}. %% Acorn Econet 166 | {define, 'ARPHRD_IRDA', 783}. %% Linux-IrDA 167 | %% ARP works differently on different FC media .. so 168 | {define, 'ARPHRD_FCPP', 784}. %% Point to point fibrechannel 169 | {define, 'ARPHRD_FCAL', 785}. %% Fibrechannel arbitrated loop 170 | {define, 'ARPHRD_FCPL', 786}. %% Fibrechannel public loop 171 | {define, 'ARPHRD_FCFABRIC', 787}. %% Fibrechannel fabric 172 | %% 787->799 reserved for fibrechannel media types 173 | {define, 'ARPHRD_IEEE802_TR', 800}. %% Magic type ident for TR 174 | {define, 'ARPHRD_IEEE80211', 801}. %% IEEE 802.11 175 | {define, 'ARPHRD_IEEE80211_PRISM', 802}. %% IEEE 802.11 + Prism2 header 176 | {define, 'ARPHRD_IEEE80211_RADIOTAP', 803}. %% IEEE 802.11 + radiotap header 177 | {define, 'ARPHRD_IEEE802154', 804}. 178 | {define, 'ARPHRD_PHONET', 820}. %% PhoNet media type 179 | {define, 'ARPHRD_PHONET_PIPE', 821}. %% PhoNet pipe header 180 | {define, 'ARPHRD_CAIF', 822}. %% CAIF media type 181 | {define, 'ARPHRD_VOID', 65535}. %% Void type, nothing is known 182 | {define, 'ARPHRD_NONE', 65534}. %% zero header length 183 | 184 | {enum, family, 185 | [ 186 | {unspec, 'AF_UNSPEC'}, 187 | {local, 'AF_LOCAL'}, 188 | {inet, 'AF_INET'}, 189 | {ax25, 'AF_AX25'}, 190 | {ipx, 'AF_IPX'}, 191 | {appletalk, 'AF_APPLETALK'}, 192 | {netrom, 'AF_NETROM'}, 193 | {bridge, 'AF_BRIDGE'}, 194 | {atmpvc, 'AF_ATMPVC'}, 195 | {x25, 'AF_X25'}, 196 | {inet6, 'AF_INET6'}, 197 | {rose, 'AF_ROSE'}, 198 | {decnet, 'AF_DECNET'}, 199 | {netbeui, 'AF_NETBEUI'}, 200 | {security, 'AF_SECURITY'}, 201 | {key, 'AF_KEY'}, 202 | {netlink, 'AF_NETLINK'}, 203 | {packet, 'AF_PACKET'}, 204 | {ash, 'AF_ASH'}, 205 | {econet, 'AF_ECONET'}, 206 | {atmsvc, 'AF_ATMSVC'}, 207 | {rds, 'AF_RDS'}, 208 | {sna, 'AF_SNA'}, 209 | {irda, 'AF_IRDA'}, 210 | {pppox, 'AF_PPPOX'}, 211 | {wanpipe, 'AF_WANPIPE'}, 212 | {llc, 'AF_LLC'}, 213 | {can, 'AF_CAN'}, 214 | {tipc, 'AF_TIPC'}, 215 | {bluetooth, 'AF_BLUETOOTH'}, 216 | {iucv, 'AF_IUCV'}, 217 | {rxrpc, 'AF_RXRPC'}, 218 | {isdn, 'AF_ISDN'}, 219 | {phonet, 'AF_PHONET'}, 220 | {ieee802154, 'AF_IEEE802154'} 221 | ]}. 222 | 223 | {enum, protocol, 224 | [ 225 | {ip, 'PROTO_IP'}, 226 | {icmp, 'PROTO_ICMP'}, 227 | {igmp, 'PROTO_IGMP'}, 228 | {ipip, 'PROTO_IPIP'}, 229 | {tcp, 'PROTO_TCP'}, 230 | {egp, 'PROTO_EGP'}, 231 | {pup, 'PROTO_PUP'}, 232 | {udp, 'PROTO_UDP'}, 233 | {idp, 'PROTO_IDP'}, 234 | {tp, 'PROTO_TP'}, 235 | {dccp, 'PROTO_DCCP'}, 236 | {ipv6, 'PROTO_IPV6'}, 237 | {routing, 'PROTO_ROUTING'}, 238 | {fragment, 'PROTO_FRAGMENT'}, 239 | {rsvp, 'PROTO_RSVP'}, 240 | {gre, 'PROTO_GRE'}, 241 | {esp, 'PROTO_ESP'}, 242 | {ah, 'PROTO_AH'}, 243 | {icmpv6, 'PROTO_ICMPV6'}, 244 | {none, 'PROTO_NONE'}, 245 | {dstopts, 'PROTO_DSTOPTS'}, 246 | {mtp, 'PROTO_MTP'}, 247 | {encap, 'PROTO_ENCAP'}, 248 | {pim, 'PROTO_PIM'}, 249 | {comp, 'PROTO_COMP'}, 250 | {sctp, 'PROTO_SCTP'}, 251 | {udplite, 'PROTO_UDPLITE'}, 252 | {raw, 'PROTO_RAW'} 253 | ]}. 254 | 255 | {enum, arphrd, 256 | [ 257 | {netrom, 'ARPHRD_NETROM'}, 258 | {ether , 'ARPHRD_ETHER '}, 259 | {eether, 'ARPHRD_EETHER'}, 260 | {ax25, 'ARPHRD_AX25'}, 261 | {pronet, 'ARPHRD_PRONET'}, 262 | {chaos, 'ARPHRD_CHAOS'}, 263 | {ieee802, 'ARPHRD_IEEE802'}, 264 | {arcnet, 'ARPHRD_ARCNET'}, 265 | {appletlk, 'ARPHRD_APPLETLK'}, 266 | {dlci, 'ARPHRD_DLCI'}, 267 | {atm, 'ARPHRD_ATM'}, 268 | {metricom, 'ARPHRD_METRICOM'}, 269 | {ieee1394, 'ARPHRD_IEEE1394'}, 270 | {eui64, 'ARPHRD_EUI64'}, 271 | {infiniband, 'ARPHRD_INFINIBAND'}, 272 | {slip, 'ARPHRD_SLIP'}, 273 | {cslip, 'ARPHRD_CSLIP'}, 274 | {slip6, 'ARPHRD_SLIP6'}, 275 | {cslip6, 'ARPHRD_CSLIP6'}, 276 | {rsrvd, 'ARPHRD_RSRVD'}, 277 | {adapt, 'ARPHRD_ADAPT'}, 278 | {rose, 'ARPHRD_ROSE'}, 279 | {x25, 'ARPHRD_X25'}, 280 | {hwx25, 'ARPHRD_HWX25'}, 281 | {can, 'ARPHRD_CAN'}, 282 | {ppp, 'ARPHRD_PPP'}, 283 | {hdlc, 'ARPHRD_HDLC'}, 284 | {lapb, 'ARPHRD_LAPB'}, 285 | {ddcmp, 'ARPHRD_DDCMP'}, 286 | {rawhdlc, 'ARPHRD_RAWHDLC'}, 287 | {tunnel, 'ARPHRD_TUNNEL'}, 288 | {tunnel6, 'ARPHRD_TUNNEL6'}, 289 | {frad, 'ARPHRD_FRAD'}, 290 | {skip, 'ARPHRD_SKIP'}, 291 | {loopback, 'ARPHRD_LOOPBACK'}, 292 | {localtlk, 'ARPHRD_LOCALTLK'}, 293 | {fddi, 'ARPHRD_FDDI'}, 294 | {bif, 'ARPHRD_BIF'}, 295 | {sit, 'ARPHRD_SIT'}, 296 | {ipddp, 'ARPHRD_IPDDP'}, 297 | {ipgre, 'ARPHRD_IPGRE'}, 298 | {pimreg, 'ARPHRD_PIMREG'}, 299 | {hippi, 'ARPHRD_HIPPI'}, 300 | {ash, 'ARPHRD_ASH'}, 301 | {econet, 'ARPHRD_ECONET'}, 302 | {irda, 'ARPHRD_IRDA'}, 303 | {fcpp, 'ARPHRD_FCPP'}, 304 | {fcal, 'ARPHRD_FCAL'}, 305 | {fcpl, 'ARPHRD_FCPL'}, 306 | {fcfabric, 'ARPHRD_FCFABRIC'}, 307 | {ieee802_tr, 'ARPHRD_IEEE802_TR'}, 308 | {ieee80211, 'ARPHRD_IEEE80211'}, 309 | {ieee80211_prism, 'ARPHRD_IEEE80211_PRISM'}, 310 | {ieee80211_radiotap, 'ARPHRD_IEEE80211_RADIOTAP'}, 311 | {ieee802154, 'ARPHRD_IEEE802154'}, 312 | {phonet, 'ARPHRD_PHONET'}, 313 | {phonet_pipe, 'ARPHRD_PHONET_PIPE'}, 314 | {caif, 'ARPHRD_CAIF'}, 315 | {void, 'ARPHRD_VOID'}, 316 | {none, 'ARPHRD_NONE'} 317 | ]}. 318 | 319 | 320 | {enum, nlmsg_type, 321 | [ 322 | {noop, 'NLMSG_NOOP'}, 323 | {error, 'NLMSG_ERROR'}, 324 | {done, 'NLMSG_DONE'}, 325 | {overrun, 'NLMSG_OVERRUN'}, 326 | {newlink, 'RTM_NEWLINK'}, 327 | {dellink, 'RTM_DELLINK'}, 328 | {getlink, 'RTM_GETLINK'}, 329 | {setlink, 'RTM_SETLINK'}, 330 | {newaddr, 'RTM_NEWADDR'}, 331 | {deladdr, 'RTM_DELADDR'}, 332 | {getaddr, 'RTM_GETADDR'}, 333 | {newroute, 'RTM_NEWROUTE'}, 334 | {delroute, 'RTM_DELROUTE'}, 335 | {getroute, 'RTM_GETROUTE'}, 336 | {newneigh, 'RTM_NEWNEIGH'}, 337 | {delneigh, 'RTM_DELNEIGH'}, 338 | {getneigh, 'RTM_GETNEIGH'}, 339 | {newrule, 'RTM_NEWRULE'}, 340 | {delrule, 'RTM_DELRULE'}, 341 | {getrule, 'RTM_GETRULE'}, 342 | {newqdisc, 'RTM_NEWQDISC'}, 343 | {delqdisc, 'RTM_DELQDISC'}, 344 | {getqdisc, 'RTM_GETQDISC'}, 345 | {newtclass, 'RTM_NEWTCLASS'}, 346 | {deltclass, 'RTM_DELTCLASS'}, 347 | {gettclass, 'RTM_GETTCLASS'}, 348 | {newtfilter, 'RTM_NEWTFILTER'}, 349 | {deltfilter, 'RTM_DELTFILTER'}, 350 | {gettfilter, 'RTM_GETTFILTER'}, 351 | {newaction, 'RTM_NEWACTION'}, 352 | {delaction, 'RTM_DELACTION'}, 353 | {getaction, 'RTM_GETACTION'}, 354 | {newprefix, 'RTM_NEWPREFIX'}, 355 | {getmulticast, 'RTM_GETMULTICAST'}, 356 | {getanycast, 'RTM_GETANYCAST'}, 357 | {newneightbl, 'RTM_NEWNEIGHTBL'}, 358 | {getneightbl, 'RTM_GETNEIGHTBL'}, 359 | {setneightbl, 'RTM_SETNEIGHTBL'}, 360 | {newnduseropt, 'RTM_NEWNDUSEROPT'}, 361 | {newaddrlabel, 'RTM_NEWADDRLABEL'}, 362 | {deladdrlabel, 'RTM_DELADDRLABEL'}, 363 | {getaddrlabel, 'RTM_GETADDRLABEL'}, 364 | {getdcb, 'RTM_GETDCB'}, 365 | {setdcb, 'RTM_SETDCB'} 366 | ]}. 367 | 368 | %% enumeration of flag numbers (up=0, broadcast=1 ...) 369 | %% used as flag then up = (1 << 0) broadcast = (1 << 1) 370 | {enum, iff_flags, 371 | [ 372 | up, 373 | broadcast, 374 | debug, 375 | loopback, 376 | pointopoint, 377 | notrailers, 378 | running, 379 | noarp, 380 | promisc, 381 | allmulti, 382 | master, 383 | slave, 384 | multicast, 385 | portsel, 386 | automedia, 387 | ynamic, 388 | lower_up, 389 | dormant, 390 | echo 391 | ]}. 392 | 393 | {enum, nlm_flags, 394 | [ 395 | {request, 0}, 396 | {multi, 1}, 397 | {ack, 2}, 398 | {echo, 3} 399 | ]}. 400 | 401 | {enum, nlm_get_flags, 402 | [ 403 | {request, 0}, 404 | {multi, 1}, 405 | {ack, 2}, 406 | {echo, 3}, 407 | {root, 8}, 408 | {match, 9}, 409 | {atomic, 10} 410 | ]}. 411 | 412 | {enum, nlm_new_flags, 413 | [ 414 | {request, 0}, 415 | {multi, 1}, 416 | {ack, 2}, 417 | {echo, 3}, 418 | {replace, 8}, 419 | {excl, 9}, 420 | {create, 10}, 421 | {append, 11} 422 | ]}. 423 | 424 | {define, 'IPCTNL_MSG_CT_NEW', 0}. 425 | {define, 'IPCTNL_MSG_CT_GET', 1}. 426 | {define, 'IPCTNL_MSG_CT_DELETE', 2}. 427 | {define, 'IPCTNL_MSG_CT_GET_CTRZERO', 3}. 428 | 429 | {enum, ctm_msgtype_netlink, 430 | [ 431 | {noop, 'NLMSG_NOOP'}, 432 | {error, 'NLMSG_ERROR'}, 433 | {done, 'NLMSG_DONE'}, 434 | {overrun, 'NLMSG_OVERRUN'} 435 | ]}. 436 | 437 | {define, 'IPCTNL_MSG_EXP_NEW', 0}. 438 | {define, 'IPCTNL_MSG_EXP_GET', 1}. 439 | {define, 'IPCTNL_MSG_EXP_DELETE', 2}. 440 | 441 | {enum, ctm_msgtype_ctnetlink, 442 | [ 443 | {new, 'IPCTNL_MSG_CT_NEW'}, 444 | {get, 'IPCTNL_MSG_CT_GET'}, 445 | {delete, 'IPCTNL_MSG_CT_DELETE'}, 446 | {get_ctrzero, 'IPCTNL_MSG_CT_GET_CTRZERO'} 447 | ]}. 448 | 449 | {enum, ctm_msgtype_ctnetlink_exp, 450 | [ 451 | {new, 'IPCTNL_MSG_EXP_NEW'}, 452 | {get, 'IPCTNL_MSG_EXP_GET'}, 453 | {delete, 'IPCTNL_MSG_EXP_DELETE'} 454 | ]}. 455 | 456 | {attribute, ctnetlink_tuple_ip, 457 | [ 458 | {unspec, binary_t}, 459 | {v4_src, ipv4_addr_t}, 460 | {v4_dst, ipv4_addr_t}, 461 | {v6_src, ipv6_addr_t}, 462 | {v6_dst, ipv6_addr_t} 463 | ]}. 464 | 465 | {attribute, ctnetlink_tuple_proto, 466 | [ 467 | {unspec, binary_t}, 468 | {num, {enum,uint8_t,protocol}}, 469 | {src_port, uint16_t}, 470 | {dst_port, uint16_t}, 471 | {icmp_id, uint16_t}, 472 | {icmp_type, uint8_t}, 473 | {icmp_code, uint8_t}, 474 | {icmpv6_id, binary_t}, 475 | {icmpv6_type, binary_t}, 476 | {icmpv6_code, binary_t} 477 | ]}. 478 | 479 | {attribute, ctnetlink_tuple, 480 | [ 481 | {unspec, binary_t}, 482 | {ip, ctnetlink_tuple_ip}, 483 | {proto, ctnetlink_tuple_proto} 484 | ]}. 485 | 486 | {attribute, ctnetlink_nat_seq_adj, 487 | [ 488 | {unspec, binary_t}, 489 | {correction_pos, uint32_t}, 490 | {offset_before, uint32_t}, 491 | {offset_after, uint32_t} 492 | ]}. 493 | 494 | {enum, ctnetlink_protoinfo_tcp_state, 495 | [ 496 | none, 497 | syn_sent, 498 | syn_recv, 499 | established, 500 | fin_wait, 501 | close_wait, 502 | last_ack, 503 | time_wait, 504 | close, 505 | listen, 506 | max, 507 | ignore 508 | ]}. 509 | 510 | {attribute, ctnetlink_protoinfo_tcp, 511 | [ 512 | {unspec, binary_t}, 513 | {state, {enum,uint8_t,ctnetlink_protoinfo_tcp_state}}, 514 | {wscale_original, uint8_t}, 515 | {wscale_reply, uint8_t}, 516 | {flags_original, uint16_t}, 517 | {flags_reply, uint16_t} 518 | ]}. 519 | 520 | 521 | {attribute, ctnetlink_protoinfo, 522 | [ 523 | {unspec, binary_t}, 524 | {tcp, ctnetlink_protoinfo_tcp}, 525 | {dccp, binary_t}, %% ctnetlink_protoinfo_dccp}, 526 | {sctp, binary_t} %% ctnetlink_protoinfo_sctp} 527 | ]}. 528 | 529 | {enum, ctnetlink_status, 530 | [ 531 | expected, 532 | seen_reply, 533 | assured, 534 | confirmed, 535 | src_nat, 536 | dst_nat, 537 | seq_adjust, 538 | src_nat_done, 539 | dst_nat_done, 540 | dying, 541 | fixed_timeout 542 | ]}. 543 | 544 | {attribute, ctnetlink_help, 545 | [ 546 | {unspec, binary_t}, 547 | {name, string_t} 548 | ]}. 549 | 550 | {attribute, ctnetlink_counters, 551 | [ 552 | {unspec, binary_t}, 553 | {packets, uint64_t}, 554 | {bytes, uint64_t}, 555 | {packets32, uint32_t}, 556 | {bytes32, uint32_t} 557 | ]}. 558 | 559 | {attribute, ctnetlink_timestamp, 560 | [ 561 | {unspec, binary_t}, 562 | {start, uint64_t}, 563 | {stop, uint64_t} 564 | ]}. 565 | 566 | {attribute, ctnetlink_exp_tuple_ip, 567 | [ 568 | {unspec, binary_t}, 569 | {v4_src, ipv4_addr_t}, 570 | {v4_dst, ipv4_addr_t}, 571 | {v6_src, ipv6_addr_t}, 572 | {v6_dst, ipv6_addr_t} 573 | ]}. 574 | 575 | {attribute, ctnetlink_exp_tuple_proto, 576 | [ 577 | {unspec, binary_t}, 578 | {num, {enum,uint8_t,protocol}}, 579 | {src_port, uint16_t}, 580 | {dst_port, uint16_t}, 581 | {icmp_id, uint16_t}, 582 | {icmp_type, uint8_t}, 583 | {icmp_code, uint8_t}, 584 | {icmpv6_id, binary_t}, 585 | {icmpv6_type, binary_t}, 586 | {icmpv6_code, binary_t} 587 | ]}. 588 | 589 | {attribute, ctnetlink_exp_tuple, 590 | [ 591 | {unspec, binary_t}, 592 | {ip, ctnetlink_exp_tuple_ip}, 593 | {proto, ctnetlink_exp_tuple_proto} 594 | ]}. 595 | 596 | {enum, ctnetlink_exp_flags, 597 | [ 598 | permanent, 599 | inactive, 600 | userspace 601 | ]}. 602 | 603 | 604 | {attribute, ctnetlink_exp, 605 | [ 606 | {unspec, binary_t}, 607 | {master, ctnetlink_exp_tuple}, 608 | {tuple, ctnetlink_exp_tuple}, 609 | {mask, ctnetlink_exp_tuple}, 610 | {timeout, uint32_t}, 611 | {id, uint32_t}, 612 | {help_name, string_t}, 613 | {zone, uint16_t}, 614 | {flags, {flags,uint32_t,ctnetlink_exp_flags}} 615 | ]}. 616 | 617 | 618 | {attribute, ctnetlink, 619 | [ 620 | {unspec, binary_t}, 621 | {tuple_orig, ctnetlink_tuple}, 622 | {tuple_reply, ctnetlink_tuple}, 623 | {status, {flags,uint32_t,ctnetlink_status}}, 624 | {protoinfo, ctnetlink_protoinfo}, 625 | {help, ctnetlink_help}, 626 | {nat_src, binary_t}, 627 | {timeout, uint32_t}, 628 | {mark, uint32_t}, 629 | {counters_orig, ctnetlink_counters}, 630 | {counters_reply, ctnetlink_counters}, 631 | {use, uint32_t}, 632 | {id, uint32_t}, 633 | {nat_dst, binary_t}, 634 | {tuple_master, ctnetlink_tuple}, 635 | {nat_seq_adj_orig, ctnetlink_nat_seq_adj}, 636 | {nat_seq_adj_reply, ctnetlink_nat_seq_adj}, 637 | {secmark, uint32_t}, 638 | {zone, uint16_t}, 639 | {secctx, binary_t}, 640 | {timestamp, ctnetlink_timestamp} 641 | ]}. 642 | 643 | 644 | {attribute, rtnetlink_neigh, 645 | [ 646 | {unspec, binary_t}, 647 | {dst, addr_t}, 648 | {lladdr, ether_addr_t}, 649 | {cacheinfo, {array,uint32_t}}, 650 | {probes, uint32_t} 651 | ]}. 652 | 653 | {enum, rtnetlink_rtm_type, 654 | [ 655 | unspec, 656 | unicast, 657 | local, 658 | broadcast, 659 | anycast, 660 | multicast, 661 | blackhole, 662 | unreachable, 663 | prohibit, 664 | throw, 665 | nat, 666 | xresolve 667 | ]}. 668 | 669 | {enum, rtnetlink_rtm_protocol, 670 | [ 671 | {unspec, 0}, 672 | {redirect, 1}, 673 | {kernel, 2}, 674 | {boot, 3}, 675 | {static, 4}, 676 | {gated, 8}, 677 | {ra, 9}, 678 | {mrt, 10}, 679 | {zebra, 11}, 680 | {bird, 12}, 681 | {dnrouted, 13}, 682 | {xorp, 14}, 683 | {ntk, 15}, 684 | {dhcp, 16} 685 | ]}. 686 | 687 | {enum, rtnetlink_rtm_scope, 688 | [ 689 | {universe, 0}, 690 | {site, 200}, 691 | {link, 253}, 692 | {host, 254}, 693 | {nowhere, 255} 694 | ]}. 695 | 696 | %% FIXME: should be bit number? 697 | {enum, rtnetlink_rtm_flags, 698 | [ 699 | {notify, 16#100}, 700 | {cloned, 16#200}, 701 | {equalize, 16#400}, 702 | {prefix, 16#800} 703 | ]}. 704 | 705 | {enum, rtnetlink_rtm_table, 706 | [ 707 | {unspec, 0}, 708 | {compat, 252}, 709 | {default, 253}, 710 | {main, 254}, 711 | {local, 255} 712 | ]}. 713 | 714 | {attribute, rtnetlink_route_metrics, 715 | [ 716 | {unspec, binary_t}, 717 | {lock, uint32_t}, 718 | {mtu, uint32_t}, 719 | {window, uint32_t}, 720 | {rtt, uint32_t}, 721 | {rttvar, uint32_t}, 722 | {ssthresh, uint32_t}, 723 | {cwnd, uint32_t}, 724 | {advmss, uint32_t}, 725 | {reordering, uint32_t}, 726 | {hoplimit, uint32_t}, 727 | {initcwnd, uint32_t}, 728 | {features, uint32_t}, 729 | {rto_min, uint32_t}, 730 | {initrwnd, uint32_t} 731 | ]}. 732 | 733 | {attribute, rtnetlink_addr, 734 | [ 735 | {unspec, binary_t}, 736 | {address, addr_t}, 737 | {local, addr_t}, 738 | {label, string_t}, 739 | {broadcast, addr_t}, 740 | {anycast, addr_t}, 741 | {cacheinfo, {array,uint32_t}}, 742 | {multicast, addr_t} 743 | ]}. 744 | 745 | {enum, rtnetlink_link_operstate, 746 | [ 747 | unknown, 748 | notpresent, 749 | down, 750 | lowerlayerdown, 751 | testing, 752 | dormant, 753 | up 754 | ]}. 755 | 756 | {enum, rtnetlink_link_linkmode, 757 | [ 758 | default, 759 | dormant 760 | ]}. 761 | 762 | {record, if_map, 763 | [ 764 | {memstart, uint64_t}, 765 | {memend, uint64_t}, 766 | {baseaddr, uint64_t}, 767 | {irq, uint16_t}, 768 | {dma, uint8_t}, 769 | {port, uint8_t} 770 | %% fixme: 64 padding? on 64 bit machine? 771 | ]}. 772 | 773 | {attribute, rtnetlink_route, 774 | [ 775 | {unspec, binary_t}, 776 | {dst, addr_t}, 777 | {src, addr_t}, 778 | {iif, uint32_t}, 779 | {oif, uint32_t}, 780 | {gateway, addr_t}, 781 | {priority, uint32_t}, 782 | {prefsrc, addr_t}, 783 | {metrics, {tlvs,rtnetlink_route_metrics}}, 784 | {multipath, binary_t}, 785 | {protoinfo, binary_t}, 786 | {flow, uint32_t}, 787 | {cacheinfo, {array,uint32_t}}, 788 | {session, binary_t}, 789 | {mp_algo, binary_t}, 790 | {table, uint32_t} 791 | ]}. 792 | 793 | {attribute, rtnetlink_link_linkinfo, 794 | [ 795 | {unspec, binary_t}, 796 | {kind, string_t}, 797 | {data, binary_t}, 798 | {xstats, binary_t} 799 | ]}. 800 | 801 | %% inet6? 802 | {enum, rtnetlink_link_protinfo_flags, 803 | [ 804 | {rs_sent, 4}, 805 | {ra_rcvd, 5}, 806 | {ra_managed, 6}, 807 | {ra_othercon, 7}, 808 | {ready, 31} 809 | ]}. 810 | 811 | %% inet6? 812 | {attribute, rtnetlink_link_protinfo, 813 | [ 814 | {unspec, binary_t}, 815 | {flags, {flags,uint32_t,rtnetlink_link_protinfo_flags}}, 816 | {conf, {array,int32_t}}, 817 | {stats, {array,uint64_t}}, 818 | {mcast, binary_t}, 819 | {cacheinfo, {array,uint32_t}}, 820 | {icmp6stats, {array,uint64_t}} 821 | ]}. 822 | 823 | 824 | {attribute, rtnetlink_link, 825 | [ 826 | {unspec, binary_t}, 827 | {address, ether_addr_t}, 828 | {broadcast, ether_addr_t}, 829 | {ifname, string_t}, 830 | {mtu, uint32_t}, 831 | {link, uint32_t}, 832 | {qdisc, string_t}, 833 | {stats, {array,uint32_t}}, 834 | {cost, binary_t}, 835 | {priority, binary_t}, 836 | {master, binary_t}, 837 | {wireless, binary_t}, 838 | {protinfo, {tlvs,rtnetlink_link_protinfo}}, 839 | {txqlen, uint32_t}, 840 | {map, if_map}, 841 | {weight, binary_t}, 842 | {operstate, {enum,uint8_t,rtnetlink_link_operstate}}, 843 | {linkmode, {enum,uint8_t,rtnetlink_link_linkmode}}, 844 | {linkinfo, {tlvs,rtnetlink_link_linkinfo}}, 845 | {net_ns_pid, binary_t}, 846 | {ifalias, string_t}, 847 | {num_vf, uint32_t}, 848 | {vfinfo_list, binary_t}, 849 | {stats64, {array,uint64_t}}, 850 | {vf_ports, binary_t}, 851 | {port_self, binary_t}, 852 | {af_spec, binary_t}, 853 | {group, uint32_t}, %% Group the device belongs to 854 | {net_ns_fd, binary_t}, 855 | {ext_mask, binary_t}, %% Extended info mask, VFs, etc 856 | {promiscuity, uint32_t} %% Promiscuity count: > 0 means acts PROMISC 857 | 858 | ] }. 859 | 860 | {attribute, rtnetlink_prefix, 861 | [ 862 | {unspec, binary_t}, 863 | {address, addr_t}, 864 | {cacheinfo, {array,uint32_t}} %% fixme: add struct rta_cacheinfo 865 | ]}. 866 | 867 | {enum, ifa_flags, 868 | [ 869 | secondary, 870 | nodad, 871 | optimistic, 872 | dadfailed, 873 | homeaddress, 874 | deprecated, 875 | tentative, 876 | permanent 877 | ]}. 878 | 879 | {record, nlmsghdr, 880 | [ 881 | {len, uint32_t}, 882 | {type, uint16_t}, 883 | {flags, uint16_t}, 884 | {seq, uint32_t}, 885 | {pid, uint32_t} 886 | ]}. 887 | 888 | {record, ifaddrmsg, 889 | [ 890 | {family, {enum,uint8_t,family}}, 891 | {prefixlen, uint8_t}, 892 | {flags, {flags,uint8_t,ifa_flags}}, 893 | {scope, uint8_t}, 894 | {index, uint32_t}, 895 | {attributes, {tlvs,rtnetlink_addr}} 896 | ]}. 897 | 898 | {record, newaddr, ifaddrmsg}. 899 | {record, deladdr, ifaddrmsg}. 900 | {record, getaddr, ifaddrmsg}. 901 | 902 | {record, ifinfomsg, 903 | [ 904 | {family, {enum,uchar_t,family}}, 905 | {'_', uchar_t}, 906 | {arphrd, {enum,ushort_t,arphrd}}, 907 | {index, int_t}, 908 | {flags, {flags,uint_t,iff_flags}}, 909 | {change, {flags,uint_t,iff_flags}}, 910 | {attributes, {tlvs,rtnetlink_link}} 911 | ]}. 912 | 913 | {record, newlink, ifinfomsg}. 914 | {record, dellink, ifinfomsg}. 915 | {record, getlink, ifinfomsg}. 916 | 917 | {record, rtmsg, 918 | [ 919 | {family, {enum,uchar_t,family}}, 920 | {dstlen, uchar_t}, 921 | {srclen, uchar_t}, 922 | {tos, uchar_t}, 923 | {table, uchar_t}, %% routing table id 924 | {protocol, {enum,uchar_t,protocol}}, 925 | {scope, uchar_t}, 926 | {rtm_type, uchar_t}, 927 | {flags, uint_t}, 928 | {attributes, {tlvs, rtnetlink_route}} 929 | ]}. 930 | 931 | {record, newroute, rtmsg}. 932 | {record, delroute, rtmsg}. 933 | {record, getroute, rtmsg}. 934 | 935 | {record, ndmsg, 936 | [ 937 | {family, {enum,uint8_t,family}}, 938 | {'_', uint8_t}, 939 | {'_', uint16_t}, 940 | {index, uint32_t}, 941 | {state, uint16_t}, 942 | {flags, uint8_t}, 943 | {nmd_type, uint8_t}, 944 | {attributes, {tlvs, rtnetlink_neigh}} 945 | ]}. 946 | 947 | {record, newneigh, ndmsg}. 948 | {record, delneigh, ndmsg}. 949 | {record, getneigh, ndmsg}. 950 | 951 | %% newrule, delrule, getrule 952 | %% newdisc, deldisc, getdisc 953 | %% newtclass, deltclass, gettclass 954 | %% newtfilter, deltfilter, gettfilter 955 | %% newaction, delaction, getaction 956 | %% newprefix, delprefix 957 | %% newneightbl, getneightbl, setneightbl 958 | %% newnduseropt 959 | %% newaddrlabel 960 | %% getdcb, setdcb 961 | 962 | {record, noop, 963 | [ 964 | ]}. 965 | 966 | {record, error, 967 | [ 968 | {errno, int_t}, 969 | {msg, nlmsghdr}, %% the original header 970 | {data, binary_t} %% truncated data? 971 | ]}. 972 | 973 | {record, done, 974 | [ 975 | {status, uint32_t} %% ? int_t? 976 | ]}. 977 | 978 | {record, overrun, 979 | [ 980 | {status, uint32_t} %% ? int_t? 981 | ]}. 982 | -------------------------------------------------------------------------------- /src/netlink_app.erl: -------------------------------------------------------------------------------- 1 | %%%---- BEGIN COPYRIGHT ------------------------------------------------------- 2 | %%% 3 | %%% Copyright (C) 2012 Feuerlabs, Inc. All rights reserved. 4 | %%% 5 | %%% This Source Code Form is subject to the terms of the Mozilla Public 6 | %%% License, v. 2.0. If a copy of the MPL was not distributed with this 7 | %%% file, You can obtain one at http://mozilla.org/MPL/2.0/. 8 | %%% 9 | %%%---- END COPYRIGHT --------------------------------------------------------- 10 | -module(netlink_app). 11 | 12 | -behaviour(application). 13 | 14 | %% Application callbacks 15 | -export([start/2, stop/1]). 16 | 17 | %% =================================================================== 18 | %% Application callbacks 19 | %% =================================================================== 20 | 21 | start(_StartType, _StartArgs) -> 22 | netlink_sup:start_link(). 23 | 24 | stop(_State) -> 25 | ok. 26 | -------------------------------------------------------------------------------- /src/netlink_codec.erl: -------------------------------------------------------------------------------- 1 | %%% @author tony 2 | %%% @copyright (C) 2013, tony 3 | %%% @doc 4 | %%% Encode / Decode of netlink messages 5 | %%% @end 6 | %%% Created : 21 May 2013 by tony 7 | 8 | -module(netlink_codec). 9 | 10 | -export([encode_flags/2]). 11 | -export([decode_flags/2]). 12 | -export([encode_tlv/1, encode_tlv_list/1]). 13 | -export([decode_tlv/1, decode_tlv_list/1]). 14 | 15 | -export([decode/2]). 16 | -export([encode/2]). 17 | 18 | -compile(export_all). 19 | 20 | -include("netlink.hrl"). 21 | -include("netl_codec.hrl"). 22 | 23 | -define(ALIGNTO, 4). 24 | -define(ALIGNMASK, (?ALIGNTO-1)). 25 | -define(NLA_ALIGN(N), (((N)+?ALIGNMASK) band (bnot ?ALIGNMASK))). 26 | -define(NLA_PAD(N), ((?ALIGNTO-((N) band ?ALIGNMASK)) band 27 | ?ALIGNMASK)). 28 | %% may need adjustment (NLA_ALIGN(sizeof(struct nlattr))) 29 | -define(NLA_HDRLEN, 4). 30 | %% -define(NLA_PAD(N), (ALIGN(N) - N)). 31 | 32 | %% prove that: 33 | %% ((N+3) band (bnot 3)) - N == (4 - (N band 3)) band 3 34 | %% 35 | 36 | encode_flags(Flags, Fun) -> 37 | encode_flags(Flags, 0, Fun). 38 | 39 | encode_flags([], Mask, _Fun) -> Mask; 40 | encode_flags([Flag|Flags], Mask, Fun) -> 41 | BitNum = Fun(Flag), 42 | encode_flags(Flags, Mask+(1 bsl BitNum), Fun). 43 | 44 | 45 | decode_flags(Value, Fun) -> 46 | decode_flags(0, Value, Fun). 47 | 48 | decode_flags(_I, 0, _Fun) -> []; 49 | decode_flags(I, Value, Fun) -> 50 | Bit = (1 bsl I), 51 | if Value band Bit =:= Bit -> 52 | [Fun(I) | decode_flags(I+1, Value band (bnot Bit), Fun)]; 53 | true -> 54 | decode_flags(I+1,Value,Fun) 55 | end. 56 | 57 | decode_attr([{Ri,_Endian,Rv}|Ds], Fun) -> 58 | [ Fun(Ri,Rv) | decode_attr(Ds, Fun)]; 59 | decode_attr([], _Fun) -> 60 | []. 61 | 62 | encode_tlv({Type0,Endian,Data}) -> 63 | Payload = if is_list(Data) -> 64 | encode_tlv_list(Data); 65 | is_binary(Data) -> Data 66 | end, 67 | Type = if is_list(Data) -> 68 | Type0 + 16#8000; 69 | Endian =:= big -> 70 | Type0 + 16#4000; 71 | true -> 72 | Type0 73 | end, 74 | Len = ?NLA_HDRLEN+byte_size(Payload), 75 | Pad = ?NLA_PAD(Len), 76 | <>. 78 | 79 | encode_tlv_list(TLVs) -> 80 | list_to_binary([encode_tlv(TLV) || TLV <- TLVs]). 81 | 82 | next_tlv(<>) -> 83 | Len = Len0 - ?NLA_HDRLEN, 84 | Pad = ?NLA_PAD(Len), 85 | <<_:Len/binary, _:Pad/unit:8, Data1/binary>> = Data, 86 | Data1. 87 | 88 | decode_tlv(<>) -> 90 | Len = Len0 - ?NLA_HDRLEN, 91 | <> = Rest, 92 | Type = Type0 band 16#3fff, 93 | if Type0 band 16#8000 =:= 16#8000 -> 94 | {Type, native, decode_tlv_list(Payload)}; 95 | Type0 band 16#4000 =:= 16#4000 -> 96 | {Type, big, Payload}; 97 | true -> 98 | {Type, native, Payload} 99 | end. 100 | 101 | decode_tlv_list(<<>>) -> 102 | []; 103 | decode_tlv_list(Data) -> 104 | TLV = decode_tlv(Data), 105 | Data1 = next_tlv(Data), 106 | [TLV | decode_tlv_list(Data1)]. 107 | 108 | 109 | decode(Part= 110 | << Len:32/native-integer, 111 | Type:16/native-integer, 112 | Flags:16/native-integer, 113 | Seq:32/native-integer, 114 | Pid:32/native-integer, 115 | Data/binary >>, Acc) -> 116 | if Len >= byte_size(Part) -> 117 | PayloadLen = Len - 16, 118 | << Payload:PayloadLen/bytes, NextPart/binary >> = Data, 119 | Msg = decode_(Type, Flags, Seq, Pid, Payload), 120 | decode(NextPart, [Msg | Acc]); 121 | true -> 122 | decode(<<>>, [{ error, format} | Acc]) 123 | end; 124 | decode(_PadPart, Acc) -> 125 | lists:reverse(Acc). 126 | 127 | decode_(Type,Flags,Seq,Pid,Payload) -> 128 | MsgType = netl_codec:dec_nlmsg_type(Type), 129 | FlagList = case msg_type(MsgType) of 130 | new -> 131 | decode_flags(Flags, fun netl_codec:dec_nlm_new_flags/1); 132 | get -> 133 | decode_flags(Flags, fun netl_codec:dec_nlm_get_flags/1); 134 | _ -> 135 | decode_flags(Flags, fun netl_codec:dec_nlm_flags/1) 136 | end, 137 | MsgPayload = apply(netl_codec, 138 | list_to_atom("dec_"++atom_to_list(MsgType)), 139 | [{native,Payload}]), 140 | H = #nlmsghdr { type=MsgType, flags=FlagList, seq=Seq, pid=Pid }, 141 | #nlmsg { hdr = H, data=MsgPayload }. 142 | 143 | encode(#nlmsghdr { type=MsgType, flags=FlagList, seq=Seq, pid=Pid }, 144 | MsgPayload ) -> 145 | Type = netl_codec:enc_nlmsg_type(MsgType), 146 | Flags = case msg_type(MsgType) of 147 | new -> 148 | encode_flags(FlagList, fun netl_codec:enc_nlm_new_flags/1); 149 | get -> 150 | encode_flags(FlagList, fun netl_codec:enc_nlm_get_flags/1); 151 | _ -> 152 | encode_flags(FlagList, fun netl_codec:enc_nlm_flags/1) 153 | end, 154 | Payload = apply(netl_codec, 155 | list_to_atom("enc_"++atom_to_list(MsgType)), 156 | [{native,MsgPayload}]), 157 | N = byte_size(Payload), 158 | Pad = ?NLA_PAD(N), 159 | Len = 16 + Pad + N, 160 | << Len:32/native-integer, 161 | Type:16/native-integer, 162 | Flags:16/native-integer, 163 | Seq:32/native-integer, 164 | Pid:32/native-integer, 165 | Payload/binary, 166 | 0:Pad/unit:8 >>. 167 | 168 | msg_type(Type) -> 169 | case Type of 170 | noop -> misc; 171 | error -> misc; 172 | done -> misc; 173 | overrun -> misc; 174 | newlink -> new; 175 | dellink -> del; 176 | getlink -> get; 177 | setlink -> set; 178 | newaddr -> new; 179 | deladdr -> del; 180 | getaddr -> get; 181 | newroute -> new; 182 | delroute -> del; 183 | getroute -> get; 184 | newneigh -> new; 185 | delneigh -> del; 186 | getneigh -> get; 187 | newrule -> new; 188 | delrule -> del; 189 | getrule -> get; 190 | newdisc -> new; 191 | delqdisc -> del; 192 | getqdisc -> get; 193 | newtclass -> new; 194 | deltclass -> del; 195 | gettclass -> get; 196 | newtfilter -> new; 197 | deltfilter -> del; 198 | gettfilter -> get; 199 | newaction -> new; 200 | delaction -> del; 201 | getaction -> get; 202 | newprefix -> new; 203 | getmulticast -> get; 204 | getanycast -> get; 205 | newneightbl -> new; 206 | getneightbl -> get; 207 | setneightbl -> set; 208 | newnduseropt -> new; 209 | newaddrlabel -> new; 210 | deladdrlabel -> del; 211 | getaddrlabel -> get; 212 | getdcb -> get; 213 | setdcb -> set 214 | end. 215 | -------------------------------------------------------------------------------- /src/netlink_drv.erl: -------------------------------------------------------------------------------- 1 | %%%---- BEGIN COPYRIGHT ------------------------------------------------------- 2 | %%% 3 | %%% Copyright (C) 2012 Feuerlabs, Inc. All rights reserved. 4 | %%% 5 | %%% This Source Code Form is subject to the terms of the Mozilla Public 6 | %%% License, v. 2.0. If a copy of the MPL was not distributed with this 7 | %%% file, You can obtain one at http://mozilla.org/MPL/2.0/. 8 | %%% 9 | %%%---- END COPYRIGHT --------------------------------------------------------- 10 | %%% @author Tony Rogvall 11 | %%% @doc 12 | %%% launch netlink_drv 13 | %%% @end 14 | %%% Created : 30 Nov 2011 by Tony Rogvall 15 | 16 | -module(netlink_drv). 17 | -export([open/1, close/1, send/2]). 18 | -export([add_membership/2, 19 | drop_membership/2, 20 | set_rcvbuf/2, set_sndbuf/2, 21 | get_rcvbuf/1, get_sndbuf/1, 22 | get_sizeof/1, 23 | deactivate/1, 24 | activate/1, 25 | activate/2, 26 | debug/2]). 27 | 28 | %% deugging 29 | -compile(export_all). 30 | 31 | -include("netlink.hrl"). 32 | 33 | -define(CMD_ADD_MEMBERSHIP, 1). 34 | -define(CMD_DROP_MEMBERSHIP, 2). 35 | -define(CMD_ACTIVE, 3). 36 | -define(CMD_DEBUG, 4). 37 | -define(CMD_SET_RCVBUF, 5). 38 | -define(CMD_SET_SNDBUF, 6). 39 | -define(CMD_GET_RCVBUF, 7). 40 | -define(CMD_GET_SNDBUF, 8). 41 | -define(CMD_GET_SIZEOF, 9). 42 | 43 | -define(DLOG_DEBUG, 7). 44 | -define(DLOG_INFO, 6). 45 | -define(DLOG_NOTICE, 5). 46 | -define(DLOG_WARNING, 4). 47 | -define(DLOG_ERROR, 3). 48 | -define(DLOG_CRITICAL, 2). 49 | -define(DLOG_ALERT, 1). 50 | -define(DLOG_EMERGENCY, 0). 51 | -define(DLOG_NONE, -1). 52 | 53 | add_membership(Port,Msg) when is_integer(Msg) -> 54 | port_call(Port, ?CMD_ADD_MEMBERSHIP, <>). 55 | 56 | drop_membership(Port,Msg) when is_integer(Msg) -> 57 | port_call(Port, ?CMD_DROP_MEMBERSHIP, <>). 58 | 59 | set_rcvbuf(Port,Size) when is_integer(Size), Size >= 0 -> 60 | port_call(Port, ?CMD_SET_RCVBUF, <>). 61 | 62 | set_sndbuf(Port,Size) when is_integer(Size), Size >= 0 -> 63 | port_call(Port, ?CMD_SET_SNDBUF, <>). 64 | 65 | get_rcvbuf(Port) -> 66 | port_call(Port, ?CMD_GET_RCVBUF, <<>>). 67 | 68 | get_sndbuf(Port) -> 69 | port_call(Port, ?CMD_GET_SNDBUF, <<>>). 70 | 71 | get_sizeof(Port) -> 72 | port_call(Port, ?CMD_GET_SIZEOF, <<>>). 73 | 74 | deactivate(Port) -> 75 | activate(Port, 0). 76 | 77 | activate(Port) -> 78 | activate(Port, -1). 79 | 80 | activate(Port, N) when is_integer(N), N >= -1, N < 16#7fffffff -> 81 | port_call(Port, ?CMD_ACTIVE, <>). 82 | 83 | debug(Port,Level) when is_atom(Level) -> 84 | L = level(Level), 85 | port_call(Port, ?CMD_DEBUG, <>). 86 | 87 | open(Protocol) when is_integer(Protocol), Protocol >= 0 -> 88 | Driver = "netlink_drv", 89 | Path = code:priv_dir(netlink), 90 | io:format("load_driver '~s' from: '~s'\n", [Driver, Path]), 91 | case erl_ddll:load_driver(Path, Driver) of 92 | ok -> 93 | Arg = integer_to_list(Protocol), 94 | erlang:open_port({spawn_driver, Driver++" "++Arg}, [binary]); 95 | {error,Error} -> 96 | io:format("Error: ~s\n", [erl_ddll:format_error_int(Error)]), 97 | erlang:error(Error) 98 | end. 99 | 100 | close(Port) -> 101 | erlang:port_close(Port). 102 | 103 | send(Port, Command) -> 104 | erlang:port_command(Port, Command). 105 | 106 | port_call(Port, Cmd, Data) -> 107 | case erlang:port_control(Port, Cmd, Data) of 108 | <<0>> -> 109 | ok; 110 | <<255,E/binary>> -> 111 | {error, erlang:binary_to_atom(E, latin1)}; 112 | <<254,E/binary>> -> 113 | {error, binary_to_list(E)}; 114 | <<1,Y:8>> -> {ok,Y}; 115 | <<1,Y:16/native-unsigned>> -> {ok, Y}; 116 | <<1,Y:32/native-unsigned>> -> {ok, Y}; 117 | <<1,Y:64/native-unsigned>> -> {ok, Y}; 118 | <<2,X:32/native-unsigned,Y:32/native-unsigned>> -> {ok,{X,Y}}; 119 | <<3,X/binary>> -> {ok,X}; 120 | <<4,X/binary>> -> {ok,binary_to_list(X)} 121 | end. 122 | 123 | %% convert symbolic to numeric level 124 | level(true) -> ?DLOG_DEBUG; 125 | level(false) -> ?DLOG_NONE; 126 | level(debug) -> ?DLOG_DEBUG; 127 | level(info) -> ?DLOG_INFO; 128 | level(notice) -> ?DLOG_NOTICE; 129 | level(warning) -> ?DLOG_WARNING; 130 | level(error) -> ?DLOG_ERROR; 131 | level(critical) -> ?DLOG_CRITICAL; 132 | level(alert) -> ?DLOG_ALERT; 133 | level(emergency) -> ?DLOG_EMERGENCY; 134 | level(none) -> ?DLOG_NONE. 135 | 136 | -------------------------------------------------------------------------------- /src/netlink_gen.erl: -------------------------------------------------------------------------------- 1 | %%% @author tony 2 | %%% @copyright (C) 2013, tony 3 | %%% @doc 4 | %%% Generate netlink decoder & header files 5 | %%% @end 6 | %%% Created : 29 May 2013 by tony 7 | 8 | -module(netlink_gen). 9 | 10 | -compile(export_all). 11 | 12 | -define(INFILE, "netlink.inc"). 13 | -define(ERL_MOD, "netl_codec"). 14 | 15 | -define(INT_SIZE_32, true). 16 | -define(LONG_SIZE_32, true). 17 | 18 | -ifdef(INT_SIZE_32). 19 | -define(int_t, int32_t). 20 | -define(uint_t, uint32_t). 21 | -else. 22 | -ifdef(INT_SIZE_64). 23 | -define(int_t, int64_t). 24 | -define(uint_t, uint64_t). 25 | -endif. 26 | -endif. 27 | 28 | -ifdef(LONG_SIZE_32). 29 | -define(long_t, int32_t). 30 | -define(ulong_t, uint32_t). 31 | -else. 32 | -ifdef(LONG_SIZE_64). 33 | -define(long_t, int64_t). 34 | -define(ulong_t, uint64_t). 35 | -endif. 36 | -endif. 37 | 38 | -define(short_t, int16_t). 39 | -define(ushort_t, uint16_t). 40 | 41 | -define(char_t, int8_t). 42 | -define(uchar_t, uint8_t). 43 | 44 | 45 | -record(gen, 46 | { 47 | error = 0 :: integer(), %% number of errors detected 48 | defs :: term(), %% Symbol -> Value 49 | enums :: term(), %% Name->[{atom(),integer()}]} 50 | attrs :: term(), %% Name->[{atom(),integer(),type()}] 51 | recs :: term() %% Name->[{atom(),integer(),type()}] 52 | }). 53 | 54 | start() -> 55 | G0 = #gen { defs = dict:new(), 56 | enums = dict:new(), 57 | attrs = dict:new(), 58 | recs = dict:new() }, 59 | {ok,Fd} = file:open(?INFILE, [read]), 60 | try fold_file_terms(fun load_term/3, G0, Fd) of 61 | {ok,G1} -> 62 | ok = emit_hrl(G1), 63 | ok = emit_erl(G1); 64 | Error -> Error 65 | after 66 | file:close(Fd) 67 | end. 68 | 69 | load_term({define,Name,Value},Ln,G) -> 70 | Value1 = lookup_value(Value, G), 71 | D = case dict:find(Name, G#gen.defs) of 72 | {ok,Value1} -> 73 | G#gen.defs; 74 | {ok,_Value2} -> 75 | io:format("~s:~w: warning ~s redefined\n", 76 | [?INFILE,Ln,Name]), 77 | dict:store(Name,Value1,G#gen.defs); 78 | error -> 79 | dict:store(Name,Value1,G#gen.defs) 80 | end, 81 | G#gen { defs = D }; 82 | load_term({enum,Name,Enums}, Ln, G) when is_atom(Name), is_list(Enums) -> 83 | case dict:find(Name, G#gen.enums) of 84 | {ok,_Enums} -> 85 | io:format("~s:~w: error ~s allready defined\n", 86 | [?INFILE,Ln,Name]), 87 | G1 = inc_error(G), 88 | load_enums(Name,Enums,Ln,G1); 89 | error -> 90 | load_enums(Name,Enums,Ln,G) 91 | end; 92 | load_term({attribute,Name,Attrs}, Ln, G) when is_atom(Name), is_list(Attrs) -> 93 | case dict:find(Name, G#gen.attrs) of 94 | {ok,_Attrs} -> 95 | io:format("~s:~w: error ~s allready defined\n", 96 | [?INFILE,Ln,Name]), 97 | G1 = inc_error(G), 98 | load_attrs(Name,Attrs,Ln,G1); 99 | error -> 100 | load_attrs(Name,Attrs,Ln,G) 101 | end; 102 | load_term({record,Name,Fields}, Ln, G) when is_atom(Name), is_list(Fields) -> 103 | case dict:find(Name, G#gen.recs) of 104 | {ok,_Attrs} -> 105 | io:format("~s:~w: error ~s allready defined\n", 106 | [?INFILE,Ln,Name]), 107 | G1 = inc_error(G), 108 | load_fields(Name,Fields,Ln,G1); 109 | error -> 110 | load_fields(Name,Fields,Ln,G) 111 | end; 112 | load_term({record,Name,Type}, Ln, G) when is_atom(Name), is_atom(Type) -> 113 | case dict:find(Type, G#gen.recs) of 114 | error -> 115 | io:format("~s:~w: error ~s not defined\n", 116 | [?INFILE,Ln,Type]), 117 | G1 = inc_error(G), 118 | G2 = load_fields(Type,[],Ln,G1), 119 | load_fields(Name,Type,Ln,G2); 120 | {ok,_} -> 121 | case dict:find(Name, G#gen.recs) of 122 | {ok,_Attrs} -> 123 | io:format("~s:~w: error ~s allready defined\n", 124 | [?INFILE,Ln,Name]), 125 | G1 = inc_error(G), 126 | load_fields(Name,Type,Ln,G1); 127 | error -> 128 | load_fields(Name,Type,Ln,G) 129 | end 130 | end; 131 | load_term(Other, Ln, G) -> 132 | io:format("~s:~w: error badly formed term ~p\n", [?INFILE,Ln,Other]), 133 | inc_error(G). 134 | 135 | 136 | %% 137 | %% Load enums, enumerate warn about multiple usage of names and values! 138 | %% 139 | load_enums(Name,Enums0,Ln,G) -> 140 | Enums = enumerate(Enums0,G), 141 | G1 = check_enumeration(Name,Enums,Ln,G), 142 | D = dict:store(Name, Enums, G1#gen.enums), 143 | G1#gen { enums = D}. 144 | 145 | check_enumeration(Name,[{E,V}|Es],Ln,G) -> 146 | case lists:keyfind(E,1,Es) of 147 | false -> 148 | case lists:keyfind(V,2,Es) of 149 | false -> 150 | check_enumeration(Name,Es,Ln,G); 151 | {E1,V} -> 152 | io:format("~s:~w: value for ~w also used by ~w\n", 153 | [?INFILE,Ln,E,E1]), 154 | G1 = inc_error(G), 155 | check_enumeration(Name,Es,Ln,G1) 156 | end; 157 | {E,_V1} -> 158 | io:format("~s:~w: enum ~s multiply defined\n", 159 | [?INFILE,Ln,E]), 160 | G1 = inc_error(G), 161 | check_enumeration(Name,Es,Ln,G1) 162 | end; 163 | check_enumeration(_Name, [], _Ln,G) -> 164 | G. 165 | 166 | %% generate uniq values for names not assigne values 167 | enumerate(Enums,G) -> 168 | Enums1 = lists:map(fun({E,V}) -> {E,lookup_value(V,G)}; 169 | (E) -> E 170 | end, Enums), 171 | Vs0 = lists:foldl(fun({_E,V},Acc) -> [V|Acc]; 172 | (_E,Acc) -> Acc 173 | end, [], Enums1), 174 | Vs1 = lists:usort(Vs0), 175 | enumerate(Enums1, 0, Vs1). 176 | 177 | enumerate([{E,V}|Es], I, Vs) when is_atom(E) -> 178 | [{E,V}|enumerate(Es, I, Vs)]; 179 | enumerate(Es0=[E|Es], I, Vs) when is_atom(E) -> 180 | case lists:member(I,Vs) of 181 | true -> enumerate(Es0,I+1,Vs); 182 | false -> [{E,I}|enumerate(Es,I+1,Vs)] 183 | end; 184 | enumerate([],_I,_Vs) -> 185 | []. 186 | 187 | %% 188 | %% Load record fields 189 | %% 190 | load_fields(Name,Type,_Ln,G) when is_atom(Type) -> 191 | D = dict:store(Name, Type, G#gen.recs), 192 | G#gen { recs = D }; 193 | load_fields(Name,Fields,Ln,G) -> 194 | Fields1 = [{F,I,T} || 195 | {I,{F,T}} <- 196 | lists:zip(lists:seq(1,length(Fields)),Fields)], 197 | G1 = check_fields(Name,Fields1,Ln,G), 198 | D = dict:store(Name, Fields1, G1#gen.recs), 199 | G1#gen { recs = D }. 200 | 201 | check_fields(Name,[{'_',_I,T}|Fs],Ln,G) -> 202 | G1 = check_type({record,Name,'_'}, T, Ln, G), 203 | check_fields(Name, Fs, Ln, G1); 204 | check_fields(Name,[{F,_I,T}|Fs],Ln,G) -> 205 | case lists:keymember(F,1,Fs) of 206 | true -> 207 | io:format("~s:~w: field ~s multiply defined\n", 208 | [?INFILE,Ln,F]), 209 | G1 = inc_error(G), 210 | G2 = check_type({record,Name,F}, T, Ln, G1), 211 | check_fields(Name, Fs, Ln, G2); 212 | false -> 213 | G1 = check_type({record,Name,F}, T, Ln, G), 214 | check_fields(Name, Fs, Ln, G1) 215 | end; 216 | check_fields(_Name,[],_Ln,G) -> 217 | G. 218 | %% 219 | %% Load attribute fields 220 | %% 221 | load_attrs(Name,Attrs,Ln,G) -> 222 | Attrs1 = [{A,I,T} || 223 | {I,{A,T}} <- lists:zip(lists:seq(0,length(Attrs)-1),Attrs)], 224 | G1 = check_attrs(Name,Attrs1,Ln,G), 225 | D = dict:store(Name, Attrs1, G1#gen.attrs), 226 | G1#gen { attrs = D }. 227 | 228 | check_attrs(Name,[{A,_I,T}|As],Ln,G) -> 229 | case lists:keymember(A,1,As) of 230 | true -> 231 | io:format("~s:~w: attribute ~s multiply defined\n", 232 | [?INFILE,Ln,A]), 233 | G1 = inc_error(G), 234 | G2 = check_type({attribute,Name,A}, T, Ln, G1), 235 | check_attrs(Name, As, Ln, G2); 236 | false -> 237 | G1 = check_type({attribute,Name,A}, T, Ln, G), 238 | check_attrs(Name, As, Ln, G1) 239 | end; 240 | check_attrs(_Name,[],_Ln,G) -> 241 | G. 242 | 243 | 244 | emit_hrl(G) -> 245 | {ok,Fd} = file:open(?ERL_MOD++".hrl", [write]), 246 | try 247 | dict:fold( 248 | fun(K,V,_A) -> 249 | io:format(Fd, "-define(~s, ~w).\n", [K, V]) 250 | end, ok, G#gen.defs), 251 | dict:fold( 252 | fun(K,V,_A) -> 253 | Fields = lookup_fields(V, G), 254 | Fs = list_to_tuple([N || {N,_I,_Type} <- Fields, N =/= '_']), 255 | io:format(Fd, "-record(~s, ~w).\n", [K, Fs]) 256 | end, ok, G#gen.recs) 257 | of 258 | R -> R 259 | after 260 | file:close(Fd) 261 | end. 262 | 263 | 264 | emit_erl(G) -> 265 | {ok,Fd} = file:open(?ERL_MOD++".erl", [write]), 266 | io:format(Fd, "-module(~s).\n", [?ERL_MOD]), 267 | io:format(Fd, "-include(~p).\n", [?ERL_MOD++".hrl"]), 268 | try emit_codec_(Fd, G) of 269 | ok -> ok 270 | after 271 | file:close(Fd) 272 | end. 273 | 274 | emit_codec_(Fd, G) -> 275 | dict:fold( 276 | fun(Name,_Tab,_) -> 277 | io:format(Fd, "-export([dec_~s/1, enc_~s/1]).\n", 278 | [Name,Name]) 279 | end, ok, G#gen.enums), 280 | dict:fold( 281 | fun(Name,_Tab,_) -> 282 | io:format(Fd, "-export([dec_~s/1, enc_~s/1]).\n", 283 | [Name,Name]) 284 | end, ok, G#gen.attrs), 285 | dict:fold( 286 | fun(Name,_Tab,_) -> 287 | io:format(Fd, "-export([dec_~s/1, enc_~s/1]).\n", 288 | [Name,Name]) 289 | end, ok, G#gen.recs), 290 | 291 | 292 | dict:fold( 293 | fun(Name,Tab,_) -> 294 | %% decode 295 | lists:foreach( 296 | fun({Enum,Value}) -> 297 | io:format(Fd,"dec_~s(~w) -> ~s;\n", [Name,Value,Enum]) 298 | end, Tab), 299 | io:format(Fd,"dec_~s(V) -> V.\n", [Name]), 300 | %% encode 301 | lists:foreach( 302 | fun({Enum,Value}) -> 303 | io:format(Fd,"enc_~s(~s) -> ~w;\n", [Name,Enum,Value]) 304 | end, Tab), 305 | io:format(Fd,"enc_~s(V) when is_integer(V) -> V;\n", [Name]), 306 | io:format(Fd,"enc_~s(E) -> erlang:error({undefined,E}).\n", 307 | [Name]) 308 | end, ok, G#gen.enums), 309 | 310 | dict:fold( 311 | fun(Name,Tab0,_) -> 312 | %% extend addr_t => ipv4_addr_t | ipv6_addr_t 313 | Tab = lists:foldr( 314 | fun({A,I,addr_t},Acc) -> 315 | [{A,I,ipv4_addr_t},{A,I,ipv6_addr_t} | Acc]; 316 | (E,Acc) -> [E|Acc] 317 | end, [], Tab0), 318 | lists:foreach( 319 | fun({Attr,Index,Type}) -> 320 | {M1,R1} = match_code(Type,native,"X",G), 321 | io:format(Fd, 322 | "dec_~s({~w,native,<<~s>>}) ->\n" 323 | " {~s,~s};\n", 324 | [Name,Index,M1,Attr,R1]), 325 | {M2,R2} = match_code(Type,big,"X",G), 326 | io:format(Fd, 327 | "dec_~s({~w,big,<<~s>>}) ->\n" 328 | " {~s,~s};\n", 329 | [Name,Index,M2,Attr,R2]) 330 | end, Tab), 331 | io:format(Fd,"dec_~s({I,_Endian,Bin}) -> {I,Bin}.\n", [Name]), 332 | 333 | lists:foreach( 334 | fun({Attr,Index,Type}) -> 335 | {M1,C1} = gen_code(Type,native,"X",G), 336 | io:format(Fd,"enc_~s({~s,native,~s}) ->\n" 337 | " {~w,native,<<~s>>};\n", 338 | [Name,Attr,M1,Index,C1]), 339 | {M2,C2} = gen_code(Type,big,"X",G), 340 | io:format(Fd,"enc_~s({~s,big,~s}) ->\n" 341 | " {~w,big,<<~s>>};\n", 342 | [Name,Attr,M2,Index,C2]) 343 | end, Tab), 344 | io:format(Fd,"enc_~s({I,Endian,X}) -> {I,Endian,X}.\n", [Name]) 345 | end, ok, G#gen.attrs), 346 | 347 | dict:fold( 348 | fun(Name,RecType,_) -> 349 | Fields = lookup_fields(RecType, G), 350 | Named = [{Fi,Ix,Ti} || {Fi,Ix,Ti} <- Fields, Fi =/= '_'], 351 | {Ms,Rs} = match_record_code(Fields, native, "X", G), 352 | M = io_list_join(Ms, ","), 353 | Rs1 = lists:map(fun({{Fi,_,_Ti},Ri}) -> 354 | [atom_to_list(Fi),"=",Ri] 355 | end, lists:zip(Named,Rs)), 356 | R1 = ["#",atom_to_list(Name),"{", io_list_join(Rs1,","), "}"], 357 | 358 | io:format(Fd,"dec_~s({native,<<~s>>}) ->\n" 359 | " ~s.\n", 360 | [Name,M,R1]), 361 | 362 | {Ts,Bs} = gen_record_code(Fields, native, "X", G), 363 | Ts1 = lists:map(fun({{Fi,_,_Ti},Ri}) -> 364 | [atom_to_list(Fi),"=",Ri] 365 | end, lists:zip(Named,Ts)), 366 | R2 = ["#",atom_to_list(Name),"{", io_list_join(Ts1,","), "}"], 367 | B = io_list_join(Bs, ","), 368 | io:format(Fd,"enc_~s({_Endian,~s}) -> <<~s>>.\n", 369 | [Name,R2,B]), 370 | ok 371 | end, ok, G#gen.recs). 372 | 373 | 374 | check_type(Ctx, {array,T}, Ln, G) -> 375 | case is_base_type(T) of 376 | true -> 377 | G; 378 | false -> 379 | io:format("~s:~w: type ~w not allowed as base type in ~w\n", 380 | [?INFILE,Ln,T,Ctx]), 381 | inc_error(G) 382 | end; 383 | check_type(_Ctx, {enum,Type,Enum}, Ln, G) 384 | when is_atom(Type), is_atom(Enum) -> 385 | case is_integer_type(Type) of 386 | true -> 387 | case dict:find(Enum, G#gen.enums) of 388 | {ok,_} -> G; 389 | error -> 390 | io:format("~s:~w: enum type ~s not defined\n", 391 | [?INFILE,Ln,Enum]), 392 | inc_error(G) 393 | end; 394 | false -> 395 | io:format("~s:~w: enum must have an integer base type\n", 396 | [?INFILE,Ln]), 397 | inc_error(G) 398 | end; 399 | check_type(_Ctx, {flags,Type,Enum}, Ln, G) 400 | when is_atom(Type), is_atom(Enum) -> 401 | case is_unsigned_type(Type) of 402 | true -> 403 | case dict:find(Enum, G#gen.enums) of 404 | {ok,_} -> G; 405 | error -> 406 | io:format("~s:~w: enum type ~s not defined\n", 407 | [?INFILE,Ln,Enum]), 408 | inc_error(G) 409 | end; 410 | false -> 411 | io:format("~s:~w: flags must have an unsigned base type\n", 412 | [?INFILE,Ln]), 413 | inc_error(G) 414 | end; 415 | check_type(Ctx, {tlvs,Name}, Ln, G) -> 416 | %% fixme, check that Ctx is {attribute,...} 417 | case dict:find(Name, G#gen.attrs) of 418 | error -> 419 | io:format("~s:~w: attribute type ~s name not found in ~w\n", 420 | [?INFILE,Ln,Name,Ctx]), 421 | inc_error(G); 422 | {ok,_} -> 423 | G 424 | end; 425 | check_type(Ctx, T, Ln, G) -> 426 | case is_base_type(T) of 427 | true -> G; 428 | false -> 429 | case T of 430 | string_t -> G; 431 | binary_t -> G; 432 | Type when is_atom(Type) -> 433 | case lookup_type(Type, G) of 434 | false -> 435 | io:format("~s:~w: type ~s name not found in ~w\n", 436 | [?INFILE,Ln,Type,Ctx]), 437 | inc_error(G); 438 | _Typedef -> 439 | G 440 | end; 441 | _ -> 442 | io:format("~s:~w: type ~w not allowed in ~w\n", 443 | [?INFILE,Ln,T,Ctx]), 444 | inc_error(G) 445 | end 446 | end. 447 | 448 | is_base_type(T) -> 449 | case is_integer_type(T) of 450 | true -> true; 451 | false -> 452 | case T of 453 | addr_t -> true; 454 | ether_addr_t -> true; 455 | ipv4_addr_t -> true; 456 | ipv6_addr_t -> true; 457 | _ -> false 458 | end 459 | end. 460 | 461 | is_integer_type(T) -> 462 | is_unsigned_type(T) orelse is_signed_type(T). 463 | 464 | is_unsigned_type(T) -> 465 | case T of 466 | ulong_t -> true; 467 | ushort_t -> true; 468 | uchar_t -> true; 469 | uint_t -> true; 470 | uint8_t -> true; 471 | uint16_t -> true; 472 | uint32_t -> true; 473 | uint64_t -> true; 474 | _ -> false 475 | end. 476 | 477 | is_signed_type(T) -> 478 | case T of 479 | long_t -> true; 480 | int_t -> true; 481 | short_t -> true; 482 | char_t -> true; 483 | int8_t -> true; 484 | int16_t -> true; 485 | int32_t -> true; 486 | int64_t -> true; 487 | _ -> false 488 | end. 489 | %% 490 | %% generate match code 491 | %% {BitMatch, TermCode} 492 | %% 493 | match_code(int_t, E, X, G) -> match_code(?int_t, E, X, G); 494 | match_code(uint_t, E, X, G) -> match_code(?uint_t, E, X, G); 495 | match_code(long_t, E, X, G) -> match_code(?long_t, E, X, G); 496 | match_code(ulong_t, E, X, G) -> match_code(?ulong_t, E, X, G); 497 | match_code(short_t, E, X, G) -> match_code(?short_t, E, X, G); 498 | match_code(ushort_t, E, X, G) -> match_code(?ushort_t, E, X, G); 499 | match_code(char_t, E, X, G) -> match_code(?char_t, E, X, G); 500 | match_code(uchar_t, E, X, G) -> match_code(?uchar_t, E, X, G); 501 | 502 | match_code(uint64_t,native,X,_G) -> match_int_code(X,64,unsigned,native); 503 | match_code(uint32_t,native,X,_G) -> match_int_code(X,32,unsigned,native); 504 | match_code(uint16_t,native,X,_G) -> match_int_code(X,16,unsigned,native); 505 | match_code(uint8_t,native,X,_G) -> match_int_code(X,8,unsigned,native); 506 | match_code(uint64_t,big,X,_G) -> match_int_code(X,64,unsigned,big); 507 | match_code(uint32_t,big,X,_G) -> match_int_code(X,32,unsigned,big); 508 | match_code(uint16_t,big,X,_G) -> match_int_code(X,16,unsigned,big); 509 | match_code(uint8_t,big,X,_G) -> match_int_code(X,8,unsigned,big); 510 | match_code(uint64_t,little,X,_G) -> match_int_code(X,64,unsigned,little); 511 | match_code(uint32_t,little,X,_G) -> match_int_code(X,32,unsigned,little); 512 | match_code(uint16_t,little,X,_G) -> match_int_code(X,16,unsigned,little); 513 | match_code(uint8_t,little,X,_G) -> match_int_code(X,8,unsigned,little); 514 | 515 | match_code(int64_t,native,X,_G) -> match_int_code(X,64,signed,native); 516 | match_code(int32_t,native,X,_G) -> match_int_code(X,32,signed,native); 517 | match_code(int16_t,native,X,_G) -> match_int_code(X,16,signed,native); 518 | match_code(int8_t,native,X,_G) -> match_int_code(X,8,signed,native); 519 | match_code(int64_t,big,X,_G) -> match_int_code(X,64,signed,big); 520 | match_code(int32_t,big,X,_G) -> match_int_code(X,32,signed,big); 521 | match_code(int16_t,big,X,_G) -> match_int_code(X,16,signed,big); 522 | match_code(int8_t, big,X,_G) -> match_int_code(X,8,signed,big); 523 | match_code(int64_t,little,X,_G) -> match_int_code(X,64,signed,little); 524 | match_code(int32_t,little,X,_G) -> match_int_code(X,32,signed,little); 525 | match_code(int16_t,little,X,_G) -> match_int_code(X,16,signed,little); 526 | match_code(int8_t,little,X,_G) -> match_int_code(X,8,signed,little); 527 | match_code(binary_t,_Endian,X,_G) -> 528 | {[X,"/binary"],X}; 529 | match_code(string_t,_Endian,X,_G) -> 530 | {[X,"/binary"], ["binary_to_list(hd(binary:split(",X,",","<<0>>)))"]}; 531 | 532 | match_code({enum,BaseType,Name},Endian,X,G) -> 533 | Xe = X++"e", 534 | Decode = "dec_"++atom_to_list(Name), 535 | {Match,Value} = match_code(BaseType,Endian,Xe,G), 536 | {Match,[Decode,"(",Value,")"]}; 537 | match_code({flags,BaseType,Name},Endian,X,G) -> 538 | Xf = X++"f", 539 | Decode = "dec_"++atom_to_list(Name), 540 | {Match,Value} = match_code(BaseType,Endian,Xf,G), 541 | {Match,["netlink_codec:decode_flags(",Value,",fun ",Decode,"/1)"]}; 542 | match_code({array,BaseType},Endian,X,G) -> 543 | %% [Xi || <> <= X ] 544 | Xi = X++"i", 545 | %% Well, Xi must be equal to Value here! 546 | {Match,Value} = match_code(BaseType,Endian,Xi,G), 547 | {[X,"/binary"], ["[",Value," || <<",Match,">> <= ",X,"]"] }; 548 | match_code({tlvs,Name},_Endian,X,_G) -> 549 | Xi = X++"i", 550 | Decode = "dec_"++atom_to_list(Name), 551 | {[X,"/binary"], 552 | ["[",Decode,"(",Xi,") || ", 553 | Xi," <- netlink_codec:decode_tlv_list(",X,")]"]}; 554 | match_code(ether_addr_t, _, X,_G) -> 555 | Xs = [X++integer_to_list(I) || I <- lists:seq(1,6)], 556 | {string:join(Xs,","), ["{", string:join(Xs,","), "}"]}; 557 | match_code(ipv4_addr_t, _, X,_G) -> 558 | Xi = [X++integer_to_list(I) || I <- lists:seq(1,4)], 559 | Xm = [J++":8" || J <- Xi], 560 | {string:join(Xm,","), 561 | ["{", string:join(Xi,","), "}"]}; 562 | match_code(ipv6_addr_t,_,X,_G) -> 563 | Xi = [X++integer_to_list(I) || I <- lists:seq(1,8)], 564 | Xm = [J++":16" || J <- Xi], 565 | {string:join(Xm,","), 566 | ["{", string:join(Xi,","), "}"]}; 567 | %% match_code(addr_t,_,X,_G) -> 568 | %% Xi = [X++integer_to_list(I) || I <- lists:seq(1,4)], 569 | %% Xm = [J++":8" || J <- Xi], 570 | %% {string:join(Xm,","), 571 | %% ["{", string:join(Xi,","), "}"]}; 572 | match_code(Name,Endian,X,G) -> 573 | case dict:find(Name, G#gen.recs) of 574 | error -> 575 | %% assume attribute! 576 | {ok,_} = dict:find(Name, G#gen.attrs), 577 | Decode = "dec_"++atom_to_list(Name), 578 | {[X,"/binary"], [Decode,"(netlink_codec:decode_tlv(",X,"))"]}; 579 | {ok,RecType} -> 580 | Fields = lookup_fields(RecType,G), 581 | Named = [{Fi,Ix,Ti} || {Fi,Ix,Ti} <- Fields, Fi =/= '_'], 582 | {Ms,Rs} = match_record_code(Fields, Endian, X, G), 583 | M = io_list_join(Ms, ","), 584 | Rs1 = lists:map(fun({{Fi,_,_Ti},Ri}) -> 585 | [atom_to_list(Fi),"=",Ri] 586 | end, lists:zip(Named,Rs)), 587 | R = ["#",atom_to_list(Name),"{", io_list_join(Rs1,","), "}"], 588 | {M, R} 589 | end. 590 | 591 | match_record_code(Fs, Endian, X, G) -> 592 | match_record_code_(Fs, Endian, X, G, [], []). 593 | 594 | match_record_code_([{'_',_Ix,Type}|Fs], Endian, X, G, Ms, Rs) -> 595 | {M,_R} = match_code(Type, Endian, "_", G), 596 | match_record_code_(Fs, Endian, X, G, [M|Ms], Rs); 597 | match_record_code_([{_Field,Ix,Type}|Fs], Endian, X, G, Ms, Rs) -> 598 | Xi = X++integer_to_list(Ix), 599 | {M,R} = match_code(Type, Endian, Xi, G), 600 | match_record_code_(Fs, Endian, X, G, [M|Ms], [R|Rs]); 601 | match_record_code_([], _Endian, _X, _G, Ms, Rs) -> 602 | {lists:reverse(Ms), lists:reverse(Rs)}. 603 | 604 | %% 605 | %% X:Size/- => Decode 606 | %% {BitMatch,Decode} 607 | %% 608 | match_int_code(X,Size,Sign,Endian) -> 609 | {[X,":",integer_to_list(Size),"/", 610 | atom_to_list(Sign),"-",atom_to_list(Endian)], X}. 611 | 612 | %% 613 | %% generate generate-code 614 | %% return {Encode, BitConstruct} 615 | %% 616 | gen_code(int_t, E, X, G) -> gen_code(?int_t, E, X, G); 617 | gen_code(uint_t, E, X, G) -> gen_code(?uint_t, E, X, G); 618 | gen_code(long_t, E, X, G) -> gen_code(?long_t, E, X, G); 619 | gen_code(ulong_t, E, X, G) -> gen_code(?ulong_t, E, X, G); 620 | gen_code(short_t, E, X, G) -> gen_code(?short_t, E, X, G); 621 | gen_code(ushort_t, E, X, G) -> gen_code(?ushort_t, E, X, G); 622 | gen_code(char_t, E, X, G) -> gen_code(?char_t, E, X, G); 623 | gen_code(uchar_t, E, X, G) -> gen_code(?uchar_t, E, X, G); 624 | 625 | gen_code(uint64_t,native,X,_G) -> gen_int_code(X,64,unsigned,native); 626 | gen_code(uint32_t,native,X,_G) -> gen_int_code(X,32,unsigned,native); 627 | gen_code(uint16_t,native,X,_G) -> gen_int_code(X,16,unsigned,native); 628 | gen_code(uint8_t,native,X,_G) -> gen_int_code(X,8,unsigned,native); 629 | gen_code(uint64_t,big,X,_G) -> gen_int_code(X,64,unsigned,big); 630 | gen_code(uint32_t,big,X,_G) -> gen_int_code(X,32,unsigned,big); 631 | gen_code(uint16_t,big,X,_G) -> gen_int_code(X,16,unsigned,big); 632 | gen_code(uint8_t,big,X,_G) -> gen_int_code(X,8,unsigned,big); 633 | gen_code(uint64_t,little,X,_G) -> gen_int_code(X,64,unsigned,little); 634 | gen_code(uint32_t,little,X,_G) -> gen_int_code(X,32,unsigned,little); 635 | gen_code(uint16_t,little,X,_G) -> gen_int_code(X,16,unsigned,little); 636 | gen_code(uint8_t,little,X,_G) -> gen_int_code(X,8,unsigned,little); 637 | 638 | gen_code(int64_t,native,X,_G) -> gen_int_code(X,64,signed,native); 639 | gen_code(int32_t,native,X,_G) -> gen_int_code(X,32,signed,native); 640 | gen_code(int16_t,native,X,_G) -> gen_int_code(X,16,signed,native); 641 | gen_code(int8_t,native,X,_G) -> gen_int_code(X,8,signed,native); 642 | gen_code(int64_t,big,X,_G) -> gen_int_code(X,64,signed,big); 643 | gen_code(int32_t,big,X,_G) -> gen_int_code(X,32,signed,big); 644 | gen_code(int16_t,big,X,_G) -> gen_int_code(X,16,signed,big); 645 | gen_code(int8_t,big,X,_G) -> gen_int_code(X,8,signed,big); 646 | gen_code(int64_t,little,X,_G) -> gen_int_code(X,64,signed,little); 647 | gen_code(int32_t,little,X,_G) -> gen_int_code(X,32,signed,little); 648 | gen_code(int16_t,little,X,_G) -> gen_int_code(X,16,signed,little); 649 | gen_code(int8_t,little,X,_G) -> gen_int_code(X,8,signed,little); 650 | 651 | gen_code(binary_t, _Endian, X,_G) -> 652 | {X, X}; 653 | gen_code(string_t, _Endian, X,_G) -> 654 | {X, ["(erlang:iolist_to_binary([",X,",0","]))/binary"]}; 655 | 656 | gen_code({enum,BaseType,Name},Endian,X,G) -> 657 | Encode = "enc_"++atom_to_list(Name), 658 | E = ["(",Encode,"(",X,"))"], 659 | {_M,C} = gen_code(BaseType,Endian,E,G), 660 | {X,C}; 661 | 662 | gen_code({flags,BaseType,Name},Endian,X,G) -> 663 | Encode = "enc_"++atom_to_list(Name), 664 | E = ["(","netlink_codec:encode_flags(",X,",fun ",Encode,"/1))"], 665 | {_M,C} = gen_code(BaseType,Endian,E,G), 666 | {X,C}; 667 | 668 | gen_code({array,BaseType},Endian,X,G) -> 669 | Xi = X++"i", 670 | {_M,C} = gen_code(BaseType,Endian,Xi,G), %% M=Xi! only simple base types! 671 | {X, ["(<< <<",C,">>", " || ",Xi," <- ",X,">>)/binary"]}; 672 | 673 | gen_code({tlvs,Name},_Endian,X,_G) -> 674 | Xi = X++"i", 675 | Encode = "enc_"++atom_to_list(Name), 676 | {X, [ "(netlink_codec:encode_tlv_list(", 677 | "[",Encode,"(",Xi,") || ", Xi," <- ",X,"]", "))/binary"]}; 678 | 679 | gen_code(ether_addr_t,_,X,_G) -> 680 | Xi = [X++integer_to_list(I) || I <- lists:seq(1,6)], 681 | Xm = [J++":8" || J <- Xi], 682 | {["{", string:join(Xi,","),"}"], string:join(Xm,",") }; 683 | gen_code(ipv4_addr_t,_,X,_G) -> 684 | Xi = [X++integer_to_list(I) || I <- lists:seq(1,4)], 685 | Xm = [J++":8" || J <- Xi], 686 | {["{", string:join(Xi,","),"}"], string:join(Xm,",")}; 687 | gen_code(ipv6_addr_t,_,X,_G) -> 688 | Xi = [X++integer_to_list(I) || I <- lists:seq(1,8)], 689 | Xm = [J++":16" || J <- Xi], 690 | {["{", string:join(Xi,","), "}"], string:join(Xm,",")}; 691 | %% gen_code(addr_t,_,X,_G) -> 692 | %% %% FIXME: use address family from message ? 693 | %% Xi = [X++integer_to_list(I) || I <- lists:seq(1,4)], 694 | %% Xm = [J++":8" || J <- Xi], 695 | %% {["{", string:join(Xi,","),"}"], string:join(Xm,",")}; 696 | gen_code(Name,Endian,X,G) -> 697 | case dict:find(Name, G#gen.recs) of 698 | error -> 699 | %% assume attribute! 700 | Encode = "enc_"++atom_to_list(Name), 701 | {X, [ "(netlink_codec:encode_tlv(",Encode,"(",X,")))"]}; 702 | {ok,RecType} -> 703 | Fields = lookup_fields(RecType,G), 704 | Named = [{Fi,Ix,Ti} || {Fi,Ix,Ti} <- Fields, Fi =/= '_'], 705 | %% must be record 706 | {Ts,Bs} = gen_record_code(Fields, Endian, X, G), 707 | Ts1 = lists:map(fun({{Fi,_,_Ti},Ri}) -> 708 | [atom_to_list(Fi),"=",Ri] 709 | end, lists:zip(Named,Ts)), 710 | R = ["#",atom_to_list(Name),"{", io_list_join(Ts1,","), "}"], 711 | B = io_list_join(Bs, ","), 712 | {R, B} 713 | end. 714 | 715 | 716 | 717 | gen_record_code(Fs, Endian, X, G) -> 718 | gen_record_code_(Fs, Endian, X, G, [], []). 719 | 720 | gen_record_code_([{'_',_Ix,Type}|Fs], Endian, X, G, Ms, Bs) -> 721 | {_M,B} = gen_code(Type, Endian, "0", G), 722 | gen_record_code_(Fs, Endian, X, G, Ms, [B|Bs]); 723 | gen_record_code_([{_Field,Ix,Type}|Fs], Endian, X, G, Ms, Bs) -> 724 | Xi = X++integer_to_list(Ix), 725 | {M,B} = gen_code(Type, Endian, Xi, G), 726 | gen_record_code_(Fs, Endian, X, G, [M|Ms], [B|Bs]); 727 | gen_record_code_([], _Endian, _X, _G, Ms, Bs) -> 728 | {lists:reverse(Ms), lists:reverse(Bs)}. 729 | 730 | %% return {TermMatch,BitConstruct} 731 | gen_int_code(X,Size,Sign,Endian) -> 732 | {X, [X,":",integer_to_list(Size),"/", 733 | atom_to_list(Sign),"-",atom_to_list(Endian)]}. 734 | 735 | %% 736 | %% io_list_join like string:join but for io_lists 737 | %% 738 | io_list_join([], _Sep) -> []; 739 | io_list_join([A], _Sep) -> [A]; 740 | io_list_join([A|As], Sep) -> [A,Sep|io_list_join(As,Sep)]. 741 | 742 | %% 743 | %% Get record indirections 744 | %% 745 | lookup_fields(Name, G) when is_atom(Name) -> 746 | case dict:find(Name, G#gen.recs) of 747 | {ok,Name1} -> 748 | lookup_fields(Name1, G) 749 | end; 750 | lookup_fields(Fields,_G) when is_list(Fields) -> 751 | Fields. 752 | 753 | %% 754 | %% Lookup defined value 755 | %% 756 | 757 | lookup_value(Value, _G) when is_integer(Value) -> 758 | Value; 759 | lookup_value(Name, G) when is_atom(Name) -> 760 | case dict:find(Name, G#gen.defs) of 761 | {ok,Name} -> Name; %% recursive! 762 | {ok,Value} when is_atom(Value) -> lookup_value(Value,G); 763 | {ok,Value} when is_integer(Value) -> Value; 764 | error -> Name 765 | end. 766 | 767 | %% lookup named type (record / attribute) 768 | lookup_type(Name, G) when is_atom(Name) -> 769 | case dict:find(Name, G#gen.attrs) of 770 | error -> 771 | case dict:find(Name, G#gen.recs) of 772 | error -> 773 | false; 774 | {ok,Value} -> {attribute,Name,Value} 775 | end; 776 | {ok,Value} -> {record,Name,Value} 777 | end. 778 | 779 | 780 | inc_error(G) -> 781 | G#gen { error = G#gen.error + 1}. 782 | 783 | 784 | %% util to fold all terms in a file 785 | fold_file_terms(Fun, Acc, Fd) -> 786 | fold_file_terms(Fun, Acc, 1, Fd). 787 | 788 | fold_file_terms(Fun, Acc, Line, Fd) -> 789 | case io:read(Fd, '', Line) of 790 | {ok,Term,EndLine} -> 791 | fold_file_terms(Fun, Fun(Term,Line,Acc), EndLine,Fd); 792 | {error,Error,Line} -> 793 | io:format("parse error:~w: ~p\n", [Line,Error]), 794 | {error,Error}; 795 | {eof,_Line} -> 796 | {ok,Acc} 797 | end. 798 | 799 | -------------------------------------------------------------------------------- /src/netlink_stat.erl: -------------------------------------------------------------------------------- 1 | %%% @author tony 2 | %%% @copyright (C) 2013, tony 3 | %%% @doc 4 | %%% Get network statistics 5 | %%% @end 6 | %%% Created : 18 Aug 2013 by tony 7 | 8 | -module(netlink_stat). 9 | 10 | -compile(export_all). 11 | 12 | -include("../include/netlink.hrl"). 13 | 14 | get_value() -> 15 | get_value("*"). 16 | 17 | get_value("") -> 18 | get_value("*"); 19 | get_value(Counter) -> 20 | case string:tokens(Counter, ".") of 21 | [] -> get_all_counters(); 22 | ["*"] -> get_all_counters(); 23 | ["*","*"] -> get_all_counters(); 24 | [Name,"*"] -> get_all_counters(Name); 25 | [Name] -> get_all_counters(Name); 26 | ["*",Var] -> 27 | Field = list_to_atom(Var), 28 | Fi = index(Field, record_info(fields, rtnl_link_stats)), 29 | if Fi =:= 0 -> 30 | []; 31 | true -> 32 | {ok,Ifs} = inet:getiflist(), 33 | select_counters_(Ifs, Fi+1, Var, []) 34 | end; 35 | [Name,Var] -> 36 | Field = list_to_atom(Var), 37 | {ok,S} = get_statistics(Name), 38 | case index(Field, record_info(fields, rtnl_link_stats)) of 39 | 0 -> []; 40 | Fi -> [{Counter,element(Fi+1, S)}] 41 | end 42 | end. 43 | 44 | get_all_counters() -> 45 | {ok,Ifs} = inet:getiflist(), 46 | get_all_counters_(Ifs,[]). 47 | 48 | get_all_counters(Name) -> 49 | {ok,S} = get_statistics(Name), 50 | Acc = get_counters_(Name, 2, record_info(fields, rtnl_link_stats),S,[]), 51 | lists:reverse(Acc). 52 | 53 | select_counters_([Name|As],Fi,Var,Acc) -> 54 | {ok,S} = get_statistics(Name), 55 | Value = element(Fi,S), 56 | select_counters_(As,Fi,Var,[{Name++"."++Var,Value}|Acc]); 57 | select_counters_([], _Fi, _Var, Acc) -> 58 | lists:reverse(Acc). 59 | 60 | get_all_counters_([Name|As],Acc) -> 61 | {ok,S} = get_statistics(Name), 62 | Acc1 = get_counters_(Name,2,record_info(fields, rtnl_link_stats),S,Acc), 63 | get_all_counters_(As,Acc1); 64 | get_all_counters_([], Acc) -> 65 | lists:reverse(Acc). 66 | 67 | get_counters_(Name, I, [F|Fs], S, Acc) -> 68 | Var = atom_to_list(F), 69 | get_counters_(Name, I+1, Fs, S, [{Name++"."++Var, element(I,S)} |Acc]); 70 | get_counters_(_Name, _I, [], _S, Acc) -> 71 | Acc. 72 | 73 | %% 74 | %% Find first Key in Position Pos in the List 75 | %% return the position in the list or 0 if not found 76 | index(Value, List) -> 77 | index_(1, Value, List). 78 | 79 | index_(I,Value,[Value|_List]) -> I; 80 | index_(I,Value,[_|List]) -> index_(I+1,Value,List); 81 | index_(_I,_Value,[]) -> 0. 82 | 83 | 84 | get_statistics(Interface) -> 85 | netlink:start(), 86 | {ok,Ref} = netlink:subscribe(Interface), 87 | netlink:invalidate(Interface, [stats,stats64]), 88 | ok = netlink:get_match(link, inet, [{stats,native,[]}]), 89 | Res = get_stats64(Ref,1000), 90 | flush_stats(Ref), 91 | netlink:unsubscribe(Ref), 92 | case Res of 93 | {ok,Stats} -> 94 | {ok,set_stats(Stats)}; 95 | Error -> 96 | Error 97 | end. 98 | 99 | %% fix to handle padded/aligned data? 100 | set_stats(Stats) -> 101 | Len = length(Stats), 102 | N = tuple_size(#rtnl_link_stats{})-1, 103 | if Len > N -> 104 | {Fields,_} = lists:split(N, Stats), 105 | list_to_tuple([rtnl_link_stats | Fields]); 106 | Len =:= N -> 107 | list_to_tuple([rtnl_link_stats | Stats]); 108 | true -> 109 | Pad = lists:duplicate(N - Len, 0), 110 | list_to_tuple([rtnl_link_stats | (Stats++Pad)]) 111 | end. 112 | 113 | get_stats64(Ref,Timeout) -> 114 | receive 115 | {netlink,Ref,_Interface,stats64,_Old,New} -> 116 | {ok,New} 117 | after Timeout -> 118 | {error,timeout} 119 | end. 120 | 121 | flush_stats(Ref) -> 122 | receive 123 | _Msg={netlink,Ref,_Interface,_,_Old,_New} -> 124 | %% io:format("flushed: ~p\n", [_Msg]), 125 | flush_stats(Ref) 126 | after 0 -> 127 | ok 128 | end. 129 | -------------------------------------------------------------------------------- /src/netlink_sup.erl: -------------------------------------------------------------------------------- 1 | %%%---- BEGIN COPYRIGHT ------------------------------------------------------- 2 | %%% 3 | %%% Copyright (C) 2012 Feuerlabs, Inc. All rights reserved. 4 | %%% 5 | %%% This Source Code Form is subject to the terms of the Mozilla Public 6 | %%% License, v. 2.0. If a copy of the MPL was not distributed with this 7 | %%% file, You can obtain one at http://mozilla.org/MPL/2.0/. 8 | %%% 9 | %%%---- END COPYRIGHT --------------------------------------------------------- 10 | 11 | -module(netlink_sup). 12 | 13 | -behaviour(supervisor). 14 | 15 | %% API 16 | -export([start_link/0]). 17 | 18 | %% Supervisor callbacks 19 | -export([init/1]). 20 | 21 | %% =================================================================== 22 | %% API functions 23 | %% =================================================================== 24 | 25 | start_link() -> 26 | supervisor:start_link({local, ?MODULE}, ?MODULE, []). 27 | 28 | %% =================================================================== 29 | %% Supervisor callbacks 30 | %% =================================================================== 31 | 32 | init([]) -> 33 | C = {netlink, {netlink, start_link, []}, 34 | permanent, 5000, worker, [netlink]}, 35 | {ok, { {one_for_one, 5, 10}, [C]}}. 36 | 37 | -------------------------------------------------------------------------------- /tetrapak/build_drv.erl: -------------------------------------------------------------------------------- 1 | -task({"build:drv", "Build the netlink driver"}). 2 | -task({"clean:drv", "Clean the netlink driver"}). 3 | 4 | run("build:drv", _) -> 5 | tetrapak:outputcmd(tetrapak:subdir("c_src"), "make", [cflags(), "all"]); 6 | 7 | run("clean:drv", _) -> 8 | tetrapak:outputcmd(tetrapak:subdir("c_src"), "make", [cflags(), "clean"]). 9 | 10 | cflags() -> 11 | ["CFLAGS=", "-O2 ", ["-I", code:root_dir(), "/erts-", erlang:system_info(version), "/include"]]. 12 | -------------------------------------------------------------------------------- /tetrapak/config.ini: -------------------------------------------------------------------------------- 1 | [build] 2 | version = "~t.~o~~~c" 3 | 4 | [package] 5 | maintainer = "Tony Rogvall " 6 | exclude = "\\.gitignore|README.md|libnl" 7 | architecture = host 8 | 9 | --------------------------------------------------------------------------------