├── .gitignore ├── COPYING ├── Makefile ├── README.md ├── build ├── main.d └── main.o ├── docs └── blitzping_logo.png ├── out └── blitzping └── src ├── cmdline ├── ansi.h ├── docs.h ├── logger.c ├── logger.h ├── parser.c └── parser.h ├── main.c ├── netlib ├── arpa.h ├── netinet.h └── protos │ ├── ip.h │ ├── ip6.h │ ├── tcp.h │ └── udp.h ├── packet.c ├── packet.h ├── program.h ├── socket.c ├── socket.h └── utils ├── endian.h └── intrins.h /.gitignore: -------------------------------------------------------------------------------- 1 | # Prerequisites 2 | *.d 3 | 4 | # Object files 5 | *.o 6 | *.ko 7 | *.obj 8 | *.elf 9 | 10 | # Linker output 11 | *.ilk 12 | *.map 13 | *.exp 14 | 15 | # Precompiled Headers 16 | *.gch 17 | *.pch 18 | 19 | # Libraries 20 | *.lib 21 | *.a 22 | *.la 23 | *.lo 24 | 25 | # Shared objects (inc. Windows DLLs) 26 | *.dll 27 | *.so 28 | *.so.* 29 | *.dylib 30 | 31 | # Executables 32 | *.exe 33 | *.out 34 | *.app 35 | *.i*86 36 | *.x86_64 37 | *.hex 38 | 39 | # Debug files 40 | *.dSYM/ 41 | *.su 42 | *.idb 43 | *.pdb 44 | 45 | # Kernel Module Compile Results 46 | *.mod* 47 | *.cmd 48 | .tmp_versions/ 49 | modules.order 50 | Module.symvers 51 | Mkfile.old 52 | dkms.conf 53 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # ---------------------------------------------------------------------- 2 | 3 | # Program name 4 | NAME := blitzping 5 | # Target triplet (https://wiki.osdev.org/Target_Triplet) 6 | TARGET ?= #mips-openwrt-linux-muslsf 7 | # Target sub-architecture 8 | SUBARCH ?= 9 | # C version (c99 or c11) 10 | C_STD ?= c11 11 | # 200112L is POSIX.1-2001 (IEEE Std 1003.1-2001), a subset of the 12 | # SUSv3 (UNIX 03) standard; Issue 6 (i.e., POSIX 2001) is the earliest 13 | # standard in which is defined. Also, Issue 6 is 14 | # "aligned" with and based on the C99 standard, and it seems to have 15 | # the most widespread support. (MacOS is SUSv3-certified.) 16 | # For more information on these extremely confusing "standards," 17 | # check https://www.man7.org/linux/man-pages/man7/standards.7.html 18 | POSIX_VER ?= 200112L 19 | 20 | # LLVM's target triplets are more straightforward for cross-compiling; 21 | # that is why Blitzping uses Clang by default. However, this codebase 22 | # is very portable, and you can still use GCC if you prefer. 23 | # 24 | # For building, llvm, clang, lld, and llvm-binutils will be required. 25 | # 26 | # Compiler (gcc or clang) 27 | CC := clang 28 | # Linker 29 | LD := lld 30 | # Strip tool 31 | STRIP := llvm-strip 32 | # Clang tidy tool 33 | TIDY := clang-tidy 34 | 35 | 36 | # Directories 37 | SRCDIR := ./src 38 | OBJDIR := ./build 39 | OUTDIR := ./out 40 | # Files 41 | rwildcard=$(foreach d,$(wildcard $1*),$(call rwildcard,$d/,$2) \ 42 | $(filter $(subst *,%,$2),$d)) 43 | SRCS := $(call rwildcard,$(SRCDIR)/,*.c) 44 | OBJS := $(patsubst $(SRCDIR)/%.c,$(OBJDIR)/%.o,$(SRCS)) 45 | DEPS := $(OBJS:.o=.d) 46 | 47 | # ---------------------------------------------------------------------- 48 | 49 | # NOTE: Do NOT insert additional spaces after function commas; 50 | # makefiles are very sensitive to whitespaces and tabs. 51 | 52 | # Compiler options 53 | # 54 | # NOTE: -Ofast can result in "illegal instructions" on some targets. 55 | CCOPT = \ 56 | -std=$(C_STD) -fhosted -D _POSIX_C_SOURCE=$(POSIX_VER) \ 57 | -Wall -Wextra -Wpedantic -Werror -pedantic-errors \ 58 | -MMD -MP \ 59 | -O3 -flto -D NDEBUG 60 | 61 | # Add additional compatibility options if C99 is specified 62 | ifeq ($(C_STD),c99) 63 | CCOPT += -Wno-unknown-warning-option \ 64 | -Wno-c99-c11-compat -Wno-c11-extensions 65 | endif 66 | 67 | # Add triple and architecture to CCOPT if they aren't empty. 68 | ifneq ($(TARGET),) 69 | CCOPT += --target=$(TARGET) 70 | endif 71 | ifneq ($(SUBARCH),) 72 | CCOPT += -march=$(SUBARCH) 73 | endif 74 | 75 | # Linker options 76 | # 77 | # For the host machine's compiler runtime (i.e., --rtlib, which is 78 | # different from the target's libc that could be musl, glibc, uclibc, 79 | # msvcrt, etc.), you could use either LLVM's 'compiler-rt' (apt install 80 | # libclang-rt-dev:{arch}) OR 'libgcc' (apt install libgcc1-{arch}-cross) 81 | # The 'platform' option will automatically choose an available one. 82 | # (GCC lacks this option and always uses libgcc.) 83 | LDOPT = \ 84 | #-static -static-libgcc -lpthread 85 | 86 | ifneq (,$(findstring gcc,$(CC))) 87 | # NOTE: GCC only works with LLVM's lld in non-LTO mode. 88 | CCOPT += -ffat-lto-objects 89 | LDOPT += -fuse-ld=$(LD) 90 | else 91 | LDOPT += -fuse-ld=$(LD) --rtlib=platform --unwindlib=none 92 | endif 93 | 94 | # NOTE: Make sure to review the following LLVM/Clang bug (by myself): 95 | # https://github.com/llvm/llvm-project/issues/102259 96 | # In short, soft-core MIPS targets need more work to get built properly; 97 | # if TARGET ends with 'sf' then we have to apply additional patches. 98 | 99 | # If TARGET hasn't been specified (i.e., no cross-compilation), fill 100 | # it with the current/host machine's info from -dumpmachine. 101 | ifeq ($(TARGET),) 102 | TARGET := $(shell $(CC) -dumpmachine) 103 | endif 104 | 105 | # Extract the parts from TARGET, separated by dashes. 106 | PARTS := $(subst -, ,$(TARGET)) 107 | 108 | # Get the number of words in TARGET, which could actually be in a 109 | # quadruplet (e.g., mips-openwrt-linux-musl vs. mips-linux-musl) format. 110 | TRIPLET_N := $(words $(PARTS)) 111 | 112 | # Extract the libc and arch from TARGET. 113 | ARCH := $(word 1, $(PARTS)) 114 | LIBC := $(subst sf,,$(lastword $(PARTS))) 115 | 116 | # Extract the architecture, [vendor], os, and libc from the TARGET. 117 | ifeq ($(TRIPLET_N),3) # Triplet 118 | VENDOR := unknown 119 | OS := $(word 2,$(PARTS)) 120 | else ifeq ($(TRIPLET_N),4) # Quadruplet 121 | VENDOR := $(word 2,$(PARTS)) 122 | OS := $(word 3,$(PARTS)) 123 | endif 124 | 125 | # Check if TARGET ends with 'sf' (soft-float) 126 | FLOAT_ABI := $(if $(findstring sf,$(TARGET)),soft,hard) 127 | 128 | # Patches for soft-core targets. 129 | ifeq ($(FLOAT_ABI),soft) 130 | CCOPT += -msoft-float -flto 131 | # Append "-sf" to the libc name for the dynamic linker. 132 | LDOPT += -Wl,--dynamic-linker=/lib/ld-$(LIBC)-$(ARCH)-sf.so.1 133 | endif 134 | 135 | # Make the aforementioned info available to the C sources. 136 | CCOPT += -D TARGET_ARCH=\"$(ARCH)\" -D TARGET_LIBC=\"$(LIBC)\" \ 137 | -D TARGET_VENDOR=\"$(VENDOR)\" -D TARGET_OS=\"$(OS)\" \ 138 | -D TARGET_TRIPLET=\"$(TARGET)\" \ 139 | -D TARGET_FLOAT_ABI=\"$(FLOAT_ABI)\" 140 | ifneq ($(SUBARCH),) 141 | CCOPT += -D TARGET_SUBARCH=\"$(SUBARCH)\" 142 | else 143 | CCOPT += -D TARGET_SUBARCH=\"generic\" 144 | endif 145 | ifeq ($(FLOAT_ABI),soft) 146 | CCOPT += -D TARGET_SOFT_FLOAT=1 147 | else 148 | CCOPT += -D TARGET_SOFT_FLOAT=0 149 | endif 150 | 151 | 152 | # 153 | # Make Targets 154 | # 155 | .PHONY: all strip clean help tidy 156 | all: $(OUTDIR)/$(NAME) 157 | 158 | help: 159 | @echo "Targets ~" 160 | @echo " help : Print this help message." 161 | @echo " all : Build the Program." 162 | @echo " strip : Strip debug info from the built program." 163 | @echo " clean : Remove all built artefacts." 164 | 165 | $(OUTDIR)/$(NAME): $(OBJS) 166 | $(CC) $(CCOPT) $(LDOPT) -o $@ $^ 167 | @file $(OUTDIR)/$(NAME) 168 | 169 | $(OBJDIR)/%.o: $(SRCDIR)/%.c 170 | mkdir -p $(dir $@) 171 | $(CC) $(CCOPT) -c $< -o $@ 172 | 173 | strip: $(OUTDIR)/$(NAME) 174 | @ls -l $(OUTDIR)/$(NAME) 175 | $(STRIP) $(OUTDIR)/$(NAME) 176 | @ls -l $(OUTDIR)/$(NAME) 177 | @file $(OUTDIR)/$(NAME) 178 | 179 | tidy: 180 | $(TIDY) $(SRCS) -- 181 | 182 | clean: 183 | rm -rf $(OBJDIR)/* $(OUTDIR)/$(NAME) 184 | 185 | -include $(DEPS) 186 | 187 | # ---------------------------------------------------------------------- 188 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

4 | Blitzping's logo 5 |

6 | 7 |

Blitzping

8 | 9 |

10 | A very high-speed, configurable, and portable packet-crafting utility optimized for embedded devices 11 |

12 | 13 | 14 |
15 | 16 | *** 17 | 18 | # Background 19 | 20 | I found [hping3](https://linux.die.net/man/8/hping3) and nmap's [nping](https://linux.die.net/man/1/nping) to be far too slow in terms of sending individual, bare-minimum (40-byte) TCP packets; other than inefficient socket I/O, they were also attempting to do far too much unnecessary processing in what should have otherwise been a tight execution loop. Furthermore, none of them were able to handle [CIDR notations](https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing) (i.e., a range of IP addresses) as their source IP parameter. Being intended for embedded devices (e.g., low-power MIPS/Arm-based routers), Blitzping only depends on standard POSIX headers and C11's libc (whether musl or gnu). To that end, even when supporting CIDR prefixes, Blitzping is significantly faster compared to hping3, nping, and whatever else that was hosted on GitHub (benchmarks below). 21 | 22 | Here are some of the performance optimizations specifically done on Blitzping: 23 | * **Pre-Generation:** All the static parts of the packet buffer get generated once, outside of the `sendto()` tightloop; 24 | * **Asynchronous:** Configuring raw sockets to be non-blocking by default; 25 | * **Socket Binding:** Using `connect()` to bind a raw socket to its destination only once, replacing `sendto()`/`sendmmsg()` with `write()`/`writev()`; 26 | * **Queueing:** Queues many packets to get processed *inside* the kernelspace (i.e., `writev()`), rather repeating userspace->kernelspace syscalls; 27 | * **Memory:** Locking memory pages and allocating the packet buffer in an *aligned* manner; 28 | * **Multithreading:** Polling the same socket in `sendto()` from multiple threads; and 29 | * **Compiler Flags:** Compiling with `-Ofast`, `-flto`, and `-march=native` (these actually had little effect; by this point, the entire bottleneck lays on the Kernel's own `sendto()` routine). 30 | 31 | ## License 32 | 33 | Blitzping's source code is licensed under the GNU General Public License v3.0 or later ("GPLv3+"), Copyright (C) 2024 Fereydoun Memarzanjany. Blitzping comes with ABSOLUTELY NO WARRANTY. Blitzping is free software, and you are welcome to redistribute it under certain conditions; see the GPLv3+. If you wish to report a bug or contribute to this project, visit this repository: https://github.com/Thraetaona/Blitzping 34 | 35 | Usage: 36 | `blitzping ` \ 37 | Example: `./blitzping 4 192.168.123.123/19 10.10.10.10:80` (this would send TCP SYN packets to `10.10.10.10`'s port `80` from a randomly chosen source IP within an entire range of `192.168.96.0` to `192.168.127.255`, using `4` threads.) 38 | 39 | ## Benchmarks 40 | 41 | I tested Blitzping against both hpign3 and nping on two different routers, both running OpenWRT 23.05.03 (Linux Kernel v5.15.150) with the "masquerading" option (i.e., NAT) turned off in firewall; one device was a single-core 32-bit MIPS SoC, and another was a 64-bit quad-core ARMv8 CPU. On the quad-core CPU, because both hping3 and nping were designed without multithreading capabilities (unlike Blitzping), I made the competition "fairer" by launching them as four individual processes, as opposed to Blitzping only using one. Across all runs and on both devices, CPU usage remained at 100%, entirely dedicated to the currently running program. Finally, the network interface cards ("NICs") themselves were not bottlenecks: the MIPS SoC had a 100 Mbps (~95.3674 MiB/s) NIC and the ARMv8 a 1000 Mbps (~953.674 MiB/s). 42 | 43 | It is important to note that Blitzping was not doing any less than hping3 and nping; in fact, *it was doing more.* While hping3 and nping only randomized the source IP and port of each packet to a fixed address, Blitzping randomized not only the source port but also the IP *within an CIDR range*---a capability that is more computionally intensive and a feature that both hping3 and nping lacked in the first place. 44 | 45 | All of the sent packets were bare-minimum TCP SYN packets; each of them was only 40 bytes in length. Lastly, hping3 and nping were both launched with the "best-case" command-line parameters as to maximize their speed and to disable their runtime stdio logging: 46 | 47 | ``` 48 | hping3 --flood --spoof 192.168.123.123 --syn 10.10.10.10 49 | ``` 50 | ``` 51 | nping --count 0 --rate 1000000 --hide-sent --no-capture --privileged --send-eth --source-ip 192.168.123.123 --source-port random --dest-ip 10.10.10.10 --tcp --flags syn 52 | ``` 53 | ``` 54 | ./blitzping 4 192.168.123.123/19 10.10.10.10:80 55 | ``` 56 | 57 | ### Quad-Core "Rockchip RK3328" CPU @ 1.3 GHz. (ARMv8-A) 58 | | ARM (4 x 1.3 GHz) | nping | hping3 | Blitzping | 59 | |:-|:-|:-|:-| 60 | | Num. Instances | 4 (1 thread) | 4 (1 thread) | 1 (4 threads) | 61 | | Pkts. per Second | ~65,000 | ~80,000 |~3,150,000 | 62 | | Bandwidth (MiB/s) | ~2.50 | ~3.00 | ~120 | 63 | 64 | ### Single-Core "Qualcomm Atheros QCA9533" SoC @ 650 MHz. (MIPS32r2) 65 | | MIPS (1 x 650 MHz) | nping | hping3 | Blitzping | 66 | |:-|:-|:-|:-| 67 | | Num. Instances | 1 (1 thread) | 1 (1 thread) | 1 (1 thread) | 68 | | Pkts. per Second | ~5,000 | ~10,000 | ~420,000 | 69 | | Bandwidth (MiB/s) | ~0.20 | ~0.40 | ~16 | 70 | 71 | # Compilation 72 | 73 | 74 | Blitzping uses C11 syntax (e.g., anonymous structs and list commas) but without any hard dependencies on actual C11 headers, so **it can compile under C99 just fine.[^1]** Blitzping's usage of libc is mostly [freestanding](https://en.cppreference.com/w/cpp/freestanding), and it only uses standard headers, mainly Berkley sockets, from the 2001 edition of POSIX.1 (IEEE Standard 1003.1-2001), without any BSD-, XSI-, SysV-, or GNU-specific additions. Blitzping can be compiled by both LLVM and GCC; because of LLVM being slightly [easier](https://clang.llvm.org/docs/CrossCompilation.html) in cross-compiling to other architectures with its target triplets, I configured the makefile to use that toolchain (i.e., clang, lld, and llvm-strip) by default. Also, Blitzping's makefile has additional workarounds for [LLVM/Clang's bug with soft-core targets.](https://github.com/llvm/llvm-project/issues/102259) 75 | 76 | [^1]: To compile under C99, supply `C_STD=c99` to the makefile; this will disable C11 threads but POSIX threads will continue to remain usable, independently. 77 | 78 | ### Install the LLVM toolchain (if you do not already have it): 79 | (LLVM/Clang, LLVM Linker, and LLVM-strip) 80 | ``` 81 | apt install llvm clang 82 | apt install lld 83 | apt install llvm-binutils 84 | ``` 85 | 86 | ## A) If you wish to only compile for your own machine (i.e., host and target are the same), you can run `make` without any additional options: 87 | 88 | ``` 89 | make 90 | ``` 91 | 92 | The compiler will then create an executable for your target device in the `./out` directory. 93 | 94 | As a final and optional post-processing step, you could strip the debuginfo symbols out of the compiled program and reduce its size: 95 | ``` 96 | make strip 97 | ``` 98 | 99 | ## B) Cross-Compilation (sample for a Debian 12 host and MIPS32r2 target) 100 | 101 | #### 1. Install your host's compiler runtime (`compiler-rt` *OR* `libgcc`) for the target machine's architecture: 102 | 103 | ``` 104 | apt install libclang-rt-dev:mips 105 | ``` 106 | *OR* 107 | ``` 108 | apt install libgcc1-mips-cross 109 | ``` 110 | 111 | While packages of common architectures, such as x86_64 and arm64, are widely supported on desktop-based Linux distros, Debian (for example) does not provide packages for older embedded targets like 32-bit MIPS\[eb\]. In those cases, if you are not able to manually acquire LLVM's `compile-rt:mips` for that architecture, you could always `apt install libgcc1-mips-cross` for libgcc. 112 | 113 | ### 2. Then, simply specify your ["target triplet"](https://wiki.osdev.org/Target_Triplet) in make; for example, a soft-float big-endian MIPS running Linux (OpenWRT) with musl libc would be as follows: 114 | ``` 115 | make TARGET=mips-openwrt-linux-muslsf 116 | ``` 117 | **Make sure that you specify the correct libc (e.g., `musl`, `gnu`, `uclibc`) _and_ whether or not it lacks an FPU (i.e., if it is soft-float and requires an `sf` suffix to libc).** 118 | 119 | Optionally, you can specify the target's sub-architecture to optimize specifically for it: 120 | ``` 121 | make TARGET=mips-linux-muslsf SUBARCH=mips32r2 122 | ``` 123 | 124 | (As mentioned earlier, you could also `apt install gcc-mips-linux-gnu` and skip LLVM/Clang altogether, if you really want to.) 125 | 126 | NOTE: If your router uses LibreCMC, be aware that the system's libc might be too old to run C programs like this; to fix that, you could either take the risk and unflag that specific package via `opkg` in order to upgrade it, or you could flash the more modern OpenWRT onto your router. 127 | NOTE: Sometimes, your target might have a different name for its libgcc, such as `libgcc-12-dev-m68k-cross` (Debian example). 128 | 129 | # FAQs 130 | 131 | ### Why rewrite hping3 and not just fork it? 132 | 133 | At first, I was planning to fork hping3 as to maintain it, but **its code just had too many questionable design choices;** there were [global variables](https://github.com/antirez/hping/blob/master/globals.h) and unnecessary function calls all over the place. In any case, the performance was abysmal because the entirety of the packet—even parts that were not supposed to change—was getting re-crafted each time. Do you want to flood the destination with only TCP packets? The code will continiously go through function within function and nested if-else branches to ["decide" at runtime](https://github.com/antirez/hping/blob/master/main.c#L375) whether it should be using UDP, TCP, etc. routines for this otherwise-TCP-only send; this is not how you write performant code! Among other things, **the code was [rather unportable](https://github.com/antirez/hping/blob/master/Makefile.in);** you have to [manually patch](https://bugs.gentoo.org/706566) many areas just to get it to compile on modern compilers, due to its noncompliance with the C standard and its dependency on libpcap. 134 | 135 | Also, both nping and hping3 use non-standard BSD/SystemV-specific extensions to the POSIX "standard" library; for some strange reason or due to mere oversight, the actual POSIX standard defines a barebones `` without actually defining a `tcphdr` *per se,* making it entirely pointless to use in the first place, and `` does not even exist as part of the POSIX standard. In any case, *those headers are not only nonstandard but are also very ancient;* they lag behind newer RFCs by decades. This warranted writing my own `"netinet.h"`, which I think is (by far) the most feature-complete and cleanest TCP/IP stack implementation in C. Also, despite supporting new fields, I still made sure to remain backward-compatible with old RFCs (for example, in IPv4, I support both the newer DSCP/ECN codepoint pools *and* the older ToS/Precedence values). 136 | 137 | ### Why not rewrite it in Rust (or C++)? 138 | 139 | Blitzping is intended to support low-power routers and embedded devices; **Rust is a terrible choice for those places.** Had Blitzping been a low-level system firmware *or* a high-level application, both `#![no_std]` and `std` Rust would have been suitable choices, respectively; however, Blitzping exists in a "middle" position, where you are still *required* to use `libc` or other syscalls and yet cannot expect to have the full Rust `std` library on your target. For one, you would be interacting with low-level syscalls (e.g., Linux's `sendto()` or `sendmmsg()`); because *there are currently no raw socket wrappers for Rust,* you would be forced to use `unsafe {...}` at every single turn there. Also, Rust's std library is not available on some of said embedded targets, such as [`mips64-openwrt-linux-musl`](https://doc.rust-lang.org/nightly/rustc/platform-support/mips64-openwrt-linux-musl.html); what will you do in such cases? **You would have to use libc anyway,** forcing you to painstakingly wrap every single C function around `unsafe {...}` and deal with its lack of interoperability; this literally defeats the entire goal of writing your program in Rust in the first place. **If anything, Rust's safety features would only tie your own hands.** 140 | 141 | People don't know how to write safe C code; that is their own fault—not C's. C might not be object-oriented like C++ and it might not have the number of compile-time constraining that Ada/Pascal offer, but it at least lets you do what you want to do with relative ease; you just have to know what you want to do with it. Also, there are plenty of very nice but often overlooked features (e.g., unions, bool, _Static_assert(), threads.h, etc.) in the C99/C11 standards that many people just appear oblivious about. Finally, compiling your code with `-Wall -Wextra -Werror -pedantic-errors` helps you avoid GNU-specific extensions that might have been making your code less portable or more suspectible to deprecation in future compiler releases; again, people just don't make use of it in the first place. 142 | 143 | C++ remains largely backward-compatible with C and actually has some really useful features (such as enum underlying types or namespaces) that are either only available in C23 (I use C11) or have not made their way into C yet. While I appreciate the syntax and wish I could type something like `TCP::FLAGS::SYN`, as opposed to `TCP_FLAGS_SYN` in C, I also cannot ignore the fact that these gains would be minoscule in practice; libc is still far more portable than libc++/libstdc++. 144 | 145 | ### Why was CIDR support important? 146 | 147 | The reason I specifically included CIDR support—something that both nping and hping3 lacked—for spoofing source IP addresses was that ISPs or mid-route routers can block "nonsense" traffic (e.g., a source IP outside of the ISP or even country's allocated range) coming from you as a client; this is called "egress filtering." However, in a DHCP-assigned scenario, you still have thousands of IP addresses in your subnet/range to spoof, which should not get caught by this filtering. Ultimately, because the source IP would be coming from an entire range of addresses, firewalls (and CDNs) will have a harder time detecting a pattern as to block it. Unfortunately, in a residential ISP scenario where you only have one "real" IP address, your spoofed source IP would be chosen from a range of otherwise-legitimate addresses; those addresses (upon unexpectedly receiving SYN-ACK from your targeted server) would usually respond back to the original server with a RST packet as to terminate the connection, making it so that your "half-open" connections (the goal of SYN flooding) do not get to last as long. 148 | 149 | Lastly, this tool only really lets you flood packets as quickly as possible. Those underpowered processors were only used as an optimization benchmark; if it runs good enough there, you could always throw more computational power and cores at it. In fact, if you have (or rent) multiple datacenter-grade bandwidth, powerful x86_64 CPUs, and lots of "real" IP addresses at your disposal, then there would really be nothing preventing you from DDoS'ing the destination address; at the very least, you could still saturate their download line's bandwidth. 150 | -------------------------------------------------------------------------------- /build/main.d: -------------------------------------------------------------------------------- 1 | build/main.o: src/main.c src/parser.h src/netinet.h src/packet.h \ 2 | src/socket.h 3 | 4 | src/parser.h: 5 | 6 | src/netinet.h: 7 | 8 | src/packet.h: 9 | 10 | src/socket.h: 11 | -------------------------------------------------------------------------------- /build/main.o: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Thraetaona/Blitzping/ed456613b4e851a4f009159a364a257ffc466e1e/build/main.o -------------------------------------------------------------------------------- /docs/blitzping_logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Thraetaona/Blitzping/ed456613b4e851a4f009159a364a257ffc466e1e/docs/blitzping_logo.png -------------------------------------------------------------------------------- /out/blitzping: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Thraetaona/Blitzping/ed456613b4e851a4f009159a364a257ffc466e1e/out/blitzping -------------------------------------------------------------------------------- /src/cmdline/ansi.h: -------------------------------------------------------------------------------- 1 | // --------------------------------------------------------------------- 2 | // SPDX-License-Identifier: GPL-3.0-or-later 3 | // ansi.h is a part of Blitzping. 4 | // --------------------------------------------------------------------- 5 | 6 | _Pragma ("once") 7 | #ifndef ANSI_H 8 | #define ANSI_H 9 | 10 | #include 11 | 12 | // Compile-time flag to enable/disable ANSI formatting 13 | // (If enabled, formatting can still be disabled at runtime.) 14 | #ifndef DISABLE_ANSI_FORMATTING 15 | # define ANSI_ENABLED 1 16 | #else 17 | # define ANSI_ENABLED 0 18 | #endif 19 | 20 | // "The name ANSI is misleading; ANSI [which was formerly known as the 21 | // "American Standards Association" (ASA)] simply stands for "American 22 | // National Standards Institute," a non-profit body that was founded in 23 | // 1918, which was meant to be a place where American industries could 24 | // agree on standards which would then be used by all companies without 25 | // variation. The theory was (and is) that by having all these 26 | // disparate groups agree on, say, the size of a washer, or the width 27 | // of a rail, then there's less infighting over forcing the customer 28 | // base/world to have to choose a specific company's standard, and the 29 | // focus is on making the American industry as a whole the dominant 30 | // factor in domestic and foreign markets. 31 | // There is a graphics standard in DOS on IBM Computers called 32 | // "ANSI" (which is actually ANSI standard X3.64-1979 or ISO standard 33 | // DP-6429 and ECMA-35) which was implemented in the early 1980s. It 34 | // allowed a certain set of escape sequences to be included in files 35 | // that would produce color and cursor movement on the screen, and was 36 | // used to great benefit on DOS machines for some time, especially some 37 | // BBS menus and welcome screens. Towards the early 1990's, an entire 38 | // "ANSI scene" rose up where people tried to outdo each other producing 39 | // elaborate ANSI images or files." 40 | // 41 | // (http://artscene.textfiles.com/ansi) 42 | // 43 | // Rooted in the English Alphabet's telegraph code of the 19th century, 44 | // the ASCII character encoding standard was developed by the American 45 | // Standards Association's (ASA, now known as ANSI) X3.2 subcommittee 46 | // (later known as the X3L2 committee) and first published in 1963 as 47 | // ASA X3.4-1963. ASCII underwent several revisions as USAS X3.4-1967, 48 | // USAS X3.4-1968, ANSI X3.4-1977, and finally ANSI X3.4-1986. Other 49 | // committees, in standards like X3.15, further addressed how ASCII 50 | // should be transmitted and recorded on tape. 51 | // ASCII had various characters reserved as "control characters," 52 | // such as XOFF (transmit off) to cause a connected tape reader to stop 53 | // as a part of communication flow control. There were various other 54 | // shortcomings and workarounds (e.g., delete vs. backspace) for use 55 | // with physical typewriters and teletype printers, too. 56 | // This brings us to the "Escape" character (ASCII 27), which was 57 | // originally meant to allow sending the aforementioned control codes as 58 | // literals instead of invoking their meaning, an "escape sequence." 59 | // Nowadays, in modern context, ESC sent to the terminal indicates the 60 | // start of a command sequence, such as moving the cursor, changing text 61 | // attributes, clearing the screen, etc. 62 | // 63 | // (https://en.wikipedia.org/wiki/ASCII) 64 | // 65 | // "Almost all manufacturers of video terminals added vendor-specific 66 | // escape sequences to perform operations such as placing the cursor at 67 | // arbitrary positions on the screen. One example is the VT52 terminal, 68 | // which allowed the cursor to be placed at an x,y location on the 69 | // screen by sending the ESC character, a Y character, and then two 70 | // characters representing numerical values equal to the x,y location 71 | // plus 32 (thus starting at the ASCII space character and avoiding 72 | // the control characters). The Hazeltine 1500 had a similar feature, 73 | // invoked using !, DC1 and then the X and Y positions separated with a 74 | // comma. While the two terminals had identical functionality in this 75 | // regard, different control sequences had to be used to invoke them. 76 | // As these sequences were different for different terminals, 77 | // elaborate libraries such as termcap ("terminal capabilities") and 78 | // utilities such as tput had to be created so programs could use the 79 | // same API to work with any terminal. In addition, many of these 80 | // terminals required sending numbers (such as row and column) as the 81 | // binary values of the characters; for some programming languages, and 82 | // for systems that did not use ASCII internally, it was often difficult 83 | // to turn a number into the correct character. 84 | // The ANSI standard attempted to address these problems by making a 85 | // command set that all terminals would use and requiring all numeric 86 | // information to be transmitted as ASCII numbers. The first standard 87 | // in the series was ECMA-48, adopted in 1976. It was a continuation of 88 | // a series of character coding standards, the first one being ECMA-6 89 | // from 1965, a 7-bit standard from which ISO 646 originates. The name 90 | // "ANSI escape sequence" dates from 1979 when ANSI adopted ANSI X3.64. 91 | // The ANSI X3L2 committee collaborated with the ECMA committee TC 1 to 92 | // produce nearly identical standards. These two standards were merged 93 | // into an international standard, ISO 6429. In 1994, ANSI withdrew its 94 | // standard in favor of the international standard. 95 | // The first popular video terminal to support these sequences was 96 | // the Digital VT100, introduced in 1978. This model was very successful 97 | // in the market, which sparked a variety of VT100 clones, among the 98 | // earliest and most popular of which was the much more affordable 99 | // Zenith Z-19 in 1979. Others included the Qume QVT-108, Televideo 100 | // TVI-970, Wyse WY-99GT as well as optional "VT100" or "VT103" or 101 | // "ANSI" modes with varying degrees of compatibility on many other 102 | // brands. The popularity of these gradually led to more and more 103 | // software (especially bulletin board systems [BBS] and other online 104 | // services) assuming the escape sequences worked, leading to almost 105 | // all new terminals and emulator programs supporting them. 106 | // In 1981, ANSI X3.64 was adopted for use in the U.S. government by 107 | // FIPS [Federal Information Processing Standards] publication 86. 108 | // Later, the U.S. government stopped duplicating industry standards, 109 | // so FIPS pub. 86 was withdrawn. 110 | // ECMA-48 has been updated several times and is currently [as 2025] 111 | // at its 5th edition, from 1991. It is also adopted by ISO and IEC 112 | // as standard ISO/IEC 6429. A version is adopted as a Japanese 113 | // Industrial Standard, as JIS X 0211. 114 | // Related standards include [United Nation's International 115 | // Telecommunication Union's] ITU T.61, the Teletex standard, and 116 | // the ISO/IEC 8613, the Open Document Architecture standard (mainly 117 | // ISO/IEC 8613-6 or ITU T.416). The two systems share many escape 118 | // codes with the ANSI system, with extensions that are not necessarily 119 | // meaningful to computer terminals. Both systems quickly fell into 120 | // disuse, but ECMA-48 marks the extensions used in them as reserved." 121 | // 122 | // (https://en.wikipedia.org/wiki/ANSI_escape_code) 123 | // 124 | // Standards (most were withdrawn in favor of ISO/IEC 6429): 125 | // ANSI X3.4-1986 126 | // U.N. ITU T.61 127 | // U.S. FIPS Publication 86 128 | // ISO/IEC DP-6429 129 | // JIS X 0211 130 | // ECMA-48 131 | 132 | // NOTE: Even though ANSI support would remain optional (configurable at 133 | // both compile-time and runtime), do still try to use only the bare- 134 | // minimum feature set of ANSI that is supported almost anywhere; many 135 | // of its features (e.g., italic, true-color, strikethrough, etc.) 136 | // are not supported universally among all terminal emulators. 137 | // As a general guideline, strive for compatibility with Linux TTY 138 | // (TeleTYpewriter) terminals. While it's true that most Linux systems 139 | // will have xterm or more advanced terminals, Windows 10/11+ will have 140 | // Windows Terminal, and that macOS will have Terminal.app, TTYs remain 141 | // the most portable, non-GUI way by default. 142 | // POSIX standardizes basic terminal I/O interfaces (tcgetattr, 143 | // tcsetattr, etc.) but the exact feature set, especially color support, 144 | // varies across systems. The TTY standard primarily defines the basic 145 | // input/output behaviors like cooked/raw modes and signal handling (^C, 146 | // ^Z) but does not mandate support for specific ANSI escape sequences 147 | // or color capabilities. 148 | // When writing cross-platform software using ANSI colors, you 149 | // generally have two options: (1) Use only the most basic 3-bit/8-color 150 | // subset that works almost everywhere, or (2) Use terminfo/termcap/ 151 | // ncurses to detect the terminal's actual capabilities at runtime. 152 | // When you see "VT100," "VT102," "xterm," or "linux" in your $TERM 153 | // variable, that indicates the emulation your terminal is claiming. 154 | // This tells programs (and libraries like ncurses) what control 155 | // sequences they can (probably) use. A "real TTY" on a physical 156 | // console (e.g., /dev/tty1 on Linux) often emulates a subset of VT102 157 | // (plus Linux-specific extras). 158 | // An "SSH TTY" (actually a pseudo-terminal, /dev/pts/...) might 159 | // advertise itself as xterm-256color or something else. 160 | // 161 | // https://en.wikipedia.org/wiki/List_of_terminal_emulators 162 | // 163 | // Jargon and Terminology: 164 | // Console 165 | // Physical display and keyboard directly connected to a computer. 166 | // Shell 167 | // Command-line interpreter that reads text commands from the user 168 | // and returns some result (e.g., bash, zsh, cmd.exe, PowerShell). 169 | // Terminal 170 | // Teletypes/video terminals that provided remote computer access. 171 | // Terminal Emulator 172 | // Software that emulates a hardware terminal (e.g., xterm, rxvt). 173 | // https://en.wikipedia.org/wiki/List_of_terminal_emulators 174 | // Virtual Terminal (VT) 175 | // Multiple terminal sessions you can switch between (tty1-tty6) 176 | // (Note that the VT in VT100 stood for "Video Terminal.") 177 | // Pseudo-terminal (PTY) 178 | // Using a terminal emulator to connect to a remote host (e.g., SSH) 179 | // https://en.wikipedia.org/wiki/Pseudoterminal 180 | // VGA Text Attributes 181 | // https://en.wikipedia.org/wiki/VGA_text_mode 182 | // https://wiki.osdev.org/Text_UI 183 | 184 | 185 | // Consult these resources for the bare-minimum ANSI escape sequences: 186 | // https://www.man7.org/linux/man-pages/man4/console_codes.4.html 187 | // https://vt100.net/docs/vt102-ug/contents.html 188 | // https://tldp.org/HOWTO/Text-Terminal-HOWTO-10.html 189 | 190 | 191 | // Initialize ANSI settings 192 | void ansi_init(); 193 | 194 | // TODO: Make the compile-time macro also make these unreachable as to 195 | // avoid having them compiled into the code when they shouldn't be. 196 | // Enable ANSI formatting at runtime 197 | void ansi_enable(); 198 | // Disable ANSI formatting at runtime 199 | void ansi_disable(); 200 | 201 | 202 | // "In order to tell the terminal we want to use an escape sequence, 203 | // and not print out a piece of text verbatim, we have a special escape 204 | // character, in unix-like systems the escape character is usually \e or 205 | // \033, after which another character follows, usually terminated by a 206 | // BEL (\007) or ST (Usually ESC). A lot of escape sequences are 207 | // terminated using various other characters. 208 | // 209 | // https://medium.com/israeli-tech-radar/ 210 | // terminal-escape-codes-are-awesome-heres-why-c8eb938b1a1c 211 | // 212 | // "A character is a control character if (before transformation 213 | // according to the mapping table) it has one of the 14 codes 00 (NUL), 214 | // 07 (BEL), 08 (BS), 09 (HT), 0a (LF), 0b (VT), 0c (FF), 0d (CR), 215 | // 0e (SO), 0f (SI), 18 (CAN), 1a (SUB), 1b (ESC), 7f (DEL). 216 | // One can set a "display control characters" mode (see below), and 217 | // allow 07, 09, 0b, 18, 1a, 7f to be displayed as glyphs. On the 218 | // other hand, in UTF-8 mode all codes 00–1f are regarded as control 219 | // characters, regardless of any "display control characters" mode." 220 | // If we have a control character, it is acted upon immediately and 221 | // then discarded (even in the middle of an escape sequence) and the 222 | // escape sequence continues with the next character. (However, ESC 223 | // starts a new escape sequence, possibly aborting a previous unfinished 224 | // one, and CAN and SUB abort any escape sequence.) The recognized 225 | // control characters are BEL, BS, HT, LF, VT, FF, CR, SO, SI, CAN, SUB, 226 | // ESC, DEL, CSI." 227 | // 228 | // NOTE: "\e" is a non-standard escape code for the ASCII ESC character; 229 | // it works in GCC/LLVM/TCC but isn't standard C. (Use "\x1b") 230 | // Standard escape codes are prefixed with Escape: 231 | // Caret/Ctrl-Key : ^[ 232 | // Octal : \033 233 | // Unicode : \u001b 234 | // Hexadecimal : \x1b 235 | // Decimal : 27 236 | #define ANSI_ESC(code) "\x1b[" #code "m" 237 | 238 | #define ESC "\x1b" 239 | #define CSI "\x1b[" 240 | 241 | 242 | // NOTE: 3-bit colors (i.e., 8 colors) are the most widely supported. 243 | // You might have heard about "16 colors," but that is a misnomer; in 244 | // reality, they are combining the "bold" attribute with the 8 colors, 245 | // making the existing 3-bit colors more intense. (Not to mention that 246 | // the "bold" attribute affects only foreground colors, not background.) 247 | // Nowadays, most terminals support 256 colors and even true-color 248 | // (i.e., 24-bit RGB), but we'll stick to basic attributes and 3-bit. 249 | // Get ANSI escape sequence based on current settings 250 | 251 | 252 | const char *ansi_get_reset(); 253 | const char *ansi_get_red(); 254 | const char *ansi_get_green(); 255 | const char *ansi_get_yellow(); 256 | const char *ansi_get_blue(); 257 | const char *ansi_get_bold(); 258 | 259 | //Reset 260 | #define reset "\e[0m" 261 | #define CRESET "\e[0m" 262 | #define COLOR_RESET "\e[0m" 263 | 264 | // Macro to generate ANSI color codes 265 | #define COLOR(code) "\x1b[" #code "m" 266 | 267 | // Predefined color codes using the macro 268 | #define RED COLOR(31) 269 | #define GREEN COLOR(32) 270 | #define YELLOW COLOR(33) 271 | #define BLUE COLOR(34) 272 | #define MAGENTA COLOR(35) 273 | #define CYAN COLOR(36) 274 | #define RESET COLOR(0) 275 | 276 | 277 | // Struct to group ANSI color strings 278 | typedef struct ansi_color_codes { 279 | const char* RESET; 280 | const char* RED; 281 | const char* GREEN; 282 | const char* YELLOW; 283 | const char* BLUE; 284 | const char* MAGENTA; 285 | const char* CYAN; 286 | // Add more color strings as needed 287 | } ansi_color_codes_t; 288 | 289 | // Initialize ANSI color codes 290 | static const ansi_color_codes_t ANSI_COLORS = { 291 | .RESET = "\x1b[0m", 292 | .RED = "\x1b[31m", 293 | .GREEN = "\x1b[32m", 294 | .YELLOW = "\x1b[33m", 295 | .BLUE = "\x1b[34m", 296 | .MAGENTA = "\x1b[35m", 297 | .CYAN = "\x1b[36m", 298 | // Initialize more colors as needed 299 | }; 300 | 301 | 302 | #if defined(_POSIX_C_SOURCE) 303 | bool enable_vt_mode() { 304 | // No need to enable manually ANSI colors on POSIX systems 305 | return true; 306 | } 307 | #elif defined(_WIN32) 308 | // Newer Windows 10 and 11 versions support ANSI colors in the console 309 | // and Windows Terminal, but they have to be enabled manually: 310 | // https://learn.microsoft.com/en-us/windows/console/ 311 | // console-virtual-terminal-sequences 312 | // 313 | // TODO: Older console versions do have formatting, but it's not ANSI. 314 | bool enable_vt_mode() { 315 | HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE); 316 | if (hOut == INVALID_HANDLE_VALUE) { 317 | return false; 318 | } 319 | 320 | DWORD dwMode = 0; 321 | if (!GetConsoleMode(hOut, &dwMode)) { 322 | return false; 323 | } 324 | 325 | dwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING; 326 | if (!SetConsoleMode(hOut, dwMode)) { 327 | return false; 328 | } 329 | 330 | return true; 331 | } 332 | #endif 333 | 334 | 335 | 336 | #endif // ANSI_H 337 | 338 | // --------------------------------------------------------------------- 339 | // END OF FILE: ansi.h 340 | // --------------------------------------------------------------------- 341 | -------------------------------------------------------------------------------- /src/cmdline/docs.h: -------------------------------------------------------------------------------- 1 | // --------------------------------------------------------------------- 2 | // SPDX-License-Identifier: GPL-3.0-or-later 3 | // docs.h is a part of Blitzping. 4 | // --------------------------------------------------------------------- 5 | 6 | 7 | // NOTE: All of the command-line outputs herein conform to the RFC 678 8 | // plaintext document standard; it is good readability practice to limit 9 | // a line of code's columns to 72 characters (which include only the 10 | // printable characters, not line endings or cursors). 11 | // I specifically chose 72 (and not some other limit like 80/132) 12 | // to ensure maximal compatibility with older technology, terminals, 13 | // paper hardcopies, and e-mails. While some other guidelines permit 14 | // more than just 72 characters, it is still important to note that 15 | // American teletypewriters could sometimes write upto only 72, and 16 | // older code (e.g., FORTRAN, Ada, COBOL, Assembler, etc.) used to 17 | // be hand-written on a "code form" in corporations like IBM; said 18 | // code form typically reserved the first 72 columns for statements, 19 | // 8 for serial numbers, and the remainder for comments, which was 20 | // finally turned into a physical punch card with 80 columns. 21 | // Even in modern times, the 72 limit can still be beneficial: 22 | // you can easily quote a 72-character line over e-mail without 23 | // requiring word-wrapping or horizontal scrolling. 24 | // As a sidenote, the reason that some guidelines, like PEP 8 25 | // (Style Guide for Python Code), recommended 79 characters (i.e., 26 | // not 80) was that the 80th character in a 80x24 terminal might 27 | // have been a bit hard to read. 28 | 29 | 30 | 31 | _Pragma ("once") 32 | #ifndef DOCS_H 33 | #define DOCS_H 34 | 35 | // TODO: Do I use ANSI code to color these? 36 | 37 | // TODO: Do I use \r\n here, or continue relying on libc? 38 | // TODO: Create a man.1 (man page) file using this 39 | // 40 | // TODO: Add an option to control memory alignment? 41 | // TODO: a 'Count' option instead of infinite sends 42 | // 43 | // NOTE: Unfortunately, C preprocessor is unable to include actual .txt 44 | // files (which could otherwise be holding this text) into strings. 45 | // (C23 is apparently able to do this using the new #embed directive.) 46 | 47 | static const char HELP_TEXT_BANNER[] = "\ 48 | test\n\ 49 | "; 50 | 51 | static const char HELP_TEXT_OVERVIEW[] = "\ 52 | Usage: blitzping [options]\n\ 53 | \n\ 54 | Options may use either -U (unix style), --gnu-style, or /dos-style\n\ 55 | conventions, and the \"=\" sign may be omitted.\n\ 56 | \n\ 57 | blitzping --num-threads=4 --proto=tcp --dest-ip=10.10.10.10\n\ 58 | blitzping --help=proto\n\ 59 | \n\ 60 | ::::::::::::::::::::::::::::::::General:::::::::::::::::::::::::::::::::\n\ 61 | -? --help= Display this help message or more info.\n\ 62 | -! --about Display information about the Program.\n\ 63 | -V --version Display the Program's version.\n\ 64 | -Q --quiet Suppress all output except errors.\n\ 65 | ::::::::::::::::::::::::::::::::Advanced::::::::::::::::::::::::::::::::\n\ 66 | -$ --bypass-checks Ignore system compatibility issues (e.g., \n\ 67 | wrong endianness) if startup checks fail.\n\ 68 | (May result in unexpected behavior.)\n\ 69 | --logger-level= Set the verbosity level of the logger.\n\ 70 | (-1: off, 0: critical, 1: error, 2: warn\n\ 71 | 3: info, 4: debug; default: 3.)\n\ 72 | --no-log-timestamp Don't prefix log messages with timestamps.\n\ 73 | -# --num-threads=<0-n> Number of threads to poll the socket with.\n\ 74 | (Default: system thread count; 0: disable\n\ 75 | threading, run everything in main thread.)\n\ 76 | --native-threads If both C11 libc and native\n\ 77 | (i.e., POSIX/Win32) threads are available,\n\ 78 | will prefer the native implementation.\n\ 79 | --buffer-size=<0-n> Number of packets to pre-craft and pass to\n\ 80 | the kernel in batches. (default: as many\n\ 81 | as possible; 0: disable buffering.)\n\ 82 | --no-async-sock Use blocking (not asynchronous) sockets.\n\ 83 | (Will severely hinder performance.)\n\ 84 | --no-mem-lock Don't lock memory pages; allow disk swap.\n\ 85 | (May reduce performance.)\n\ 86 | --no-cpu-prefetch Don't prefetch packet buffer to CPU cache.\n\ 87 | (May reduce performance.)\n\ 88 | --no-zero-copy By default, and only on GNU/Linux 2.4+, the\n\ 89 | Program uses shared ring buffers as a kernel\n\ 90 | bypass method; this flag will disable said\n\ 91 | feature on otherwise-supported platforms.\n\ 92 | (Will severely hinder performance.)\n\ 93 | "; 94 | 95 | // TODO: Have a layer 2 ether and "raw" (no protocol) layer 3 option. 96 | 97 | static const char HELP_TEXT_IPV4[] = "\ 98 | ::::::::::::::::::::::::::::L3. IPv4 Header::::::::::::::::::::::::::::\n\ 99 | | Byte |0,1,2,3,4,5,6,7|0,1,2,3,4,5,6,7|0,1,2,3,4,5,6,7|0,1,2,3,4,5,6,7|\n\ 100 | +------+-------+-------+-----------+---+---------------+---------------+\n\ 101 | | 0-4 |Version| IHL | DSCP |ECN| Total Length |\n\ 102 | +------+-------+-------+-----------+---+-----+-------------------------+\n\ 103 | | 4-8 | Identification |E|D|M| Fragment Offset |\n\ 104 | +------+---------------+---------------+-----+-------------------------+\n\ 105 | | 8-12| Time to Live | Protocol | Header Checksum |\n\ 106 | +------+---------------+---------------+-------------------------------+\n\ 107 | | 12-16| Source Address |\n\ 108 | +------+---------------------------------------------------------------+\n\ 109 | | 16-20| Destination Address |\n\ 110 | +------+---------------------------------------------------------------+\n\ 111 | : 20-56: [options & padding] :\n\ 112 | +------+---------------------------------------------------------------+\n\ 113 | -4 --ipv4 IPv4 layer 3 indicator.\n\ 114 | --src-ip= [OVERRIDE] IPv4 source address to spoof.\n\ 115 | --dest-ip= IPv4 destination address.\n\ 116 | --ver=<4|0-15> [OVERRIDE] IP version to spoof.\n\ 117 | --ihl=<5|0-15> [OVERRIDE] IPv4 header length in 32-bit\n\ 118 | increments; minimum \"should\" be 5 (i.e.,\n\ 119 | 5x32 = 160 bits = 20 bytes) by standard.\n\ 120 | --tos=<0-255> Type of Service; obsolete by DSCP+ECN.\n\ 121 | | ToS itself is divided into precedence,\n\ 122 | | throughput, reliability, cost, and mbz:\n\ 123 | | --prec=<...|0-7> RFC 791 IP Precedence/priority\n\ 124 | | (\"--help=prec\" for textual entries);\n\ 125 | | --min-delay Minimize delay;\n\ 126 | | --max-tput Maximize throughput;\n\ 127 | | --max-rely Maximize reliability;\n\ 128 | | --min-cost Minimize monetary cost (RFC 1349); and\n\ 129 | | --mbz-one Set the MBZ (\"Must-be-Zero\") bit to 1.\n\ 130 | --dscp=<...|0-64> Differentiated Services Code Point\n\ 131 | (\"--help=dscp\" for textual entries.)\n\ 132 | --ecn=<...|0-3> Explicit Congestion Notification\n\ 133 | (\"--help=ecn\" for textual entries.)\n\ 134 | --len=<0-65535> [OVERRIDE] total packet (+data) length.\n\ 135 | --ident=<0-65535> Packet identification (in fragmentation).\n\ 136 | --flags=<0-7> Bitfield for IPv4 flags:\n\ 137 | | --evil-bit [E]vil (RFC 3514)/Reserved bit;\n\ 138 | | --dont-frag [D]on't Fragment (DF); and\n\ 139 | | --more-frag [M]ore Fragments (MF).\n\ 140 | --frag-ofs=<0-8191> Fragment Offset\n\ 141 | --ttl=<0-255> Time-to-live (hop-limit) for the packet.\n\ 142 | --proto=<...|0-255> [OVERRIDE] protocol number (e.g., tcp, 6)\n\ 143 | (\"--help=proto\" for textual entries.)\n\ 144 | --chksum=<0-65535> [OVERRIDE] IPv4 header checksum.\n\ 145 | --options=<> [[UNFINISHED]]\n\ 146 | "; 147 | 148 | static const char HELP_TEXT_IPV6[] = "\ 149 | ::::::::::::::::::::::::::::L3. IPv6 Header::::::::::::::::::::::::::::\n\ 150 | -6 --ipv6 IPv6 layer 3 indicator.\n\ 151 | --src-ip= [OVERRIDE] IPv6 source address to spoof.\n\ 152 | --dest-ip= IPv6 destination address.\n\ 153 | --next-hdr=<...|0-255> Next header, akin to IPv4's \"proto\" field.\n\ 154 | (\"--help=next-header\" for text entries.)\n\ 155 | --hop-limit=<0-255> Similar to IPv4's \"ttl\" field.\n\ 156 | --flow-label=<0-1048575> Flow Label (experimental; RFC 2460).\n\ 157 | [[UNIMPLEMENTED]]\n\ 158 | "; 159 | 160 | // TODO: Make the bitfield also take one-letter flags 161 | static const char HELP_TEXT_TCP[] = "\ 162 | ::::::::::::::::::::::::::::L4. TCP Header:::::::::::::::::::::::::::::\n\ 163 | | Byte |0,1,2,3,4,5,6,7|0,1,2,3,4,5,6,7|0,1,2,3,4,5,6,7|0,1,2,3,4,5,6,7|\n\ 164 | +------+---------------+---------------+---------------+---------------+\n\ 165 | | 0-4 | Source Port | Destination Port |\n\ 166 | +------+-------------------------------+-------------------------------+\n\ 167 | | 4-8 | Sequence Number |\n\ 168 | +------+---------------------------------------------------------------+\n\ 169 | | 8-12| Acknowledgment Number |\n\ 170 | +------+-------+-------+-+-+-+-+-+-+-+-+-------------------------------+\n\ 171 | | 12-16|DataOfs| Rsrvd |C|E|U|A|P|R|S|F| Window |\n\ 172 | +------+-------+-------+-+-+-+-+-+-+-+-+-------------------------------+\n\ 173 | | 16-20| Checksum | Urgent Pointer |\n\ 174 | +------+-------------------------------+-------------------------------+\n\ 175 | : 20-56: [options & padding] :\n\ 176 | +------+---------------------------------------------------------------+\n\ 177 | -T --tcp TCP layer 4 indicator.\n\ 178 | --src-port=<0-65535> [OVERRIDE] Source port.\n\ 179 | --dest-port=<0-65535> Destination port.\n\ 180 | --seq-num=<0-4294967295> Sequence number.\n\ 181 | --ack-num=<0-4294967295> Acknowledgement number.\n\ 182 | --data-ofs=<0-15> Data Offset (in 32-bit words).\n\ 183 | --reserved=<0-15> TCP Reserved/unused bits (default: 0000).\n\ 184 | --flags=<0-255> Bitfield for TCP flags:\n\ 185 | | --cwr [C]ongestion Window Reduced (RFC 3168);\n\ 186 | | --ece [E]CN-Echo (RFC 3168);\n\ 187 | | --urg [U]rgent;\n\ 188 | | --ack [A]cknowledgment;\n\ 189 | | --psh [P]ush;\n\ 190 | | --rst [R]eset;\n\ 191 | | --syn [S]ynchronize; and\n\ 192 | | --fin [F]inish.\n\ 193 | --window=<0-65535> Window Size\n\ 194 | --chksum=<0-65535> [OVERRIDE] Checksum\n\ 195 | --urg-ptr=<0-65535> Urgent Pointer\n\ 196 | --options=<> [[UNFINISHED]]\n\ 197 | "; 198 | 199 | static const char HELP_TEXT_UDP[] = "\ 200 | ::::::::::::::::::::::::::::L4. UDP Header:::::::::::::::::::::::::::::\n\ 201 | -U --udp UDP layer 4 indicator.\n\ 202 | [[UNIMPLEMENTED]]\n\ 203 | "; 204 | 205 | static const char HELP_TEXT_ICMP[] = "\ 206 | ::::::::::::::::::::::::::::L4. ICMP Header::::::::::::::::::::::::::::\n\ 207 | -I --icmp ICMP layer 4 indicator.\n\ 208 | [[UNIMPLEMENTED]]\n\ 209 | "; 210 | 211 | // NOTE: These were "divided into sections because C99+ compilers 212 | // might not support single string literals exceeding 4095 characters. 213 | // 214 | // NOTE: The help texts alone take up a few kilobytes of space; you 215 | // could change this to an empty string to save on that, if need be. 216 | #define HELP_TEXT_ALL "%s%s%s%s%s%s", \ 217 | HELP_TEXT_OVERVIEW, HELP_TEXT_IPV4, HELP_TEXT_IPV6, \ 218 | HELP_TEXT_TCP, HELP_TEXT_UDP, HELP_TEXT_ICMP 219 | 220 | 221 | static const char HELP_PAGE_PROTO[] = "\ 222 | IPv4/IPv6 Protocols:\n\ 223 | \n\ 224 | icmp 1 Internet Control Message Protocol\n\ 225 | tcp 6 Transmission Control Protocol\n\ 226 | udp 17 User Datagram Protocol\n\ 227 | "; 228 | 229 | static const char HELP_PAGE_PREC[] = "\ 230 | IPv4 Precedence Codes:\n\ 231 | \n\ 232 | RFC 791\n\ 233 | routine 0 Routine\n\ 234 | priority 1 Priority\n\ 235 | immediate 2 Immediate\n\ 236 | flash 3 Flash\n\ 237 | OVERRIDE 4 Flash-OVERRIDE\n\ 238 | critical 5 Critic/Critical\n\ 239 | internetwork 6 Internetwork Control\n\ 240 | network 7 Network Control\n\ 241 | "; 242 | 243 | static const char HELP_PAGE_DSCP[] = "\ 244 | IPv4 Differentiated Services Code Points:\n\ 245 | \n\ 246 | DSCP Pool 1 Codepoints\n\ 247 | RFC 2474 (Class Selector PHBs)\n\ 248 | df 0 Default Forwarding (DF) PHB\n\ 249 | cs0 0 CS0 (standard)\n\ 250 | cs1 8 CS1 (low-priority data)\n\ 251 | cs2 16 CS2 (network operations/OAM)\n\ 252 | cs3 24 CS3 (broadcast video)\n\ 253 | cs4 32 CS4 (real-time interactive)\n\ 254 | cs5 40 CS5 (signaling)\n\ 255 | cs6 48 CS6 (network control)\n\ 256 | cs7 56 CS7 (reserved)\n\ 257 | RFC 2597 (Assured Forwarding [AF] PHB)\n\ 258 | af11 10 AF11 (high-throughput)\n\ 259 | af12 12 AF12 (high-throughput)\n\ 260 | af13 14 AF13 (high-throughput)\n\ 261 | af21 18 AF21 (low-latency)\n\ 262 | af22 20 AF22 (low-latency)\n\ 263 | af23 22 AF23 (low-latency)\n\ 264 | af31 26 AF31 (multimedia stream)\n\ 265 | af32 28 AF32 (multimedia stream)\n\ 266 | af33 30 AF33 (multimedia stream)\n\ 267 | af41 34 AF41 (multimedia conference)\n\ 268 | af42 36 AF42 (multimedia conference)\n\ 269 | af43 38 AF43 (multimedia conference)\n\ 270 | RFC 3246 (Expedited Forwarding [EF] PHB)\n\ 271 | ef 46 EF (telephony)\n\ 272 | RFC 5865 (Voice-Admit)\n\ 273 | va 44 Voice-Admit\n\ 274 | DSCP Pool 2 Codepoints\n\ 275 | \n\ 276 | DSCP Pool 3 Codepoints\n\ 277 | RFC 8622\n\ 278 | le 1 Lower-Effort PHB\n\ 279 | "; 280 | 281 | static const char HELP_PAGE_ECN[] = "\ 282 | IPv4 Explicit Congestion Notifications:\n\ 283 | \n\ 284 | RFC 3168\n\ 285 | not 0 Not ECN-Capable Transport\n\ 286 | RFC 8311 / RFC Errata 5399 / RFC 9331\n\ 287 | ect1 1 ECN-Capable Transport(1)\n\ 288 | RFC 3168\n\ 289 | ect0 2 ECN-Capable Transport(0)\n\ 290 | ce 3 Congestion Experienced\n\ 291 | "; 292 | 293 | 294 | static const char ABOUT_TEXT[] = "\ 295 | Blitzping Copyright (C) 2024 Fereydoun Memarzanjany\n\ 296 | This program comes with ABSOLUTELY NO WARRANTY.\n\ 297 | \n\ 298 | This is free software, and you are welcome to redistribute it\n\ 299 | under certain conditions; see the GNU General Public License v3.0.\n\ 300 | If you wish to report a bug or contribute to this project,\n\ 301 | visit this repository: https://github.com/Thraetaona/Blitzping\n\ 302 | "; 303 | 304 | static const char VERSION_TEXT[] = "Blitzping v1.7.0"; 305 | 306 | #endif // DOCS_H 307 | 308 | // --------------------------------------------------------------------- 309 | // END OF FILE: docs.h 310 | // --------------------------------------------------------------------- 311 | -------------------------------------------------------------------------------- /src/cmdline/logger.c: -------------------------------------------------------------------------------- 1 | // --------------------------------------------------------------------- 2 | // SPDX-License-Identifier: GPL-3.0-or-later 3 | // logger.c is a part of Blitzping. 4 | // --------------------------------------------------------------------- 5 | 6 | 7 | #include "logger.h" 8 | 9 | 10 | static enum LogLevel CURRENT_LOG_LEVEL = LOG_DEBUG; 11 | static bool LOG_TIMESTAMPS = true; 12 | 13 | // TODO: Mutexes? (for thread-safety) 14 | void logger_set_level(const enum LogLevel level) { 15 | CURRENT_LOG_LEVEL = level; 16 | } 17 | 18 | void logger_set_timestamps(const bool timestamp) { 19 | LOG_TIMESTAMPS = timestamp; 20 | } 21 | 22 | 23 | #define TIMESTAMP_SIZE 26 24 | _Static_assert(TIMESTAMP_SIZE >= 20, 25 | "timestamp array must be at least 20 characters long"); 26 | 27 | // NOTE: size should be at least 20. 28 | static int generate_timestamp( 29 | char *const timestamp, const size_t size 30 | ) { 31 | const time_t now = time(NULL); 32 | if (now == ((time_t) -1)) { 33 | snprintf(timestamp, size, "%-*s", 34 | (int)(size-1), "unknown time"); 35 | return 1; 36 | } 37 | 38 | const struct tm *const t = localtime(&now); 39 | if (t == NULL) { 40 | snprintf( 41 | timestamp, size, 42 | "U-%ld%-*s", (long)now, (int)(size - 1 43 | - snprintf(NULL, 0, "U-%ld", (long)now)), "" 44 | ); 45 | return 1; 46 | } 47 | 48 | if (strftime(timestamp, size, "%Y/%m/%d@%H:%M:%S", t) == 0) { 49 | snprintf(timestamp, size, 50 | "%04d/%02d/%02d@%02d:%02d:%02d", 51 | (t->tm_year + 1900) % 10000, 52 | (t->tm_mon + 1) % 13, 53 | t->tm_mday % 32, 54 | t->tm_hour % 24, 55 | t->tm_min % 60, 56 | t->tm_sec % 60 57 | ); 58 | return 1; 59 | } 60 | 61 | return 0; 62 | } 63 | 64 | // NOTE: These are ordered (according to the enum LogLevel). 65 | static const char *const LEVEL_STRINGS[] = { 66 | "CRIT", 67 | "ERRR", 68 | "WARN", 69 | "INFO", 70 | "DBUG" 71 | }; 72 | 73 | void logger(const enum LogLevel level, const char *const format, ...) { 74 | if (level > CURRENT_LOG_LEVEL) { 75 | return; 76 | } 77 | const int old_errno = errno; // Save the old errno value 78 | 79 | FILE *const output_stream = level <= LOG_WARN ? stderr : stdout; 80 | 81 | if (LOG_TIMESTAMPS) { 82 | char timestamp[TIMESTAMP_SIZE] = {0}; 83 | // Get the current time (if possible) 84 | (void)generate_timestamp(timestamp, TIMESTAMP_SIZE); 85 | fprintf(output_stream, "[%s|%s] ", 86 | LEVEL_STRINGS[level], timestamp); 87 | } 88 | else { 89 | fprintf(output_stream, "[%s] ", 90 | LEVEL_STRINGS[level]); 91 | } 92 | 93 | va_list args; 94 | va_start(args, format); 95 | errno = 0; 96 | const int print_status = vfprintf(output_stream, format, args); 97 | va_end(args); 98 | 99 | fprintf(output_stream, "\n"); 100 | 101 | // TODO: See if there is a better way to error-check these. 102 | if (ferror(output_stream) || print_status < 0) { 103 | perror("Error logging message"); 104 | clearerr(output_stream); 105 | } 106 | 107 | errno = 0; // Reset errno 108 | if (fflush(output_stream) == EOF) { 109 | perror("Error flushing stream"); 110 | } 111 | 112 | // Check for errors on the output stream 113 | if (ferror(output_stream)) { 114 | perror("Error after flushing stream"); 115 | clearerr(output_stream); 116 | } 117 | 118 | errno = old_errno; // Restore the old errno value 119 | } 120 | 121 | 122 | // --------------------------------------------------------------------- 123 | // END OF FILE: logger.c 124 | // --------------------------------------------------------------------- 125 | -------------------------------------------------------------------------------- /src/cmdline/logger.h: -------------------------------------------------------------------------------- 1 | // --------------------------------------------------------------------- 2 | // SPDX-License-Identifier: GPL-3.0-or-later 3 | // logger.h is a part of Blitzping. 4 | // --------------------------------------------------------------------- 5 | 6 | _Pragma ("once") 7 | #ifndef LOGGER_H 8 | #define LOGGER_H 9 | 10 | 11 | #include 12 | #include 13 | 14 | #include 15 | #include 16 | #include 17 | 18 | extern int errno; 19 | 20 | typedef enum LogLevel { 21 | LOG_NONE = -1, 22 | LOG_CRIT = 0, 23 | LOG_ERROR = 1, 24 | LOG_WARN = 2, 25 | LOG_INFO = 3, 26 | LOG_DEBUG = 4 27 | } log_level_t; 28 | 29 | void logger_set_level(const enum LogLevel level); 30 | void logger_set_timestamps(const bool timestamp); 31 | void logger(const enum LogLevel level, const char *const format, ...); 32 | 33 | #define DEBUG_MSG(format, ...) (logger(LOG_DEBUG, \ 34 | "[%s()@%s:%d] " format, __func__, __FILE__, __LINE__, __VA_ARGS__)) 35 | 36 | #endif // LOGGER_H 37 | 38 | // --------------------------------------------------------------------- 39 | // END OF FILE: logger.h 40 | // --------------------------------------------------------------------- 41 | -------------------------------------------------------------------------------- /src/cmdline/parser.c: -------------------------------------------------------------------------------- 1 | // --------------------------------------------------------------------- 2 | // SPDX-License-Identifier: GPL-3.0-or-later 3 | // parser.c is a part of Blitzping. 4 | // --------------------------------------------------------------------- 5 | 6 | 7 | #include "parser.h" 8 | 9 | 10 | 11 | static char *duplicate_string(const char *str) { 12 | char *new_str = (char *)malloc(strlen(str) + 1); 13 | if (new_str == NULL) { 14 | logger(LOG_ERROR, "Memory allocation failed."); 15 | return NULL; 16 | } 17 | strcpy(new_str, str); 18 | return new_str; 19 | } 20 | 21 | static char *to_lowercase(const char *str) { 22 | char *lowercase_str = duplicate_string(str); 23 | if (lowercase_str == NULL) { 24 | return NULL; 25 | } 26 | for (char *p = lowercase_str; *p; ++p) { 27 | *p = tolower((unsigned char)*p); 28 | } 29 | 30 | return lowercase_str; 31 | } 32 | 33 | /* 34 | static char *to_uppercase(const char *str) { 35 | char *uppercase_str = duplicate_string(str); 36 | if (uppercase_str == NULL) { 37 | return NULL; 38 | } 39 | for (char *p = uppercase_str; *p; ++p) { 40 | *p = toupper((unsigned char)*p); 41 | } 42 | 43 | return uppercase_str; 44 | } 45 | */ 46 | 47 | struct NameKey { 48 | const char *const name; 49 | const int key; 50 | }; 51 | 52 | static long get_key_from_name( 53 | const struct NameKey *const name_keys, 54 | const size_t num_keys, 55 | const char *const value_str, 56 | const bool case_insensitive, 57 | const char *const error_name, 58 | bool *const error_occured 59 | ) { 60 | char *comparison_value = NULL; 61 | if (case_insensitive) { 62 | comparison_value = to_lowercase(value_str); 63 | } 64 | else { 65 | comparison_value = (char *)value_str; 66 | } 67 | 68 | for (size_t i = 0; i < num_keys; i++) { 69 | char *comparison_name = NULL; 70 | if (case_insensitive) { 71 | comparison_name = to_lowercase(name_keys[i].name); 72 | } 73 | else { 74 | comparison_name = (char *)name_keys[i].name; 75 | } 76 | 77 | if (strcmp(comparison_name, comparison_value) == 0) { 78 | if (case_insensitive) { 79 | free(comparison_value); 80 | free(comparison_name); 81 | } 82 | return name_keys[i].key; 83 | } 84 | 85 | if (case_insensitive) { 86 | free(comparison_name); 87 | } 88 | } 89 | 90 | if (case_insensitive) { 91 | free(comparison_value); 92 | } 93 | // Not found 94 | 95 | // Make a list of valid options to print to the user 96 | char *valid_options = NULL; 97 | size_t len = 0; 98 | for (size_t i = 0; i < num_keys; i++) { 99 | len += strlen(name_keys[i].name) + 2; 100 | } 101 | valid_options = malloc(len + 1); 102 | if (valid_options == NULL) { 103 | DEBUG_MSG("Memory allocation failed.", 0); 104 | } 105 | valid_options[0] = '\0'; 106 | for (size_t i = 0; i < num_keys; i++) { 107 | strcat(valid_options, name_keys[i].name); 108 | if (i < num_keys - 1) { 109 | strcat(valid_options, ", "); 110 | } 111 | } 112 | logger(LOG_ERROR, 113 | "\"%s\" is not a valid textual entry for the \"--%s\" option;\n" 114 | "valid entries are as follows (%s):\n %s.\n" 115 | "(Use \"--help=%s\" for a description on those.)", 116 | value_str, error_name, 117 | case_insensitive ? "case-insensitive" : "case-sensitive", 118 | valid_options, error_name 119 | ); 120 | free(valid_options); 121 | 122 | *error_occured = true; 123 | return -1; 124 | } 125 | 126 | static long validate_range( 127 | const char *const value_str, 128 | const long min, 129 | const long max, 130 | const char *const error_name, 131 | bool *const error_occured 132 | ) { 133 | errno = 0; 134 | 135 | char *endptr; 136 | long result = strtol(value_str, &endptr, 10); 137 | 138 | // Check for conversion errors and out-of-bounds values 139 | if (errno != 0 || *endptr != '\0' || result < min || result > max) { 140 | if (errno != 0) { 141 | logger(LOG_ERROR, 142 | "Error in strtol() conversion: %s", strerror(errno) 143 | ); 144 | } 145 | 146 | logger(LOG_ERROR, 147 | "Value of \"--%s\" must be [%ld, %ld].", 148 | error_name, min, max 149 | ); 150 | 151 | *error_occured = true; 152 | return -1; 153 | } 154 | 155 | return result; 156 | } 157 | 158 | static long parse_text_or_int( 159 | const struct NameKey *const name_keys, 160 | const size_t num_keys, 161 | const char *const value_str, 162 | const bool case_insensitive, 163 | const long min, 164 | const long max, 165 | const char *const error_name, 166 | bool *const error_occured 167 | ) { 168 | long result; 169 | 170 | if (isdigit(*value_str)) { 171 | result = validate_range( 172 | value_str, min, max, error_name, error_occured 173 | ); 174 | } 175 | else { 176 | result = get_key_from_name( 177 | name_keys, num_keys, value_str, case_insensitive, 178 | error_name, error_occured 179 | ); 180 | } 181 | 182 | return result; 183 | } 184 | 185 | 186 | static const struct NameKey IP_PROTOCOLS[] = { 187 | {"ip", IP_PROTO_IP}, 188 | {"icmp", IP_PROTO_ICMP}, 189 | {"tcp", IP_PROTO_TCP}, 190 | {"udp", IP_PROTO_UDP} 191 | }; 192 | 193 | static const struct NameKey IP_TOS_PREC_CODES[] = { 194 | {"routine", IP_TOS_PREC_ROUTINE}, 195 | {"priority", IP_TOS_PREC_PRIORITY}, 196 | {"immediate", IP_TOS_PREC_IMMEDIATE}, 197 | {"flash", IP_TOS_PREC_FLASH}, 198 | {"override", IP_TOS_PREC_FLASH_OVERRIDE}, 199 | {"critical", IP_TOS_PREC_CRITIC_ECP}, 200 | {"internetwork", IP_TOS_PREC_INTERNETWORK_CONTROL}, 201 | {"network", IP_TOS_PREC_NETWORK_CONTROL} 202 | }; 203 | 204 | static const struct NameKey IP_ECN_CODES[] = { 205 | {"not", IP_ECN_NOT_ECT}, 206 | {"ect1", IP_ECN_ECT_1}, 207 | {"ect0", IP_ECN_ECT_0}, 208 | {"ce", IP_ECN_CE} 209 | }; 210 | 211 | static const struct NameKey IP_DSCP_CODES[] = { 212 | {"df", IP_DSCP_DF}, 213 | {"cs0", IP_DSCP_CS0}, 214 | {"cs1", IP_DSCP_CS1}, 215 | {"cs2", IP_DSCP_CS2}, 216 | {"cs3", IP_DSCP_CS3}, 217 | {"cs4", IP_DSCP_CS4}, 218 | {"cs5", IP_DSCP_CS5}, 219 | {"cs6", IP_DSCP_CS6}, 220 | {"cs7", IP_DSCP_CS7}, 221 | {"af11", IP_DSCP_AF11}, 222 | {"af12", IP_DSCP_AF12}, 223 | {"af13", IP_DSCP_AF13}, 224 | {"af21", IP_DSCP_AF21}, 225 | {"af22", IP_DSCP_AF22}, 226 | {"af23", IP_DSCP_AF23}, 227 | {"af31", IP_DSCP_AF31}, 228 | {"af32", IP_DSCP_AF32}, 229 | {"af33", IP_DSCP_AF33}, 230 | {"af41", IP_DSCP_AF41}, 231 | {"af42", IP_DSCP_AF42}, 232 | {"af43", IP_DSCP_AF43}, 233 | {"ef", IP_DSCP_EF}, 234 | {"va", IP_DSCP_VA}, 235 | {"le", IP_DSCP_LE} 236 | }; 237 | 238 | 239 | 240 | // TODO: Bring more macro detections from here: 241 | // TODO: add runtime reports? 242 | // https://github.com/cpredef/predef 243 | static const char HELP_DIAGNOSTICS[] = 244 | "Compilation Diagnostics:\n" 245 | #if defined(__DATE__) && defined(__TIME__) 246 | " Build Time : " __DATE__ " @ " __TIME__ "\n" 247 | #else 248 | " Build Time : unknown\n" 249 | #endif 250 | 251 | #if defined(__VERSION__) 252 | " Compiler : " __VERSION__ "\n" 253 | #else 254 | " Compiler : unknown\n" 255 | #endif 256 | 257 | // NOTE: These are defined in the makefile. 258 | #if defined(TARGET_TRIPLET) && defined(TARGET_ARCH) \ 259 | && defined(TARGET_SUBARCH) && defined(TARGET_VENDOR) \ 260 | && defined(TARGET_OS) && defined(TARGET_LIBC) \ 261 | && defined(TARGET_FLOAT_ABI) 262 | " Target Triplet : " TARGET_TRIPLET "\n" 263 | " Architecture : " TARGET_ARCH "\n" 264 | " Sub-Architecture : " TARGET_SUBARCH "\n" 265 | " Vendor : " TARGET_VENDOR "\n" 266 | " Operating System : " TARGET_OS "\n" 267 | " C Library (libc) : " TARGET_LIBC "\n" 268 | " Float ABI : " TARGET_FLOAT_ABI "\n" 269 | #endif 270 | 271 | #if defined(__LITTLE_ENDIAN__) 272 | " Endianness : little\n" 273 | #elif defined(__BIG_ENDIAN__) 274 | " Endianness : big\n" 275 | #else 276 | " Endianness : unknown\n"; 277 | #endif 278 | 279 | #if defined(__STDC_VERSION__) 280 | " C Version : " STRINGIFY(__STDC_VERSION__) "\n" 281 | # if __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_THREADS__) 282 | " C11 Threads : compiled\n" 283 | # else 284 | " C11 Threads : not compiled\n" 285 | # endif 286 | #endif 287 | 288 | #if defined(_POSIX_C_SOURCE) 289 | " Userland API : POSIX\n" 290 | " POSIX C Source : " STRINGIFY(_POSIX_C_SOURCE) "\n" 291 | # if defined(_POSIX_THREADS) && _POSIX_THREADS >= 0 292 | " POSIX Threads : compiled\n" 293 | # else 294 | " POSIX Threads : not compiled\n" 295 | # endif 296 | " Max Vectored I/O : " STRINGIFY(UIO_MAXIOV) "\n" 297 | #elif defined(_WIN32) 298 | " Userland API : Win32\n" 299 | #else 300 | " Userland API : unknown\n" 301 | #endif 302 | ; 303 | 304 | 305 | enum OptionKind { 306 | OPTION_NONE = 0, 307 | // General 308 | OPTION_HELP, 309 | OPTION_ABOUT, 310 | OPTION_VERSION, 311 | OPTION_QUIET, 312 | // Advanced 313 | OPTION_BYPASS_CHECKS, 314 | OPTION_LOGGER_LEVEL, 315 | OPTION_NO_LOG_TIMESTAMP, 316 | OPTION_NUM_THREADS, 317 | OPTION_NATIVE_THREADS, 318 | OPTION_BUFFER_SIZE, 319 | OPTION_NO_ASYNC_SOCK, 320 | OPTION_NO_MEM_LOCK, 321 | OPTION_NO_CPU_PREFETCH, 322 | // IPv4 Header 323 | OPTION_IPV4, 324 | OPTION_SRC_IP, 325 | OPTION_DEST_IP, 326 | OPTION_IP_VER, 327 | OPTION_IP_IHL, 328 | OPTION_IP_TOS, 329 | OPTION_IP_PREC, 330 | OPTION_IP_MIN_DELAY, 331 | OPTION_IP_MAX_TPUT, 332 | OPTION_IP_MAX_RELY, 333 | OPTION_IP_MIN_COST, 334 | OPTION_IP_MBZ_ONE, 335 | OPTION_IP_DSCP, 336 | OPTION_IP_ECN, 337 | OPTION_IP_LEN, 338 | OPTION_IP_IDENT, 339 | OPTION_IP_FLAGS, 340 | OPTION_IP_EVIL_BIT, 341 | OPTION_IP_DONT_FRAG, 342 | OPTION_IP_MORE_FRAG, 343 | OPTION_IP_FRAG_OFS, 344 | OPTION_IP_TTL, 345 | OPTION_IP_PROTO, 346 | OPTION_IP_CHECKSUM, 347 | OPTION_IP_OPTIONS, 348 | // IPv6 Header 349 | OPTION_IPV6, 350 | OPTION_IP6_NEXT_HEADER, 351 | OPTION_IP6_HOP_LIMIT, 352 | OPTION_IP6_FLOW_LABEL, 353 | // [[UNFINISHED]] 354 | // TCP Header 355 | OPTION_TCP, 356 | // UDP Header 357 | OPTION_UDP, 358 | // ICMP Header 359 | OPTION_ICMP, 360 | }; 361 | 362 | struct Option { 363 | const char flag; 364 | const char *const name; 365 | const bool has_arg; 366 | const enum OptionKind kind; 367 | }; 368 | 369 | static const struct Option OPTIONS[] = { 370 | {'\0', "\0", false, OPTION_NONE}, 371 | // General 372 | {'?', "help", false, OPTION_HELP}, 373 | {'!', "about", false, OPTION_ABOUT}, 374 | {'V', "version", false, OPTION_VERSION}, 375 | {'Q', "quiet", false, OPTION_QUIET}, 376 | // Advanced 377 | {'$', "bypass-checks", false, OPTION_BYPASS_CHECKS}, 378 | {'\0', "logger-level", true, OPTION_LOGGER_LEVEL}, 379 | {'\0', "no-log-timestamp", false, OPTION_NO_LOG_TIMESTAMP}, 380 | {'#', "num-threads", true, OPTION_NUM_THREADS}, 381 | {'\0', "native-threads", false, OPTION_NATIVE_THREADS}, 382 | {'\0', "buffer-size", true, OPTION_BUFFER_SIZE}, 383 | {'\0', "no-async-sock", false, OPTION_NO_ASYNC_SOCK}, 384 | {'\0', "no-mem-lock", false, OPTION_NO_MEM_LOCK}, 385 | {'\0', "no-cpu-prefetch", false, OPTION_NO_CPU_PREFETCH}, 386 | // Multi-options (switches that may refer to multiple headers 387 | // and need extra processing to determine which one). 388 | {'\0', "src-ip", true, OPTION_SRC_IP}, 389 | {'\0', "dest-ip", true, OPTION_DEST_IP}, 390 | {'\0', "flags", true, OPTION_IP_FLAGS}, 391 | {'\0', "chksum", true, OPTION_IP_CHECKSUM}, 392 | {'\0', "options", true, OPTION_IP_OPTIONS}, 393 | // IPv4 Header 394 | {'4', "ipv4", false, OPTION_IPV4}, 395 | /* src-ip */ 396 | /* dest-ip */ 397 | {'\0', "ver", true, OPTION_IP_VER}, 398 | {'\0', "ihl", true, OPTION_IP_IHL}, 399 | {'\0', "tos", true, OPTION_IP_TOS}, 400 | {'\0', "prec", true, OPTION_IP_PREC}, 401 | {'\0', "min-delay", false, OPTION_IP_MIN_DELAY}, 402 | {'\0', "max-tput", false, OPTION_IP_MAX_TPUT}, 403 | {'\0', "max-rely", false, OPTION_IP_MAX_RELY}, 404 | {'\0', "min-cost", false, OPTION_IP_MIN_COST}, 405 | {'\0', "mbz-one", false, OPTION_IP_MBZ_ONE}, 406 | {'\0', "dscp", true, OPTION_IP_DSCP}, 407 | {'\0', "ecn", true, OPTION_IP_ECN}, 408 | {'\0', "len", true, OPTION_IP_LEN}, 409 | {'\0', "ident", true, OPTION_IP_IDENT}, 410 | /* flags */ 411 | {'\0', "evil-bit", false, OPTION_IP_EVIL_BIT}, 412 | {'\0', "dont-frag", false, OPTION_IP_DONT_FRAG}, 413 | {'\0', "more-frag", false, OPTION_IP_MORE_FRAG}, 414 | {'\0', "frag-ofs", true, OPTION_IP_FRAG_OFS}, 415 | {'\0', "ttl", true, OPTION_IP_TTL}, 416 | {'\0', "proto", true, OPTION_IP_PROTO}, 417 | /* chksum */ 418 | /* options */ 419 | // IPv6 Header 420 | {'6', "ipv6", false, OPTION_IPV6}, 421 | /* src-ip */ 422 | /* dest-ip */ 423 | {'\0', "next-header", true, OPTION_IP6_NEXT_HEADER}, 424 | {'\0', "hop-limit", true, OPTION_IP6_HOP_LIMIT}, 425 | {'\0', "flow-label", true, OPTION_IP6_FLOW_LABEL}, 426 | // unfinished 427 | // TCP Header 428 | {'T', "tcp", false, OPTION_TCP}, 429 | /* src-port */ 430 | /* dest-port */ 431 | {'\0', "seq-num", true, OPTION_NONE}, 432 | {'\0', "ack-num", true, OPTION_NONE}, 433 | {'\0', "data-ofs", true, OPTION_NONE}, 434 | {'\0', "reserved", true, OPTION_NONE}, 435 | /* flags */ 436 | {'\0', "cwr", false, OPTION_NONE}, 437 | {'\0', "ece", false, OPTION_NONE}, 438 | {'\0', "urg", false, OPTION_NONE}, 439 | {'\0', "ack", false, OPTION_NONE}, 440 | {'\0', "psh", false, OPTION_NONE}, 441 | {'\0', "rst", false, OPTION_NONE}, 442 | {'\0', "syn", false, OPTION_NONE}, 443 | {'\0', "fin", false, OPTION_NONE}, 444 | {'\0', "window", true, OPTION_NONE}, 445 | /* chksum */ 446 | {'\0', "urg-ptr", true, OPTION_NONE}, 447 | /* options */ 448 | // UDP Header 449 | {'U', "udp", false, OPTION_UDP}, 450 | // ICMP Header 451 | {'I', "icmp", false, OPTION_ICMP}, 452 | }; 453 | 454 | 455 | struct LayerAlias { 456 | const char *name; 457 | osi_layer_t layer; 458 | }; 459 | 460 | static const struct LayerAlias LAYER_ALIASES[] = { 461 | // OSI (Open Systems Interconnection) 462 | {"layer1", LAYER_PHYSICAL}, 463 | {"l1", LAYER_PHYSICAL}, 464 | {"physical", LAYER_PHYSICAL}, 465 | {"phys", LAYER_PHYSICAL}, 466 | // PDU (Protocol Data Unit) 467 | {"symbol", LAYER_PHYSICAL}, 468 | {"bits", LAYER_PHYSICAL}, 469 | 470 | // OSI 471 | {"layer2", LAYER_DATALINK}, 472 | {"l2", LAYER_DATALINK}, 473 | {"datalink", LAYER_DATALINK}, 474 | {"data", LAYER_DATALINK}, 475 | {"frame", LAYER_DATALINK}, 476 | {"layer3", LAYER_NETWORK}, 477 | {"l3", LAYER_NETWORK}, 478 | {"network", LAYER_NETWORK}, 479 | {"net", LAYER_NETWORK}, 480 | // PDU 481 | {"packet", LAYER_NETWORK}, 482 | 483 | // OSI 484 | {"layer4", LAYER_TRANSPORT}, 485 | {"l4", LAYER_TRANSPORT}, 486 | {"transport", LAYER_TRANSPORT}, 487 | {"trans", LAYER_TRANSPORT}, 488 | // PDU 489 | {"segment", LAYER_TRANSPORT}, 490 | {"datagram", LAYER_TRANSPORT}, 491 | 492 | // OSI 493 | {"layer5", LAYER_SESSION}, 494 | {"l5", LAYER_SESSION}, 495 | {"session", LAYER_SESSION}, 496 | {"sess", LAYER_SESSION}, 497 | // PDU 498 | {"data", LAYER_SESSION}, 499 | 500 | // OSI 501 | {"layer6", LAYER_PRESENTATION}, 502 | {"l6", LAYER_PRESENTATION}, 503 | {"presentation", LAYER_PRESENTATION}, 504 | {"pres", LAYER_PRESENTATION}, 505 | // PDU 506 | {"data", LAYER_PRESENTATION}, 507 | 508 | // OSI 509 | {"layer7", LAYER_APPLICATION}, 510 | {"l7", LAYER_APPLICATION}, 511 | {"application", LAYER_APPLICATION}, 512 | {"app", LAYER_APPLICATION}, 513 | // PDU 514 | {"data", LAYER_APPLICATION} 515 | }; 516 | 517 | static osi_layer_t current_layer = LAYER_NONE; 518 | 519 | static int str_compare_nocase(const char *s1, const char *s2) { 520 | while (*s1 && *s2) { 521 | int c1 = tolower((unsigned char)*s1); 522 | int c2 = tolower((unsigned char)*s2); 523 | if (c1 != c2) { 524 | return c1 - c2; 525 | } 526 | s1++; 527 | s2++; 528 | } 529 | return tolower((unsigned char)*s1) - tolower((unsigned char)*s2); 530 | } 531 | 532 | static bool is_layer_subcommand(const char *arg) { 533 | for (size_t i = 0; i < ARRAY_SIZE(LAYER_ALIASES); i++) { 534 | if (str_compare_nocase(arg, LAYER_ALIASES[i].name) == 0) { 535 | current_layer = LAYER_ALIASES[i].layer; 536 | return true; 537 | } 538 | } 539 | return false; 540 | } 541 | 542 | static bool handle_option( 543 | const struct Option *const cmdline_option, 544 | const char *const value, 545 | struct ProgramArgs *const program_args 546 | ) { 547 | bool error_occured = false; 548 | 549 | switch (cmdline_option->kind) { 550 | // General 551 | case OPTION_HELP: { 552 | // TODO: Handle sub-help commands. 553 | program_args->general.opt_info = true; 554 | 555 | // TODO: Mention or pipe this through 'less' for limited 556 | // terminal widths. 557 | fprintf(stderr, HELP_TEXT_ALL); 558 | break; 559 | } 560 | case OPTION_ABOUT: { 561 | program_args->general.opt_info = true; 562 | 563 | fprintf(stderr, "%s\n%s", ABOUT_TEXT, HELP_DIAGNOSTICS); 564 | break; 565 | } 566 | case OPTION_VERSION: { 567 | program_args->general.opt_info = true; 568 | 569 | fprintf(stderr, "%s\n", VERSION_TEXT); 570 | break; 571 | } 572 | case OPTION_QUIET: { 573 | program_args->general.logger_level = LOG_WARN; 574 | break; 575 | } 576 | // Advanced 577 | case OPTION_BYPASS_CHECKS: { 578 | program_args->advanced.bypass_checks = true; 579 | break; 580 | } 581 | case OPTION_LOGGER_LEVEL: { 582 | program_args->general.logger_level = 583 | (log_level_t)validate_range( 584 | value, LOG_NONE, LOG_DEBUG, cmdline_option->name, 585 | &error_occured); 586 | break; 587 | } 588 | case OPTION_NO_LOG_TIMESTAMP: { 589 | program_args->advanced.no_log_timestamp = true; 590 | break; 591 | } 592 | case OPTION_NUM_THREADS: { 593 | program_args->advanced.num_threads = 594 | (unsigned int)validate_range( 595 | value, 0, UINT_MAX, cmdline_option->name, 596 | &error_occured); 597 | break; 598 | } 599 | case OPTION_NATIVE_THREADS: { 600 | program_args->advanced.native_threads = true; 601 | break; 602 | } 603 | case OPTION_BUFFER_SIZE: { 604 | program_args->advanced.buffer_size = 605 | (unsigned int)validate_range( 606 | value, 0, UIO_MAXIOV, cmdline_option->name, 607 | &error_occured); 608 | break; 609 | } 610 | case OPTION_NO_ASYNC_SOCK: { 611 | program_args->advanced.no_async_sock = true; 612 | break; 613 | } 614 | case OPTION_NO_MEM_LOCK: { 615 | program_args->advanced.no_mem_lock = true; 616 | break; 617 | } 618 | case OPTION_NO_CPU_PREFETCH: { 619 | program_args->advanced.no_cpu_prefetch = true; 620 | break; 621 | } 622 | // IPv4 623 | case OPTION_IPV4: { 624 | program_args->parser.current_layer = LAYER_3; 625 | program_args->parser.current_proto = PROTO_L3_IPV4; 626 | break; 627 | } 628 | case OPTION_SRC_IP: { 629 | program_args->ipv4_misc.override_source = true; 630 | 631 | uint32_t temp; 632 | if (inet_pton(AF_INET, value, &temp) != 1) { 633 | logger(LOG_ERROR, 634 | "Invalid source IPv4 address: %s", value); 635 | error_occured = true; 636 | } 637 | program_args->ipv4->saddr.address = htonl(temp); 638 | break; 639 | } 640 | case OPTION_DEST_IP: { 641 | uint32_t temp; 642 | if (inet_pton(AF_INET, value, &temp) != 1) { 643 | logger(LOG_ERROR, 644 | "Invalid dest IPv4 address: %s", value); 645 | error_occured = true; 646 | } 647 | program_args->ipv4->daddr.address = htonl(temp); 648 | break; 649 | } 650 | case OPTION_IP_VER: { 651 | program_args->ipv4->ver = (uint8_t)validate_range( 652 | value, 0, 15, cmdline_option->name, &error_occured); 653 | break; 654 | } 655 | case OPTION_IP_IHL: { 656 | program_args->ipv4->ihl = (uint8_t)validate_range( 657 | value, 0, 15, cmdline_option->name, &error_occured); 658 | break; 659 | } 660 | case OPTION_IP_TOS: { 661 | program_args->ipv4->tos.bitfield = (uint8_t)validate_range( 662 | value, 0, 255, cmdline_option->name, 663 | &error_occured); 664 | break; 665 | } 666 | case OPTION_IP_PREC: { 667 | program_args->ipv4->tos.precedence = 668 | (ip_tos_prec_t)parse_text_or_int( 669 | IP_TOS_PREC_CODES, 670 | ARRAY_SIZE(IP_TOS_PREC_CODES), 671 | value, 672 | true, 673 | 0, 674 | 7, 675 | cmdline_option->name, 676 | &error_occured 677 | ); 678 | break; 679 | } 680 | case OPTION_IP_MIN_DELAY: { 681 | program_args->ipv4->tos.low_delay = true; 682 | break; 683 | } 684 | case OPTION_IP_MAX_TPUT: { 685 | program_args->ipv4->tos.high_throughput = true; 686 | break; 687 | } 688 | case OPTION_IP_MAX_RELY: { 689 | program_args->ipv4->tos.high_reliability = true; 690 | break; 691 | } 692 | case OPTION_IP_MIN_COST: { 693 | program_args->ipv4->tos.low_cost = true; 694 | break; 695 | } 696 | case OPTION_IP_MBZ_ONE: { 697 | program_args->ipv4->tos.mbz_bit = true; 698 | break; 699 | } 700 | case OPTION_IP_DSCP: { 701 | program_args->ipv4->dscp = 702 | (ip_dscp_code_t)parse_text_or_int( 703 | IP_DSCP_CODES, 704 | ARRAY_SIZE(IP_DSCP_CODES), 705 | value, 706 | true, 707 | 0, 708 | 64, 709 | cmdline_option->name, 710 | &error_occured 711 | ); 712 | break; 713 | } 714 | case OPTION_IP_ECN: { 715 | program_args->ipv4->ecn = 716 | (ip_ecn_code_t)parse_text_or_int( 717 | IP_ECN_CODES, 718 | ARRAY_SIZE(IP_ECN_CODES), 719 | value, 720 | true, 721 | 0, 722 | 3, 723 | cmdline_option->name, 724 | &error_occured 725 | ); 726 | break; 727 | } 728 | case OPTION_IP_LEN: { 729 | program_args->ipv4_misc.override_length = true; 730 | 731 | program_args->ipv4->len = 732 | (uint16_t)validate_range( 733 | value, 0, 65535, cmdline_option->name, 734 | &error_occured); 735 | break; 736 | } 737 | case OPTION_IP_IDENT: { 738 | program_args->ipv4->id = 739 | (uint16_t)validate_range( 740 | value, 0, 65535, cmdline_option->name, 741 | &error_occured); 742 | break; 743 | } 744 | case OPTION_IP_FLAGS: { 745 | program_args->ipv4->flag_bits = 746 | (ip_flag_t)validate_range( 747 | value, 0, 7, cmdline_option->name, 748 | &error_occured); 749 | break; 750 | } 751 | case OPTION_IP_EVIL_BIT: { 752 | program_args->ipv4->flags.ev = true; 753 | break; 754 | } 755 | case OPTION_IP_DONT_FRAG: { 756 | program_args->ipv4->flags.df = true; 757 | break; 758 | } 759 | case OPTION_IP_MORE_FRAG: { 760 | program_args->ipv4->flags.mf = true; 761 | break; 762 | } 763 | case OPTION_IP_FRAG_OFS: { 764 | program_args->ipv4->fragofs = 765 | (uint16_t)validate_range( 766 | value, 0, 8191, cmdline_option->name, 767 | &error_occured); 768 | break; 769 | } 770 | case OPTION_IP_TTL: { 771 | program_args->ipv4->ttl = (uint8_t)validate_range( 772 | value, 0, 255, cmdline_option->name, 773 | &error_occured); 774 | break; 775 | } 776 | case OPTION_IP_PROTO: { 777 | program_args->ipv4->proto = 778 | (ip_proto_t)parse_text_or_int( 779 | IP_PROTOCOLS, 780 | ARRAY_SIZE(IP_PROTOCOLS), 781 | value, 782 | true, 783 | 0, 784 | 255, 785 | cmdline_option->name, 786 | &error_occured 787 | ); 788 | break; 789 | } 790 | case OPTION_IP_CHECKSUM: { 791 | program_args->ipv4_misc.override_checksum = true; 792 | 793 | program_args->ipv4->chksum = (uint16_t)validate_range( 794 | value, 0, 65535, cmdline_option->name, 795 | &error_occured); 796 | break; 797 | } 798 | case OPTION_IP_OPTIONS: { 799 | // TODO: options 800 | break; 801 | } 802 | // IPv6 803 | case OPTION_IPV6: { 804 | program_args->parser.current_layer = LAYER_3; 805 | program_args->parser.current_proto = PROTO_L3_IPV6; 806 | break; 807 | } 808 | case OPTION_IP6_NEXT_HEADER: { 809 | break; 810 | } 811 | case OPTION_IP6_HOP_LIMIT: { 812 | break; 813 | } 814 | case OPTION_IP6_FLOW_LABEL: { 815 | break; 816 | } 817 | // unfinished 818 | // TCP Header 819 | case OPTION_TCP: { 820 | program_args->parser.current_layer = LAYER_4; 821 | program_args->parser.current_proto = PROTO_L4_TCP; 822 | break; 823 | } 824 | // UDP Header 825 | case OPTION_UDP: { 826 | program_args->parser.current_layer = LAYER_4; 827 | program_args->parser.current_proto = PROTO_L4_UDP; 828 | break; 829 | } 830 | // ICMP Header 831 | case OPTION_ICMP: { 832 | program_args->parser.current_layer = LAYER_4; 833 | program_args->parser.current_proto = PROTO_L4_ICMP; 834 | break; 835 | } 836 | // Null Option (this shouldn't happen) 837 | case OPTION_NONE: 838 | default: { 839 | logger(LOG_CRIT, "Null option given, somehow."); 840 | error_occured = true; 841 | } 842 | } 843 | 844 | return error_occured; 845 | } 846 | 847 | 848 | int parse_args( 849 | const int argc, 850 | char *const argv[], 851 | struct ProgramArgs *const program_args 852 | ) { 853 | program_args->diagnostics.executable_name = argv[0]; 854 | 855 | // If no arguments were given, print the help text and return. 856 | if (argc == 1) { 857 | fprintf(stderr, HELP_TEXT_ALL); 858 | return 1; 859 | } 860 | 861 | // argv[0] is the program name itself. 862 | for (int i = 1; i < argc; i++) { 863 | const char *const arg = argv[i]; 864 | 865 | if (is_layer_subcommand(arg)) { 866 | continue; // Found layer command, skip to next arg 867 | } 868 | 869 | if (arg[0] == '-' || arg[0] == '/') { 870 | const char *const opt_name = arg + (arg[1] == '-' ? 2 : 1); 871 | const char *opt_val = NULL; 872 | 873 | /* 874 | for (size_t j = 0; j < ARRAY_SIZE(OPTIONS); j++) { 875 | if (matches_option(&OPTIONS[j], opt_name)) { 876 | // Process option if it belongs to current layer 877 | if (option_matches_layer(&OPTIONS[j], 878 | current_layer)) { 879 | process_option( 880 | &OPTIONS[j], value, program_args 881 | ); 882 | } else { 883 | logger( 884 | LOG_ERROR, 885 | "Option --%s not valid for current layer", 886 | opt_name 887 | ); 888 | return 1; 889 | } 890 | break; 891 | } 892 | } 893 | */ 894 | 895 | for (size_t j = 0; j < ARRAY_SIZE(OPTIONS); j++) { 896 | const size_t opt_len = 897 | strlen(OPTIONS[j].name); 898 | 899 | // Check if the current argument is a valid option 900 | if (strncmp(opt_name, OPTIONS[j].name, opt_len) == 0 && 901 | (opt_name[opt_len] == '\0' || 902 | opt_name[opt_len] == '=') 903 | ) { 904 | // Check if the argument contains an optional 905 | // '=' sign, as well as where it's located. 906 | const char *const has_equal = 907 | strchr(opt_name, '='); 908 | 909 | // If so, the value will come after the = 910 | if (has_equal) { 911 | opt_val = has_equal + 1; 912 | } 913 | else if (i + 1 < argc && argv[i + 1][0] != '-' 914 | && argv[i + 1][0] != '/' 915 | ) { 916 | opt_val = argv[++i]; 917 | } 918 | 919 | if (OPTIONS[j].has_arg && (!opt_val 920 | || opt_val[0] == '\0' || opt_val[0] == ' ') 921 | ) { 922 | logger(LOG_ERROR, 923 | "Option \"--%s\" requires an argument!", 924 | OPTIONS[j].name 925 | ); 926 | return 1; 927 | } 928 | 929 | bool error_occured = handle_option( 930 | &OPTIONS[j], opt_val, program_args); 931 | 932 | if (error_occured) { 933 | return 1; 934 | } 935 | 936 | break; 937 | } 938 | // Compared all options and found no valid match 939 | else if (j == ARRAY_SIZE(OPTIONS)-1) { 940 | logger(LOG_ERROR, 941 | "\"--%s\" is not a known option;\n" 942 | "use \"--help\" for more information.", 943 | opt_name 944 | ); 945 | return 1; 946 | } 947 | } 948 | 949 | // Rest of your code... 950 | } 951 | else { 952 | // Unrecognized switch character 953 | fprintf(stderr, HELP_TEXT_ALL); 954 | return 1; 955 | } 956 | } 957 | 958 | return 0; 959 | } 960 | 961 | 962 | /* 963 | int parse_ip_cidr( 964 | const char *cidr_str, struct ip_addr_range *ip_range 965 | ) { 966 | if (strlen(cidr_str) > MAX_IP_CIDR_LENGTH) { 967 | fprintf(stderr, "IP/CIDR notation is too long: %s\n", cidr_str); 968 | return 1; 969 | } 970 | 971 | char cidr_copy[MAX_IP_CIDR_LENGTH+1]; // +1 for null terminator 972 | strncpy(cidr_copy, cidr_str, sizeof (cidr_copy)); 973 | cidr_copy[sizeof (cidr_copy) - 1] = '\0'; 974 | 975 | char *ip_str = strtok(cidr_copy, "/"); 976 | char *prefix_len_str = strtok(NULL, "/"); 977 | 978 | if (ip_str == NULL || prefix_len_str == NULL) { 979 | fprintf(stderr, "Invalid IP/CIDR notation: %s\n", cidr_str); 980 | return 1; 981 | } 982 | 983 | struct in_addr ip_addr; 984 | if (inet_pton(AF_INET, ip_str, &ip_addr) != 1) { 985 | fprintf(stderr, "Invalid IP address: %s\n", ip_str); 986 | return 1; 987 | } 988 | 989 | int prefix_len = atoi(prefix_len_str); 990 | if (prefix_len < 0 || prefix_len > 32) { 991 | fprintf(stderr, "Invalid prefix length: %s\n", prefix_len_str); 992 | return 1; 993 | } 994 | 995 | uint32_t mask = htonl((uint32_t)~0 << (32 - prefix_len)); 996 | ip_range->start.address = ntohl(ip_addr.s_addr & mask); 997 | ip_range->end.address = ntohl(ip_addr.s_addr | ~mask); 998 | 999 | { 1000 | char start[INET_ADDRSTRLEN]; 1001 | char end[INET_ADDRSTRLEN]; 1002 | 1003 | inet_ntop(AF_INET, &(ip_range->start), start, INET_ADDRSTRLEN); 1004 | inet_ntop(AF_INET, &(ip_range->end), end, INET_ADDRSTRLEN); 1005 | 1006 | printf("Starting IP range: %s\n", start); 1007 | printf("Ending IP range: %s\n", end); 1008 | } 1009 | 1010 | return 0; 1011 | } 1012 | 1013 | int parse_ip_port( 1014 | const char *ip_port_str, ip_addr_t *ip, int *port 1015 | ) { 1016 | if (strlen(ip_port_str) > MAX_IP_PORT_LENGTH) { 1017 | fprintf(stderr, "IP:Port notation is too long: %s\n", 1018 | ip_port_str); 1019 | return 1; 1020 | } 1021 | 1022 | char ip_port_copy[MAX_IP_PORT_LENGTH + 1]; 1023 | strncpy(ip_port_copy, ip_port_str, sizeof (ip_port_copy)); 1024 | ip_port_copy[sizeof (ip_port_copy) - 1] = '\0'; 1025 | 1026 | char *ip_str = strtok(ip_port_copy, ":"); 1027 | char *port_str = strtok(NULL, ":"); 1028 | 1029 | if (ip_str == NULL || port_str == NULL) { 1030 | fprintf(stderr, "Invalid IP:Port notation: %s\n", 1031 | ip_port_str); 1032 | return 1; 1033 | } 1034 | 1035 | ip->address = inet_addr(ip_str); 1036 | if (ip->address == INADDR_NONE) { 1037 | fprintf(stderr, "Invalid IP address: %s\n", ip_str); 1038 | return 1; 1039 | } 1040 | 1041 | *port = atoi(port_str); 1042 | if (*port < PORT_MIN || *port > PORT_MAX) { 1043 | fprintf(stderr, "Invalid port: %d\n", *port); 1044 | return 1; 1045 | } 1046 | 1047 | return 0; 1048 | } 1049 | */ 1050 | 1051 | 1052 | // --------------------------------------------------------------------- 1053 | // END OF FILE: parser.c 1054 | // --------------------------------------------------------------------- 1055 | -------------------------------------------------------------------------------- /src/cmdline/parser.h: -------------------------------------------------------------------------------- 1 | // --------------------------------------------------------------------- 2 | // SPDX-License-Identifier: GPL-3.0-or-later 3 | // parser.h is a part of Blitzping. 4 | // --------------------------------------------------------------------- 5 | 6 | #pragma once 7 | #ifndef PARSER_H 8 | #define PARSER_H 9 | 10 | 11 | #include "../program.h" 12 | #include "../netlib/netinet.h" 13 | #include "./logger.h" 14 | #include "docs.h" 15 | 16 | 17 | #include 18 | #include 19 | #include 20 | #include 21 | 22 | #include 23 | #include 24 | #include 25 | 26 | #if defined(_POSIX_C_SOURCE) 27 | # include 28 | # include 29 | # include 30 | #elif defined(_WIN32) 31 | //# include 32 | #endif 33 | 34 | // A CIDR notation string is in the following format xxx.xxx.xxx.xxx/xx 35 | // (e.g., 255.255.255.255/32); there can be a total of 18 characters. 36 | #define MAX_IP_CIDR_LENGTH 18 // xxx.xxx.xxx.xxx/xx 37 | #define MAX_IP_PORT_LENGTH 21 // xxx.xxx.xxx.xxx:xxxxx 38 | 39 | // TODO: Move to netlib 40 | #define PORT_MIN 0 41 | #define PORT_MAX 65535 // 2^16 - 1 42 | 43 | extern int errno; // Declared in 44 | 45 | 46 | int parse_args( 47 | const int argc, 48 | char *const argv[], 49 | struct ProgramArgs *const program_args 50 | ); 51 | 52 | // This indirection is necessary for eager evaluation of macros. 53 | // https://stackoverflow.com/a/5459929/12660750 54 | #define STRINGIFY_HELPER(x) #x 55 | #define STRINGIFY(x) STRINGIFY_HELPER(x) 56 | 57 | #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0])) 58 | 59 | #endif // PARSER_H 60 | 61 | // --------------------------------------------------------------------- 62 | // END OF FILE: parser.h 63 | // --------------------------------------------------------------------- 64 | -------------------------------------------------------------------------------- /src/main.c: -------------------------------------------------------------------------------- 1 | // --------------------------------------------------------------------- 2 | // SPDX-License-Identifier: GPL-3.0-or-later 3 | // 4 | // Blitzping: Sending IP packets as fast as possible in userland. 5 | // Copyright (C) 2024 Fereydoun Memarzanjany 6 | // 7 | // This program is free software: you can redistribute it and/or modify 8 | // it under the terms of the GNU General Public License as published by 9 | // the Free Software Foundation, either version 3 of the License, or 10 | // (at your option) any later version. 11 | // 12 | // This program is distributed in the hope that it will be useful, 13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | // GNU General Public License for more details. 16 | // 17 | // You should have received a copy of the GNU General Public License 18 | // along with this program; if not, see . 19 | // --------------------------------------------------------------------- 20 | 21 | 22 | #include "./program.h" 23 | #include "./cmdline/logger.h" 24 | #include "./cmdline/parser.h" 25 | #include "packet.h" 26 | #include "socket.h" 27 | #include "./netlib/netinet.h" 28 | 29 | #include 30 | #include 31 | #include 32 | 33 | #include 34 | #include 35 | // C11 threads (glibc >=2.28, musl >=1.1.5, Windows SDK >~10.0.22620) 36 | #if __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_THREADS__) 37 | # include 38 | int __attribute__((weak)) thrd_create( 39 | thrd_t *thr, thrd_start_t func, void *arg 40 | ); 41 | int __attribute__((weak)) thrd_join( 42 | thrd_t thr, int *res 43 | ); 44 | #endif 45 | 46 | #if defined(_POSIX_C_SOURCE) 47 | # include 48 | # if defined(_POSIX_THREADS) && _POSIX_THREADS >= 0 49 | # include 50 | int __attribute__((weak)) pthread_create( 51 | pthread_t *thread, const pthread_attr_t *attr, 52 | void *(*start_routine) (void *), void *arg 53 | ); 54 | int __attribute__((weak)) pthread_join( 55 | pthread_t thread, void **retval 56 | ); 57 | # endif 58 | #elif defined(_WIN32) 59 | //# 60 | #endif 61 | 62 | 63 | 64 | void diagnose_system(struct ProgramArgs *const program_args) { 65 | //bool checks_succeeded = true; 66 | 67 | program_args->diagnostics.runtime.endianness = check_endianness(); 68 | #if __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_THREADS__) 69 | program_args->diagnostics.runtime.c11_threads = 70 | (&thrd_create != NULL) && (&thrd_join != NULL); 71 | #endif 72 | #if defined(_POSIX_THREADS) && _POSIX_THREADS >= 0 73 | program_args->diagnostics.runtime.posix_threads = 74 | (&pthread_create != NULL) && (&pthread_join != NULL); 75 | #endif 76 | program_args->diagnostics.runtime.num_cores = 77 | #if defined(_POSIX_C_SOURCE) 78 | sysconf(_SC_NPROCESSORS_ONLN); 79 | #else 80 | 0; 81 | #endif 82 | 83 | /* 84 | // TODO: use capabilities to also verify privilage level in raw sockets 85 | // Check to see if the currently running machine's endianness 86 | // matches what was expected to be the target's endianness at 87 | // the time of compilation. 88 | #if defined(__LITTLE_ENDIAN__) 89 | if (runtime_endianness != little_endian) { 90 | logger(LOG_ERROR, 91 | "Program was compiled for little endian,\n" 92 | "but this machine is somehow big endian!\n" 93 | ); 94 | #elif defined(__BIG_ENDIAN__) 95 | if (runtime_endianness != big_endian) { 96 | logger(LOG_ERROR, 97 | "Program was compiled for big endian,\n" 98 | "but this machine is somehow little endian!\n" 99 | ); 100 | #endif 101 | checks_succeeded = false; 102 | } 103 | 104 | if (!thrd_create || !thrd_join) { 105 | fprintf(stderr, 106 | "This program was compiled with C11 ,\n" 107 | "but this system appears to lack thrd_create() or\n" 108 | "thrd_join(); this could be due to an old C library.\n" 109 | "try using \"--native-threads\" for POSIX/Win32\n" 110 | "threads or \"--num-threads=0\" to disable threading.\n" 111 | ); 112 | return 1; 113 | } 114 | 115 | fprintf(stderr, 116 | "This program was compiled without C11 ;\n" 117 | "try using \"--native-threads\" for POSIX/Win32\n" 118 | "threads or \"--num-threads=0\" to disable threading.\n" 119 | ); 120 | */ 121 | //return checks_succeeded; 122 | } 123 | 124 | void fill_defaults(struct ProgramArgs *const program_args) { 125 | // General 126 | program_args->general.logger_level = LOG_INFO; 127 | 128 | // Advanced 129 | program_args->advanced.num_threads = 130 | program_args->diagnostics.runtime.num_cores; 131 | 132 | // IPv4 133 | // 134 | // NOTE: Unfortunately, there is no POSIX-compliant way to 135 | // get the current interface's ip address; getifaddrs() is 136 | // not standardized. 137 | // TODO: Use unprivilaged sendto() as an alternative. 138 | *(program_args->ipv4) = (struct ip_hdr){ 139 | .ver = 4, 140 | .ihl = 5, 141 | .ttl = 128, 142 | .proto = IP_PROTO_TCP, 143 | .len = htons(sizeof(struct ip_hdr) + sizeof(struct tcp_hdr)), 144 | .saddr.address = 0, 145 | .daddr.address = 0 146 | }; 147 | } 148 | 149 | int main(int argc, char *argv[]) { 150 | struct ProgramArgs program_args = {0}; 151 | struct ip_hdr *ipv4_header_args = 152 | (struct ip_hdr *)calloc(1, sizeof(struct ip_hdr)); 153 | 154 | if (ipv4_header_args == NULL) { 155 | program_args.diagnostics.unrecoverable_error = true; 156 | logger(LOG_ERROR, 157 | "Failed to allocate memory for program arguments."); 158 | goto CLEANUP; 159 | } 160 | program_args.ipv4 = ipv4_header_args; 161 | 162 | 163 | diagnose_system(&program_args); 164 | 165 | fill_defaults(&program_args); 166 | 167 | /*if (!diagnose_system(&program_args)) { 168 | // TODO: Add an argument to let the user continue regardless. 169 | //if () { 170 | program_args.diagnostics.unrecoverable_error = true; 171 | goto CLEANUP; 172 | //} 173 | logger(LOG_WARN, 174 | "System verification failed but was told to continue\n" 175 | "regardless; expect potentially undefined behavior.\n" 176 | ); 177 | }*/ 178 | 179 | 180 | if (parse_args(argc, argv, &program_args) != 0) { 181 | program_args.diagnostics.unrecoverable_error = true; 182 | logger(LOG_INFO, "Quitting due to invalid arguments."); 183 | goto CLEANUP; 184 | } 185 | else if (program_args.general.opt_info) { 186 | // User just wanted to see the --help, --about, etc. text. 187 | goto CLEANUP; 188 | } 189 | 190 | 191 | logger_set_level(program_args.general.logger_level); 192 | logger_set_timestamps(!program_args.advanced.no_log_timestamp); 193 | 194 | int socket_descriptor = setup_posix_socket( 195 | true, !program_args.advanced.no_async_sock 196 | ); // TODO: make raw sockets optional 197 | if (socket_descriptor == -1) { 198 | program_args.diagnostics.unrecoverable_error = true; 199 | logger(LOG_INFO, "Quitting after failing to create a socket."); 200 | goto CLEANUP; 201 | } 202 | 203 | program_args.socket = socket_descriptor; 204 | 205 | send_packets(&program_args); 206 | 207 | 208 | if (shutdown(socket_descriptor, SHUT_RDWR) == -1) { 209 | logger(LOG_WARN, "Socket shutdown failed: %s", strerror(errno)); 210 | } 211 | else { 212 | logger(LOG_INFO, "Socket shutdown successfully."); 213 | } 214 | 215 | if (close(socket_descriptor) == -1) { 216 | logger(LOG_WARN, "Socket closing failed: %s", strerror(errno)); 217 | } 218 | else { 219 | logger(LOG_INFO, "Socket closed successfully."); 220 | } 221 | 222 | CLEANUP: 223 | 224 | free(ipv4_header_args); 225 | 226 | logger(LOG_INFO, "Done; exiting program..."); 227 | 228 | if (program_args.diagnostics.unrecoverable_error) { 229 | return EXIT_FAILURE; 230 | } 231 | else { 232 | return EXIT_SUCCESS; 233 | } 234 | } 235 | 236 | 237 | // --------------------------------------------------------------------- 238 | // END OF FILE: main.c 239 | // --------------------------------------------------------------------- 240 | -------------------------------------------------------------------------------- /src/netlib/arpa.h: -------------------------------------------------------------------------------- 1 | // --------------------------------------------------------------------- 2 | // SPDX-License-Identifier: GPL-3.0-or-later 3 | // arpa.h is a part of Blitzping. 4 | // --------------------------------------------------------------------- 5 | 6 | _Pragma ("once") 7 | #ifndef ARPA_H 8 | #define ARPA_H 9 | 10 | 11 | 12 | 13 | 14 | #endif // ARPA_H 15 | 16 | // --------------------------------------------------------------------- 17 | // END OF FILE: arpa.h 18 | // --------------------------------------------------------------------- 19 | -------------------------------------------------------------------------------- /src/netlib/netinet.h: -------------------------------------------------------------------------------- 1 | // --------------------------------------------------------------------- 2 | // SPDX-License-Identifier: GPL-3.0-or-later 3 | // netinet.h is a part of Blitzping. 4 | // --------------------------------------------------------------------- 5 | 6 | _Pragma ("once") 7 | #ifndef NETINET_H 8 | #define NETINET_H 9 | 10 | 11 | // NOTE: Unfortunately, is NOT a part of the POSIX 12 | // standard, while and somehow are. 13 | // However, even the latter are rather useless, because most of their 14 | // definitions are hidden behind non-standard BSD or System V-specific 15 | // feature flags. In any case, the headers defined there are far 16 | // too outdated, still referring to many fields as "reserved." 17 | // For that reason, and for future compatibility with Win32, 18 | // it is better to define our own protocol header structures. 19 | 20 | 21 | // NOTE: These included header files should not actually make this 22 | // file dependent upon libc (at runtime), because they are all 23 | // "compile-time" dependencies. In other words, they should compile 24 | // just fine under a -ffreestanding or -nolibc environment. 25 | #include 26 | #include 27 | 28 | 29 | // NOTE: Binary integer literals (e.g., 0b10101010) are a GNU extension; 30 | // unfortunately, they are not part of the C11 standard. (C23 N2549) 31 | 32 | // NOTE: Use the standard C99 _Pragma statement rather than #pragma. 33 | 34 | // NOTE: You cannot use enums directly inside macro expansions! 35 | 36 | // NOTE: C does not let you put "flexible array members" inside 37 | // of unions (or nested structs in unions), even if they both 38 | // have the exact same type... 39 | 40 | // NOTE: You can not define anonymous members of unions inside structs, 41 | // so you will have to copy-paste the same union definition for each. 42 | // To make it easier, I had to define some union definitions as pre- 43 | // processor macros. This is especially imperative if your union 44 | // contains non-byte bitfields (which are expected to get packed 45 | // in the exterior struct), because the compiler does not seem 46 | // to honor the "internal" bitfields inside of nested unions/structs. 47 | 48 | // NOTE: Do NOT pack the "main" structs (e.g., ip_hdr or tcp_hdr); 49 | // they will be casted to pointers, and we don't want half-words there. 50 | 51 | // NOTE: You cannot have namespaces (i.e., enums inside named structs) 52 | // in C, unlike C++. For that reason, make sure to use prefixes to 53 | // properly denote enums/defines, such as TCP_FLAGS_SYN instead of 54 | // just SYN or TCP_SYN. 55 | 56 | // NOTE: The C Standardization Committee was sometimes so out-of- 57 | // touch with their decisions; namely, at least before C23, you are 58 | // unable to specify the underlying "type" of an enum. This means that 59 | // an enum with values that are all between 0-255 "may or may not" 60 | // result in a uint8_t, depending on the compiler's discretion. 61 | // Yes, C was supposed to be a "portable assembler," but it is also 62 | // widely used as a systems programming language, where bit-level and 63 | // endianness control is crucial. (C23 N3030) 64 | // Check for C23 support 65 | #if __STDC_VERSION__ >= 202300L // C23 or later 66 | # define ENUM_UNDERLYING(type) : type 67 | #else // Fallback for older standards (e.g., C11) 68 | # define ENUM_UNDERLYING(type) __attribute__((packed)) 69 | #endif 70 | 71 | 72 | // NOTE: Unfortunately, only GCC supports the scalar_storage_order 73 | // attribute/pragma, and LLVM/MSVC don't have it yet; for that reason, 74 | // we have to resort to old-fashioned macro definitions. 75 | // https://km.kkrach.de/p_little_vs_big_endian 76 | // https://github.com/llvm/llvm-project/issues/34641 77 | #include "../utils/endian.h" 78 | 79 | 80 | /* Protocol Definitions */ 81 | // TODO: Separete protos into layer names in their folders. 82 | #include "./protos/ip.h" 83 | #include "./protos/tcp.h" 84 | 85 | typedef enum OsiLayer { 86 | LAYER_0 = 0, // None (doesn't exist) 87 | LAYER_1 = 1, // MAC/Ethernet 88 | LAYER_2 = 2, // IPv4/IPv6 89 | LAYER_3 = 3, // 90 | LAYER_4 = 4, // 91 | LAYER_5 = 5, // 92 | LAYER_6 = 6, // 93 | LAYER_7 = 7, // 94 | 95 | // Aliases 96 | LAYER_NONE = LAYER_0, 97 | LAYER_PHYSICAL = LAYER_1, 98 | LAYER_DATALINK = LAYER_2, 99 | LAYER_NETWORK = LAYER_3, 100 | LAYER_TRANSPORT = LAYER_4, 101 | LAYER_SESSION = LAYER_5, 102 | LAYER_PRESENTATION = LAYER_6, 103 | LAYER_APPLICATION = LAYER_7 104 | } osi_layer_t; 105 | 106 | // TODO: We don't have namespaces, but can we somehow group this in OSI? 107 | typedef enum osi_protocol { 108 | // Layer 3 (Network) 109 | PROTO_L3_RAW, 110 | PROTO_L3_IPV4, 111 | PROTO_L3_IPV6, 112 | // Layer 4 (Transport) 113 | PROTO_L4_RAW, 114 | PROTO_L4_TCP, 115 | PROTO_L4_UDP, 116 | PROTO_L4_ICMP // TODO: ICMP shouldn't belong in L4. 117 | } osi_proto_t; 118 | 119 | 120 | #endif // NETINET_H 121 | 122 | // --------------------------------------------------------------------- 123 | // END OF FILE: netinet.h 124 | // --------------------------------------------------------------------- 125 | -------------------------------------------------------------------------------- /src/netlib/protos/ip.h: -------------------------------------------------------------------------------- 1 | // --------------------------------------------------------------------- 2 | // SPDX-License-Identifier: GPL-3.0-or-later 3 | // ip.h is a part of Blitzping. 4 | // --------------------------------------------------------------------- 5 | 6 | _Pragma ("once") 7 | #ifndef IP_H 8 | #define IP_H 9 | 10 | 11 | // IP Address type(s) 12 | typedef union ip_addr_view { 13 | uint32_t address; // IP address in uint32_t form 14 | uint8_t octets[4]; // Four octets (bytes) notation 15 | } ip_addr_t; 16 | 17 | 18 | // IP Protocol definitions 19 | _Pragma ("pack(push)") 20 | typedef enum __attribute__((packed)) ip_proto { 21 | IP_PROTO_IP = 0, 22 | IP_PROTO_ICMP = 1, 23 | IP_PROTO_TCP = 6, 24 | IP_PROTO_UDP = 17, 25 | } ip_proto_t; 26 | _Pragma ("pack(pop)") 27 | 28 | 29 | _Pragma ("pack(push)") 30 | typedef enum __attribute__((packed)) ip_tos_prec { 31 | // RFC 791 32 | IP_TOS_PREC_ROUTINE = 0, // 0b000 33 | IP_TOS_PREC_PRIORITY = 1, // 0b001 34 | IP_TOS_PREC_IMMEDIATE = 2, // 0b010 35 | IP_TOS_PREC_FLASH = 3, // 0b011 36 | IP_TOS_PREC_FLASH_OVERRIDE = 4, // 0b100 37 | IP_TOS_PREC_CRITIC_ECP = 5, // 0b101 38 | IP_TOS_PREC_INTERNETWORK_CONTROL = 6, // 0b110 39 | IP_TOS_PREC_NETWORK_CONTROL = 7, // 0b111 40 | } ip_tos_prec_t; 41 | _Pragma ("pack(pop)") 42 | 43 | // ECN Operations definitions 44 | // (NOT backward-compatible with the old ToS field.) 45 | _Pragma ("pack(push)") 46 | typedef enum __attribute__((packed)) ip_ecn_code { 47 | // RFC 3168 48 | IP_ECN_NOT_ECT = 0, // 0b00: Not ECN-Capable Transport 49 | // RFC 8311 / RFC Errata 5399 / RFC 9331 50 | IP_ECN_ECT_1 = 1, // 0b01: ECN-Capable Transport 1 (experimental) 51 | // RFC 3168 52 | IP_ECN_ECT_0 = 2, // 0b10: ECN-Capable Transport 0 53 | IP_ECN_CE = 3, // 0b11: Congestion Experienced (CE) 54 | } ip_ecn_code_t; 55 | _Pragma ("pack(pop)") 56 | 57 | // DSCP definitions / Per-Hop Behaviors 58 | // (somewhat backward-compatible with the old ToS precedence bits.) 59 | // iana.org/assignments/dscp-registry/dscp-registry.xhtml 60 | _Pragma ("pack(push)") 61 | typedef enum __attribute__((packed)) ip_dscp_code { 62 | /* DSCP Pool 1 Codepoints */ 63 | // RFC 2474 (Class Selector PHBs) 64 | IP_DSCP_DF = 0, // Default Forwarding (DF) PHB 65 | IP_DSCP_CS0 = 0, // CS 0 (standard) 66 | IP_DSCP_CS1 = 8, // CS 1 (low-priority data) 67 | IP_DSCP_CS2 = 16, // CS 2 (network operations/OAM) 68 | IP_DSCP_CS3 = 24, // CS 3 (broadcast video)) 69 | IP_DSCP_CS4 = 32, // CS 4 (real-time interactive) 70 | IP_DSCP_CS5 = 40, // CS 5 (signaling) 71 | IP_DSCP_CS6 = 48, // CS 6 (network control) 72 | IP_DSCP_CS7 = 56, // CS 7 (reserved) 73 | // RFC 2597 (Assured Forwarding [AF] PHB) 74 | IP_DSCP_AF11 = 10, // AF 11 (high-throughput) 75 | IP_DSCP_AF12 = 12, // AF 12 (high-throughput) 76 | IP_DSCP_AF13 = 14, // AF 13 (high-throughput) 77 | IP_DSCP_AF21 = 18, // AF 21 (low-latency) 78 | IP_DSCP_AF22 = 20, // AF 22 (low-latency) 79 | IP_DSCP_AF23 = 22, // AF 23 (low-latency) 80 | IP_DSCP_AF31 = 26, // AF 31 (multimedia stream) 81 | IP_DSCP_AF32 = 28, // AF 32 (multimedia stream) 82 | IP_DSCP_AF33 = 30, // AF 33 (multimedia stream) 83 | IP_DSCP_AF41 = 34, // AF 41 (multimedia conference) 84 | IP_DSCP_AF42 = 36, // AF 42 (multimedia conference) 85 | IP_DSCP_AF43 = 38, // AF 43 (multimedia conference) 86 | // RFC 3246 (Expedited Forwarding [EF] PHB) 87 | IP_DSCP_EF = 46, // EF (telephony) 88 | // RFC 5865 (Voice-Admit) 89 | IP_DSCP_VA = 44, // Voice-Admit 90 | /* DSCP Pool 2 Codepoints */ 91 | // "Reserved for Experimental and Local Use" (empty) 92 | /* DSCP Pool 3 Codepoints */ 93 | // RFC 8622 94 | IP_DSCP_LE = 1, // Lower-Effort PHB 95 | } ip_dscp_code_t; 96 | _Pragma ("pack(pop)") 97 | 98 | // The "Type of Service" field is largely unused (or ignored) nowadays. 99 | // It went through many changes, which makes it confusing to see how it 100 | // maps out to values. I included the original (now deprecated) ToS 101 | // field with its expanded bits as well as the "modern" DSCP + ECN. 102 | union ip_tos_view { 103 | uint8_t bitfield; 104 | // RFC 791 and RFC 1349 (deprecated) 105 | struct { // ToS 106 | #if defined(__LITTLE_ENDIAN__) 107 | bool mbz_bit : 1; // "Must-be-Zero" bit 108 | bool low_cost : 1; // RFC 1349 109 | bool high_reliability : 1; 110 | bool high_throughput : 1; 111 | bool low_delay : 1; 112 | ip_tos_prec_t precedence : 3; 113 | #elif defined(__BIG_ENDIAN__) 114 | ip_tos_prec_t precedence : 3; 115 | bool low_delay : 1; 116 | bool high_throughput : 1; 117 | bool high_reliability : 1; 118 | bool low_cost : 1; 119 | bool mbz_bit : 1; 120 | #endif 121 | }; 122 | }; 123 | 124 | // IP flag definitions 125 | _Pragma ("pack(push)") 126 | typedef enum __attribute__((packed)) ip_flag { 127 | IP_FLAG_EV = 1 << 2, // 0b100: Reserved bit (RFC 3514 "evil bit") 128 | IP_FLAG_DF = 1 << 1, // 0b010: Don't Fragment 129 | IP_FLAG_MF = 1 << 0, // 0b001: More Fragments 130 | } ip_flag_t; 131 | _Pragma ("pack(pop)") 132 | 133 | // Cannot nest bitfields and pack them externally; read the top note. 134 | // 135 | // Basically, because the fragment offset (fragofs) and flags field 136 | // in an IPv4 packet are packed in a weird way (13 + 3 bits = 16), 137 | // C compilers packs those 3 bits (if they are defined inside their 138 | // own struct) into a full 8-bit byte, meaning that it becomes 13 + 8 139 | // = 21 bits. To fix that, I had to copy-paste this otherwise-neat 140 | // union inside the ip_hdr struct and also add some hacky padding 141 | // ("uint16_t __fragofs_bug : 13;") to work around this issue. 142 | union ip_flag_view { 143 | // View no. 1 (as an entire bitfield) 144 | ip_flag_t bitfield : 3; 145 | // View no. 2 (with expanded flag bits) 146 | struct { 147 | #if defined(__LITTLE_ENDIAN__) 148 | bool mf : 1; // More Fragments 149 | bool df : 1; // Don't Fragment 150 | bool ev : 1; // Evil/reserved bit 151 | #elif defined(__BIG_ENDIAN__) 152 | bool ev : 1; 153 | bool df : 1; 154 | bool mf : 1; 155 | #endif 156 | }; 157 | }; 158 | 159 | 160 | // 0 1 2 3 161 | // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 162 | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 163 | // |Version| IHL | DSCP |ECN| Total Length | 164 | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 165 | // | Identification |Flags| Fragment Offset | 166 | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 167 | // | Time to Live | Protocol | Header Checksum | 168 | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 169 | // | Source Address | 170 | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 171 | // | Destination Address | 172 | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 173 | // | Options | Padding | 174 | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 175 | typedef struct ip_hdr { 176 | #if defined(__LITTLE_ENDIAN__) 177 | uint8_t ihl : 4; // Internet Header Length 178 | uint8_t ver : 4; // IP Version 179 | #elif defined(__BIG_ENDIAN__) 180 | uint8_t ver : 4; 181 | uint8_t ihl : 4; 182 | #endif 183 | union { 184 | // RFC 791 and RFC 1349 185 | union ip_tos_view tos; // Type of Service (ToS) 186 | // RFC 2474 (DSCP + ECN) 187 | struct { 188 | #if defined(__LITTLE_ENDIAN__) 189 | ip_ecn_code_t ecn : 2; // Explicit Congestion Notif 190 | ip_dscp_code_t dscp : 6; // Differentiated Services 191 | #elif defined(__BIG_ENDIAN__) 192 | ip_dscp_code_t dscp : 6; 193 | ip_ecn_code_t ecn : 2; 194 | #endif 195 | }; 196 | }; 197 | uint16_t len; // Total Length 198 | uint16_t id; // Identification 199 | #if defined(__LITTLE_ENDIAN__) 200 | union { 201 | struct { 202 | uint16_t fragofs : 13; // Fragment Offset 203 | //union ip_flag_view flags; // "Would-be" flags 204 | ip_flag_t flag_bits : 3; // Workaround flag bitfield 205 | }; 206 | struct { 207 | uint16_t __struct_bug__ : 13; // [Read ip_flag_view note] (*) 208 | bool mf : 1; // More Fragments 209 | bool df : 1; // Don't Fragment 210 | bool ev : 1; // Evil/reserved bit 211 | } flags; 212 | }; 213 | #elif defined(__BIG_ENDIAN__) 214 | union { 215 | struct { 216 | ip_flag_t flag_bits : 3; 217 | //union ip_flag_view flags; 218 | uint16_t fragofs : 13; 219 | }; 220 | struct { 221 | bool mf : 1; 222 | bool df : 1; 223 | bool ev : 1; 224 | uint16_t __struct_bug__ : 13; // [Read ip_flag_view note] (*) 225 | } flags; 226 | }; 227 | #endif 228 | uint8_t ttl; // Time to live 229 | ip_proto_t proto : 8; // Protocol 230 | uint16_t chksum; // Header Checksum 231 | ip_addr_t saddr; // Source Address 232 | ip_addr_t daddr; // Destination Address 233 | uint32_t options[]; // IP Options (0-320 bits) 234 | } ip_hdr_t; 235 | // TODO: Make a struct for IP options 236 | _Static_assert(sizeof (ip_hdr_t) == 20, 237 | "An empty ip_hdr struct should only be 20 bytes!"); 238 | 239 | 240 | 241 | #endif // IP_H 242 | 243 | // --------------------------------------------------------------------- 244 | // END OF FILE: ip.h 245 | // --------------------------------------------------------------------- 246 | -------------------------------------------------------------------------------- /src/netlib/protos/ip6.h: -------------------------------------------------------------------------------- 1 | // --------------------------------------------------------------------- 2 | // SPDX-License-Identifier: GPL-3.0-or-later 3 | // ip6.h is a part of Blitzping. 4 | // --------------------------------------------------------------------- 5 | 6 | _Pragma ("once") 7 | #ifndef IP6_H 8 | #define IP6_H 9 | 10 | 11 | 12 | 13 | 14 | #endif // IP6_H 15 | 16 | // --------------------------------------------------------------------- 17 | // END OF FILE: ip6.h 18 | // --------------------------------------------------------------------- 19 | -------------------------------------------------------------------------------- /src/netlib/protos/tcp.h: -------------------------------------------------------------------------------- 1 | // --------------------------------------------------------------------- 2 | // SPDX-License-Identifier: GPL-3.0-or-later 3 | // tcp.h is a part of Blitzping. 4 | // --------------------------------------------------------------------- 5 | 6 | _Pragma ("once") 7 | #ifndef TCP_H 8 | #define TCP_H 9 | 10 | 11 | // TCP flag definitions 12 | _Pragma ("pack(push)") 13 | typedef enum __attribute__((packed)) tcp_flag { 14 | TCP_FLAG_FIN = 1 << 0, // 0b00000001: Finish 15 | TCP_FLAG_SYN = 1 << 1, // 0b00000010: Synchronize 16 | TCP_FLAG_RST = 1 << 2, // 0b00000100: Reset 17 | TCP_FLAG_PSH = 1 << 3, // 0b00001000: Push 18 | TCP_FLAG_ACK = 1 << 4, // 0b00010000: Acknowledgment 19 | TCP_FLAG_URG = 1 << 5, // 0b00100000: Urgent 20 | TCP_FLAG_ECE = 1 << 6, // 0b01000000: ECN-Echo 21 | TCP_FLAG_CWR = 1 << 7, // 0b10000000: Congestion Window Reduced 22 | } tcp_flag_t; 23 | _Pragma ("pack(pop)") 24 | 25 | union tcp_flag_view { 26 | // View no. 1 (as an entire byte) 27 | tcp_flag_t bitfield : 8; 28 | // View no. 2 (with expanded flag bits) 29 | struct { 30 | #if defined(__LITTLE_ENDIAN__) 31 | bool fin : 1; // Finish 32 | bool syn : 1; // Synchronize 33 | bool rst : 1; // Reset 34 | bool psh : 1; // Push 35 | bool ack : 1; // Acknowledgment 36 | bool urg : 1; // Urgent 37 | bool ece : 1; // ECN-Echo (RFC 3168) 38 | bool cwr : 1; // Congestion Window Reduced (RFC 3168) 39 | #elif defined(__BIG_ENDIAN__) 40 | bool cwr : 1; 41 | bool ece : 1; 42 | bool urg : 1; 43 | bool ack : 1; 44 | bool psh : 1; 45 | bool rst : 1; 46 | bool syn : 1; 47 | bool fin : 1; 48 | #endif 49 | }; 50 | }; 51 | 52 | // TCP options definitions 53 | // iana.org/assignments/tcp-parameters/tcp-parameters.xhtml 54 | // NOTE: [*] indicates that the option is considered "obsolete." 55 | _Pragma ("pack(push)") 56 | typedef enum __attribute__((packed)) tcp_option_kind { 57 | // RFC 9293 58 | TCP_OPT_KIND_EOL = 0, // End of Option List 59 | TCP_OPT_KIND_NOP = 1, // No-Operation 60 | TCP_OPT_KIND_MSS = 2, // Maximum Segment Size 61 | // RFC 7323 62 | TCP_OPT_KIND_WS = 3, // Window Scale 63 | // RFC 2018 64 | TCP_OPT_KIND_SACK_PERM = 4, // SACK Permitted 65 | TCP_OPT_KIND_SACK = 5, // SACK Block 66 | // RFC 1072 & RFC 6247 67 | TCP_OPT_KIND_ECHO = 6, // [*] Echo (8) 68 | TCP_OPT_KIND_ECHO_REPLY = 7, // [*] Echo-Reply (8) 69 | // RFC 7323 70 | TCP_OPT_KIND_TIMESTAMP = 8, // Timestamps 71 | // RFC 1693 & RFC 6247 72 | TCP_OPT_KIND_PARTIAL_PERM = 9, // [*] Part Order Connect Perm. 73 | TCP_OPT_KIND_PARTIAL_PROF = 10, // [*] Part Order Serve Profile 74 | TCP_OPT_KIND_CC = 11, // [*] Connection Count 75 | TCP_OPT_KIND_CC_NEW = 12, // [*] Connection Count New 76 | TCP_OPT_KIND_CC_ECHO = 13, // [*] Connection Count Echo 77 | TCP_OPT_KIND_ALT_CHK_REQ = 14, // [*] Alternative Chksum Req. 78 | TCP_OPT_KIND_ALT_CHK_DAT = 15, // [*] Alternative Chksum Data 79 | // "Stev Knowles" 80 | TCP_OPT_KIND_SKEETER = 16, // Skeeter (???) 81 | TCP_OPT_KIND_BUBBA = 17, // Bubba (???) 82 | // "Subbu Subramaniam" & "Monroe Bridges" 83 | TCP_OPT_KIND_TRAILER_CHK = 18, // Trailer Checksum Option 84 | // RFC 2385 85 | TCP_OPT_KIND_MD5_SIG = 19, // [*] MD5 Signature (29) 86 | // "Keith Scott" 87 | TCP_OPT_KIND_SCPS_CAPABLE = 20, // SCPS Capabilities 88 | TCP_OPT_KIND_SEL_NEG_ACK = 21, // Selective Negative Ack. 89 | TCP_OPT_KIND_RECORD_BOUNDS = 22, // Record Boundaries 90 | TCP_OPT_KIND_CORRUPT_EXP = 23, // Corruption Experienced 91 | TCP_OPT_KIND_SNAP = 24, // SNAP (???) 92 | // -blank- 93 | TCP_OPT_KIND_UNASSIGNED25 = 25, // Unassigned (12/28/2000) 94 | // "Steve Bellovin" 95 | TCP_OPT_KIND_COMPRESS_FILT = 26, // Compression Filter 96 | // RFC 4782 97 | TCP_OPT_KIND_QUICK_START = 27, // Quick-Start Response 98 | // RFC 5482 99 | TCP_OPT_KIND_USER_TIMEOUT = 28, // User Timeout (other uses) 100 | // RFC 5925 101 | TCP_OPT_KIND_AUTH_OPT = 29, // Authentication (TCP-AO) 102 | // RFC 8684 103 | TCP_OPT_KIND_MULTIPATH = 30, // Multipath TCP (MPTCP) 104 | // [31-33] RESERVED 105 | // RFC 7413 106 | TCP_OPT_KIND_FAST_OPEN_COOK = 34, // Fast Open Cookie 107 | // [35-68] RESERVED 108 | // RFC 8547 109 | TCP_OPT_KIND_ENCRYPT_NEGOT = 69, // Encryption Negotiatio 110 | // [70-171] RESERVED 111 | TCP_OPT_KIND_ACC_ECN_ORD0 = 172, // Accurate ECN Order 0 112 | // [173] RESERVED 113 | TCP_OPT_KIND_ACC_ECN_ORD1 = 174, // Accurate ECN Order 1 114 | // [175-252] RESERVED 115 | TCP_OPT_KIND_RFC3692_EXP1 = 253, // RFC 3692 Experiment 1 116 | TCP_OPT_KIND_RFC3692_EXP2 = 254, // RFC 3692 Experiment 2 117 | } tcp_option_kind_t; 118 | _Pragma ("pack(pop)") 119 | 120 | // 0 1 2 3 121 | // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 122 | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 123 | // | Source Port | Destination Port | 124 | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 125 | // | Sequence Number | 126 | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 127 | // | Acknowledgment Number | 128 | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 129 | // | Data | |C|E|U|A|P|R|S|F| | 130 | // | Offset| Rsrvd |W|C|R|C|S|S|Y|I| Window | 131 | // | | |R|E|G|K|H|T|N|N| | 132 | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 133 | // | Checksum | Urgent Pointer | 134 | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 135 | // | [Options] | 136 | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 137 | // | : 138 | // : Data : 139 | // : | 140 | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 141 | typedef struct tcp_hdr { 142 | uint16_t sport; // Source port number 143 | uint16_t dport; // Destination port number 144 | uint32_t seqnum; // Sequence number 145 | uint32_t acknum; // Acknowledgement number 146 | #if defined(__LITTLE_ENDIAN__) 147 | uint8_t reserved : 4; // Reserved (unused) bits 148 | uint8_t dataofs : 4; // Offset to data/options 149 | #elif defined(__BIG_ENDIAN__) 150 | uint8_t dataofs : 4; // Offset to data/options 151 | uint8_t reserved : 4; // Reserved (unused) bits 152 | #endif 153 | union tcp_flag_view flags; // TCP flags 154 | uint16_t window; // Window size 155 | uint16_t chksum; // Checksum 156 | uint16_t urgptr; // Pointer to urgent data 157 | uint32_t options[]; // TCP Options (0-320 bits) 158 | } tcp_hdr_t; 159 | // TODO: Make options a struct 160 | _Static_assert(sizeof (tcp_hdr_t) == 20, 161 | "An empty tcp_hdr struct should only be 20 bytes!"); 162 | 163 | 164 | #endif // TCP_H 165 | 166 | // --------------------------------------------------------------------- 167 | // END OF FILE: tcp.h 168 | // --------------------------------------------------------------------- 169 | -------------------------------------------------------------------------------- /src/netlib/protos/udp.h: -------------------------------------------------------------------------------- 1 | // --------------------------------------------------------------------- 2 | // SPDX-License-Identifier: GPL-3.0-or-later 3 | // udp.h is a part of Blitzping. 4 | // --------------------------------------------------------------------- 5 | 6 | _Pragma ("once") 7 | #ifndef UDP_H 8 | #define UDP_H 9 | 10 | 11 | 12 | 13 | 14 | #endif // UDP_H 15 | 16 | // --------------------------------------------------------------------- 17 | // END OF FILE: udp.h 18 | // --------------------------------------------------------------------- 19 | -------------------------------------------------------------------------------- /src/packet.c: -------------------------------------------------------------------------------- 1 | // --------------------------------------------------------------------- 2 | // SPDX-License-Identifier: GPL-3.0-or-later 3 | // packet.c is a part of Blitzping. 4 | // --------------------------------------------------------------------- 5 | 6 | 7 | #include "packet.h" 8 | 9 | /* WORK IN-PROGRESS */ 10 | 11 | 12 | 13 | // TODO: Split the packet crafting logic to another function. 14 | // Thread callback 15 | static int send_loop(void *arg) { 16 | const struct ProgramArgs *const program_args = 17 | (const struct ProgramArgs *const)arg; 18 | 19 | // Initialize the seed for random number generation. 20 | // TODO: make this a program parameter 21 | srand(time(0)); 22 | 23 | // Initialize an empty packet buffer on the stack and align it 24 | // for potentially faster access from memory. 25 | // TODO: malloc() this buffer instead? 26 | _Alignas (_Alignof (max_align_t)) uint8_t 27 | packet_buffer[IP_PKT_MTU] = {0}; 28 | 29 | 30 | // Make the IP and TCP header structures "point" to their 31 | // respective locations in the aforementioned buffer 32 | struct ip_hdr *ip_header = 33 | (struct ip_hdr *)packet_buffer; 34 | struct tcp_hdr *tcp_header = 35 | (struct tcp_hdr *)(packet_buffer + sizeof (struct ip_hdr)); 36 | 37 | 38 | *ip_header = *(program_args->ipv4); 39 | 40 | // TODO: parametrize 41 | *tcp_header = (struct tcp_hdr){ 42 | .sport = htons(rand() % 65536), 43 | .dport = htons(80), 44 | .seqnum = rand(), 45 | .flags.syn = true 46 | }; 47 | 48 | 49 | // if override_source 50 | uint32_t ip_diff = 0; 51 | // If CIDR 52 | //uint32_t ip_diff = program_args->src_ip_end.address 53 | // - program_args->src_ip_start.address + 1; 54 | 55 | // Set the default destination address 56 | struct sockaddr_in dest_info = { 57 | .sin_family = AF_INET, 58 | .sin_port = ntohs(tcp_header->dport), 59 | .sin_addr.s_addr = ntohl(ip_header->daddr.address) 60 | }; 61 | 62 | // NOTE: Instead of using sento() or sendmmsg(), both of which 63 | // require a "destination info" struct, you can pre-bind your 64 | // socket to a fixed destination by using connect() accompanied 65 | // by write() or writev(). However, if you do want to change 66 | // your destination with every call, then it might be better 67 | // to use the former functions, because they'd be handling 68 | // this binding inside kernelspace, bypassing what would 69 | // otherwise be an extraneous overhead to a separate connect(). 70 | int connection_status = connect( 71 | program_args->socket, 72 | (struct sockaddr *)&dest_info, 73 | sizeof(dest_info) 74 | ); 75 | 76 | if (connection_status != 0) { 77 | logger(LOG_ERROR, 78 | "Failed to bind socket to the destination address: %s", 79 | strerror(errno) 80 | ); 81 | return 1; 82 | } 83 | 84 | size_t packet_length = ntohs(ip_header->len); 85 | 86 | 87 | //int num_threads = 4; // number of threads 88 | 89 | //int X = UIO_MAXIOV / (packet_length * num_threads); 90 | 91 | // NOTE: The addresses in this array of buffers all point 92 | // to the same packet buffer. This might seem wasteful at 93 | // first, but a benefit is that the "for-loop" part of this 94 | // iteration will now be able to exist in kernelspace, 95 | // bypassing expensive syscalls. 96 | // TODO: Maybe pre-craft the changing parts of multiple packeets, 97 | // as to "queue" them for sending? 98 | _Alignas (_Alignof (max_align_t)) struct iovec iov[UIO_MAXIOV]; 99 | for (int i = 0; i < 37; i++) { 100 | iov[i].iov_base = packet_buffer; 101 | iov[i].iov_len = packet_length; 102 | } 103 | // Compiler optimizations likely override this anyhow 104 | if (!program_args->advanced.no_cpu_prefetch) { 105 | PREFETCH(packet_buffer, 1, 3); 106 | PREFETCH(iov, 0, 3); 107 | } 108 | 109 | uint32_t next_ip; 110 | uint16_t next_port; 111 | ssize_t bytes_written; 112 | 113 | struct pollfd pfd; 114 | pfd.fd = program_args->socket; 115 | pfd.events = POLLOUT; 116 | 117 | for (;;) { 118 | // Randomize source IP and port for the next packet 119 | next_ip = htonl( 120 | program_args->ipv4->saddr.address 121 | + (rand() % ip_diff) 122 | ); 123 | next_port = htons(rand() % 65536); 124 | 125 | bytes_written = writev(program_args->socket, iov, 37); 126 | 127 | if (bytes_written == -1) { 128 | if (errno == EAGAIN || errno == EWOULDBLOCK) { 129 | // The socket is non-blocking and the write would block. 130 | if (poll(&pfd, 1, -1) == -1) { 131 | logger(LOG_ERROR, 132 | "Failed to poll the socket: %s", 133 | strerror(errno) 134 | ); 135 | break; 136 | } 137 | } 138 | else { 139 | logger(LOG_ERROR, 140 | "Failed to write packet to the socket: %s", 141 | strerror(errno) 142 | ); 143 | break; 144 | } 145 | } 146 | else if (bytes_written < (ssize_t)(packet_length * 37)) { 147 | logger(LOG_WARN, 148 | "Not all data was written; %ld bytes remain;\n" 149 | "try to lower the buffer size passed to writev().", 150 | (packet_length * 37) - bytes_written 151 | ); 152 | } 153 | 154 | // Now that the socket is ready, update the source IP and port 155 | ip_header->saddr.address = next_ip; 156 | tcp_header->sport = next_port; 157 | } 158 | 159 | 160 | // For maximal performance, do the bare-minimum processing in this 161 | // loop. As of now, the Kernel syscall is the bottleneck. 162 | /*for (;;) { 163 | // Randomize source IP and port 164 | ip_header->saddr.address = htonl( 165 | program_args->src_ip_start.address 166 | + (rand() % ip_diff) 167 | ); 168 | tcp_header->sport = htons(rand() % 65536); 169 | 170 | //sendmsg(program_args->socket, &msg, 0); 171 | //write(program_args->socket, packet_buffer, packet_length); 172 | writev(program_args->socket, iov, 37); 173 | //ssize_t bytes_written = writev(program_args->socket, iov, 37); 174 | //if (bytes_written == -1) { 175 | // perror("writev failed"); 176 | //} 177 | }*/ 178 | 179 | #if __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_THREADS__) 180 | return thrd_success; 181 | #else 182 | return 0; 183 | #endif 184 | } 185 | 186 | 187 | 188 | // TODO: Use xorshift 189 | // TODO: check for POSIX_MEMLOCK 190 | int send_packets(struct ProgramArgs *const program_args) { 191 | 192 | if (!program_args->advanced.no_mem_lock) { 193 | if (mlockall(MCL_FUTURE) == -1) { 194 | logger(LOG_ERROR, 195 | "Failed to lock memory: %s", strerror(errno) 196 | ); 197 | return 1; 198 | } 199 | else { 200 | logger(LOG_INFO, "Locked memory."); 201 | } 202 | } 203 | 204 | // TODO: See if this is required for a raw sendto()? 205 | /* 206 | struct sockaddr_in dest_info; 207 | dest_info.sin_family = AF_INET; 208 | dest_info.sin_port = tcp_header->dport; 209 | dest_info.sin_addr.s_addr = ip_header->daddr.address; 210 | size_t packet_length = ntohs(ip_header->len); 211 | struct sockaddr *dest_addr = (struct sockaddr *)&dest_info; 212 | size_t addr_len = sizeof (dest_info); 213 | */ 214 | 215 | /*struct msghdr msg = { 216 | .msg_name = &(struct sockaddr_in){ 217 | .sin_family = AF_INET, 218 | .sin_port = tcp_header->dport, 219 | .sin_addr.s_addr = ip_header->daddr.address 220 | }, 221 | .msg_namelen = sizeof (struct sockaddr_in), 222 | .msg_iov = (struct iovec[1]){ 223 | { 224 | .iov_base = packet_buffer, 225 | .iov_len = ntohs(ip_header->len) 226 | } 227 | }, 228 | .msg_iovlen = 1 229 | };*/ 230 | 231 | /* 232 | printf("Packet:\n"); 233 | printf("Source IP: %s\n", inet_ntoa(*(struct in_addr*)&ip_header->saddr.address)); 234 | printf("Destination IP: %s\n", inet_ntoa(*(struct in_addr*)&ip_header->daddr.address)); 235 | printf("Source Port: %d\n", ntohs(tcp_header->sport)); 236 | printf("Destination Port: %d\n", ntohs(tcp_header->dport)); 237 | printf("TTL: %d\n", ip_header->ttl); 238 | printf("Header Length: %d\n", ip_header->ihl * 4); // ihl is in 32-bit words 239 | printf("Total Length: %d\n", ntohs(ip_header->len)); 240 | printf("SYN Flag: %s\n", tcp_header->flags.syn ? "Set" : "Not set"); 241 | printf("\n"); 242 | */ 243 | 244 | 245 | 246 | unsigned int num_threads = program_args->advanced.num_threads; 247 | 248 | // TODO: Use dlsym to check for thrds at RUNTIME. 249 | if (num_threads == 0) { // Run in main thread. 250 | send_loop(program_args); 251 | } 252 | else { // Multi-threaded 253 | #if __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_THREADS__) 254 | //thrd_t *threads = 255 | // malloc(args.num_threads * sizeof (thrd_t)); 256 | thrd_t threads[MAX_THREADS]; 257 | 258 | for (unsigned int i = 0; i < num_threads; i++) { 259 | int thread_status = thrd_create( 260 | &threads[i], send_loop, program_args 261 | ); 262 | 263 | if (thread_status != thrd_success) { 264 | logger(LOG_ERROR, "Failed to spawn thread %d.", i); 265 | // Cleanup already-created threads 266 | for (unsigned int j = 0; j < i; j++) { 267 | thrd_join(threads[j], NULL); 268 | } 269 | //free(threads); 270 | return 1; 271 | } 272 | } 273 | 274 | // TODO: This is never reached; add a signal handler? 275 | for (unsigned int i = 0; i < num_threads; i++) { 276 | thrd_join(threads[i], NULL); 277 | } 278 | #else 279 | return 1; 280 | #endif 281 | } 282 | 283 | 284 | 285 | 286 | if (!program_args->advanced.no_mem_lock) { 287 | if (munlockall() == -1) { 288 | logger(LOG_ERROR, 289 | "Failed to unlock used memory: %s", strerror(errno) 290 | ); 291 | return 1; 292 | } 293 | else { 294 | logger(LOG_INFO, "Unlocked used memory."); 295 | } 296 | } 297 | 298 | return 0; 299 | } 300 | 301 | 302 | // --------------------------------------------------------------------- 303 | // END OF FILE: packet.c 304 | // --------------------------------------------------------------------- 305 | -------------------------------------------------------------------------------- /src/packet.h: -------------------------------------------------------------------------------- 1 | // --------------------------------------------------------------------- 2 | // SPDX-License-Identifier: GPL-3.0-or-later 3 | // packet.h is a part of Blitzping. 4 | // --------------------------------------------------------------------- 5 | 6 | #pragma once 7 | #ifndef PACKET_H 8 | #define PACKET_H 9 | 10 | 11 | #include "./utils/intrins.h" 12 | #include "./netlib/netinet.h" 13 | #include "./cmdline/parser.h" 14 | 15 | #include 16 | #if __STDC_VERSION__ >= 201112L 17 | # include 18 | #else 19 | typedef union { 20 | long long int __long_long_int; 21 | long double __long_double; 22 | void *__void_ptr; 23 | } max_align_t; 24 | #endif 25 | #include 26 | 27 | #include 28 | #include 29 | 30 | #include 31 | #include 32 | // C11 threads (glibc >=2.28, musl >=1.1.5, Windows SDK >~10.0.22620) 33 | #if __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_THREADS__) 34 | # include 35 | #endif 36 | 37 | #if defined(_POSIX_C_SOURCE) 38 | # include 39 | # include 40 | # if defined(_POSIX_THREADS) && _POSIX_THREADS >= 0 41 | # include 42 | # endif 43 | # include 44 | # include 45 | # include 46 | # include 47 | #elif defined(_WIN32) 48 | //#include 49 | #endif 50 | 51 | extern int errno; // Declared in 52 | 53 | #define IP_PKT_MTU 1500 // Same as Ethernet II MTU (bytes) 54 | #define MAX_THREADS 100 // Arbitrary limit (TODO: Remove?) 55 | 56 | 57 | // Thread callback 58 | int send_packets(struct ProgramArgs *const program_args); 59 | 60 | 61 | #endif // PACKET_H 62 | 63 | // --------------------------------------------------------------------- 64 | // END OF FILE: packet.h 65 | // --------------------------------------------------------------------- 66 | -------------------------------------------------------------------------------- /src/program.h: -------------------------------------------------------------------------------- 1 | // --------------------------------------------------------------------- 2 | // SPDX-License-Identifier: GPL-3.0-or-later 3 | // program.h is a part of Blitzping. 4 | // --------------------------------------------------------------------- 5 | 6 | #pragma once 7 | #ifndef PROGRAM_H 8 | #define PROGRAM_H 9 | 10 | 11 | #include "./netlib/netinet.h" 12 | #include "./cmdline/logger.h" 13 | #include "./utils/endian.h" 14 | 15 | #include 16 | #include 17 | 18 | 19 | // It is better to contain everything within a single struct, as 20 | // opposed to having a bunch of global variables all over the place. 21 | // 22 | // NOTE: I did not use bitfields here because they are not 23 | // going to help with compile-time safety, and they'd also 24 | // come with a performance cost and lack of addressability. 25 | typedef struct ProgramArgs { 26 | int socket; // Socket descriptor 27 | // Parser Internals 28 | struct { 29 | osi_layer_t current_layer; 30 | osi_proto_t current_proto; 31 | } parser; 32 | // System Diagnostics 33 | struct { 34 | char *executable_name; // argv[0] 35 | bool unrecoverable_error; 36 | struct { 37 | endianness_t endianness; 38 | } compile; 39 | struct { 40 | endianness_t endianness; 41 | unsigned int num_cores; 42 | bool c11_threads; 43 | bool posix_threads; 44 | } runtime; 45 | } diagnostics; 46 | // General 47 | struct { 48 | bool opt_info; 49 | log_level_t logger_level; 50 | } general; 51 | // Advanced 52 | struct { 53 | bool bypass_checks; 54 | bool no_log_timestamp; 55 | unsigned int num_threads; 56 | bool native_threads; 57 | unsigned int buffer_size; 58 | bool no_async_sock; 59 | bool no_mem_lock; 60 | bool no_cpu_prefetch; 61 | } advanced; 62 | // IPv4 63 | struct ip_hdr *ipv4; 64 | struct { 65 | bool is_cidr; 66 | struct { 67 | ip_addr_t start; 68 | ip_addr_t end; 69 | } source_cidr; 70 | bool override_checksum; 71 | bool override_source; 72 | bool override_length; 73 | } ipv4_misc; 74 | // TODO: IPv6 75 | // TCP 76 | struct tcp_hdr *tcp; 77 | // TODO: UDP 78 | // TODO: ICMP 79 | } program_args_t; 80 | 81 | 82 | #endif // PROGRAM_H 83 | 84 | // --------------------------------------------------------------------- 85 | // END OF FILE: program.h 86 | // --------------------------------------------------------------------- 87 | -------------------------------------------------------------------------------- /src/socket.c: -------------------------------------------------------------------------------- 1 | // --------------------------------------------------------------------- 2 | // SPDX-License-Identifier: GPL-3.0-or-later 3 | // socket.c is a part of Blitzping. 4 | // --------------------------------------------------------------------- 5 | 6 | 7 | #include "socket.h" 8 | 9 | 10 | #if defined(_POSIX_C_SOURCE) 11 | 12 | // NOTE: Document somewhere that raw sockets would require 13 | // enabling the "Mirrored" networking mode for WSL2. 14 | int setup_posix_socket(const bool is_raw, const bool is_async) { 15 | // Setting the 'errno' flag to 0 indicates "no errors" so 16 | // that a previously set value does not affect us. 17 | errno = 0; 18 | 19 | int sock_opts = 0; 20 | sock_opts |= is_raw ? SOCK_RAW : SOCK_STREAM; 21 | 22 | // Attempt to create the specified socket. 23 | // https://stackoverflow.com/questions/49309029 24 | // TODO: Kernel fills-in IPs whenever they are zero'ed; find 25 | // a way to actually let the 0 pass unchanged. 26 | // TODO: see if pf_packet + bind() is faster 27 | // TODO: MSG_DONTROUTE? 28 | // TODO: MSG_OOB and out-of-bound? 29 | int socket_descriptor = socket( 30 | AF_INET, // Domain 31 | sock_opts, // Type (+ options) 32 | IPPROTO_RAW // Protocol (implies IP_HDRINCL) 33 | ); 34 | 35 | if (socket_descriptor == -1) { 36 | // Socket creation failed (maybe non-root privileges?) 37 | logger(LOG_CRIT, 38 | "Failed to create POSIX socket: %s", strerror(errno)); 39 | return -1; 40 | } 41 | 42 | // NOTE: This, under Linux, would have been a one-liner: 43 | // sock_opts |= is_async ? SOCK_NONBLOCK : 0; 44 | // Unfortunately, that is a Linux-only and non-POSIX-compliant way; 45 | // POSIX 2001 requires using O_NONBLOCK with fcntl() instead. 46 | if (is_async) { 47 | // Get the current flags for the socket 48 | int flags = fcntl(socket_descriptor, F_GETFL, 0); 49 | if (flags == -1) { 50 | logger(LOG_ERROR, 51 | "Failed to get socket flags: %s", strerror(errno)); 52 | return -1; 53 | } 54 | 55 | flags |= O_NONBLOCK; 56 | 57 | int status = fcntl(socket_descriptor, F_SETFL, flags); 58 | if (status == -1) { 59 | logger(LOG_ERROR, 60 | "Failed to set socket to asynchronous mode: %s", 61 | strerror(errno)); 62 | return -1; 63 | } 64 | } 65 | 66 | 67 | return socket_descriptor; 68 | } 69 | 70 | # if defined(__linux__) 71 | 72 | // AF_PACKET + SOCK_RAW is the "lowest" you can go in terms of raw 73 | // sockets; they're also known as a packet-socket. However, unlike 74 | // the above function, they aren't POSIX-compliant. 75 | // The most important advantage of packet-sockets is that they 76 | // let you memory-map (mmap) them using shared ring buffers, bypassing 77 | // most kernel layers and removing some of the overhead of syscalls: 78 | // https://stackoverflow.com/questions/49309029 79 | // https://docs.kernel.org/networking/packet_mmap.html 80 | // https://blog.cloudflare.com/kernel-bypass/ 81 | // https://stackoverflow.com/questions/4873956/ 82 | int setup_mmap_socket(const char *const interface_name) { 83 | // NOTE: A protocol of 0 means we only want to transmit packets via 84 | // this socket; this will avoid expensive syscalls to packet_rcv(). 85 | const int socket_descriptor = socket( 86 | AF_PACKET, 87 | SOCK_RAW, 88 | 0 89 | ); 90 | if (socket_descriptor == -1) { 91 | logger(LOG_CRIT, 92 | "Failed to create packet-socket: %s", strerror(errno)); 93 | return -1; 94 | } 95 | 96 | // Identifies the link-layer "address" and protocol: 97 | // https://stackoverflow.com/questions/70995951/ 98 | // TODO: On systems with multiple network interfaces, see if 99 | // passing 0 to sll_ifindex improves performance. 100 | const struct sockaddr_ll socket_address = { 101 | .sll_family = AF_PACKET, 102 | .sll_protocol = 0, 103 | .sll_ifindex = if_nametoindex(interface_name) 104 | }; 105 | if (socket_address.sll_ifindex == 0) { 106 | logger(LOG_CRIT, 107 | "Failed to get interface index: %s", strerror(errno)); 108 | return -1; 109 | } 110 | 111 | // Bind the socket 112 | const int bind_status = bind( 113 | socket_descriptor, 114 | (struct sockaddr*)&socket_address, 115 | sizeof(socket_address) 116 | ); 117 | if (bind_status == -1) { 118 | logger(LOG_ERROR, 119 | "Failed to bind the socket: %s", strerror(errno)); 120 | return -1; 121 | } 122 | 123 | // Set up the PACKET_TX_RING option 124 | // TODO: Make these configurable and also calculate maximums 125 | // https://www.kernel.org/doc/Documentation/networking/pktgen.txt 126 | // https://www.reddit.com/r/golang/comments/1bcexhp/ 127 | const struct tpacket_req ring_buffer_cfg = { 128 | .tp_block_size = 4096, 129 | .tp_block_nr = 64, 130 | .tp_frame_size = 4096, 131 | .tp_frame_nr = 64 132 | }; 133 | const int opt_status = setsockopt( 134 | socket_descriptor, 135 | SOL_PACKET, 136 | PACKET_TX_RING, 137 | &ring_buffer_cfg, 138 | sizeof(ring_buffer_cfg) 139 | ); 140 | if (opt_status == -1) { 141 | logger(LOG_ERROR, 142 | "Failed to set PACKET_TX_RING option: %s", strerror(errno)); 143 | return -1; 144 | } 145 | 146 | // Memory-map the ring buffer to user-space 147 | const void *const map = mmap( 148 | NULL, 149 | ring_buffer_cfg.tp_block_size * ring_buffer_cfg.tp_block_nr, 150 | PROT_READ | PROT_WRITE, 151 | MAP_SHARED, 152 | socket_descriptor, 153 | 0 154 | ); 155 | if (map == MAP_FAILED) { 156 | logger(LOG_ERROR, 157 | "Failed to memory-map packet-socket's ring buffer: %s", 158 | strerror(errno) 159 | ); 160 | return -1; 161 | } 162 | 163 | // TODO: PACKET_QDISC_BYPASS seems very promising (kernel 3.14+) 164 | // TODO: MSG_ZEROCOPY vs. af_packet? 165 | 166 | // The socket is now ready to use with the mapped buffer 167 | return socket_descriptor; 168 | } 169 | 170 | // TODO: Investigate AF_XDP, as it appears to have the potential to 171 | // be faster than packet-sockets, but it might also require loading 172 | // BPF objects into kernel and/or having specific models of NICs. (?) 173 | // Other than running directly on the NIC (where very few smartNICs 174 | // even support this capability), you can also hook the XDP in the 175 | // driver itself (again, without widespreads upport); finally, 176 | // you may also run the XDP in a "generic" SKB mode, which seems to 177 | // defeat its performance benefits and also prevent zero-copy'ing. 178 | // https://www.youtube.com/watch?v=hO2tlxURXJ0 179 | // https://qmonnet.github.io/whirl-offload/2016/09/01/dive-into-bpf 180 | // https://github.com/xdp-project/ 181 | // xdp-project/blob/master/areas/drivers/README.org 182 | // https://pantheon.tech/what-is-af_xdp 183 | // https://stackoverflow.com/questions/78990613/ 184 | // https://forum.suricata.io/t/ 185 | // difference-between-af-packet-mode-and-af-xdp-mode/4754 186 | // https://stackoverflow.com/questions/ 187 | // https://blog.cloudflare.com/ 188 | // a-story-about-af-xdp-network-namespaces-and-a-cookie/ 189 | // https://blog.freifunk.net/2024/05/31/gsoc-2024-ebpf- 190 | // performance-optimizations-for-a-new-openwrt-firewall/ 191 | // https://toonk.io/building-an-xdp-express-data-path- 192 | // based-bgp-peering-router/index.html 193 | // https://www.netdevconf.org/0x14/pub/slides/37/ 194 | // Adding%20AF_XDP%20zero-copy%20support%20to%20drivers.pdf 195 | // Also, it appears that AF_XDP is the "successor" to AF_PACKET v3; 196 | // AF_PACKET v4 never seems to have taken off (?): 197 | // https://lore.kernel.org/netdev/ 198 | // 95aaafdc-ef8a-c4b9-6104-a1a753c81820@intel.com/ 199 | // https://lwn.net/Articles/737947/ 200 | // https://www.netdevconf.info/2.2/slides/karlsson-afpacket-talk.pdf 201 | // https://www.youtube.com/watch?v=RSFX7z1qF2g 202 | // 203 | // Ultimately, it appears that the "fastest" method is to write our 204 | // own driver for a specific NIC, but that is obviously not portable. 205 | // (DPDK, VPP, libpcap, etc. do exactly this for a handful of NICs.) 206 | 207 | # endif /* defined(__linux__) */ 208 | 209 | #endif /* defined(_POSIX_C_SOURCE) */ 210 | 211 | 212 | // --------------------------------------------------------------------- 213 | // END OF FILE: socket.c 214 | // --------------------------------------------------------------------- 215 | -------------------------------------------------------------------------------- /src/socket.h: -------------------------------------------------------------------------------- 1 | // --------------------------------------------------------------------- 2 | // SPDX-License-Identifier: GPL-3.0-or-later 3 | // socket.h is a part of Blitzping. 4 | // --------------------------------------------------------------------- 5 | 6 | 7 | #pragma once 8 | #ifndef SOCKET_H 9 | #define SOCKET_H 10 | 11 | #include "./cmdline/logger.h" 12 | 13 | #include 14 | #include 15 | 16 | #include 17 | #include 18 | #include 19 | 20 | #if defined(_POSIX_C_SOURCE) 21 | # include 22 | # include 23 | # include 24 | # include 25 | # include 26 | # if defined(__linux__) 27 | # include 28 | # endif 29 | #elif defined(_WIN32) 30 | //#include 31 | #endif 32 | 33 | extern int errno; // Declared in 34 | 35 | 36 | int setup_posix_socket(const bool is_raw, const bool is_async); 37 | 38 | 39 | #endif // SOCKET_H 40 | 41 | // --------------------------------------------------------------------- 42 | // END OF FILE: socket.h 43 | // --------------------------------------------------------------------- 44 | -------------------------------------------------------------------------------- /src/utils/endian.h: -------------------------------------------------------------------------------- 1 | // --------------------------------------------------------------------- 2 | // SPDX-License-Identifier: GPL-3.0-or-later 3 | // endian.h is a part of Blitzping. 4 | // --------------------------------------------------------------------- 5 | 6 | _Pragma ("once") 7 | #ifndef ENDIAN_H 8 | #define ENDIAN_H 9 | 10 | 11 | typedef enum Endianness { 12 | little_endian, 13 | big_endian, 14 | } endianness_t; 15 | 16 | // NOTE: Unfortunately, only GCC supports the scalar_storage_order 17 | // attribute/pragma, and LLVM/MSVC don't have it yet; for that reason, 18 | // we have to resort to old-fashioned macro definitions. 19 | // https://km.kkrach.de/p_little_vs_big_endian 20 | // https://github.com/llvm/llvm-project/issues/34641 21 | 22 | // Check endianness at compile-time for the target machine 23 | #if defined(__BYTE_ORDER__) && !(defined(__LITTLE_ENDIAN__) \ 24 | || defined(__BIG_ENDIAN__)) 25 | # if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ 26 | # define __LITTLE_ENDIAN__ 27 | # elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ 28 | # define __BIG_ENDIAN__ 29 | # else 30 | # error "Define endianness: __LITTLE_ENDIAN__ or __BIG_ENDIAN__." 31 | # endif 32 | #endif 33 | 34 | // Double-check endianness at runtime on the target machine. 35 | inline endianness_t check_endianness() { 36 | union { 37 | int word; 38 | char byte[sizeof (int)]; 39 | } same_memory; 40 | 41 | same_memory.word = 1; 42 | // Check if the least-significant stored byte is 1 (little endian) 43 | endianness_t runtime_endianness = (same_memory.byte[0] == 1) ? 44 | little_endian : big_endian; 45 | 46 | return runtime_endianness; 47 | } 48 | 49 | 50 | #endif // ENDIAN_H 51 | 52 | // --------------------------------------------------------------------- 53 | // END OF FILE: endian.h 54 | // --------------------------------------------------------------------- 55 | -------------------------------------------------------------------------------- /src/utils/intrins.h: -------------------------------------------------------------------------------- 1 | // --------------------------------------------------------------------- 2 | // SPDX-License-Identifier: GPL-3.0-or-later 3 | // intrins.h is a part of Blitzping. 4 | // --------------------------------------------------------------------- 5 | 6 | _Pragma ("once") 7 | #ifndef INTRINS_H 8 | #define INTRINS_H 9 | 10 | 11 | #if defined (__GNUC__) || defined (__llvm__) 12 | # define PREFETCH(addr, rw, locality) ( \ 13 | __builtin_prefetch(addr, rw, locality) \ 14 | ) 15 | #elif defined(_MSC_VER) 16 | # include 17 | # define PREFETCH(addr, rw, locality) ( \ 18 | (void)(rw), (void)(locality), \ 19 | _mm_prefetch((char*)(addr), _MM_HINT_T0) \ 20 | ) 21 | #else 22 | # define PREFETCH(addr, rw, locality) ( \ 23 | (void)(addr), (void)(rw), (void)(locality) 24 | ) 25 | #endif 26 | 27 | #endif // INTRINS_H 28 | 29 | // --------------------------------------------------------------------- 30 | // END OF FILE: intrins.h 31 | // --------------------------------------------------------------------- 32 | --------------------------------------------------------------------------------