├── .github └── workflows │ ├── c-cpp.yml │ ├── code-coverage.yml │ └── codeql.yml ├── .gitignore ├── AUTHORS ├── COPYING ├── ChangeLog ├── Makefile.am ├── NEWS ├── README ├── README.md ├── TODO ├── acinclude.m4 ├── check-sizes.c ├── check-tcp-scan-run1 ├── configure.ac ├── error.c ├── getopt.c ├── getopt.h ├── getopt1.c ├── ip.h ├── mt19937ar.c ├── strlcat.c ├── strlcpy.c ├── tcp-scan-services ├── tcp-scan.1 ├── tcp-scan.c ├── tcp-scan.h ├── tcp.h ├── utils.c └── wrappers.c /.github/workflows/c-cpp.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | 3 | on: 4 | push: 5 | branches: [ "master" ] 6 | pull_request: 7 | branches: [ "master" ] 8 | 9 | jobs: 10 | build: 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - uses: actions/checkout@v3 15 | - name: install libpcap 16 | run: | 17 | sudo apt-get update -qq 18 | sudo apt-get install -qq libpcap0.8-dev 19 | - name: autoreconf 20 | run: autoreconf --install 21 | - name: configure 22 | run: ./configure 23 | - name: make 24 | run: make 25 | - name: make check 26 | run: make check 27 | - name: make distcheck 28 | run: make distcheck 29 | - name: print info 30 | run: | 31 | uname -a 32 | gcc --version 33 | ./tcp-scan --version 34 | 35 | -------------------------------------------------------------------------------- /.github/workflows/code-coverage.yml: -------------------------------------------------------------------------------- 1 | name: coverage 2 | on: 3 | push: 4 | branches: [ "master" ] 5 | pull_request: 6 | branches: [ "master" ] 7 | 8 | # Allows you to run this workflow manually from the Actions tab 9 | workflow_dispatch: 10 | 11 | jobs: 12 | coverage: 13 | runs-on: ubuntu-latest 14 | 15 | steps: 16 | - uses: actions/checkout@v3 17 | - name: install libpcap and lcov 18 | run: | 19 | sudo apt-get update -qq 20 | sudo apt-get install -qq libpcap0.8-dev lcov 21 | - name: autoreconf 22 | run: autoreconf --install 23 | - name: configure with gcov 24 | run: ./configure --enable-gcov 25 | - name: make 26 | run: make 27 | - name: make check 28 | run: make check 29 | - name: create lcov.info 30 | run: lcov --directory . --capture --output-file lcov.info 31 | - name: Coveralls 32 | uses: coverallsapp/github-action@master 33 | with: 34 | github-token: ${{ secrets.GITHUB_TOKEN }} 35 | path-to-lcov: ./lcov.info 36 | -------------------------------------------------------------------------------- /.github/workflows/codeql.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | # 7 | # ******** NOTE ******** 8 | # We have attempted to detect the languages in your repository. Please check 9 | # the `language` matrix defined below to confirm you have the correct set of 10 | # supported CodeQL languages. 11 | # 12 | name: "CodeQL" 13 | 14 | on: 15 | push: 16 | branches: [ "master" ] 17 | pull_request: 18 | # The branches below must be a subset of the branches above 19 | branches: [ "master" ] 20 | schedule: 21 | - cron: '24 21 * * 6' 22 | 23 | jobs: 24 | analyze: 25 | name: Analyze 26 | runs-on: ubuntu-latest 27 | permissions: 28 | actions: read 29 | contents: read 30 | security-events: write 31 | 32 | strategy: 33 | fail-fast: false 34 | matrix: 35 | language: [ 'cpp' ] 36 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] 37 | # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support 38 | 39 | steps: 40 | - name: Checkout repository 41 | uses: actions/checkout@v3 42 | 43 | - name: install libpcap 44 | run: | 45 | sudo apt-get update -qq 46 | sudo apt-get install -qq libpcap0.8-dev 47 | 48 | # Initializes the CodeQL tools for scanning. 49 | - name: Initialize CodeQL 50 | uses: github/codeql-action/init@v2 51 | with: 52 | languages: ${{ matrix.language }} 53 | # If you wish to specify custom queries, you can do so here or in a config file. 54 | # By default, queries listed here will override any specified in a config file. 55 | # Prefix the list here with "+" to use these queries and those in the config file. 56 | 57 | # Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs 58 | # queries: security-extended,security-and-quality 59 | 60 | 61 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 62 | # If this step fails, then you should remove it and run the build manually (see below) 63 | - name: Autobuild 64 | uses: github/codeql-action/autobuild@v2 65 | 66 | # ℹ️ Command-line programs to run using the OS shell. 67 | # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun 68 | 69 | # If the Autobuild fails above, remove it and uncomment the following three lines. 70 | # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance. 71 | 72 | # - run: | 73 | # echo "Run, Build Application using script" 74 | # ./location_of_script_within_repo/buildscript.sh 75 | 76 | - name: Perform CodeQL Analysis 77 | uses: github/codeql-action/analyze@v2 78 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Autoconf and automake generated files 2 | .deps/ 3 | INSTALL 4 | Makefile 5 | Makefile.in 6 | aclocal.m4 7 | autom4te.cache/ 8 | config.guess 9 | config.h 10 | config.h.in 11 | config.log 12 | config.status 13 | config.sub 14 | configure 15 | depcomp 16 | install-sh 17 | missing 18 | stamp-h1 19 | compile 20 | test-driver 21 | # Compiler output files 22 | *.o 23 | *.gcno 24 | *.gcda 25 | *.gcov 26 | tcp-scan 27 | check-sizes 28 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | The author of tcp-scan is: 2 | 3 | Roy Hills 4 | 5 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /ChangeLog: -------------------------------------------------------------------------------- 1 | 2022-10-04 Roy Hills 2 | 3 | * acinclude.m4: fix typo in 'if test "X$CC" != "X"' checks. Declare main() as 4 | int to fix -Wimplicit-int errors. 5 | 6 | * configure.ac: Increment version to 1.21. Update pcap library check to 7 | check for pcap_set_immediate_mode() instead of pcap_lib_version() because 8 | we need pcap version 1.5 or later. Remove checks for ANSI C compiler as 9 | we now assume this to be present. 10 | 11 | * wrappers.c: New function my_lookupdev() to replace pcap_lookupdev() 12 | which is depreciated in libpcap 1.9.0 and later. 13 | 14 | * tcp-scan.c: use pcap_create(), pcap_set_XXX() , pcap_activate() instead of 15 | the old pcap_open_live(). 16 | 17 | * tcp-scan.h: Include STDC headers unconditionally. 18 | 19 | 2022-09-18 Roy Hills 20 | 21 | * check-tcp-scan-run1: Changed "$srcdir/tcp-scan" to "./tcp-scan" 22 | in test scripts so "make distcheck" succeeds. 23 | 24 | 2022-09-14 Roy Hills 25 | 26 | * README.md, .github/workflows/*: Migrated from travis-ci to github 27 | actions for CI/CD build check and code coverage report. 28 | 29 | * .travis.yml: removed as no longer needed. 30 | 31 | 2013-12-01 Roy Hills 32 | 33 | * configure.ac, .gitignore: Added configure option --enable-gcov to 34 | enable gcov code coverage. 35 | 36 | 2013-09-05 Roy Hills 37 | 38 | * configure.ac: Change the bug-report string in AC_INIT from the 39 | tcp-scan email address to the github URL. 40 | 41 | * tcp-scan.c, check-tcp-scan-run1: updated to take account of 42 | changes to bug-report string. 43 | 44 | 2013-08-16 Roy Hills 45 | 46 | * .gitignore: New file listing patterns to exclude from the repository. 47 | 48 | * COPYING: New file. 49 | 50 | * Removed $Id$ keywords from all files, and associated rcsid variables 51 | from C source. These are not really needed and they don't work with 52 | git. 53 | 54 | 2013-08-15 Roy Hills 55 | 56 | * Final SVN revision before moving to git. 57 | 58 | 2013-05-02 Roy Hills 59 | 60 | * tcp-scan.c: Removed unneeded errlen declaration to avoid "set but 61 | not used" warning with GCC 4.6 and later. 62 | 63 | * check-sizes.c: Added conditional include for , which is 64 | needed to define CHAR_BIT on Debian Wheezy. 65 | 66 | * configure.ac: Added check for limits.h header. Incremented version 67 | number to 1.20. 68 | 69 | 2011-08-18 Roy Hills 70 | 71 | * tcp-scan.1: Added options section to manpage. 72 | 73 | * tcp-scan.c: Use pcap_get_selectable_fd() rather than pcap_fileno() 74 | to get the pcap file descriptor. Use "stdin" instead of 75 | fdopen(0,"r") when using --filename=- 76 | 77 | 2011-07-01 Roy Hills 78 | 79 | * acinclude.m4: Updated to latest version from arp-scan source tree. 80 | This includes the GCC_WEXTRA macro and removes the dependence on the 81 | header. 82 | 83 | * configure.ac: Removed version number from AM_INIT_AUTOMAKE macro, 84 | as this usage is obsolete now. Added -Wshadow warning switch and 85 | Added GCC_WEXTRA macro to determine if the C compiler supports the 86 | -Wextra switch to enable extra warnings. Define ATTRIBUTE_UNUSED 87 | macro to enable portable use of attribute unused to mark possibly 88 | unused function arguments. 89 | 90 | * tcp-scan.c, tcp-scan.h, utils.c: Remove unused variables, address 91 | signed/unsigned comparisons highlighted by -Wextra and address 92 | shadowed variable warnings. 93 | 94 | 2009-08-15 Roy Hills 95 | 96 | * tcp-scan.c, utils.c: Improve handling of --bandwidth and 97 | --interval options: Allow either upper or lowercase 98 | multiplier letters and give an error if an unknown multiplier 99 | character is used. Previously an unknown multiplier character 100 | or one with the wrong case was silently ignored and treated as 101 | no multiplier at all. 102 | 103 | * wrappers.c: Change Strtoul so it gives an error if the 104 | underlying strtoul function finishes at an unconvertable 105 | character other than NULL or whitespace. 106 | 107 | * configure.ac: Added extra warning "-Wwrite-strings" for gcc. 108 | 109 | 2009-05-06 Roy Hills 110 | 111 | * configure.ac: upgraded for autoconf 2.61 112 | 113 | 2009-03-06 Roy Hills 114 | 115 | * acinclude.m4: Added macros to detect compiler support for 116 | -fstack-protect, -D_FORTIFY_SOURCE and -Wformat-security. 117 | 118 | * configure.ac: Conditionally enable compiler flags for 119 | -fstack-protect, -D_FORTIFY_SOURCE and -Wformat-security using 120 | the new acinclude.m4 autoconf macros. 121 | 122 | * configure.ac: Incremented version to 1.18 123 | 124 | 2008-10-30 Roy Hills 125 | 126 | * check-sizes.c: New program to check the sizes of key types and 127 | structures. 128 | 129 | 2008-10-25 Roy Hills 130 | 131 | * tcp-scan.c: Added new --pcapsavefile (-C) option to allow 132 | received TCP packets to be saved to a pcap file for later 133 | analysis. 134 | 135 | * configure.ac: Improved checks for pcap library. 136 | 137 | * Minor code changes to improve portability. 138 | 139 | 2008-10-24 Roy Hills 140 | 141 | * configure.ac: incremented version number to 1.16. 142 | First beta test version for DK, DC & AP. 143 | 144 | * tarball: tcp-scan-1.16.tar.gz 145 | Size: 167,451 MD5: 9fa6ea49e2648cba49a94a61ccadcfbe 146 | 147 | 2008-07-11 Roy Hills 148 | 149 | * tcp-scan.c: Removed reference to RMIF environment variable. 150 | tcp-scan now uses the value specified with --interface, or 151 | if that is not specified, picks an interface with 152 | pcap_lookupdev(). 153 | 154 | 2008-02-04 Roy Hills 155 | 156 | * tcp-scan.c: Improved get_source_ip function: close socket descriptor 157 | after use, and give better error message if the interface has no 158 | IP address. 159 | 160 | * tcp-scan.c: Added new --port (-p) option to replace the now 161 | depreciated --data (-D) option. 162 | 163 | * tcp-scan.c: Modified usage() so that it can output either brief or 164 | detailed help output depending on a new "detailed" argument. Now, 165 | detailed output, including information on the available options, is 166 | only displayed when ike-scan is run with the --help option. For 167 | error conditions such as incorrect options, it only produces brief 168 | output. 169 | 170 | * tcp-scan.c: Added --servicefile2 (-E) option to allow the TCP service 171 | filename to be specified. 172 | 173 | * configure.ac: Increment version number to 1.15. 174 | 175 | 2008-02-04 Roy Hills 176 | 177 | * configure.ac, tcp-scan.h: Add Posix regular expression support with 178 | header file regex.h. 179 | 180 | * configure.ac: Increment version number to 1.14. 181 | 182 | * tcp-scan.c: Improved algorithm to create port name map from 183 | services file. This new algorithm uses Posix regex functions. 184 | 185 | * tcp-scan-services: Improved port list in services file. 186 | 187 | 2007-12-31 Roy Hills 188 | 189 | * tcp-scan.c: Use mersenne twister PRNG to generate random values 190 | for seq_no, ack_no and source_port rather than using an md5 hash. 191 | 192 | * md5.c, md5.h: Source files removed as they are no longer needed. 193 | 194 | * tcp-scan.h: Removed include for md5.h. 195 | 196 | * tcp-scan-services: New TCP services file. 197 | 198 | * tcp-scan.c: Use TCP service file in DATADIR rather than using hard- 199 | coded absolute path. 200 | 201 | * tcp-scan.1: New manpage file. 202 | 203 | 2007-12-24 Roy Hills 204 | 205 | * Removed rawip-scan-engine.c and rawip-scan-engine.h. Code moved to 206 | tcp-scan.c and definitions to tcp-scan.h 207 | 208 | * New source file: utils.c, containing utility functions. 209 | 210 | * Added mt19937ar.c: mersenne twister PRNG. 211 | Changed random number implementation to use the mersenne twister 212 | functions from mt19937ar.c rather than random() from the C 213 | library. This improves portability, as random() is not part of 214 | standard C. 215 | 216 | * Removed unneeded --protocol (-p) option. 217 | 218 | * configure.ac: Added checks for strlcat and strlcpy, with 219 | replacement functions using the OpenBSD implementations if they are 220 | not present. 221 | 222 | * strlcat.c, strlcpy.c: New source files from the OpenBSD source at 223 | http://www.openbsd.org/cgi-bin/cvsweb/src/lib/libc/string 224 | 225 | * *.c: replaced calls to strcat and strncat with strlcat, and 226 | calls to strcpy and strncpy with strlcpy. 227 | 228 | * configure.ac, tcp-scan.h: Added checks for headers sys/ioctl.h, 229 | net/if.h and sys/utsname.h, and made these conditional includes. 230 | 231 | * tcp-scan.h, tcp-scan.c: Change structure definitions to 232 | typedefs. i.e. change "struct foo {defs};" to 233 | typedef struct {defs} foo;". 234 | 235 | * tcp-scan.c: Removed unneeded Gettimeofday() call in 236 | add_host_port(). 237 | 238 | * tcp-scan.c: Change calls to strtol() to use the new 239 | wrapper function Strtol() instead, because this checks for 240 | errors. Previously, a non-numeric value would be converted to 241 | zero without any error, meaning something like "--snap=xxx" 242 | would be silently accepted. Now such invalid inputs results in 243 | an error. 244 | 245 | 2007-12-21 Roy Hills 246 | 247 | * Converted tcp-scan to GPL license. Previous versions were 248 | NTA Monitor internal use only. 249 | 250 | Added GPL text to beginning of all source files and to 251 | --version output. 252 | 253 | Added files AUTHORS, ChangeLog, NEWS, README and TODO. 254 | 255 | Removed unneeded files random.c, generic-ip-scan.c and 256 | generic-ip-scan.h. 257 | 258 | Removed variables "scanner_name" and "scanner_version" and replaced 259 | with PACKAGE_STRING. 260 | 261 | Removed DNS lookup for tcp-scan-target. 262 | 263 | Removed syslog code. We don't use this any more, and I doubt that 264 | anyone else needs it. 265 | 266 | configure.ac: Incremented version to 1.13 267 | -------------------------------------------------------------------------------- /Makefile.am: -------------------------------------------------------------------------------- 1 | # Process this file with automake to produce Makefile.in 2 | # 3 | AM_CPPFLAGS = -DDATADIR=\"$(pkgdatadir)\" 4 | # 5 | bin_PROGRAMS = tcp-scan 6 | check_PROGRAMS = check-sizes 7 | # 8 | dist_check_SCRIPTS = check-tcp-scan-run1 9 | # 10 | dist_man_MANS = tcp-scan.1 11 | # 12 | tcp_scan_SOURCES = tcp-scan.c tcp-scan.h error.c wrappers.c utils.c ip.h tcp.h mt19937ar.c 13 | tcp_scan_LDADD = $(LIBOBJS) 14 | check_sizes_SOURCES = check-sizes.c error.c tcp-scan.h ip.h tcp.h 15 | check_sizes_LDADD = $(LIBOBJS) 16 | # 17 | dist_pkgdata_DATA = tcp-scan-services 18 | # 19 | TESTS = $(check_PROGRAMS) $(dist_check_SCRIPTS) 20 | -------------------------------------------------------------------------------- /NEWS: -------------------------------------------------------------------------------- 1 | This file gives a brief overview of the major changes between each tcp-scan 2 | release. For more details please read the ChangeLog file. 3 | 4 | -------------------------------------------------------------------------------- /README: -------------------------------------------------------------------------------- 1 | README.md -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # tcp-scan 2 | 3 | [![Build](https://github.com/royhills/tcp-scan/actions/workflows/c-cpp.yml/badge.svg)](https://github.com/royhills/tcp-scan/actions/workflows/c-cpp.yml) 4 | [![Coverage Status](https://coveralls.io/repos/github/royhills/tcp-scan/badge.svg?branch=master)](https://coveralls.io/github/royhills/tcp-scan?branch=master) 5 | [![CodeQL](https://github.com/royhills/tcp-scan/actions/workflows/codeql.yml/badge.svg)](https://github.com/royhills/tcp-scan/actions/workflows/codeql.yml) 6 | 7 | The TCP scanner. 8 | 9 | Installation 10 | ------------ 11 | 12 | tcp-scan uses the standard GNU automake and autoconf tools, so the typical installation process is: 13 | 14 | - Run ```git clone https://github.com/royhills/tcp-scan.git``` to obtain the project source code 15 | - Run ```cd tcp-scan``` to enter source directory 16 | - Run ```autoreconf --install``` to generate a viable ./configure file 17 | - Run ```./configure``` to generate a makefile for your system 18 | - Run ```make``` to build the project 19 | - Optionally run ```make check``` to verify that everything works as expected 20 | - Run ```make install``` to install (you'll need root or sudo for this part) 21 | 22 | You will need GNU automake and autoconf, the make utility, an ANSI C compiler (for example gcc or clang), and the development header files and libraries. 23 | 24 | You can pass various options to "configure" to control the build and 25 | installation process. See the file INSTALL for more details. 26 | 27 | tcp-scan is known to compile and run on the following platforms: 28 | 29 | - Linux 30 | 31 | The IP packets are sent using raw sockets, and the responses are received 32 | using libpcap (http://www.tcpdump.org/). 33 | 34 | Documentation 35 | ------------- 36 | 37 | For usage information, including details of all the options, use: 38 | 39 | ```tcp-scan --help``` 40 | 41 | -------------------------------------------------------------------------------- /TODO: -------------------------------------------------------------------------------- 1 | Don't display closed ports by default [need to check NTA engine usage]. 2 | 3 | Display port names by default [need to check NTA engine usage]. 4 | 5 | Review default bandwidth and possibly increase it. 6 | 7 | Add better "make check" tests and measure code coverage. 8 | 9 | Allow the use of networks and ranges for the target hosts. 10 | 11 | Add IPv6 support 12 | 13 | Complete manpage tcp-scan.1 14 | 15 | Remove deprecated --data (-D) option after modifying NTA engine. 16 | 17 | Add details about tcp-scan homepage and wiki to help output. 18 | 19 | Rename "servicefile" option to "portfile" and "servicefile2" 20 | to "servicefile" [need to check NTA engine usage]. 21 | 22 | create_port_list() uses the old strobe service file parsing code, which 23 | does not work with long service names, or names containing slashes. 24 | 25 | Change format of the services files that are used to select which ports are 26 | scanned, so that these contain just the port numbers and optional comments. 27 | These files are called services.*. They live in /opt/nta/script and are in 28 | SVN under test_scripts/port_scans 29 | -------------------------------------------------------------------------------- /acinclude.m4: -------------------------------------------------------------------------------- 1 | dnl NTA Monitor autoconf macros 2 | 3 | dnl AC_NTA_CHECK_TYPE -- See if a type exists using reasonable includes 4 | dnl 5 | dnl Although there is a standard macro AC_CHECK_TYPE, we can't always 6 | dnl use this because it doesn't include enough header files. 7 | dnl 8 | AC_DEFUN([AC_NTA_CHECK_TYPE], 9 | [AC_MSG_CHECKING([for $1 using $CC]) 10 | AC_CACHE_VAL(ac_cv_nta_have_$1, 11 | AC_TRY_COMPILE([ 12 | # include "confdefs.h" 13 | # include 14 | # if HAVE_SYS_TYPES_H 15 | # include 16 | # endif 17 | # if HAVE_SYS_STAT_H 18 | # include 19 | # endif 20 | # ifdef STDC_HEADERS 21 | # include 22 | # include 23 | # endif 24 | # if HAVE_INTTYPES_H 25 | # include 26 | # else 27 | # if HAVE_STDINT_H 28 | # include 29 | # endif 30 | # endif 31 | # if HAVE_UNISTD_H 32 | # include 33 | # endif 34 | # ifdef HAVE_ARPA_INET_H 35 | # include 36 | # endif 37 | # ifdef HAVE_NETDB_H 38 | # include 39 | # endif 40 | # ifdef HAVE_NETINET_IN_H 41 | # include 42 | # endif 43 | # ifdef SYS_SOCKET_H 44 | # include 45 | # endif 46 | ], 47 | [$1 i], 48 | ac_cv_nta_have_$1=yes, 49 | ac_cv_nta_have_$1=no)) 50 | AC_MSG_RESULT($ac_cv_nta_have_$1) 51 | if test $ac_cv_nta_have_$1 = no ; then 52 | AC_DEFINE($1, $2, [Define to required type if we don't have $1]) 53 | fi]) 54 | 55 | dnl AC_NTA_NET_SIZE_T -- Determine type of 3rd argument to accept 56 | dnl 57 | dnl This type is normally socklen_t but is sometimes size_t or int instead. 58 | dnl We try, in order: socklen_t, int, size_t until we find one that compiles 59 | dnl 60 | AC_DEFUN([AC_NTA_NET_SIZE_T], 61 | [AC_MSG_CHECKING([for socklen_t or equivalent using $CC]) 62 | ac_nta_net_size_t=no 63 | AC_TRY_COMPILE([ 64 | # include "confdefs.h" 65 | # include 66 | # ifdef HAVE_SYS_SOCKET_H 67 | # include 68 | # endif], 69 | [int s; 70 | struct sockaddr addr; 71 | socklen_t addrlen; 72 | int result; 73 | result=accept(s, &addr, &addrlen)], 74 | ac_nta_net_size_t=socklen_t,ac_nta_net_size_t=no) 75 | if test $ac_nta_net_size_t = no; then 76 | AC_TRY_COMPILE([ 77 | # include "confdefs.h" 78 | # include 79 | # ifdef HAVE_SYS_SOCKET_H 80 | # include 81 | # endif], 82 | [int s; 83 | struct sockaddr addr; 84 | int addrlen; 85 | int result; 86 | result=accept(s, &addr, &addrlen)], 87 | ac_nta_net_size_t=int,ac_nta_net_size_t=no) 88 | fi 89 | if test $ac_nta_net_size_t = no; then 90 | AC_TRY_COMPILE([ 91 | # include "confdefs.h" 92 | # include 93 | # ifdef HAVE_SYS_SOCKET_H 94 | # include 95 | # endif], 96 | [int s; 97 | struct sockaddr addr; 98 | size_t addrlen; 99 | int result; 100 | result=accept(s, &addr, &addrlen)], 101 | ac_nta_net_size_t=size_t,ac_nta_net_size_t=no) 102 | fi 103 | if test $ac_nta_net_size_t = no; then 104 | AC_MSG_ERROR([Cannot find acceptable type for 3rd arg to accept()]) 105 | else 106 | AC_MSG_RESULT($ac_nta_net_size_t) 107 | AC_DEFINE_UNQUOTED(NET_SIZE_T, $ac_nta_net_size_t, [Define required type for 3rd arg to accept()]) 108 | fi 109 | ]) 110 | 111 | dnl PGAC_TYPE_64BIT_INT(TYPE) 112 | dnl ------------------------- 113 | dnl Check if TYPE is a working 64 bit integer type. Set HAVE_TYPE_64 to 114 | dnl yes or no respectively, and define HAVE_TYPE_64 if yes. 115 | dnl 116 | dnl This function comes from the Postgresql file: 117 | dnl pgsql/config/c-compiler.m4,v 1.13 118 | dnl 119 | AC_DEFUN([PGAC_TYPE_64BIT_INT], 120 | [define([Ac_define], [translit([have_$1_64], [a-z *], [A-Z_P])])dnl 121 | define([Ac_cachevar], [translit([pgac_cv_type_$1_64], [ *], [_p])])dnl 122 | AC_CACHE_CHECK([whether $1 is 64 bits], [Ac_cachevar], 123 | [AC_TRY_RUN( 124 | [typedef $1 int64; 125 | 126 | /* 127 | * These are globals to discourage the compiler from folding all the 128 | * arithmetic tests down to compile-time constants. 129 | */ 130 | int64 a = 20000001; 131 | int64 b = 40000005; 132 | 133 | int does_int64_work() 134 | { 135 | int64 c,d; 136 | 137 | if (sizeof(int64) != 8) 138 | return 0; /* definitely not the right size */ 139 | 140 | /* Do perfunctory checks to see if 64-bit arithmetic seems to work */ 141 | c = a * b; 142 | d = (c + b) / b; 143 | if (d != a+1) 144 | return 0; 145 | return 1; 146 | } 147 | int main() { 148 | exit(! does_int64_work()); 149 | }], 150 | [Ac_cachevar=yes], 151 | [Ac_cachevar=no], 152 | [# If cross-compiling, check the size reported by the compiler and 153 | # trust that the arithmetic works. 154 | AC_COMPILE_IFELSE([AC_LANG_BOOL_COMPILE_TRY([], [sizeof($1) == 8])], 155 | Ac_cachevar=yes, 156 | Ac_cachevar=no)])]) 157 | 158 | Ac_define=$Ac_cachevar 159 | if test x"$Ac_cachevar" = xyes ; then 160 | AC_DEFINE(Ac_define,, [Define to 1 if `]$1[' works and is 64 bits.]) 161 | fi 162 | undefine([Ac_define])dnl 163 | undefine([Ac_cachevar])dnl 164 | ])# PGAC_TYPE_64BIT_INT 165 | 166 | dnl PGAC_FUNC_SNPRINTF_LONG_LONG_INT_FORMAT 167 | dnl --------------------------------------- 168 | dnl Determine which format snprintf uses for long long int. We handle 169 | dnl %lld, %qd, %I64d. The result is in shell variable 170 | dnl LONG_LONG_INT_FORMAT. 171 | dnl 172 | dnl MinGW uses '%I64d', though gcc throws an warning with -Wall, 173 | dnl while '%lld' doesn't generate a warning, but doesn't work. 174 | dnl 175 | dnl This function comes from the Postgresql file: 176 | dnl pgsql/config/c-library.m4,v 1.28 177 | dnl 178 | AC_DEFUN([PGAC_FUNC_SNPRINTF_LONG_LONG_INT_FORMAT], 179 | [AC_MSG_CHECKING([snprintf format for long long int]) 180 | AC_CACHE_VAL(pgac_cv_snprintf_long_long_int_format, 181 | [for pgac_format in '%lld' '%qd' '%I64d'; do 182 | AC_TRY_RUN([#include 183 | typedef long long int int64; 184 | #define INT64_FORMAT "$pgac_format" 185 | 186 | int64 a = 20000001; 187 | int64 b = 40000005; 188 | 189 | int does_int64_snprintf_work() 190 | { 191 | int64 c; 192 | char buf[100]; 193 | 194 | if (sizeof(int64) != 8) 195 | return 0; /* doesn't look like the right size */ 196 | 197 | c = a * b; 198 | snprintf(buf, 100, INT64_FORMAT, c); 199 | if (strcmp(buf, "800000140000005") != 0) 200 | return 0; /* either multiply or snprintf is busted */ 201 | return 1; 202 | } 203 | int main() { 204 | exit(! does_int64_snprintf_work()); 205 | }], 206 | [pgac_cv_snprintf_long_long_int_format=$pgac_format; break], 207 | [], 208 | [pgac_cv_snprintf_long_long_int_format=cross; break]) 209 | done])dnl AC_CACHE_VAL 210 | 211 | LONG_LONG_INT_FORMAT='' 212 | 213 | case $pgac_cv_snprintf_long_long_int_format in 214 | cross) AC_MSG_RESULT([cannot test (not on host machine)]);; 215 | ?*) AC_MSG_RESULT([$pgac_cv_snprintf_long_long_int_format]) 216 | LONG_LONG_INT_FORMAT=$pgac_cv_snprintf_long_long_int_format;; 217 | *) AC_MSG_RESULT(none);; 218 | esac])# PGAC_FUNC_SNPRINTF_LONG_LONG_INT_FORMAT 219 | 220 | dnl 221 | dnl Useful macros for autoconf to check for ssp-patched gcc 222 | dnl 1.0 - September 2003 - Tiago Sousa 223 | dnl 224 | dnl About ssp: 225 | dnl GCC extension for protecting applications from stack-smashing attacks 226 | dnl http://www.research.ibm.com/trl/projects/security/ssp/ 227 | dnl 228 | dnl Usage: 229 | dnl After calling the correct AC_LANG_*, use the corresponding macro: 230 | dnl 231 | dnl GCC_STACK_PROTECT_CC 232 | dnl checks -fstack-protector with the C compiler, if it exists then updates 233 | dnl CFLAGS and defines ENABLE_SSP_CC 234 | dnl 235 | dnl GCC_STACK_PROTECT_CXX 236 | dnl checks -fstack-protector with the C++ compiler, if it exists then updates 237 | dnl CXXFLAGS and defines ENABLE_SSP_CXX 238 | dnl 239 | AC_DEFUN([GCC_STACK_PROTECT_CC],[ 240 | ssp_cc=yes 241 | if test "X$CC" != "X"; then 242 | AC_MSG_CHECKING([whether ${CC} accepts -fstack-protector]) 243 | ssp_old_cflags="$CFLAGS" 244 | CFLAGS="$CFLAGS -fstack-protector" 245 | AC_TRY_COMPILE(,,, ssp_cc=no) 246 | echo $ssp_cc 247 | if test "X$ssp_cc" = "Xno"; then 248 | CFLAGS="$ssp_old_cflags" 249 | else 250 | AC_DEFINE([ENABLE_SSP_CC], 1, [Define if SSP C support is enabled.]) 251 | fi 252 | fi 253 | ]) 254 | 255 | AC_DEFUN([GCC_STACK_PROTECT_CXX],[ 256 | ssp_cxx=yes 257 | if test "X$CXX" != "X"; then 258 | AC_MSG_CHECKING([whether ${CXX} accepts -fstack-protector]) 259 | ssp_old_cxxflags="$CXXFLAGS" 260 | CXXFLAGS="$CXXFLAGS -fstack-protector" 261 | AC_TRY_COMPILE(,,, ssp_cxx=no) 262 | echo $ssp_cxx 263 | if test "X$ssp_cxx" = "Xno"; then 264 | CXXFLAGS="$ssp_old_cxxflags" 265 | else 266 | AC_DEFINE([ENABLE_SSP_CXX], 1, [Define if SSP C++ support is enabled.]) 267 | fi 268 | fi 269 | ]) 270 | 271 | dnl Check whether GCC accepts -D_FORTIFY_SOURCE 272 | dnl 273 | dnl This was introduced in GCC 4.1 and glibc 2.4, but was present in earlier 274 | dnl versions on redhat systems (specifically GCC 3.4.3 and above). 275 | dnl 276 | dnl We define the GNUC_PREREQ macro to the same definition as __GNUC_PREREQ 277 | dnl in . We don't use __GNUC_PREREQ directly because 278 | dnl is not present on all the operating systems that we support, e.g. OpenBSD. 279 | dnl 280 | AC_DEFUN([GCC_FORTIFY_SOURCE],[ 281 | if test "X$CC" != "X"; then 282 | AC_MSG_CHECKING([whether ${CC} accepts -D_FORTIFY_SOURCE]) 283 | AC_TRY_COMPILE(,[ 284 | #define GNUC_PREREQ(maj, min) ((__GNUC__ << 16) + __GNUC_MINOR__ >= ((maj) << 16) + (min)) 285 | #if !(GNUC_PREREQ (4, 1) \ 286 | || (defined __GNUC_RH_RELEASE__ && GNUC_PREREQ (4, 0)) \ 287 | || (defined __GNUC_RH_RELEASE__ && GNUC_PREREQ (3, 4) \ 288 | && __GNUC_MINOR__ == 4 \ 289 | && (__GNUC_PATCHLEVEL__ > 2 \ 290 | || (__GNUC_PATCHLEVEL__ == 2 && __GNUC_RH_RELEASE__ >= 8)))) 291 | #error No FORTIFY_SOURCE support 292 | #endif 293 | ], [ 294 | AC_MSG_RESULT(yes) 295 | CFLAGS="$CFLAGS -D_FORTIFY_SOURCE=2" 296 | ], [ 297 | AC_MSG_RESULT(no) 298 | ]) 299 | fi 300 | ]) 301 | 302 | dnl Check for support of the GCC -Wformat-security option. 303 | dnl This option was introduced in GCC 3.0. 304 | dnl 305 | dnl Note that in this test, the test compilation fails if the option is 306 | dnl supported, and succeeds if it is not supported. 307 | dnl 308 | dnl If this option is supported, then the test program will produce a 309 | dnl warning like "format not a string literal and no format arguments". 310 | dnl If it is not supported, then the test program will compile without 311 | dnl warnings. 312 | dnl 313 | AC_DEFUN([GCC_FORMAT_SECURITY],[ 314 | if test "X$CC" != "X"; then 315 | AC_MSG_CHECKING([whether ${CC} accepts -Wformat-security]) 316 | wfs_old_cflags="$CFLAGS" 317 | CFLAGS="$CFLAGS -Wall -Werror -Wformat -Wformat-security" 318 | AC_TRY_COMPILE([#include ], [ 319 | char *fmt=NULL; 320 | printf(fmt); 321 | return 0; 322 | ], [ 323 | AC_MSG_RESULT(no) 324 | CFLAGS="$wfs_old_cflags" 325 | ], [ 326 | AC_MSG_RESULT(yes) 327 | CFLAGS="$wfs_old_cflags -Wformat -Wformat-security" 328 | ]) 329 | fi 330 | ]) 331 | 332 | dnl Check for support of the GCC -Wextra option, which enables extra warnings. 333 | dnl Support for this option was added in gcc 3.4.0. 334 | dnl 335 | AC_DEFUN([GCC_WEXTRA],[ 336 | gcc_wextra=yes 337 | if test "X$CC" != "X"; then 338 | AC_MSG_CHECKING([whether ${CC} accepts -Wextra]) 339 | gcc_old_cflags="$CFLAGS" 340 | CFLAGS="$CFLAGS -Wextra" 341 | AC_TRY_COMPILE(,,[ 342 | AC_MSG_RESULT(yes) 343 | ],[ 344 | AC_MSG_RESULT(no) 345 | gcc_wextra=no 346 | CFLAGS="$ssp_old_cflags" 347 | ]) 348 | fi 349 | ]) 350 | -------------------------------------------------------------------------------- /check-sizes.c: -------------------------------------------------------------------------------- 1 | /* 2 | * The TCP Scanner (tcp-scan) is Copyright (C) 2003-2008 Roy Hills, 3 | * NTA Monitor Ltd. 4 | * 5 | * This file is part of tcp-scan. 6 | * 7 | * tcp-scan 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 | * tcp-scan 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 tcp-scan. If not, see . 19 | * 20 | * If this license is unacceptable to you, I may be willing to negotiate 21 | * alternative licenses (contact tcp-scan@nta-monitor.com). 22 | * 23 | * You are encouraged to send comments, improvements or suggestions to 24 | * me at tcp-scan@nta-monitor.com. 25 | * 26 | * check-sizes -- Check sizes of structures and types 27 | * 28 | * Author: Roy Hills 29 | * Date: 30 October 2008 30 | * 31 | * Check that the sizes of the various structs are what we expect them 32 | * to be. If they are not, then we return with a failure status. 33 | */ 34 | 35 | #include "tcp-scan.h" 36 | 37 | #ifdef HAVE_LIMITS_H 38 | #include 39 | #endif 40 | 41 | #define EXPECTED_IP_HDR 20 42 | #define EXPECTED_TCP_HDR 20 43 | #define EXPECTED_PSEUDO_HDR 12 44 | 45 | #define EXPECTED_UINT8_T 1 46 | #define EXPECTED_UINT16_T 2 47 | #define EXPECTED_UINT32_T 4 48 | 49 | int 50 | main() { 51 | unsigned octets_per_char; /* Almost always 1 */ 52 | int error=0; 53 | 54 | if (CHAR_BIT % 8) 55 | err_msg("CHAR_BIT is not a multiple of 8"); 56 | 57 | octets_per_char = CHAR_BIT/8; 58 | 59 | printf("Structure\tExpect\tObserved\n\n"); 60 | 61 | printf("iphdr\t\t%u\t%lu\t", EXPECTED_IP_HDR, 62 | (unsigned long) (octets_per_char * sizeof(struct iphdr))); 63 | if (octets_per_char * sizeof(struct iphdr) != EXPECTED_IP_HDR) { 64 | error++; 65 | printf("ERROR\n"); 66 | } else { 67 | printf("ok\n"); 68 | } 69 | 70 | printf("tcphdr\t\t%u\t%lu\t", EXPECTED_TCP_HDR, 71 | (unsigned long) (octets_per_char * sizeof(struct tcphdr))); 72 | if (octets_per_char * sizeof(struct tcphdr) != EXPECTED_TCP_HDR) { 73 | error++; 74 | printf("ERROR\n"); 75 | } else { 76 | printf("ok\n"); 77 | } 78 | 79 | printf("pseudo_hdr\t%u\t%lu\t", EXPECTED_PSEUDO_HDR, 80 | (unsigned long) (octets_per_char * sizeof(pseudo_hdr))); 81 | if (octets_per_char * sizeof(pseudo_hdr) != EXPECTED_PSEUDO_HDR) { 82 | error++; 83 | printf("ERROR\n"); 84 | } else { 85 | printf("ok\n"); 86 | } 87 | 88 | printf("\nType\t\tExpect\tObserved\n\n"); 89 | 90 | printf("uint8_t\t\t%u\t%lu\t", EXPECTED_UINT8_T, 91 | (unsigned long) (octets_per_char * sizeof(uint8_t))); 92 | if (octets_per_char * sizeof(uint8_t) != EXPECTED_UINT8_T) { 93 | error++; 94 | printf("ERROR\n"); 95 | } else { 96 | printf("ok\n"); 97 | } 98 | 99 | printf("uint16_t\t%u\t%lu\t", EXPECTED_UINT16_T, 100 | (unsigned long) (octets_per_char * sizeof(uint16_t))); 101 | if (octets_per_char * sizeof(uint16_t) != EXPECTED_UINT16_T) { 102 | error++; 103 | printf("ERROR\n"); 104 | } else { 105 | printf("ok\n"); 106 | } 107 | 108 | printf("uint32_t\t%u\t%lu\t", EXPECTED_UINT32_T, 109 | (unsigned long) (octets_per_char * sizeof(uint32_t))); 110 | if (octets_per_char * sizeof(uint32_t) != EXPECTED_UINT32_T) { 111 | error++; 112 | printf("ERROR\n"); 113 | } else { 114 | printf("ok\n"); 115 | } 116 | 117 | if (error) 118 | return EXIT_FAILURE; 119 | else 120 | return EXIT_SUCCESS; 121 | } 122 | -------------------------------------------------------------------------------- /check-tcp-scan-run1: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # The TCP Scanner (tcp-scan) is Copyright (C) 2003-2008 Roy Hills, 3 | # NTA Monitor Ltd. 4 | # 5 | # This file is part of tcp-scan. 6 | # 7 | # tcp-scan 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 | # tcp-scan 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 tcp-scan. If not, see . 19 | # 20 | # check-tcp-scan-run1 -- Shell script to test tcp-scan basic functionality 21 | # 22 | # Author: Roy Hills 23 | # Date: 9 March 2006 24 | # 25 | # This shell script checks that "tcp-scan --help" and "tcp-scan --version" 26 | # work. These options don't use much of the tcp-scan functionallity, so if 27 | # they fail, then there is a fundimental problem with the program. 28 | # 29 | TMPFILE=/tmp/tcp-scan-test.$$.tmp 30 | # 31 | echo "Checking tcp-scan --help ..." 32 | ./tcp-scan --help 2> $TMPFILE 33 | if test $? -ne 0; then 34 | rm -f $TMPFILE 35 | echo "FAILED" 36 | exit 1 37 | fi 38 | grep '^Report bugs or send suggestions at ' $TMPFILE >/dev/null 39 | if test $? -ne 0; then 40 | rm -f $TMPFILE 41 | echo "FAILED" 42 | exit 1 43 | fi 44 | echo "ok" 45 | # 46 | echo "Checking tcp-scan --version ..." 47 | ./tcp-scan --version 2> $TMPFILE 48 | if test $? -ne 0; then 49 | rm -f $TMPFILE 50 | echo "FAILED" 51 | exit 1 52 | fi 53 | grep '^Copyright (C) ' $TMPFILE >/dev/null 54 | if test $? -ne 0; then 55 | rm -f $TMPFILE 56 | echo "FAILED" 57 | exit 1 58 | fi 59 | echo "ok" 60 | # 61 | rm -f $TMPFILE 62 | -------------------------------------------------------------------------------- /configure.ac: -------------------------------------------------------------------------------- 1 | dnl Process this file with autoconf to produce a configure script. 2 | 3 | AC_INIT([tcp-scan],[1.21],[https://github.com/royhills/tcp-scan]) 4 | AC_PREREQ(2.61) 5 | AC_REVISION($Revision$) 6 | AC_CONFIG_SRCDIR([tcp-scan.c]) 7 | AM_INIT_AUTOMAKE 8 | 9 | AC_CONFIG_HEADERS([config.h]) 10 | 11 | dnl Define the appropriate compiler flags if the user has enabled gcov 12 | dnl code coverage. We do this before calling AC_PROG_CC because we override 13 | dnl the default compiler options when running with gcov. 14 | AC_MSG_CHECKING([if gcov code coverage is enabled]) 15 | AC_ARG_ENABLE(gcov, 16 | AS_HELP_STRING([--enable-gcov],[enable gcov code coverage analysis]), 17 | [ 18 | if test "x$enableval" != "xno" ; then 19 | AC_MSG_RESULT(yes) 20 | CFLAGS="-O0 -g -fno-inline -fprofile-arcs -ftest-coverage" 21 | else 22 | AC_MSG_RESULT(no) 23 | fi 24 | ], 25 | [ 26 | AC_MSG_RESULT(no) 27 | ] ) 28 | dnl Checks for programs. 29 | AC_PROG_CC 30 | if test -n "$GCC"; then 31 | AC_DEFINE([ATTRIBUTE_UNUSED], [__attribute__ ((__unused__))], 32 | [Define to the compiler's unused pragma]) 33 | CFLAGS="$CFLAGS -Wall -Wshadow -Wwrite-strings" 34 | GCC_WEXTRA 35 | GCC_STACK_PROTECT_CC 36 | GCC_FORTIFY_SOURCE 37 | GCC_FORMAT_SECURITY 38 | else 39 | AC_DEFINE([ATTRIBUTE_UNUSED], [], 40 | [Define to the compiler's unused pragma]) 41 | fi 42 | AC_PROG_INSTALL 43 | AC_PROG_LN_S 44 | dnl Check endian-ness. MD5 and SHA1 hash functions need to know this. 45 | AC_C_BIGENDIAN 46 | 47 | dnl Checks for libraries. 48 | dnl Solaris 8 needs nsl and socket. Linux and {Free,Open}BSD do not. 49 | dnl Just about everything will need pcap. 50 | AC_SEARCH_LIBS([gethostbyname], [nsl]) 51 | AC_SEARCH_LIBS([socket], [socket]) 52 | AC_SEARCH_LIBS([pcap_open_live], [pcap], , 53 | [ 54 | AC_MSG_NOTICE([Cannot find pcap library containing pcap_open_live]) 55 | AC_MSG_ERROR([Check that you have libpcap version 1.5 or later installed]) 56 | ]) 57 | 58 | dnl Check that the pcap library contains pcap_set_immediate_mode() 59 | dnl This was introduced in libpcap version 1.5, and our application requires it. 60 | dnl 61 | dnl We perform this check as a seperate step, rather than just checking for 62 | dnl pcap_lib_version in the earlier AC_SEARCH_LIBS call, because it 63 | dnl allows us to provide different error messages for missing pcap and non 64 | dnl functional pcap and so avoids confusing generic error messages. 65 | dnl 66 | AC_MSG_CHECKING([for a compatible pcap library]) 67 | AC_LINK_IFELSE([AC_LANG_CALL([], [pcap_set_immediate_mode])], 68 | [AC_MSG_RESULT([yes])], 69 | [ 70 | AC_MSG_RESULT([no]) 71 | AC_MSG_NOTICE([Cannot find pcap_set_immediate_mode in pcap library]) 72 | AC_MSG_ERROR([Check that the pcap library is at least version 1.5]) 73 | ]) 74 | 75 | dnl Checks for header files. 76 | AC_CHECK_HEADERS([arpa/inet.h netdb.h netinet/in.h sys/socket.h sys/time.h unistd.h getopt.h pcap.h sys/ioctl.h net/if.h sys/utsname.h limits.h]) 77 | 78 | dnl Checks for typedefs, structures, and compiler characteristics. 79 | AC_TYPE_SIZE_T 80 | 81 | dnl Check for the uint{8,16,32}_t types and, if we don't have them, define 82 | dnl them using types which will work on most systems. 83 | AC_NTA_CHECK_TYPE(uint8_t, unsigned char) 84 | AC_NTA_CHECK_TYPE(uint16_t, unsigned short) 85 | AC_NTA_CHECK_TYPE(uint32_t, unsigned int) 86 | 87 | dnl Checks for 64-bit integer types. These checks are from postgresql. 88 | dnl Check to see if we have a working 64-bit integer type. 89 | dnl This breaks down into two steps: 90 | dnl (1) figure out if the compiler has a 64-bit int type with working 91 | dnl arithmetic, and if so 92 | dnl (2) see whether snprintf() can format the type correctly. 93 | 94 | PGAC_TYPE_64BIT_INT([long int]) 95 | 96 | if test x"$HAVE_LONG_INT_64" = x"yes" ; then 97 | INT64_TYPE="long int" 98 | UINT64_TYPE="unsigned long int" 99 | else 100 | PGAC_TYPE_64BIT_INT([long long int]) 101 | if test x"$HAVE_LONG_LONG_INT_64" = x"yes" ; then 102 | INT64_TYPE="long long int" 103 | UINT64_TYPE="unsigned long long int" 104 | else 105 | AC_MSG_ERROR([cannot determine 64-bit integer type]) 106 | fi 107 | fi 108 | 109 | AC_DEFINE_UNQUOTED(TCP_INT64, $INT64_TYPE, 110 | [Define to the appropriate type for 64-bit ints.]) 111 | AC_DEFINE_UNQUOTED(TCP_UINT64, $UINT64_TYPE, 112 | [Define to the appropriate type for unsigned 64-bit ints.]) 113 | 114 | dnl If we found "long int" is 64 bits, assume snprintf handles it. If 115 | dnl we found we need to use "long long int", better check. We cope with 116 | dnl snprintfs that use %lld, %qd, or %I64d as the format. 117 | dnl 118 | if test "$HAVE_LONG_LONG_INT_64" = yes ; then 119 | PGAC_FUNC_SNPRINTF_LONG_LONG_INT_FORMAT 120 | if test "$LONG_LONG_INT_FORMAT" = ""; then 121 | AC_MSG_ERROR([cannot determine snprintf format string for long long int]) 122 | fi 123 | LONG_LONG_UINT_FORMAT=`echo "$LONG_LONG_INT_FORMAT" | sed 's/d$/u/'` 124 | INT64_FORMAT="\"$LONG_LONG_INT_FORMAT\"" 125 | UINT64_FORMAT="\"$LONG_LONG_UINT_FORMAT\"" 126 | else 127 | # Here if we are not using 'long long int' at all 128 | INT64_FORMAT='"%ld"' 129 | UINT64_FORMAT='"%lu"' 130 | fi 131 | 132 | AC_DEFINE_UNQUOTED(TCP_INT64_FORMAT, $INT64_FORMAT, 133 | [Define to the appropriate snprintf format for 64-bit ints.]) 134 | 135 | AC_DEFINE_UNQUOTED(TCP_UINT64_FORMAT, $UINT64_FORMAT, 136 | [Define to the appropriate snprintf format for unsigned 64-bit ints.]) 137 | 138 | dnl Checks for library functions. 139 | AC_CHECK_FUNCS([malloc gethostbyname gettimeofday inet_ntoa memset select socket strerror]) 140 | 141 | dnl Determine type for 3rd arg to accept() 142 | dnl This is normally socklen_t, but can sometimes be size_t or int. 143 | AC_NTA_NET_SIZE_T 144 | 145 | dnl Check if the Posix regular expression functions "regcomp" and "regexec" 146 | dnl and the header file "regex.h" are present. 147 | AC_MSG_CHECKING([for posix regular expression support]) 148 | AC_LINK_IFELSE([AC_LANG_PROGRAM([[ 149 | #include 150 | #include ]], 151 | [[regcomp(0, 0, 0); 152 | regexec(0, 0, 0, 0, 0)]])], 153 | [ac_nta_posix_regex=yes], 154 | [ac_nta_posic_regex=no]) 155 | AC_MSG_RESULT([$ac_nta_posix_regex]) 156 | if test $ac_nta_posix_regex = no; then 157 | AC_MSG_ERROR([You don't seem to have posix regular expression support]) 158 | else 159 | AC_DEFINE(HAVE_REGEX_H, 1, [Define to 1 if you have posix regex support]) 160 | fi 161 | 162 | dnl GNU systems e.g. Linux have getopt_long_only, but many other systems 163 | dnl e.g. FreeBSD 4.3 and Solaris 8 do not. For systems that don't have it, 164 | dnl use the GNU getopt sources (obtained from glibc). 165 | AC_CHECK_FUNC([getopt_long_only], , 166 | [ AC_LIBOBJ(getopt) 167 | AC_LIBOBJ(getopt1) 168 | AC_LIBSOURCE(getopt.h) ]) 169 | 170 | dnl Check for strlcat and strlcpy. If we don't have them, use the replacement 171 | dnl functions from OpenBSD. Most modern C libraries have these functions, 172 | dnl but some such as as glibc don't. 173 | AC_CHECK_FUNC([strlcat], 174 | [AC_DEFINE(HAVE_STRLCAT, 1, [Define to 1 if the C library includes the strlcat function])], 175 | [AC_LIBOBJ(strlcat)]) 176 | AC_CHECK_FUNC([strlcpy], 177 | [AC_DEFINE(HAVE_STRLCPY, 1, [Define to 1 if the C library includes the strlcpy function])], 178 | [AC_LIBOBJ(strlcpy)]) 179 | 180 | AC_CONFIG_FILES([Makefile]) 181 | AC_OUTPUT 182 | -------------------------------------------------------------------------------- /error.c: -------------------------------------------------------------------------------- 1 | /* 2 | * The TCP Scanner (tcp-scan) is Copyright (C) 2003-2008 Roy Hills, 3 | * NTA Monitor Ltd. 4 | * 5 | * This file is part of tcp-scan. 6 | * 7 | * tcp-scan 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 | * tcp-scan 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 tcp-scan. If not, see . 19 | * 20 | * error.c -- error routines for tcp-scan 21 | * 22 | * Author: Roy Hills 23 | * Date: 1 December 2001 24 | */ 25 | 26 | #include "tcp-scan.h" 27 | 28 | int daemon_proc; /* Non-zero if process is a daemon */ 29 | 30 | /* 31 | * Function to handle fatal system call errors. 32 | */ 33 | void 34 | err_sys(const char *fmt,...) { 35 | va_list ap; 36 | 37 | va_start(ap, fmt); 38 | err_print(1, fmt, ap); 39 | va_end(ap); 40 | exit(EXIT_FAILURE); 41 | } 42 | 43 | /* 44 | * Function to handle non-fatal system call errors. 45 | */ 46 | void 47 | warn_sys(const char *fmt,...) { 48 | va_list ap; 49 | 50 | va_start(ap, fmt); 51 | err_print(1, fmt, ap); 52 | va_end(ap); 53 | } 54 | 55 | /* 56 | * Function to handle fatal errors not from system calls. 57 | */ 58 | void 59 | err_msg(const char *fmt,...) { 60 | va_list ap; 61 | 62 | va_start(ap, fmt); 63 | err_print(0, fmt, ap); 64 | va_end(ap); 65 | exit(EXIT_FAILURE); 66 | } 67 | 68 | /* 69 | * Function to handle non-fatal errors not from system calls. 70 | */ 71 | void 72 | warn_msg(const char *fmt,...) { 73 | va_list ap; 74 | 75 | va_start(ap, fmt); 76 | err_print(0, fmt, ap); 77 | va_end(ap); 78 | } 79 | 80 | /* 81 | * General error printing function used by all the above 82 | * functions. 83 | */ 84 | void 85 | err_print (int errnoflag, const char *fmt, va_list ap) { 86 | int errno_save; 87 | size_t n; 88 | char buf[MAXLINE]; 89 | 90 | errno_save=errno; 91 | 92 | vsnprintf(buf, MAXLINE, fmt, ap); 93 | n=strlen(buf); 94 | if (errnoflag) 95 | snprintf(buf+n, MAXLINE-n, ": %s", strerror(errno_save)); 96 | strlcat(buf, "\n", sizeof(buf)); 97 | 98 | fflush(stdout); /* In case stdout and stderr are the same */ 99 | fputs(buf, stderr); 100 | fflush(stderr); 101 | } 102 | -------------------------------------------------------------------------------- /getopt.c: -------------------------------------------------------------------------------- 1 | /* Getopt for GNU. 2 | NOTE: getopt is now part of the C library, so if you don't know what 3 | "Keep this file name-space clean" means, talk to drepper@gnu.org 4 | before changing it! 5 | Copyright (C) 1987,88,89,90,91,92,93,94,95,96,98,99,2000,2001,2002 6 | Free Software Foundation, Inc. 7 | This file is part of the GNU C Library. 8 | 9 | The GNU C Library is free software; you can redistribute it and/or 10 | modify it under the terms of the GNU Lesser General Public 11 | License as published by the Free Software Foundation; either 12 | version 2.1 of the License, or (at your option) any later version. 13 | 14 | The GNU C Library is distributed in the hope that it will be useful, 15 | but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 17 | Lesser General Public License for more details. 18 | 19 | You should have received a copy of the GNU Lesser General Public 20 | License along with the GNU C Library; if not, write to the Free 21 | Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 22 | 02111-1307 USA. */ 23 | 24 | /* This tells Alpha OSF/1 not to define a getopt prototype in . 25 | Ditto for AIX 3.2 and . */ 26 | #ifndef _NO_PROTO 27 | # define _NO_PROTO 28 | #endif 29 | 30 | #ifdef HAVE_CONFIG_H 31 | # include 32 | #endif 33 | 34 | #if !defined __STDC__ || !__STDC__ 35 | /* This is a separate conditional since some stdc systems 36 | reject `defined (const)'. */ 37 | # ifndef const 38 | # define const 39 | # endif 40 | #endif 41 | 42 | #include 43 | 44 | /* Comment out all this code if we are using the GNU C Library, and are not 45 | actually compiling the library itself. This code is part of the GNU C 46 | Library, but also included in many other GNU distributions. Compiling 47 | and linking in this code is a waste when using the GNU C library 48 | (especially if it is a shared library). Rather than having every GNU 49 | program understand `configure --with-gnu-libc' and omit the object files, 50 | it is simpler to just do this in the source for each such file. */ 51 | 52 | #define GETOPT_INTERFACE_VERSION 2 53 | #if !defined _LIBC && defined __GLIBC__ && __GLIBC__ >= 2 54 | # include 55 | # if _GNU_GETOPT_INTERFACE_VERSION == GETOPT_INTERFACE_VERSION 56 | # define ELIDE_CODE 57 | # endif 58 | #endif 59 | 60 | #ifndef ELIDE_CODE 61 | 62 | 63 | /* This needs to come after some library #include 64 | to get __GNU_LIBRARY__ defined. */ 65 | #ifdef __GNU_LIBRARY__ 66 | /* Don't include stdlib.h for non-GNU C libraries because some of them 67 | contain conflicting prototypes for getopt. */ 68 | # include 69 | # include 70 | #endif /* GNU C library. */ 71 | 72 | #ifdef VMS 73 | # include 74 | # if HAVE_STRING_H - 0 75 | # include 76 | # endif 77 | #endif 78 | 79 | #ifndef _ 80 | /* This is for other GNU distributions with internationalized messages. */ 81 | # if (HAVE_LIBINTL_H && ENABLE_NLS) || defined _LIBC 82 | # include 83 | # ifndef _ 84 | # define _(msgid) gettext (msgid) 85 | # endif 86 | # else 87 | # define _(msgid) (msgid) 88 | # endif 89 | # if defined _LIBC && defined USE_IN_LIBIO 90 | # include 91 | # endif 92 | #endif 93 | 94 | #ifndef attribute_hidden 95 | # define attribute_hidden 96 | #endif 97 | 98 | /* This version of `getopt' appears to the caller like standard Unix `getopt' 99 | but it behaves differently for the user, since it allows the user 100 | to intersperse the options with the other arguments. 101 | 102 | As `getopt' works, it permutes the elements of ARGV so that, 103 | when it is done, all the options precede everything else. Thus 104 | all application programs are extended to handle flexible argument order. 105 | 106 | Setting the environment variable POSIXLY_CORRECT disables permutation. 107 | Then the behavior is completely standard. 108 | 109 | GNU application programs can use a third alternative mode in which 110 | they can distinguish the relative order of options and other arguments. */ 111 | 112 | #include "getopt.h" 113 | 114 | /* For communication from `getopt' to the caller. 115 | When `getopt' finds an option that takes an argument, 116 | the argument value is returned here. 117 | Also, when `ordering' is RETURN_IN_ORDER, 118 | each non-option ARGV-element is returned here. */ 119 | 120 | char *optarg; 121 | 122 | /* Index in ARGV of the next element to be scanned. 123 | This is used for communication to and from the caller 124 | and for communication between successive calls to `getopt'. 125 | 126 | On entry to `getopt', zero means this is the first call; initialize. 127 | 128 | When `getopt' returns -1, this is the index of the first of the 129 | non-option elements that the caller should itself scan. 130 | 131 | Otherwise, `optind' communicates from one call to the next 132 | how much of ARGV has been scanned so far. */ 133 | 134 | /* 1003.2 says this must be 1 before any call. */ 135 | int optind = 1; 136 | 137 | /* Formerly, initialization of getopt depended on optind==0, which 138 | causes problems with re-calling getopt as programs generally don't 139 | know that. */ 140 | 141 | int __getopt_initialized attribute_hidden; 142 | 143 | /* The next char to be scanned in the option-element 144 | in which the last option character we returned was found. 145 | This allows us to pick up the scan where we left off. 146 | 147 | If this is zero, or a null string, it means resume the scan 148 | by advancing to the next ARGV-element. */ 149 | 150 | static char *nextchar; 151 | 152 | /* Callers store zero here to inhibit the error message 153 | for unrecognized options. */ 154 | 155 | int opterr = 1; 156 | 157 | /* Set to an option character which was unrecognized. 158 | This must be initialized on some systems to avoid linking in the 159 | system's own getopt implementation. */ 160 | 161 | int optopt = '?'; 162 | 163 | /* Describe how to deal with options that follow non-option ARGV-elements. 164 | 165 | If the caller did not specify anything, 166 | the default is REQUIRE_ORDER if the environment variable 167 | POSIXLY_CORRECT is defined, PERMUTE otherwise. 168 | 169 | REQUIRE_ORDER means don't recognize them as options; 170 | stop option processing when the first non-option is seen. 171 | This is what Unix does. 172 | This mode of operation is selected by either setting the environment 173 | variable POSIXLY_CORRECT, or using `+' as the first character 174 | of the list of option characters. 175 | 176 | PERMUTE is the default. We permute the contents of ARGV as we scan, 177 | so that eventually all the non-options are at the end. This allows options 178 | to be given in any order, even with programs that were not written to 179 | expect this. 180 | 181 | RETURN_IN_ORDER is an option available to programs that were written 182 | to expect options and other ARGV-elements in any order and that care about 183 | the ordering of the two. We describe each non-option ARGV-element 184 | as if it were the argument of an option with character code 1. 185 | Using `-' as the first character of the list of option characters 186 | selects this mode of operation. 187 | 188 | The special argument `--' forces an end of option-scanning regardless 189 | of the value of `ordering'. In the case of RETURN_IN_ORDER, only 190 | `--' can cause `getopt' to return -1 with `optind' != ARGC. */ 191 | 192 | static enum 193 | { 194 | REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER 195 | } ordering; 196 | 197 | /* Value of POSIXLY_CORRECT environment variable. */ 198 | static char *posixly_correct; 199 | 200 | #ifdef __GNU_LIBRARY__ 201 | /* We want to avoid inclusion of string.h with non-GNU libraries 202 | because there are many ways it can cause trouble. 203 | On some systems, it contains special magic macros that don't work 204 | in GCC. */ 205 | # include 206 | # define my_index strchr 207 | #else 208 | 209 | # if HAVE_STRING_H 210 | # include 211 | # else 212 | # include 213 | # endif 214 | 215 | /* Avoid depending on library functions or files 216 | whose names are inconsistent. */ 217 | 218 | #ifndef getenv 219 | extern char *getenv (); 220 | #endif 221 | 222 | static char * 223 | my_index (str, chr) 224 | const char *str; 225 | int chr; 226 | { 227 | while (*str) 228 | { 229 | if (*str == chr) 230 | return (char *) str; 231 | str++; 232 | } 233 | return 0; 234 | } 235 | 236 | /* If using GCC, we can safely declare strlen this way. 237 | If not using GCC, it is ok not to declare it. */ 238 | #ifdef __GNUC__ 239 | /* Note that Motorola Delta 68k R3V7 comes with GCC but not stddef.h. 240 | That was relevant to code that was here before. */ 241 | # if (!defined __STDC__ || !__STDC__) && !defined strlen 242 | /* gcc with -traditional declares the built-in strlen to return int, 243 | and has done so at least since version 2.4.5. -- rms. */ 244 | extern int strlen (const char *); 245 | # endif /* not __STDC__ */ 246 | #endif /* __GNUC__ */ 247 | 248 | #endif /* not __GNU_LIBRARY__ */ 249 | 250 | /* Handle permutation of arguments. */ 251 | 252 | /* Describe the part of ARGV that contains non-options that have 253 | been skipped. `first_nonopt' is the index in ARGV of the first of them; 254 | `last_nonopt' is the index after the last of them. */ 255 | 256 | static int first_nonopt; 257 | static int last_nonopt; 258 | 259 | #ifdef _LIBC 260 | /* Stored original parameters. 261 | XXX This is no good solution. We should rather copy the args so 262 | that we can compare them later. But we must not use malloc(3). */ 263 | extern int __libc_argc; 264 | extern char **__libc_argv; 265 | 266 | /* Bash 2.0 gives us an environment variable containing flags 267 | indicating ARGV elements that should not be considered arguments. */ 268 | 269 | # ifdef USE_NONOPTION_FLAGS 270 | /* Defined in getopt_init.c */ 271 | extern char *__getopt_nonoption_flags; 272 | 273 | static int nonoption_flags_max_len; 274 | static int nonoption_flags_len; 275 | # endif 276 | 277 | # ifdef USE_NONOPTION_FLAGS 278 | # define SWAP_FLAGS(ch1, ch2) \ 279 | if (nonoption_flags_len > 0) \ 280 | { \ 281 | char __tmp = __getopt_nonoption_flags[ch1]; \ 282 | __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2]; \ 283 | __getopt_nonoption_flags[ch2] = __tmp; \ 284 | } 285 | # else 286 | # define SWAP_FLAGS(ch1, ch2) 287 | # endif 288 | #else /* !_LIBC */ 289 | # define SWAP_FLAGS(ch1, ch2) 290 | #endif /* _LIBC */ 291 | 292 | /* Exchange two adjacent subsequences of ARGV. 293 | One subsequence is elements [first_nonopt,last_nonopt) 294 | which contains all the non-options that have been skipped so far. 295 | The other is elements [last_nonopt,optind), which contains all 296 | the options processed since those non-options were skipped. 297 | 298 | `first_nonopt' and `last_nonopt' are relocated so that they describe 299 | the new indices of the non-options in ARGV after they are moved. */ 300 | 301 | #if defined __STDC__ && __STDC__ 302 | static void exchange (char **); 303 | #endif 304 | 305 | static void 306 | exchange (argv) 307 | char **argv; 308 | { 309 | int bottom = first_nonopt; 310 | int middle = last_nonopt; 311 | int top = optind; 312 | char *tem; 313 | 314 | /* Exchange the shorter segment with the far end of the longer segment. 315 | That puts the shorter segment into the right place. 316 | It leaves the longer segment in the right place overall, 317 | but it consists of two parts that need to be swapped next. */ 318 | 319 | #if defined _LIBC && defined USE_NONOPTION_FLAGS 320 | /* First make sure the handling of the `__getopt_nonoption_flags' 321 | string can work normally. Our top argument must be in the range 322 | of the string. */ 323 | if (nonoption_flags_len > 0 && top >= nonoption_flags_max_len) 324 | { 325 | /* We must extend the array. The user plays games with us and 326 | presents new arguments. */ 327 | char *new_str = malloc (top + 1); 328 | if (new_str == NULL) 329 | nonoption_flags_len = nonoption_flags_max_len = 0; 330 | else 331 | { 332 | memset (__mempcpy (new_str, __getopt_nonoption_flags, 333 | nonoption_flags_max_len), 334 | '\0', top + 1 - nonoption_flags_max_len); 335 | nonoption_flags_max_len = top + 1; 336 | __getopt_nonoption_flags = new_str; 337 | } 338 | } 339 | #endif 340 | 341 | while (top > middle && middle > bottom) 342 | { 343 | if (top - middle > middle - bottom) 344 | { 345 | /* Bottom segment is the short one. */ 346 | int len = middle - bottom; 347 | register int i; 348 | 349 | /* Swap it with the top part of the top segment. */ 350 | for (i = 0; i < len; i++) 351 | { 352 | tem = argv[bottom + i]; 353 | argv[bottom + i] = argv[top - (middle - bottom) + i]; 354 | argv[top - (middle - bottom) + i] = tem; 355 | SWAP_FLAGS (bottom + i, top - (middle - bottom) + i); 356 | } 357 | /* Exclude the moved bottom segment from further swapping. */ 358 | top -= len; 359 | } 360 | else 361 | { 362 | /* Top segment is the short one. */ 363 | int len = top - middle; 364 | register int i; 365 | 366 | /* Swap it with the bottom part of the bottom segment. */ 367 | for (i = 0; i < len; i++) 368 | { 369 | tem = argv[bottom + i]; 370 | argv[bottom + i] = argv[middle + i]; 371 | argv[middle + i] = tem; 372 | SWAP_FLAGS (bottom + i, middle + i); 373 | } 374 | /* Exclude the moved top segment from further swapping. */ 375 | bottom += len; 376 | } 377 | } 378 | 379 | /* Update records for the slots the non-options now occupy. */ 380 | 381 | first_nonopt += (optind - last_nonopt); 382 | last_nonopt = optind; 383 | } 384 | 385 | /* Initialize the internal data when the first call is made. */ 386 | 387 | #if defined __STDC__ && __STDC__ 388 | static const char *_getopt_initialize (int, char *const *, const char *); 389 | #endif 390 | static const char * 391 | _getopt_initialize (argc, argv, optstring) 392 | int argc; 393 | char *const *argv; 394 | const char *optstring; 395 | { 396 | /* Start processing options with ARGV-element 1 (since ARGV-element 0 397 | is the program name); the sequence of previously skipped 398 | non-option ARGV-elements is empty. */ 399 | 400 | first_nonopt = last_nonopt = optind; 401 | 402 | nextchar = NULL; 403 | 404 | posixly_correct = getenv ("POSIXLY_CORRECT"); 405 | 406 | /* Determine how to handle the ordering of options and nonoptions. */ 407 | 408 | if (optstring[0] == '-') 409 | { 410 | ordering = RETURN_IN_ORDER; 411 | ++optstring; 412 | } 413 | else if (optstring[0] == '+') 414 | { 415 | ordering = REQUIRE_ORDER; 416 | ++optstring; 417 | } 418 | else if (posixly_correct != NULL) 419 | ordering = REQUIRE_ORDER; 420 | else 421 | ordering = PERMUTE; 422 | 423 | #if defined _LIBC && defined USE_NONOPTION_FLAGS 424 | if (posixly_correct == NULL 425 | && argc == __libc_argc && argv == __libc_argv) 426 | { 427 | if (nonoption_flags_max_len == 0) 428 | { 429 | if (__getopt_nonoption_flags == NULL 430 | || __getopt_nonoption_flags[0] == '\0') 431 | nonoption_flags_max_len = -1; 432 | else 433 | { 434 | const char *orig_str = __getopt_nonoption_flags; 435 | int len = nonoption_flags_max_len = strlen (orig_str); 436 | if (nonoption_flags_max_len < argc) 437 | nonoption_flags_max_len = argc; 438 | __getopt_nonoption_flags = 439 | (char *) malloc (nonoption_flags_max_len); 440 | if (__getopt_nonoption_flags == NULL) 441 | nonoption_flags_max_len = -1; 442 | else 443 | memset (__mempcpy (__getopt_nonoption_flags, orig_str, len), 444 | '\0', nonoption_flags_max_len - len); 445 | } 446 | } 447 | nonoption_flags_len = nonoption_flags_max_len; 448 | } 449 | else 450 | nonoption_flags_len = 0; 451 | #endif 452 | 453 | return optstring; 454 | } 455 | 456 | /* Scan elements of ARGV (whose length is ARGC) for option characters 457 | given in OPTSTRING. 458 | 459 | If an element of ARGV starts with '-', and is not exactly "-" or "--", 460 | then it is an option element. The characters of this element 461 | (aside from the initial '-') are option characters. If `getopt' 462 | is called repeatedly, it returns successively each of the option characters 463 | from each of the option elements. 464 | 465 | If `getopt' finds another option character, it returns that character, 466 | updating `optind' and `nextchar' so that the next call to `getopt' can 467 | resume the scan with the following option character or ARGV-element. 468 | 469 | If there are no more option characters, `getopt' returns -1. 470 | Then `optind' is the index in ARGV of the first ARGV-element 471 | that is not an option. (The ARGV-elements have been permuted 472 | so that those that are not options now come last.) 473 | 474 | OPTSTRING is a string containing the legitimate option characters. 475 | If an option character is seen that is not listed in OPTSTRING, 476 | return '?' after printing an error message. If you set `opterr' to 477 | zero, the error message is suppressed but we still return '?'. 478 | 479 | If a char in OPTSTRING is followed by a colon, that means it wants an arg, 480 | so the following text in the same ARGV-element, or the text of the following 481 | ARGV-element, is returned in `optarg'. Two colons mean an option that 482 | wants an optional arg; if there is text in the current ARGV-element, 483 | it is returned in `optarg', otherwise `optarg' is set to zero. 484 | 485 | If OPTSTRING starts with `-' or `+', it requests different methods of 486 | handling the non-option ARGV-elements. 487 | See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above. 488 | 489 | Long-named options begin with `--' instead of `-'. 490 | Their names may be abbreviated as long as the abbreviation is unique 491 | or is an exact match for some defined option. If they have an 492 | argument, it follows the option name in the same ARGV-element, separated 493 | from the option name by a `=', or else the in next ARGV-element. 494 | When `getopt' finds a long-named option, it returns 0 if that option's 495 | `flag' field is nonzero, the value of the option's `val' field 496 | if the `flag' field is zero. 497 | 498 | The elements of ARGV aren't really const, because we permute them. 499 | But we pretend they're const in the prototype to be compatible 500 | with other systems. 501 | 502 | LONGOPTS is a vector of `struct option' terminated by an 503 | element containing a name which is zero. 504 | 505 | LONGIND returns the index in LONGOPT of the long-named option found. 506 | It is only valid when a long-named option has been found by the most 507 | recent call. 508 | 509 | If LONG_ONLY is nonzero, '-' as well as '--' can introduce 510 | long-named options. */ 511 | 512 | int 513 | _getopt_internal (argc, argv, optstring, longopts, longind, long_only) 514 | int argc; 515 | char *const *argv; 516 | const char *optstring; 517 | const struct option *longopts; 518 | int *longind; 519 | int long_only; 520 | { 521 | int print_errors = opterr; 522 | if (optstring[0] == ':') 523 | print_errors = 0; 524 | 525 | if (argc < 1) 526 | return -1; 527 | 528 | optarg = NULL; 529 | 530 | if (optind == 0 || !__getopt_initialized) 531 | { 532 | if (optind == 0) 533 | optind = 1; /* Don't scan ARGV[0], the program name. */ 534 | optstring = _getopt_initialize (argc, argv, optstring); 535 | __getopt_initialized = 1; 536 | } 537 | 538 | /* Test whether ARGV[optind] points to a non-option argument. 539 | Either it does not have option syntax, or there is an environment flag 540 | from the shell indicating it is not an option. The later information 541 | is only used when the used in the GNU libc. */ 542 | #if defined _LIBC && defined USE_NONOPTION_FLAGS 543 | # define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0' \ 544 | || (optind < nonoption_flags_len \ 545 | && __getopt_nonoption_flags[optind] == '1')) 546 | #else 547 | # define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0') 548 | #endif 549 | 550 | if (nextchar == NULL || *nextchar == '\0') 551 | { 552 | /* Advance to the next ARGV-element. */ 553 | 554 | /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been 555 | moved back by the user (who may also have changed the arguments). */ 556 | if (last_nonopt > optind) 557 | last_nonopt = optind; 558 | if (first_nonopt > optind) 559 | first_nonopt = optind; 560 | 561 | if (ordering == PERMUTE) 562 | { 563 | /* If we have just processed some options following some non-options, 564 | exchange them so that the options come first. */ 565 | 566 | if (first_nonopt != last_nonopt && last_nonopt != optind) 567 | exchange ((char **) argv); 568 | else if (last_nonopt != optind) 569 | first_nonopt = optind; 570 | 571 | /* Skip any additional non-options 572 | and extend the range of non-options previously skipped. */ 573 | 574 | while (optind < argc && NONOPTION_P) 575 | optind++; 576 | last_nonopt = optind; 577 | } 578 | 579 | /* The special ARGV-element `--' means premature end of options. 580 | Skip it like a null option, 581 | then exchange with previous non-options as if it were an option, 582 | then skip everything else like a non-option. */ 583 | 584 | if (optind != argc && !strcmp (argv[optind], "--")) 585 | { 586 | optind++; 587 | 588 | if (first_nonopt != last_nonopt && last_nonopt != optind) 589 | exchange ((char **) argv); 590 | else if (first_nonopt == last_nonopt) 591 | first_nonopt = optind; 592 | last_nonopt = argc; 593 | 594 | optind = argc; 595 | } 596 | 597 | /* If we have done all the ARGV-elements, stop the scan 598 | and back over any non-options that we skipped and permuted. */ 599 | 600 | if (optind == argc) 601 | { 602 | /* Set the next-arg-index to point at the non-options 603 | that we previously skipped, so the caller will digest them. */ 604 | if (first_nonopt != last_nonopt) 605 | optind = first_nonopt; 606 | return -1; 607 | } 608 | 609 | /* If we have come to a non-option and did not permute it, 610 | either stop the scan or describe it to the caller and pass it by. */ 611 | 612 | if (NONOPTION_P) 613 | { 614 | if (ordering == REQUIRE_ORDER) 615 | return -1; 616 | optarg = argv[optind++]; 617 | return 1; 618 | } 619 | 620 | /* We have found another option-ARGV-element. 621 | Skip the initial punctuation. */ 622 | 623 | nextchar = (argv[optind] + 1 624 | + (longopts != NULL && argv[optind][1] == '-')); 625 | } 626 | 627 | /* Decode the current option-ARGV-element. */ 628 | 629 | /* Check whether the ARGV-element is a long option. 630 | 631 | If long_only and the ARGV-element has the form "-f", where f is 632 | a valid short option, don't consider it an abbreviated form of 633 | a long option that starts with f. Otherwise there would be no 634 | way to give the -f short option. 635 | 636 | On the other hand, if there's a long option "fubar" and 637 | the ARGV-element is "-fu", do consider that an abbreviation of 638 | the long option, just like "--fu", and not "-f" with arg "u". 639 | 640 | This distinction seems to be the most useful approach. */ 641 | 642 | if (longopts != NULL 643 | && (argv[optind][1] == '-' 644 | || (long_only && (argv[optind][2] || !my_index (optstring, argv[optind][1]))))) 645 | { 646 | char *nameend; 647 | const struct option *p; 648 | const struct option *pfound = NULL; 649 | int exact = 0; 650 | int ambig = 0; 651 | int indfound = -1; 652 | int option_index; 653 | 654 | for (nameend = nextchar; *nameend && *nameend != '='; nameend++) 655 | /* Do nothing. */ ; 656 | 657 | /* Test all long options for either exact match 658 | or abbreviated matches. */ 659 | for (p = longopts, option_index = 0; p->name; p++, option_index++) 660 | if (!strncmp (p->name, nextchar, nameend - nextchar)) 661 | { 662 | if ((unsigned int) (nameend - nextchar) 663 | == (unsigned int) strlen (p->name)) 664 | { 665 | /* Exact match found. */ 666 | pfound = p; 667 | indfound = option_index; 668 | exact = 1; 669 | break; 670 | } 671 | else if (pfound == NULL) 672 | { 673 | /* First nonexact match found. */ 674 | pfound = p; 675 | indfound = option_index; 676 | } 677 | else if (long_only 678 | || pfound->has_arg != p->has_arg 679 | || pfound->flag != p->flag 680 | || pfound->val != p->val) 681 | /* Second or later nonexact match found. */ 682 | ambig = 1; 683 | } 684 | 685 | if (ambig && !exact) 686 | { 687 | if (print_errors) 688 | { 689 | #if defined _LIBC && defined USE_IN_LIBIO 690 | char *buf; 691 | 692 | if (__asprintf (&buf, _("%s: option `%s' is ambiguous\n"), 693 | argv[0], argv[optind]) >= 0) 694 | { 695 | 696 | if (_IO_fwide (stderr, 0) > 0) 697 | __fwprintf (stderr, L"%s", buf); 698 | else 699 | fputs (buf, stderr); 700 | 701 | free (buf); 702 | } 703 | #else 704 | fprintf (stderr, _("%s: option `%s' is ambiguous\n"), 705 | argv[0], argv[optind]); 706 | #endif 707 | } 708 | nextchar += strlen (nextchar); 709 | optind++; 710 | optopt = 0; 711 | return '?'; 712 | } 713 | 714 | if (pfound != NULL) 715 | { 716 | option_index = indfound; 717 | optind++; 718 | if (*nameend) 719 | { 720 | /* Don't test has_arg with >, because some C compilers don't 721 | allow it to be used on enums. */ 722 | if (pfound->has_arg) 723 | optarg = nameend + 1; 724 | else 725 | { 726 | if (print_errors) 727 | { 728 | #if defined _LIBC && defined USE_IN_LIBIO 729 | char *buf; 730 | int n; 731 | #endif 732 | 733 | if (argv[optind - 1][1] == '-') 734 | { 735 | /* --option */ 736 | #if defined _LIBC && defined USE_IN_LIBIO 737 | n = __asprintf (&buf, _("\ 738 | %s: option `--%s' doesn't allow an argument\n"), 739 | argv[0], pfound->name); 740 | #else 741 | fprintf (stderr, _("\ 742 | %s: option `--%s' doesn't allow an argument\n"), 743 | argv[0], pfound->name); 744 | #endif 745 | } 746 | else 747 | { 748 | /* +option or -option */ 749 | #if defined _LIBC && defined USE_IN_LIBIO 750 | n = __asprintf (&buf, _("\ 751 | %s: option `%c%s' doesn't allow an argument\n"), 752 | argv[0], argv[optind - 1][0], 753 | pfound->name); 754 | #else 755 | fprintf (stderr, _("\ 756 | %s: option `%c%s' doesn't allow an argument\n"), 757 | argv[0], argv[optind - 1][0], pfound->name); 758 | #endif 759 | } 760 | 761 | #if defined _LIBC && defined USE_IN_LIBIO 762 | if (n >= 0) 763 | { 764 | if (_IO_fwide (stderr, 0) > 0) 765 | __fwprintf (stderr, L"%s", buf); 766 | else 767 | fputs (buf, stderr); 768 | 769 | free (buf); 770 | } 771 | #endif 772 | } 773 | 774 | nextchar += strlen (nextchar); 775 | 776 | optopt = pfound->val; 777 | return '?'; 778 | } 779 | } 780 | else if (pfound->has_arg == 1) 781 | { 782 | if (optind < argc) 783 | optarg = argv[optind++]; 784 | else 785 | { 786 | if (print_errors) 787 | { 788 | #if defined _LIBC && defined USE_IN_LIBIO 789 | char *buf; 790 | 791 | if (__asprintf (&buf, _("\ 792 | %s: option `%s' requires an argument\n"), 793 | argv[0], argv[optind - 1]) >= 0) 794 | { 795 | if (_IO_fwide (stderr, 0) > 0) 796 | __fwprintf (stderr, L"%s", buf); 797 | else 798 | fputs (buf, stderr); 799 | 800 | free (buf); 801 | } 802 | #else 803 | fprintf (stderr, 804 | _("%s: option `%s' requires an argument\n"), 805 | argv[0], argv[optind - 1]); 806 | #endif 807 | } 808 | nextchar += strlen (nextchar); 809 | optopt = pfound->val; 810 | return optstring[0] == ':' ? ':' : '?'; 811 | } 812 | } 813 | nextchar += strlen (nextchar); 814 | if (longind != NULL) 815 | *longind = option_index; 816 | if (pfound->flag) 817 | { 818 | *(pfound->flag) = pfound->val; 819 | return 0; 820 | } 821 | return pfound->val; 822 | } 823 | 824 | /* Can't find it as a long option. If this is not getopt_long_only, 825 | or the option starts with '--' or is not a valid short 826 | option, then it's an error. 827 | Otherwise interpret it as a short option. */ 828 | if (!long_only || argv[optind][1] == '-' 829 | || my_index (optstring, *nextchar) == NULL) 830 | { 831 | if (print_errors) 832 | { 833 | #if defined _LIBC && defined USE_IN_LIBIO 834 | char *buf; 835 | int n; 836 | #endif 837 | 838 | if (argv[optind][1] == '-') 839 | { 840 | /* --option */ 841 | #if defined _LIBC && defined USE_IN_LIBIO 842 | n = __asprintf (&buf, _("%s: unrecognized option `--%s'\n"), 843 | argv[0], nextchar); 844 | #else 845 | fprintf (stderr, _("%s: unrecognized option `--%s'\n"), 846 | argv[0], nextchar); 847 | #endif 848 | } 849 | else 850 | { 851 | /* +option or -option */ 852 | #if defined _LIBC && defined USE_IN_LIBIO 853 | n = __asprintf (&buf, _("%s: unrecognized option `%c%s'\n"), 854 | argv[0], argv[optind][0], nextchar); 855 | #else 856 | fprintf (stderr, _("%s: unrecognized option `%c%s'\n"), 857 | argv[0], argv[optind][0], nextchar); 858 | #endif 859 | } 860 | 861 | #if defined _LIBC && defined USE_IN_LIBIO 862 | if (n >= 0) 863 | { 864 | if (_IO_fwide (stderr, 0) > 0) 865 | __fwprintf (stderr, L"%s", buf); 866 | else 867 | fputs (buf, stderr); 868 | 869 | free (buf); 870 | } 871 | #endif 872 | } 873 | nextchar = (char *) ""; 874 | optind++; 875 | optopt = 0; 876 | return '?'; 877 | } 878 | } 879 | 880 | /* Look at and handle the next short option-character. */ 881 | 882 | { 883 | char c = *nextchar++; 884 | char *temp = my_index (optstring, c); 885 | 886 | /* Increment `optind' when we start to process its last character. */ 887 | if (*nextchar == '\0') 888 | ++optind; 889 | 890 | if (temp == NULL || c == ':') 891 | { 892 | if (print_errors) 893 | { 894 | #if defined _LIBC && defined USE_IN_LIBIO 895 | char *buf; 896 | int n; 897 | #endif 898 | 899 | if (posixly_correct) 900 | { 901 | /* 1003.2 specifies the format of this message. */ 902 | #if defined _LIBC && defined USE_IN_LIBIO 903 | n = __asprintf (&buf, _("%s: illegal option -- %c\n"), 904 | argv[0], c); 905 | #else 906 | fprintf (stderr, _("%s: illegal option -- %c\n"), argv[0], c); 907 | #endif 908 | } 909 | else 910 | { 911 | #if defined _LIBC && defined USE_IN_LIBIO 912 | n = __asprintf (&buf, _("%s: invalid option -- %c\n"), 913 | argv[0], c); 914 | #else 915 | fprintf (stderr, _("%s: invalid option -- %c\n"), argv[0], c); 916 | #endif 917 | } 918 | 919 | #if defined _LIBC && defined USE_IN_LIBIO 920 | if (n >= 0) 921 | { 922 | if (_IO_fwide (stderr, 0) > 0) 923 | __fwprintf (stderr, L"%s", buf); 924 | else 925 | fputs (buf, stderr); 926 | 927 | free (buf); 928 | } 929 | #endif 930 | } 931 | optopt = c; 932 | return '?'; 933 | } 934 | /* Convenience. Treat POSIX -W foo same as long option --foo */ 935 | if (temp[0] == 'W' && temp[1] == ';') 936 | { 937 | char *nameend; 938 | const struct option *p; 939 | const struct option *pfound = NULL; 940 | int exact = 0; 941 | int ambig = 0; 942 | int indfound = 0; 943 | int option_index; 944 | 945 | /* This is an option that requires an argument. */ 946 | if (*nextchar != '\0') 947 | { 948 | optarg = nextchar; 949 | /* If we end this ARGV-element by taking the rest as an arg, 950 | we must advance to the next element now. */ 951 | optind++; 952 | } 953 | else if (optind == argc) 954 | { 955 | if (print_errors) 956 | { 957 | /* 1003.2 specifies the format of this message. */ 958 | #if defined _LIBC && defined USE_IN_LIBIO 959 | char *buf; 960 | 961 | if (__asprintf (&buf, 962 | _("%s: option requires an argument -- %c\n"), 963 | argv[0], c) >= 0) 964 | { 965 | if (_IO_fwide (stderr, 0) > 0) 966 | __fwprintf (stderr, L"%s", buf); 967 | else 968 | fputs (buf, stderr); 969 | 970 | free (buf); 971 | } 972 | #else 973 | fprintf (stderr, _("%s: option requires an argument -- %c\n"), 974 | argv[0], c); 975 | #endif 976 | } 977 | optopt = c; 978 | if (optstring[0] == ':') 979 | c = ':'; 980 | else 981 | c = '?'; 982 | return c; 983 | } 984 | else 985 | /* We already incremented `optind' once; 986 | increment it again when taking next ARGV-elt as argument. */ 987 | optarg = argv[optind++]; 988 | 989 | /* optarg is now the argument, see if it's in the 990 | table of longopts. */ 991 | 992 | for (nextchar = nameend = optarg; *nameend && *nameend != '='; nameend++) 993 | /* Do nothing. */ ; 994 | 995 | /* Test all long options for either exact match 996 | or abbreviated matches. */ 997 | for (p = longopts, option_index = 0; p->name; p++, option_index++) 998 | if (!strncmp (p->name, nextchar, nameend - nextchar)) 999 | { 1000 | if ((unsigned int) (nameend - nextchar) == strlen (p->name)) 1001 | { 1002 | /* Exact match found. */ 1003 | pfound = p; 1004 | indfound = option_index; 1005 | exact = 1; 1006 | break; 1007 | } 1008 | else if (pfound == NULL) 1009 | { 1010 | /* First nonexact match found. */ 1011 | pfound = p; 1012 | indfound = option_index; 1013 | } 1014 | else 1015 | /* Second or later nonexact match found. */ 1016 | ambig = 1; 1017 | } 1018 | if (ambig && !exact) 1019 | { 1020 | if (print_errors) 1021 | { 1022 | #if defined _LIBC && defined USE_IN_LIBIO 1023 | char *buf; 1024 | 1025 | if (__asprintf (&buf, _("%s: option `-W %s' is ambiguous\n"), 1026 | argv[0], argv[optind]) >= 0) 1027 | { 1028 | if (_IO_fwide (stderr, 0) > 0) 1029 | __fwprintf (stderr, L"%s", buf); 1030 | else 1031 | fputs (buf, stderr); 1032 | 1033 | free (buf); 1034 | } 1035 | #else 1036 | fprintf (stderr, _("%s: option `-W %s' is ambiguous\n"), 1037 | argv[0], argv[optind]); 1038 | #endif 1039 | } 1040 | nextchar += strlen (nextchar); 1041 | optind++; 1042 | return '?'; 1043 | } 1044 | if (pfound != NULL) 1045 | { 1046 | option_index = indfound; 1047 | if (*nameend) 1048 | { 1049 | /* Don't test has_arg with >, because some C compilers don't 1050 | allow it to be used on enums. */ 1051 | if (pfound->has_arg) 1052 | optarg = nameend + 1; 1053 | else 1054 | { 1055 | if (print_errors) 1056 | { 1057 | #if defined _LIBC && defined USE_IN_LIBIO 1058 | char *buf; 1059 | 1060 | if (__asprintf (&buf, _("\ 1061 | %s: option `-W %s' doesn't allow an argument\n"), 1062 | argv[0], pfound->name) >= 0) 1063 | { 1064 | if (_IO_fwide (stderr, 0) > 0) 1065 | __fwprintf (stderr, L"%s", buf); 1066 | else 1067 | fputs (buf, stderr); 1068 | 1069 | free (buf); 1070 | } 1071 | #else 1072 | fprintf (stderr, _("\ 1073 | %s: option `-W %s' doesn't allow an argument\n"), 1074 | argv[0], pfound->name); 1075 | #endif 1076 | } 1077 | 1078 | nextchar += strlen (nextchar); 1079 | return '?'; 1080 | } 1081 | } 1082 | else if (pfound->has_arg == 1) 1083 | { 1084 | if (optind < argc) 1085 | optarg = argv[optind++]; 1086 | else 1087 | { 1088 | if (print_errors) 1089 | { 1090 | #if defined _LIBC && defined USE_IN_LIBIO 1091 | char *buf; 1092 | 1093 | if (__asprintf (&buf, _("\ 1094 | %s: option `%s' requires an argument\n"), 1095 | argv[0], argv[optind - 1]) >= 0) 1096 | { 1097 | if (_IO_fwide (stderr, 0) > 0) 1098 | __fwprintf (stderr, L"%s", buf); 1099 | else 1100 | fputs (buf, stderr); 1101 | 1102 | free (buf); 1103 | } 1104 | #else 1105 | fprintf (stderr, 1106 | _("%s: option `%s' requires an argument\n"), 1107 | argv[0], argv[optind - 1]); 1108 | #endif 1109 | } 1110 | nextchar += strlen (nextchar); 1111 | return optstring[0] == ':' ? ':' : '?'; 1112 | } 1113 | } 1114 | nextchar += strlen (nextchar); 1115 | if (longind != NULL) 1116 | *longind = option_index; 1117 | if (pfound->flag) 1118 | { 1119 | *(pfound->flag) = pfound->val; 1120 | return 0; 1121 | } 1122 | return pfound->val; 1123 | } 1124 | nextchar = NULL; 1125 | return 'W'; /* Let the application handle it. */ 1126 | } 1127 | if (temp[1] == ':') 1128 | { 1129 | if (temp[2] == ':') 1130 | { 1131 | /* This is an option that accepts an argument optionally. */ 1132 | if (*nextchar != '\0') 1133 | { 1134 | optarg = nextchar; 1135 | optind++; 1136 | } 1137 | else 1138 | optarg = NULL; 1139 | nextchar = NULL; 1140 | } 1141 | else 1142 | { 1143 | /* This is an option that requires an argument. */ 1144 | if (*nextchar != '\0') 1145 | { 1146 | optarg = nextchar; 1147 | /* If we end this ARGV-element by taking the rest as an arg, 1148 | we must advance to the next element now. */ 1149 | optind++; 1150 | } 1151 | else if (optind == argc) 1152 | { 1153 | if (print_errors) 1154 | { 1155 | /* 1003.2 specifies the format of this message. */ 1156 | #if defined _LIBC && defined USE_IN_LIBIO 1157 | char *buf; 1158 | 1159 | if (__asprintf (&buf, _("\ 1160 | %s: option requires an argument -- %c\n"), 1161 | argv[0], c) >= 0) 1162 | { 1163 | if (_IO_fwide (stderr, 0) > 0) 1164 | __fwprintf (stderr, L"%s", buf); 1165 | else 1166 | fputs (buf, stderr); 1167 | 1168 | free (buf); 1169 | } 1170 | #else 1171 | fprintf (stderr, 1172 | _("%s: option requires an argument -- %c\n"), 1173 | argv[0], c); 1174 | #endif 1175 | } 1176 | optopt = c; 1177 | if (optstring[0] == ':') 1178 | c = ':'; 1179 | else 1180 | c = '?'; 1181 | } 1182 | else 1183 | /* We already incremented `optind' once; 1184 | increment it again when taking next ARGV-elt as argument. */ 1185 | optarg = argv[optind++]; 1186 | nextchar = NULL; 1187 | } 1188 | } 1189 | return c; 1190 | } 1191 | } 1192 | 1193 | int 1194 | getopt (argc, argv, optstring) 1195 | int argc; 1196 | char *const *argv; 1197 | const char *optstring; 1198 | { 1199 | return _getopt_internal (argc, argv, optstring, 1200 | (const struct option *) 0, 1201 | (int *) 0, 1202 | 0); 1203 | } 1204 | 1205 | #endif /* Not ELIDE_CODE. */ 1206 | 1207 | #ifdef TEST 1208 | 1209 | /* Compile with -DTEST to make an executable for use in testing 1210 | the above definition of `getopt'. */ 1211 | 1212 | int 1213 | main (argc, argv) 1214 | int argc; 1215 | char **argv; 1216 | { 1217 | int c; 1218 | int digit_optind = 0; 1219 | 1220 | while (1) 1221 | { 1222 | int this_option_optind = optind ? optind : 1; 1223 | 1224 | c = getopt (argc, argv, "abc:d:0123456789"); 1225 | if (c == -1) 1226 | break; 1227 | 1228 | switch (c) 1229 | { 1230 | case '0': 1231 | case '1': 1232 | case '2': 1233 | case '3': 1234 | case '4': 1235 | case '5': 1236 | case '6': 1237 | case '7': 1238 | case '8': 1239 | case '9': 1240 | if (digit_optind != 0 && digit_optind != this_option_optind) 1241 | printf ("digits occur in two different argv-elements.\n"); 1242 | digit_optind = this_option_optind; 1243 | printf ("option %c\n", c); 1244 | break; 1245 | 1246 | case 'a': 1247 | printf ("option a\n"); 1248 | break; 1249 | 1250 | case 'b': 1251 | printf ("option b\n"); 1252 | break; 1253 | 1254 | case 'c': 1255 | printf ("option c with value `%s'\n", optarg); 1256 | break; 1257 | 1258 | case '?': 1259 | break; 1260 | 1261 | default: 1262 | printf ("?? getopt returned character code 0%o ??\n", c); 1263 | } 1264 | } 1265 | 1266 | if (optind < argc) 1267 | { 1268 | printf ("non-option ARGV-elements: "); 1269 | while (optind < argc) 1270 | printf ("%s ", argv[optind++]); 1271 | printf ("\n"); 1272 | } 1273 | 1274 | exit (0); 1275 | } 1276 | 1277 | #endif /* TEST */ 1278 | -------------------------------------------------------------------------------- /getopt.h: -------------------------------------------------------------------------------- 1 | /* Declarations for getopt. 2 | Copyright (C) 1989-1994, 1996-1999, 2001 Free Software Foundation, Inc. 3 | This file is part of the GNU C Library. 4 | 5 | The GNU C Library is free software; you can redistribute it and/or 6 | modify it under the terms of the GNU Lesser General Public 7 | License as published by the Free Software Foundation; either 8 | version 2.1 of the License, or (at your option) any later version. 9 | 10 | The GNU C Library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with the GNU C Library; if not, write to the Free 17 | Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 18 | 02111-1307 USA. */ 19 | 20 | #ifndef _GETOPT_H 21 | 22 | #ifndef __need_getopt 23 | # define _GETOPT_H 1 24 | #endif 25 | 26 | /* If __GNU_LIBRARY__ is not already defined, either we are being used 27 | standalone, or this is the first header included in the source file. 28 | If we are being used with glibc, we need to include , but 29 | that does not exist if we are standalone. So: if __GNU_LIBRARY__ is 30 | not defined, include , which will pull in for us 31 | if it's from glibc. (Why ctype.h? It's guaranteed to exist and it 32 | doesn't flood the namespace with stuff the way some other headers do.) */ 33 | #if !defined __GNU_LIBRARY__ 34 | # include 35 | #endif 36 | 37 | #ifdef __cplusplus 38 | extern "C" { 39 | #endif 40 | 41 | /* For communication from `getopt' to the caller. 42 | When `getopt' finds an option that takes an argument, 43 | the argument value is returned here. 44 | Also, when `ordering' is RETURN_IN_ORDER, 45 | each non-option ARGV-element is returned here. */ 46 | 47 | extern char *optarg; 48 | 49 | /* Index in ARGV of the next element to be scanned. 50 | This is used for communication to and from the caller 51 | and for communication between successive calls to `getopt'. 52 | 53 | On entry to `getopt', zero means this is the first call; initialize. 54 | 55 | When `getopt' returns -1, this is the index of the first of the 56 | non-option elements that the caller should itself scan. 57 | 58 | Otherwise, `optind' communicates from one call to the next 59 | how much of ARGV has been scanned so far. */ 60 | 61 | extern int optind; 62 | 63 | /* Callers store zero here to inhibit the error message `getopt' prints 64 | for unrecognized options. */ 65 | 66 | extern int opterr; 67 | 68 | /* Set to an option character which was unrecognized. */ 69 | 70 | extern int optopt; 71 | 72 | #ifndef __need_getopt 73 | /* Describe the long-named options requested by the application. 74 | The LONG_OPTIONS argument to getopt_long or getopt_long_only is a vector 75 | of `struct option' terminated by an element containing a name which is 76 | zero. 77 | 78 | The field `has_arg' is: 79 | no_argument (or 0) if the option does not take an argument, 80 | required_argument (or 1) if the option requires an argument, 81 | optional_argument (or 2) if the option takes an optional argument. 82 | 83 | If the field `flag' is not NULL, it points to a variable that is set 84 | to the value given in the field `val' when the option is found, but 85 | left unchanged if the option is not found. 86 | 87 | To have a long-named option do something other than set an `int' to 88 | a compiled-in constant, such as set a value from `optarg', set the 89 | option's `flag' field to zero and its `val' field to a nonzero 90 | value (the equivalent single-letter option character, if there is 91 | one). For long options that have a zero `flag' field, `getopt' 92 | returns the contents of the `val' field. */ 93 | 94 | struct option 95 | { 96 | # if (defined __STDC__ && __STDC__) || defined __cplusplus 97 | const char *name; 98 | # else 99 | char *name; 100 | # endif 101 | /* has_arg can't be an enum because some compilers complain about 102 | type mismatches in all the code that assumes it is an int. */ 103 | int has_arg; 104 | int *flag; 105 | int val; 106 | }; 107 | 108 | /* Names for the values of the `has_arg' field of `struct option'. */ 109 | 110 | # define no_argument 0 111 | # define required_argument 1 112 | # define optional_argument 2 113 | #endif /* need getopt */ 114 | 115 | 116 | /* Get definitions and prototypes for functions to process the 117 | arguments in ARGV (ARGC of them, minus the program name) for 118 | options given in OPTS. 119 | 120 | Return the option character from OPTS just read. Return -1 when 121 | there are no more options. For unrecognized options, or options 122 | missing arguments, `optopt' is set to the option letter, and '?' is 123 | returned. 124 | 125 | The OPTS string is a list of characters which are recognized option 126 | letters, optionally followed by colons, specifying that that letter 127 | takes an argument, to be placed in `optarg'. 128 | 129 | If a letter in OPTS is followed by two colons, its argument is 130 | optional. This behavior is specific to the GNU `getopt'. 131 | 132 | The argument `--' causes premature termination of argument 133 | scanning, explicitly telling `getopt' that there are no more 134 | options. 135 | 136 | If OPTS begins with `--', then non-option arguments are treated as 137 | arguments to the option '\0'. This behavior is specific to the GNU 138 | `getopt'. */ 139 | 140 | #if (defined __STDC__ && __STDC__) || defined __cplusplus 141 | # ifdef __GNU_LIBRARY__ 142 | /* Many other libraries have conflicting prototypes for getopt, with 143 | differences in the consts, in stdlib.h. To avoid compilation 144 | errors, only prototype getopt for the GNU C library. */ 145 | extern int getopt (int ___argc, char *const *___argv, const char *__shortopts); 146 | # else /* not __GNU_LIBRARY__ */ 147 | extern int getopt (); 148 | # endif /* __GNU_LIBRARY__ */ 149 | 150 | # ifndef __need_getopt 151 | extern int getopt_long (int ___argc, char *const *___argv, 152 | const char *__shortopts, 153 | const struct option *__longopts, int *__longind); 154 | extern int getopt_long_only (int ___argc, char *const *___argv, 155 | const char *__shortopts, 156 | const struct option *__longopts, int *__longind); 157 | 158 | /* Internal only. Users should not call this directly. */ 159 | extern int _getopt_internal (int ___argc, char *const *___argv, 160 | const char *__shortopts, 161 | const struct option *__longopts, int *__longind, 162 | int __long_only); 163 | # endif 164 | #else /* not __STDC__ */ 165 | extern int getopt (); 166 | # ifndef __need_getopt 167 | extern int getopt_long (); 168 | extern int getopt_long_only (); 169 | 170 | extern int _getopt_internal (); 171 | # endif 172 | #endif /* __STDC__ */ 173 | 174 | #ifdef __cplusplus 175 | } 176 | #endif 177 | 178 | /* Make sure we later can get all the definitions and declarations. */ 179 | #undef __need_getopt 180 | 181 | #endif /* getopt.h */ 182 | -------------------------------------------------------------------------------- /getopt1.c: -------------------------------------------------------------------------------- 1 | /* getopt_long and getopt_long_only entry points for GNU getopt. 2 | Copyright (C) 1987,88,89,90,91,92,93,94,96,97,98 3 | Free Software Foundation, Inc. 4 | This file is part of the GNU C Library. 5 | 6 | The GNU C Library is free software; you can redistribute it and/or 7 | modify it under the terms of the GNU Lesser General Public 8 | License as published by the Free Software Foundation; either 9 | version 2.1 of the License, or (at your option) any later version. 10 | 11 | The GNU C Library is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 14 | Lesser General Public License for more details. 15 | 16 | You should have received a copy of the GNU Lesser General Public 17 | License along with the GNU C Library; if not, write to the Free 18 | Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 19 | 02111-1307 USA. */ 20 | 21 | #ifdef HAVE_CONFIG_H 22 | #include 23 | #endif 24 | 25 | #ifdef _LIBC 26 | # include 27 | #else 28 | # include "getopt.h" 29 | #endif 30 | 31 | #if !defined __STDC__ || !__STDC__ 32 | /* This is a separate conditional since some stdc systems 33 | reject `defined (const)'. */ 34 | #ifndef const 35 | #define const 36 | #endif 37 | #endif 38 | 39 | #include 40 | 41 | /* Comment out all this code if we are using the GNU C Library, and are not 42 | actually compiling the library itself. This code is part of the GNU C 43 | Library, but also included in many other GNU distributions. Compiling 44 | and linking in this code is a waste when using the GNU C library 45 | (especially if it is a shared library). Rather than having every GNU 46 | program understand `configure --with-gnu-libc' and omit the object files, 47 | it is simpler to just do this in the source for each such file. */ 48 | 49 | #define GETOPT_INTERFACE_VERSION 2 50 | #if !defined _LIBC && defined __GLIBC__ && __GLIBC__ >= 2 51 | #include 52 | #if _GNU_GETOPT_INTERFACE_VERSION == GETOPT_INTERFACE_VERSION 53 | #define ELIDE_CODE 54 | #endif 55 | #endif 56 | 57 | #ifndef ELIDE_CODE 58 | 59 | 60 | /* This needs to come after some library #include 61 | to get __GNU_LIBRARY__ defined. */ 62 | #ifdef __GNU_LIBRARY__ 63 | #include 64 | #endif 65 | 66 | #ifndef NULL 67 | #define NULL 0 68 | #endif 69 | 70 | int 71 | getopt_long (argc, argv, options, long_options, opt_index) 72 | int argc; 73 | char *const *argv; 74 | const char *options; 75 | const struct option *long_options; 76 | int *opt_index; 77 | { 78 | return _getopt_internal (argc, argv, options, long_options, opt_index, 0); 79 | } 80 | 81 | /* Like getopt_long, but '-' as well as '--' can indicate a long option. 82 | If an option that starts with '-' (not '--') doesn't match a long option, 83 | but does match a short option, it is parsed as a short option 84 | instead. */ 85 | 86 | int 87 | getopt_long_only (argc, argv, options, long_options, opt_index) 88 | int argc; 89 | char *const *argv; 90 | const char *options; 91 | const struct option *long_options; 92 | int *opt_index; 93 | { 94 | return _getopt_internal (argc, argv, options, long_options, opt_index, 1); 95 | } 96 | 97 | # ifdef _LIBC 98 | libc_hidden_def (getopt_long) 99 | libc_hidden_def (getopt_long_only) 100 | # endif 101 | 102 | #endif /* Not ELIDE_CODE. */ 103 | 104 | #ifdef TEST 105 | 106 | #include 107 | 108 | int 109 | main (argc, argv) 110 | int argc; 111 | char **argv; 112 | { 113 | int c; 114 | int digit_optind = 0; 115 | 116 | while (1) 117 | { 118 | int this_option_optind = optind ? optind : 1; 119 | int option_index = 0; 120 | static struct option long_options[] = 121 | { 122 | {"add", 1, 0, 0}, 123 | {"append", 0, 0, 0}, 124 | {"delete", 1, 0, 0}, 125 | {"verbose", 0, 0, 0}, 126 | {"create", 0, 0, 0}, 127 | {"file", 1, 0, 0}, 128 | {0, 0, 0, 0} 129 | }; 130 | 131 | c = getopt_long (argc, argv, "abc:d:0123456789", 132 | long_options, &option_index); 133 | if (c == -1) 134 | break; 135 | 136 | switch (c) 137 | { 138 | case 0: 139 | printf ("option %s", long_options[option_index].name); 140 | if (optarg) 141 | printf (" with arg %s", optarg); 142 | printf ("\n"); 143 | break; 144 | 145 | case '0': 146 | case '1': 147 | case '2': 148 | case '3': 149 | case '4': 150 | case '5': 151 | case '6': 152 | case '7': 153 | case '8': 154 | case '9': 155 | if (digit_optind != 0 && digit_optind != this_option_optind) 156 | printf ("digits occur in two different argv-elements.\n"); 157 | digit_optind = this_option_optind; 158 | printf ("option %c\n", c); 159 | break; 160 | 161 | case 'a': 162 | printf ("option a\n"); 163 | break; 164 | 165 | case 'b': 166 | printf ("option b\n"); 167 | break; 168 | 169 | case 'c': 170 | printf ("option c with value `%s'\n", optarg); 171 | break; 172 | 173 | case 'd': 174 | printf ("option d with value `%s'\n", optarg); 175 | break; 176 | 177 | case '?': 178 | break; 179 | 180 | default: 181 | printf ("?? getopt returned character code 0%o ??\n", c); 182 | } 183 | } 184 | 185 | if (optind < argc) 186 | { 187 | printf ("non-option ARGV-elements: "); 188 | while (optind < argc) 189 | printf ("%s ", argv[optind++]); 190 | printf ("\n"); 191 | } 192 | 193 | exit (0); 194 | } 195 | 196 | #endif /* TEST */ 197 | -------------------------------------------------------------------------------- /ip.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (C) 1991,92,93,95,96,97,98,99,2000 Free Software Foundation, Inc. 3 | This file is part of the GNU C Library. 4 | 5 | The GNU C Library is free software; you can redistribute it and/or 6 | modify it under the terms of the GNU Lesser General Public 7 | License as published by the Free Software Foundation; either 8 | version 2.1 of the License, or (at your option) any later version. 9 | 10 | The GNU C Library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with the GNU C Library; if not, write to the Free 17 | Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 18 | 02111-1307 USA. */ 19 | 20 | #ifndef NTA_NETINET_IP_H 21 | #define NTA_NETINET_IP_H 1 22 | 23 | struct timestamp 24 | { 25 | u_int8_t len; 26 | u_int8_t ptr; 27 | #ifdef WORDS_BIGENDIAN 28 | unsigned int overflow:4; 29 | unsigned int flags:4; 30 | #else 31 | unsigned int flags:4; 32 | unsigned int overflow:4; 33 | #endif 34 | u_int32_t data[9]; 35 | }; 36 | 37 | struct iphdr 38 | { 39 | #ifdef WORDS_BIGENDIAN 40 | unsigned int version:4; 41 | unsigned int ihl:4; 42 | #else 43 | unsigned int ihl:4; 44 | unsigned int version:4; 45 | #endif 46 | u_int8_t tos; 47 | u_int16_t tot_len; 48 | u_int16_t id; 49 | u_int16_t frag_off; 50 | u_int8_t ttl; 51 | u_int8_t protocol; 52 | u_int16_t check; 53 | u_int32_t saddr; 54 | u_int32_t daddr; 55 | /*The options start here. */ 56 | }; 57 | 58 | #define IPVERSION 4 /* IP version number */ 59 | #define IP_MAXPACKET 65535 /* maximum packet size */ 60 | 61 | /* 62 | * Definitions for IP type of service (ip_tos) 63 | */ 64 | #define IPTOS_TOS_MASK 0x1E 65 | #define IPTOS_TOS(tos) ((tos) & IPTOS_TOS_MASK) 66 | #define IPTOS_LOWDELAY 0x10 67 | #define IPTOS_THROUGHPUT 0x08 68 | #define IPTOS_RELIABILITY 0x04 69 | #define IPTOS_LOWCOST 0x02 70 | #define IPTOS_MINCOST IPTOS_LOWCOST 71 | 72 | /* 73 | * Definitions for IP precedence (also in ip_tos) (hopefully unused) 74 | */ 75 | #define IPTOS_PREC_MASK 0xe0 76 | #define IPTOS_PREC(tos) ((tos) & IPTOS_PREC_MASK) 77 | #define IPTOS_PREC_NETCONTROL 0xe0 78 | #define IPTOS_PREC_INTERNETCONTROL 0xc0 79 | #define IPTOS_PREC_CRITIC_ECP 0xa0 80 | #define IPTOS_PREC_FLASHOVERRIDE 0x80 81 | #define IPTOS_PREC_FLASH 0x60 82 | #define IPTOS_PREC_IMMEDIATE 0x40 83 | #define IPTOS_PREC_PRIORITY 0x20 84 | #define IPTOS_PREC_ROUTINE 0x00 85 | 86 | /* 87 | * Definitions for options. 88 | */ 89 | #define IPOPT_COPY 0x80 90 | #define IPOPT_CLASS_MASK 0x60 91 | #define IPOPT_NUMBER_MASK 0x1f 92 | 93 | #define IPOPT_COPIED(o) ((o) & IPOPT_COPY) 94 | #define IPOPT_CLASS(o) ((o) & IPOPT_CLASS_MASK) 95 | #define IPOPT_NUMBER(o) ((o) & IPOPT_NUMBER_MASK) 96 | 97 | #define IPOPT_CONTROL 0x00 98 | #define IPOPT_RESERVED1 0x20 99 | #define IPOPT_DEBMEAS 0x40 100 | #define IPOPT_MEASUREMENT IPOPT_DEBMEAS 101 | #define IPOPT_RESERVED2 0x60 102 | 103 | #define IPOPT_EOL 0 /* end of option list */ 104 | #define IPOPT_END IPOPT_EOL 105 | #define IPOPT_NOP 1 /* no operation */ 106 | #define IPOPT_NOOP IPOPT_NOP 107 | 108 | #define IPOPT_RR 7 /* record packet route */ 109 | #define IPOPT_TS 68 /* timestamp */ 110 | #define IPOPT_TIMESTAMP IPOPT_TS 111 | #define IPOPT_SECURITY 130 /* provide s,c,h,tcc */ 112 | #define IPOPT_SEC IPOPT_SECURITY 113 | #define IPOPT_LSRR 131 /* loose source route */ 114 | #define IPOPT_SATID 136 /* satnet id */ 115 | #define IPOPT_SID IPOPT_SATID 116 | #define IPOPT_SSRR 137 /* strict source route */ 117 | #define IPOPT_RA 148 /* router alert */ 118 | 119 | /* 120 | * Offsets to fields in options other than EOL and NOP. 121 | */ 122 | #define IPOPT_OPTVAL 0 /* option ID */ 123 | #define IPOPT_OLEN 1 /* option length */ 124 | #define IPOPT_OFFSET 2 /* offset within option */ 125 | #define IPOPT_MINOFF 4 /* min value of above */ 126 | 127 | #define MAX_IPOPTLEN 40 128 | 129 | /* flag bits for ipt_flg */ 130 | #define IPOPT_TS_TSONLY 0 /* timestamps only */ 131 | #define IPOPT_TS_TSANDADDR 1 /* timestamps and addresses */ 132 | #define IPOPT_TS_PRESPEC 3 /* specified modules only */ 133 | 134 | /* bits for security (not byte swapped) */ 135 | #define IPOPT_SECUR_UNCLASS 0x0000 136 | #define IPOPT_SECUR_CONFID 0xf135 137 | #define IPOPT_SECUR_EFTO 0x789a 138 | #define IPOPT_SECUR_MMMM 0xbc4d 139 | #define IPOPT_SECUR_RESTR 0xaf13 140 | #define IPOPT_SECUR_SECRET 0xd788 141 | #define IPOPT_SECUR_TOPSECRET 0x6bc5 142 | 143 | /* 144 | * Internet implementation parameters. 145 | */ 146 | #define MAXTTL 255 /* maximum time to live (seconds) */ 147 | #define IPDEFTTL 64 /* default ttl, from RFC 1340 */ 148 | #define IPFRAGTTL 60 /* time to live for frags, slowhz */ 149 | #define IPTTLDEC 1 /* subtracted when forwarding */ 150 | 151 | #define IP_MSS 576 /* default maximum segment size */ 152 | 153 | #endif /* NTA_NETINET_IP_H */ 154 | -------------------------------------------------------------------------------- /mt19937ar.c: -------------------------------------------------------------------------------- 1 | /* 2 | A C-program for MT19937, with initialization improved 2002/1/26. 3 | Coded by Takuji Nishimura and Makoto Matsumoto. 4 | 5 | Before using, initialize the state by using init_genrand(seed) 6 | or init_by_array(init_key, key_length). 7 | 8 | Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, 9 | All rights reserved. 10 | 11 | Redistribution and use in source and binary forms, with or without 12 | modification, are permitted provided that the following conditions 13 | are met: 14 | 15 | 1. Redistributions of source code must retain the above copyright 16 | notice, this list of conditions and the following disclaimer. 17 | 18 | 2. Redistributions in binary form must reproduce the above copyright 19 | notice, this list of conditions and the following disclaimer in the 20 | documentation and/or other materials provided with the distribution. 21 | 22 | 3. The names of its contributors may not be used to endorse or promote 23 | products derived from this software without specific prior written 24 | permission. 25 | 26 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 27 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 28 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 29 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 30 | CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 31 | EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 32 | PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 33 | PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 34 | LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 35 | NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 36 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 37 | 38 | 39 | Any feedback is very welcome. 40 | http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html 41 | email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space) 42 | */ 43 | 44 | #include 45 | 46 | /* Period parameters */ 47 | #define N 624 48 | #define M 397 49 | #define MATRIX_A 0x9908b0dfUL /* constant vector a */ 50 | #define UPPER_MASK 0x80000000UL /* most significant w-r bits */ 51 | #define LOWER_MASK 0x7fffffffUL /* least significant r bits */ 52 | 53 | static unsigned long mt[N]; /* the array for the state vector */ 54 | static int mti=N+1; /* mti==N+1 means mt[N] is not initialized */ 55 | 56 | /* initializes mt[N] with a seed */ 57 | void init_genrand(unsigned long s) 58 | { 59 | mt[0]= s & 0xffffffffUL; 60 | for (mti=1; mti> 30)) + mti); 63 | /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */ 64 | /* In the previous versions, MSBs of the seed affect */ 65 | /* only MSBs of the array mt[]. */ 66 | /* 2002/01/09 modified by Makoto Matsumoto */ 67 | mt[mti] &= 0xffffffffUL; 68 | /* for >32 bit machines */ 69 | } 70 | } 71 | 72 | /* initialize by an array with array-length */ 73 | /* init_key is the array for initializing keys */ 74 | /* key_length is its length */ 75 | /* slight change for C++, 2004/2/26 */ 76 | void init_by_array(unsigned long init_key[], int key_length) 77 | { 78 | int i, j, k; 79 | init_genrand(19650218UL); 80 | i=1; j=0; 81 | k = (N>key_length ? N : key_length); 82 | for (; k; k--) { 83 | mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525UL)) 84 | + init_key[j] + j; /* non linear */ 85 | mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */ 86 | i++; j++; 87 | if (i>=N) { mt[0] = mt[N-1]; i=1; } 88 | if (j>=key_length) j=0; 89 | } 90 | for (k=N-1; k; k--) { 91 | mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941UL)) 92 | - i; /* non linear */ 93 | mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */ 94 | i++; 95 | if (i>=N) { mt[0] = mt[N-1]; i=1; } 96 | } 97 | 98 | mt[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */ 99 | } 100 | 101 | /* generates a random number on [0,0xffffffff]-interval */ 102 | unsigned long genrand_int32(void) 103 | { 104 | unsigned long y; 105 | static unsigned long mag01[2]={0x0UL, MATRIX_A}; 106 | /* mag01[x] = x * MATRIX_A for x=0,1 */ 107 | 108 | if (mti >= N) { /* generate N words at one time */ 109 | int kk; 110 | 111 | if (mti == N+1) /* if init_genrand() has not been called, */ 112 | init_genrand(5489UL); /* a default initial seed is used */ 113 | 114 | for (kk=0;kk> 1) ^ mag01[y & 0x1UL]; 117 | } 118 | for (;kk> 1) ^ mag01[y & 0x1UL]; 121 | } 122 | y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK); 123 | mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1UL]; 124 | 125 | mti = 0; 126 | } 127 | 128 | y = mt[mti++]; 129 | 130 | /* Tempering */ 131 | y ^= (y >> 11); 132 | y ^= (y << 7) & 0x9d2c5680UL; 133 | y ^= (y << 15) & 0xefc60000UL; 134 | y ^= (y >> 18); 135 | 136 | return y; 137 | } 138 | 139 | /* generates a random number on [0,0x7fffffff]-interval */ 140 | long genrand_int31(void) 141 | { 142 | return (long)(genrand_int32()>>1); 143 | } 144 | 145 | /* generates a random number on [0,1]-real-interval */ 146 | double genrand_real1(void) 147 | { 148 | return genrand_int32()*(1.0/4294967295.0); 149 | /* divided by 2^32-1 */ 150 | } 151 | 152 | /* generates a random number on [0,1)-real-interval */ 153 | double genrand_real2(void) 154 | { 155 | return genrand_int32()*(1.0/4294967296.0); 156 | /* divided by 2^32 */ 157 | } 158 | 159 | /* generates a random number on (0,1)-real-interval */ 160 | double genrand_real3(void) 161 | { 162 | return (((double)genrand_int32()) + 0.5)*(1.0/4294967296.0); 163 | /* divided by 2^32 */ 164 | } 165 | 166 | /* generates a random number on [0,1) with 53-bit resolution*/ 167 | double genrand_res53(void) 168 | { 169 | unsigned long a=genrand_int32()>>5, b=genrand_int32()>>6; 170 | return(a*67108864.0+b)*(1.0/9007199254740992.0); 171 | } 172 | /* These real versions are due to Isaku Wada, 2002/01/09 added */ 173 | 174 | #ifdef MT19937AR_TESTING 175 | int main(void) 176 | { 177 | int i; 178 | unsigned long init[4]={0x123, 0x234, 0x345, 0x456}, length=4; 179 | init_by_array(init, length); 180 | printf("1000 outputs of genrand_int32()\n"); 181 | for (i=0; i<1000; i++) { 182 | printf("%10lu ", genrand_int32()); 183 | if (i%5==4) printf("\n"); 184 | } 185 | printf("\n1000 outputs of genrand_real2()\n"); 186 | for (i=0; i<1000; i++) { 187 | printf("%10.8f ", genrand_real2()); 188 | if (i%5==4) printf("\n"); 189 | } 190 | return 0; 191 | } 192 | #endif 193 | -------------------------------------------------------------------------------- /strlcat.c: -------------------------------------------------------------------------------- 1 | /* from http://www.openbsd.org/cgi-bin/cvsweb/src/lib/libc/string/ */ 2 | 3 | /* 4 | * Copyright (c) 1998 Todd C. Miller 5 | * 6 | * Permission to use, copy, modify, and distribute this software for any 7 | * purpose with or without fee is hereby granted, provided that the above 8 | * copyright notice and this permission notice appear in all copies. 9 | * 10 | * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 11 | * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 12 | * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 13 | * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 14 | * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 15 | * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 16 | * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 17 | */ 18 | 19 | #include 20 | #include 21 | 22 | /* 23 | * Appends src to string dst of size siz (unlike strncat, siz is the 24 | * full size of dst, not space left). At most siz-1 characters 25 | * will be copied. Always NUL terminates (unless siz <= strlen(dst)). 26 | * Returns strlen(src) + MIN(siz, strlen(initial dst)). 27 | * If retval >= siz, truncation occurred. 28 | */ 29 | size_t 30 | strlcat(char *dst, const char *src, size_t siz) 31 | { 32 | char *d = dst; 33 | const char *s = src; 34 | size_t n = siz; 35 | size_t dlen; 36 | 37 | /* Find the end of dst and adjust bytes left but don't go past end */ 38 | while (n-- != 0 && *d != '\0') 39 | d++; 40 | dlen = d - dst; 41 | n = siz - dlen; 42 | 43 | if (n == 0) 44 | return(dlen + strlen(s)); 45 | while (*s != '\0') { 46 | if (n != 1) { 47 | *d++ = *s; 48 | n--; 49 | } 50 | s++; 51 | } 52 | *d = '\0'; 53 | 54 | return(dlen + (s - src)); /* count does not include NUL */ 55 | } 56 | -------------------------------------------------------------------------------- /strlcpy.c: -------------------------------------------------------------------------------- 1 | /* from http://www.openbsd.org/cgi-bin/cvsweb/src/lib/libc/string/ */ 2 | 3 | /* 4 | * Copyright (c) 1998 Todd C. Miller 5 | * 6 | * Permission to use, copy, modify, and distribute this software for any 7 | * purpose with or without fee is hereby granted, provided that the above 8 | * copyright notice and this permission notice appear in all copies. 9 | * 10 | * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 11 | * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 12 | * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 13 | * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 14 | * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 15 | * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 16 | * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 17 | */ 18 | 19 | #include 20 | #include 21 | 22 | /* 23 | * Copy src to string dst of size siz. At most siz-1 characters 24 | * will be copied. Always NUL terminates (unless siz == 0). 25 | * Returns strlen(src); if retval >= siz, truncation occurred. 26 | */ 27 | size_t 28 | strlcpy(char *dst, const char *src, size_t siz) 29 | { 30 | char *d = dst; 31 | const char *s = src; 32 | size_t n = siz; 33 | 34 | /* Copy as many bytes as will fit */ 35 | if (n != 0) { 36 | while (--n != 0) { 37 | if ((*d++ = *s++) == '\0') 38 | break; 39 | } 40 | } 41 | 42 | /* Not enough room in dst, add NUL and traverse rest of src */ 43 | if (n == 0) { 44 | if (siz != 0) 45 | *d = '\0'; /* NUL-terminate dst */ 46 | while (*s++) 47 | ; 48 | } 49 | 50 | return(s - src - 1); /* count does not include NUL */ 51 | } 52 | -------------------------------------------------------------------------------- /tcp-scan.1: -------------------------------------------------------------------------------- 1 | .\" Copyright (C) Roy Hills, NTA Monitor Ltd. 2 | .\" 3 | .\" Copying and distribution of this file, with or without modification, 4 | .\" are permitted in any medium without royalty provided the copyright 5 | .\" notice and this notice are preserved. 6 | .\" 7 | .TH TCP-SCAN 1 "August 18, 2011" 8 | .\" Please adjust this date whenever revising the man page. 9 | .SH NAME 10 | tcp-scan \- Bandwidth-optimised half-open TCP portscanner 11 | .SH SYNOPSIS 12 | .B tcp-scan 13 | .RI [ options ] " " [ hosts ...] 14 | .PP 15 | Target hosts must be specified on the command line unless the 16 | .B --file 17 | option is given, in which case the targets are read from the specified file 18 | instead. 19 | .PP 20 | You will need to be root, or 21 | .B tcp-scan 22 | must be SUID root, in order to run 23 | .BR tcp-scan , 24 | because the functions that it uses to read and write packets require root 25 | privilege. 26 | .PP 27 | The target hosts can be specified as IP addresses or hostnames. 28 | .SH DESCRIPTION 29 | .SH OPTIONS 30 | .TP 31 | .B --help or -h 32 | Display this usage message and exit. 33 | .TP 34 | .B --file= or -f 35 | Read hostnames or addresses from the specified file 36 | instead of from the command line. One name or IP 37 | address per line. Use "-" for standard input. 38 | .TP 39 | .B --retry= or -r 40 | Set total number of attempts per host to , 41 | default=3. 42 | .TP 43 | .B --timeout= or -t 44 | Set initial per host timeout to ms, default=500. 45 | This timeout is for the first packet sent to each host. 46 | subsequent timeouts are multiplied by the backoff 47 | factor which is set with --backoff. 48 | .TP 49 | .B --bandwidth= or -B 50 | Set desired outbound bandwidth to , default=56000 51 | The value is in bits per second by default. If you 52 | append "K" to the value, then the units are kilobits 53 | per sec; and if you append "M" to the value, the 54 | units are megabits per second. 55 | The "K" and "M" suffixes represent the decimal, not 56 | binary, multiples. So 64K is 64000, not 65536. 57 | .TP 58 | .B --interval= or -i 59 | Set minimum packet interval to ms. 60 | The packet interval will be no smaller than this number. 61 | The interval specified is in milliseconds by default. 62 | if "u" is appended to the value, then the interval 63 | is in microseconds, and if "s" is appended, the 64 | interval is in seconds. 65 | If you want to use up to a given bandwidth, then it is 66 | easier to use the --bandwidth option instead. 67 | You cannot specify both --interval and --bandwidth 68 | because they are just different ways to change the 69 | same underlying variable. 70 | .TP 71 | .B --backoff= or -b 72 | Set timeout backoff factor to , default=1.50. 73 | The per-host timeout is multiplied by this factor 74 | after each timeout. So, if the number of retrys 75 | is 3, the initial per-host timeout is 500ms and the 76 | backoff factor is 1.5, then the first timeout will be 77 | 500ms, the second 750ms and the third 1125ms. 78 | .TP 79 | .B --verbose or -v 80 | Display verbose progress messages. 81 | Use more than once for greater effect: 82 | .IP "" 83 | 1 - Show when hosts are removed from the list and 84 | when packets with invalid cookies are received. 85 | .IP "" 86 | 2 - Show each packet sent and received. 87 | .IP "" 88 | 3 - Display the host list before 89 | scanning starts. 90 | .TP 91 | .B --version or -V 92 | Display program version and exit. 93 | .TP 94 | .B --random or -R 95 | Randomise the host list. 96 | .TP 97 | .B --numeric or -N 98 | IP addresses only, no hostnames. 99 | With this option, all hosts must be specified as 100 | IP addresses. Hostnames are not permitted. 101 | .TP 102 | .B --port=

or -p

103 | Specify TCP destination port(s). 104 | This option can be a single port, a list of ports 105 | separated by commas, or an inclusive range with the 106 | bounds separated by "-". 107 | .TP 108 | .B --sport=

or -s

109 | Specify TCP source port. 110 | The default is a random port in the range 32678-65535. 111 | .TP 112 | .B --seq= or -e 113 | Specify initial sequence number. 114 | The default initial sequence number is random. 115 | .TP 116 | .B --ack= or -c 117 | Specify initial acknowledgement number. 118 | The default initial acknowledgement number is random. 119 | This is only applicable when the ACK flag is set in 120 | outgoing packets. 121 | .TP 122 | .B --window= or -w 123 | Specify the TCP window size. 124 | The default window size is 5840. 125 | .TP 126 | .B --openonly or -o 127 | Only display open ports. 128 | With this option, closed ports are not displayed. 129 | .TP 130 | .B --servicefile= or -S 131 | Use service file for TCP ports. 132 | If this option is specified, then the TCP ports to 133 | scan are read from the specified file. The file is 134 | same format as used by "strobe". 135 | .TP 136 | .B --mss= or -m 137 | Use TCP MSS . Default is 1460 138 | A non-zero MSS adds the MSS TCP option to the SYN packet 139 | which adds 4 bytes to the packet length. If the MSS 140 | is specified as zero, then no MSS option is added. 141 | .TP 142 | .B --wscale or -W 143 | Add the WSCALE TCP option 144 | This option adds 4 bytes to the packet length. 145 | .TP 146 | .B --sack or -a 147 | Add the SACKOK TCP option 148 | This option adds 4 bytes to the packet length. However 149 | it does not increase packet size when used with the 150 | .B --timestamp option. 151 | .TP 152 | .B --timestamp or -T 153 | Add the TIMESTAMP TCP option 154 | The number of seconds since midnight 1/1/1970 is used 155 | for the timestamp value. 156 | This option adds 12 bytes to the packet length. 157 | .TP 158 | .B --snap= or -n 159 | Set the pcap snap length to . Default=94. 160 | This specifies the frame capture length. This 161 | length includes the data-link header as well as the 162 | IP and transport headers. The default is normally 163 | sufficient. 164 | .TP 165 | .B --ttl= or -l 166 | Set the IP TTL to . Default=64. 167 | You can specify a higher value if the targets are 168 | many hops away, or you can specify a lower value to 169 | limit the scope to the local network. 170 | .TP 171 | .B --interface= or -I 172 | Use network interface . 173 | If this option is not specified, tcp-scan will search 174 | the system interface list for the lowest numbered, 175 | configured up interface (excluding loopback). 176 | .TP 177 | .B --quiet or -q 178 | Don't decode the received packet. 179 | If this option is specified, then only the minimum 180 | information is displayed. This can be useful if you 181 | only want to know if a port is open or not, or if 182 | strange packets confuse the decoding process 183 | .TP 184 | .B --ignoredups or -g 185 | Don't display duplicate packets. 186 | By default, duplicate packets are displayed and flagged 187 | with "(DUP: n)" where n is the number of packets 188 | received from that host so far. 189 | .TP 190 | .B --df= or -F 191 | Enable (1) or disable (0) DF flag. Default=1 192 | Setting this option to 1 sets the DF flag in the IP 193 | header of the outbound SYN packets. Setting it to 0 194 | clears the DF flag. 195 | .TP 196 | .B --tos= or -O 197 | Set IP TOS (Type of Service) to . Default=0 198 | This sets the TOS value in the IP header for outbound 199 | packets. 200 | .TP 201 | .B --portname or -P 202 | Display port names as well as numbers. 203 | .TP 204 | .B --servicefile2= or -E 205 | Use TCP service filename . 206 | The service file is used when displaying TCP port names. 207 | It is in the standard "/etc/services" file format. 208 | By default, the services file supplied with tcp-scan is 209 | used. 210 | .TP 211 | .B --flags= or -L 212 | Specify TCP flags to be set in outgoing packets. 213 | The flags should be specified as a comma-separated list 214 | from the set of: CWR,ECN,URG,ACK,PSH,RST,SYN,FIN. 215 | If this option is not specified, the flags default 216 | to SYN. 217 | .TP 218 | .B --pcapsavefile=

or -C

219 | Write received packets to pcap savefile

. 220 | This option causes received TCP packets to be written 221 | to a pcap savefile with the specified name. This 222 | savefile can be analyzed with programs that understand 223 | the pcap file format, such as "tcpdump" and "wireshark". 224 | .SH FILES 225 | .TP 226 | .I /usr/local/share/tcp-scan/tcp-scan-services 227 | TCP port number to service name map file for tcp-scan. 228 | .SH EXAMPLES 229 | .SH AUTHOR 230 | Roy Hills 231 | .SH "SEE ALSO" 232 | .I http://www.nta-monitor.com/wiki/ 233 | The tcp-scan wiki page. 234 | .PP 235 | .I http://www.nta-monitor.com/tools/tcp-scan/ 236 | The tcp-scan homepage. 237 | -------------------------------------------------------------------------------- /tcp-scan.h: -------------------------------------------------------------------------------- 1 | /* 2 | * The TCP Scanner (tcp-scan) is Copyright (C) 2003-2008 Roy Hills, 3 | * NTA Monitor Ltd. 4 | * 5 | * This file is part of tcp-scan. 6 | * 7 | * tcp-scan 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 | * tcp-scan 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 tcp-scan. If not, see . 19 | * 20 | * tcp-scan.h -- Header file for TCP protocol specific scanner 21 | * 22 | * Author: Roy Hills 23 | * Date: 16 September 2003 24 | * 25 | * This header file contains definitions required by only the protocol- 26 | * specific code. 27 | */ 28 | 29 | /* Includes */ 30 | #ifdef HAVE_CONFIG_H 31 | #include "config.h" 32 | #endif 33 | 34 | /* C89 standard headers */ 35 | #include 36 | #include 37 | #include 38 | #include 39 | #include 40 | #include 41 | #include 42 | 43 | #include /* FreeBSD needs explicit include for sys/types.h */ 44 | 45 | #ifdef __CYGWIN__ 46 | #include /* Include windows.h if compiling under Cygwin */ 47 | #endif 48 | 49 | #ifdef HAVE_UNISTD_H 50 | #include 51 | #endif 52 | 53 | #ifdef HAVE_NETDB_H 54 | #include 55 | #endif 56 | 57 | #ifdef HAVE_GETOPT_H 58 | #include 59 | #else 60 | /* Include getopt.h for the sake of getopt_long. 61 | We don't need the declaration of getopt, and it could conflict 62 | with something from a system header file, so effectively nullify that. */ 63 | #define getopt getopt_loser 64 | #include "getopt.h" 65 | #undef getopt 66 | #endif 67 | 68 | #ifdef HAVE_NETINET_IN_H 69 | #include 70 | #endif 71 | 72 | #ifdef HAVE_SYS_TIME_H 73 | #include 74 | #endif 75 | 76 | #ifdef HAVE_SYS_SOCKET_H 77 | #include /* For struct sockaddr */ 78 | #endif 79 | 80 | #ifdef HAVE_ARPA_INET_H 81 | #include 82 | #endif 83 | 84 | #ifdef HAVE_REGEX_H 85 | #include /* Posix regular expression support */ 86 | #endif 87 | 88 | #ifdef HAVE_PCAP_H 89 | #include 90 | #endif 91 | 92 | #ifdef HAVE_SYS_IOCTL_H 93 | #include 94 | #endif 95 | 96 | #ifdef HAVE_NET_IF_H 97 | #include 98 | #endif 99 | 100 | #ifdef HAVE_SYS_UTSNAME_H 101 | #include 102 | #endif 103 | 104 | #include "ip.h" 105 | #include "tcp.h" 106 | 107 | /* Defines */ 108 | 109 | #define MAXLINE 255 /* Max line length for input files */ 110 | #define MAXIP 65515 /* Max IP data size = 64k - 20 */ 111 | #define REALLOC_COUNT 1000 /* Entries to realloc at once */ 112 | #define DEFAULT_BANDWIDTH 56000 /* Default bandwidth in bits/sec */ 113 | #define MINIMUM_FRAME_SIZE 46 /* Minimum data size for layer 2 */ 114 | #define PACKET_OVERHEAD 18 /* Size of Ethernet header */ 115 | /* IP protocol 6 = TCP */ 116 | #define IP_PROTOCOL 6 /* Default IP Protocol */ 117 | #define DEFAULT_BACKOFF_FACTOR 1.5 /* Default timeout backoff factor */ 118 | #define DEFAULT_RETRY 3 /* Default number of retries */ 119 | #define DEFAULT_TIMEOUT 2000 /* Default per-host timeout in ms */ 120 | #define SNAPLEN 94 /* 14 (ether) + 20 (IP) + 60 (TCP) */ 121 | #define PROMISC 0 /* Enable promiscuous mode */ 122 | #define TO_MS 0 /* Timeout for pcap_open_live() */ 123 | #define OPTIMISE 1 /* Optimise pcap filter */ 124 | #define DEFAULT_WINDOW 5840 /* TCP Window */ 125 | #define DEFAULT_MSS 1460 /* TCP MSS */ 126 | #define DEFAULT_TTL 64 /* IP TTL */ 127 | #define DEFAULT_DF 1 /* IP DF Flag */ 128 | #define DEFAULT_TOS 0 /* IP TOS Field */ 129 | #define SERVICE_FILE "tcp-scan-services" 130 | 131 | /* Structures */ 132 | 133 | typedef union { 134 | struct in_addr v4; 135 | struct in6_addr v6; 136 | } ip_address; 137 | 138 | typedef struct { 139 | unsigned n; /* Ordinal number for this entry */ 140 | unsigned timeout; /* Timeout for this host in us */ 141 | ip_address addr; /* Host IP address */ 142 | struct timeval last_send_time; /* Time when last packet sent to this addr */ 143 | unsigned short num_sent; /* Number of packets sent */ 144 | unsigned short num_recv; /* Number of packets received */ 145 | uint16_t dport; /* Destination port */ 146 | unsigned char live; /* Set when awaiting response */ 147 | } host_entry; 148 | 149 | typedef struct { 150 | int cwr; 151 | int ecn; 152 | int urg; 153 | int ack; 154 | int psh; 155 | int rst; 156 | int syn; 157 | int fin; 158 | } tcp_flags_struct; 159 | 160 | /* TCP Pseudo Header for checksum calculation */ 161 | typedef struct { 162 | uint32_t s_addr; 163 | uint32_t d_addr; 164 | uint8_t mbz; 165 | uint8_t proto; 166 | uint16_t len; 167 | } pseudo_hdr; 168 | 169 | /* Functions */ 170 | 171 | #ifndef HAVE_STRLCAT 172 | size_t strlcat(char *dst, const char *src, size_t siz); 173 | #endif 174 | #ifndef HAVE_STRLCPY 175 | size_t strlcpy(char *dst, const char *src, size_t siz); 176 | #endif 177 | 178 | void err_sys(const char *, ...); 179 | void warn_sys(const char *, ...); 180 | void err_msg(const char *, ...); 181 | void warn_msg(const char *, ...); 182 | void err_print(int, const char *, va_list); 183 | void usage(int, int); 184 | void add_host(const char *, unsigned); 185 | int send_packet(int, host_entry *, int, struct timeval *); 186 | void recvfrom_wto(int, int); 187 | void remove_host(host_entry **); 188 | void timeval_diff(const struct timeval *, const struct timeval *, 189 | struct timeval *); 190 | host_entry *find_host(host_entry **, const struct in_addr *, 191 | const unsigned char *, unsigned); 192 | void display_packet(unsigned, const unsigned char *, const host_entry *, 193 | const struct in_addr *); 194 | void advance_cursor(void); 195 | void dump_list(void); 196 | void print_times(void); 197 | void initialise(void); 198 | void clean_up(void); 199 | void tcp_scan_version(void); 200 | char *make_message(const char *, ...); 201 | char *printable(const unsigned char*, size_t); 202 | void callback(u_char *, const struct pcap_pkthdr *, const u_char *); 203 | void process_options(int, char *[]); 204 | ip_address *get_host_address(const char *, int, ip_address *, char **); 205 | const char *my_ntoa(ip_address, int); 206 | /* Wrappers */ 207 | int Gettimeofday(struct timeval *); 208 | void *Malloc(size_t); 209 | void *Realloc(void *, size_t); 210 | unsigned long int Strtoul(const char *, int); 211 | long int Strtol(const char *, int); 212 | char *my_lookupdev(char *); 213 | unsigned int hstr_i(const char *); 214 | uint16_t in_cksum(const uint16_t *, int); 215 | uint32_t get_source_ip(const char *); 216 | void add_host_port(const char *, unsigned, unsigned); 217 | void create_port_list(const char *); 218 | void process_tcp_flags(const char *); 219 | unsigned str_to_bandwidth(const char *); 220 | unsigned str_to_interval(const char *); 221 | char *dupstr(const char *); 222 | /* MT19937 prototypes */ 223 | void init_genrand(unsigned long); 224 | void init_by_array(unsigned long[], int); 225 | unsigned long genrand_int32(void); 226 | long genrand_int31(void); 227 | double genrand_real1(void); 228 | double genrand_real2(void); 229 | double genrand_real3(void); 230 | double genrand_res53(void); 231 | -------------------------------------------------------------------------------- /tcp.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 1982, 1986, 1993 3 | * The Regents of the University of California. All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions 7 | * are met: 8 | * 1. Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * 2. Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in the 12 | * documentation and/or other materials provided with the distribution. 13 | * 4. Neither the name of the University nor the names of its contributors 14 | * may be used to endorse or promote products derived from this software 15 | * without specific prior written permission. 16 | * 17 | * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 18 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 19 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 20 | * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 21 | * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 22 | * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 23 | * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 24 | * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 25 | * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 26 | * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 27 | * SUCH DAMAGE. 28 | * 29 | * @(#)tcp.h 8.1 (Berkeley) 6/10/93 30 | */ 31 | 32 | #ifndef NTA_NETINET_TCP_H 33 | #define NTA_NETINET_TCP_H 1 34 | 35 | /* 36 | * User-settable options (used with setsockopt). 37 | */ 38 | #define TCP_NODELAY 1 /* Don't delay send to coalesce packets */ 39 | #define TCP_MAXSEG 2 /* Set maximum segment size */ 40 | #define TCP_CORK 3 /* Control sending of partial frames */ 41 | #define TCP_KEEPIDLE 4 /* Start keeplives after this period */ 42 | #define TCP_KEEPINTVL 5 /* Interval between keepalives */ 43 | #define TCP_KEEPCNT 6 /* Number of keepalives before death */ 44 | #define TCP_SYNCNT 7 /* Number of SYN retransmits */ 45 | #define TCP_LINGER2 8 /* Life time of orphaned FIN-WAIT-2 state */ 46 | #define TCP_DEFER_ACCEPT 9 /* Wake up listener only when data arrive */ 47 | #define TCP_WINDOW_CLAMP 10 /* Bound advertised window */ 48 | #define TCP_INFO 11 /* Information about this connection. */ 49 | #define TCP_QUICKACK 12 /* Bock/reenable quick ACKs. */ 50 | 51 | struct tcphdr 52 | { 53 | u_int16_t source; 54 | u_int16_t dest; 55 | u_int32_t seq; 56 | u_int32_t ack_seq; 57 | #ifdef WORDS_BIGENDIAN 58 | u_int16_t doff:4; 59 | u_int16_t res1:4; 60 | u_int16_t cwr:1; 61 | u_int16_t ecn:1; 62 | u_int16_t urg:1; 63 | u_int16_t ack:1; 64 | u_int16_t psh:1; 65 | u_int16_t rst:1; 66 | u_int16_t syn:1; 67 | u_int16_t fin:1; 68 | #else 69 | u_int16_t res1:4; 70 | u_int16_t doff:4; 71 | u_int16_t fin:1; 72 | u_int16_t syn:1; 73 | u_int16_t rst:1; 74 | u_int16_t psh:1; 75 | u_int16_t ack:1; 76 | u_int16_t urg:1; 77 | u_int16_t ecn:1; 78 | u_int16_t cwr:1; 79 | #endif 80 | u_int16_t window; 81 | u_int16_t check; 82 | u_int16_t urg_ptr; 83 | }; 84 | 85 | enum 86 | { 87 | TCP_ESTABLISHED = 1, 88 | TCP_SYN_SENT, 89 | TCP_SYN_RECV, 90 | TCP_FIN_WAIT1, 91 | TCP_FIN_WAIT2, 92 | TCP_TIME_WAIT, 93 | TCP_CLOSE, 94 | TCP_CLOSE_WAIT, 95 | TCP_LAST_ACK, 96 | TCP_LISTEN, 97 | TCP_CLOSING /* now a valid state */ 98 | }; 99 | 100 | # define TCPOPT_EOL 0 101 | # define TCPOPT_NOP 1 102 | # define TCPOPT_MAXSEG 2 103 | # define TCPOLEN_MAXSEG 4 104 | # define TCPOPT_WINDOW 3 105 | # define TCPOLEN_WINDOW 3 106 | # define TCPOPT_SACK_PERMITTED 4 /* Experimental */ 107 | # define TCPOLEN_SACK_PERMITTED 2 108 | # define TCPOPT_SACK 5 /* Experimental */ 109 | # define TCPOPT_TIMESTAMP 8 110 | # define TCPOLEN_TIMESTAMP 10 111 | # define TCPOLEN_TSTAMP_APPA (TCPOLEN_TIMESTAMP+2) /* appendix A */ 112 | 113 | # define TCPOPT_TSTAMP_HDR \ 114 | (TCPOPT_NOP<<24|TCPOPT_NOP<<16|TCPOPT_TIMESTAMP<<8|TCPOLEN_TIMESTAMP) 115 | 116 | /* 117 | * Default maximum segment size for TCP. 118 | * With an IP MSS of 576, this is 536, 119 | * but 512 is probably more convenient. 120 | * This should be defined as MIN(512, IP_MSS - sizeof (struct tcpiphdr)). 121 | */ 122 | # define TCP_MSS 512 123 | 124 | # define TCP_MAXWIN 65535 /* largest value for (unscaled) window */ 125 | 126 | # define TCP_MAX_WINSHIFT 14 /* maximum window shift */ 127 | 128 | # define SOL_TCP 6 /* TCP level */ 129 | 130 | 131 | # define TCPI_OPT_TIMESTAMPS 1 132 | # define TCPI_OPT_SACK 2 133 | # define TCPI_OPT_WSCALE 4 134 | # define TCPI_OPT_ECN 8 135 | 136 | /* Values for tcpi_state. */ 137 | enum tcp_ca_state 138 | { 139 | TCP_CA_Open = 0, 140 | TCP_CA_Disorder = 1, 141 | TCP_CA_CWR = 2, 142 | TCP_CA_Recovery = 3, 143 | TCP_CA_Loss = 4 144 | }; 145 | 146 | struct tcp_info 147 | { 148 | u_int8_t tcpi_state; 149 | u_int8_t tcpi_ca_state; 150 | u_int8_t tcpi_retransmits; 151 | u_int8_t tcpi_probes; 152 | u_int8_t tcpi_backoff; 153 | u_int8_t tcpi_options; 154 | u_int8_t tcpi_snd_wscale : 4, tcpi_rcv_wscale : 4; 155 | 156 | u_int32_t tcpi_rto; 157 | u_int32_t tcpi_ato; 158 | u_int32_t tcpi_snd_mss; 159 | u_int32_t tcpi_rcv_mss; 160 | 161 | u_int32_t tcpi_unacked; 162 | u_int32_t tcpi_sacked; 163 | u_int32_t tcpi_lost; 164 | u_int32_t tcpi_retrans; 165 | u_int32_t tcpi_fackets; 166 | 167 | /* Times. */ 168 | u_int32_t tcpi_last_data_sent; 169 | u_int32_t tcpi_last_ack_sent; /* Not remembered, sorry. */ 170 | u_int32_t tcpi_last_data_recv; 171 | u_int32_t tcpi_last_ack_recv; 172 | 173 | /* Metrics. */ 174 | u_int32_t tcpi_pmtu; 175 | u_int32_t tcpi_rcv_ssthresh; 176 | u_int32_t tcpi_rtt; 177 | u_int32_t tcpi_rttvar; 178 | u_int32_t tcpi_snd_ssthresh; 179 | u_int32_t tcpi_snd_cwnd; 180 | u_int32_t tcpi_advmss; 181 | u_int32_t tcpi_reordering; 182 | }; 183 | 184 | #endif /* NTA_NETINET_TCP_H */ 185 | -------------------------------------------------------------------------------- /utils.c: -------------------------------------------------------------------------------- 1 | /* 2 | * The TCP Scanner (tcp-scan) is Copyright (C) 2003-2008 Roy Hills, 3 | * NTA Monitor Ltd. 4 | * 5 | * This file is part of tcp-scan. 6 | * 7 | * tcp-scan 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 | * tcp-scan 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 tcp-scan. If not, see . 19 | * 20 | * Author: Roy Hills 21 | * Date: 5 April 2004 22 | * 23 | * This file contains various utility functions used by tcp-scan. 24 | */ 25 | 26 | #include "tcp-scan.h" 27 | 28 | /* 29 | * timeval_diff -- Calculates the difference between two timevals 30 | * and returns this difference in a third timeval. 31 | * 32 | * Inputs: 33 | * 34 | * a = First timeval 35 | * b = Second timeval 36 | * diff = Difference between timevals (a - b). 37 | * 38 | * Returns: 39 | * 40 | * None. 41 | */ 42 | void 43 | timeval_diff(const struct timeval *a, const struct timeval *b, 44 | struct timeval *diff) { 45 | struct timeval temp; 46 | 47 | temp.tv_sec = b->tv_sec; 48 | temp.tv_usec = b->tv_usec; 49 | 50 | /* Perform the carry for the later subtraction by updating b. */ 51 | if (a->tv_usec < temp.tv_usec) { 52 | int nsec = (temp.tv_usec - a->tv_usec) / 1000000 + 1; 53 | temp.tv_usec -= 1000000 * nsec; 54 | temp.tv_sec += nsec; 55 | } 56 | if (a->tv_usec - temp.tv_usec > 1000000) { 57 | int nsec = (a->tv_usec - temp.tv_usec) / 1000000; 58 | temp.tv_usec += 1000000 * nsec; 59 | temp.tv_sec -= nsec; 60 | } 61 | 62 | /* Compute the time difference 63 | tv_usec is certainly positive. */ 64 | diff->tv_sec = a->tv_sec - temp.tv_sec; 65 | diff->tv_usec = a->tv_usec - temp.tv_usec; 66 | } 67 | 68 | /* 69 | * hstr_i -- Convert two-digit hex string to unsigned integer 70 | * 71 | * Inputs: 72 | * 73 | * cptr Two-digit hex string 74 | * 75 | * Returns: 76 | * 77 | * Number corresponding to input hex value. 78 | * 79 | * An input of "0A" or "0a" would return 10. 80 | * Note that this function does no sanity checking, it's up to the 81 | * caller to ensure that *cptr points to at least two hex digits. 82 | * 83 | * This function is a modified version of hstr_i at www.snippets.org. 84 | */ 85 | unsigned int 86 | hstr_i(const char *cptr) 87 | { 88 | unsigned int i; 89 | unsigned int j = 0; 90 | int k; 91 | 92 | for (k=0; k<2; k++) { 93 | i = *cptr++ - '0'; 94 | if (9 < i) 95 | i -= 7; 96 | j <<= 4; 97 | j |= (i & 0x0f); 98 | } 99 | return j; 100 | } 101 | 102 | /* 103 | * make_message -- allocate a sufficiently large string and print into it. 104 | * 105 | * Inputs: 106 | * 107 | * Format and variable number of arguments. 108 | * 109 | * Outputs: 110 | * 111 | * Pointer to the string, 112 | * 113 | * The code for this function is from the Debian Linux "woody" sprintf man 114 | * page. Modified slightly to use wrapper functions for malloc and realloc. 115 | */ 116 | char * 117 | make_message(const char *fmt, ...) { 118 | int n; 119 | /* Guess we need no more than 100 bytes. */ 120 | size_t size = 100; 121 | char *p; 122 | va_list ap; 123 | p = Malloc (size); 124 | while (1) { 125 | /* Try to print in the allocated space. */ 126 | va_start(ap, fmt); 127 | n = vsnprintf (p, size, fmt, ap); 128 | va_end(ap); 129 | /* If that worked, return the string. */ 130 | if (n > -1 && n < (int) size) 131 | return p; 132 | /* Else try again with more space. */ 133 | if (n > -1) /* glibc 2.1 */ 134 | size = n+1; /* precisely what is needed */ 135 | else /* glibc 2.0 */ 136 | size *= 2; /* twice the old size */ 137 | p = Realloc (p, size); 138 | } 139 | } 140 | 141 | /* 142 | * printable -- Convert string to printable form using C-style escapes 143 | * 144 | * Inputs: 145 | * 146 | * string Pointer to input string. 147 | * size Size of input string. 0 means that string is null-terminated. 148 | * 149 | * Returns: 150 | * 151 | * Pointer to the printable string. 152 | * 153 | * Any non-printable characters are replaced by C-Style escapes, e.g. 154 | * "\n" for newline. As a result, the returned string may be longer than 155 | * the one supplied. 156 | * 157 | * This function makes two passes through the input string: one to 158 | * determine the required output length, then a second to perform the 159 | * conversion. 160 | * 161 | * The pointer returned points to malloc'ed storage which should be 162 | * free'ed by the caller when it's no longer needed. 163 | */ 164 | char * 165 | printable(const unsigned char *string, size_t size) { 166 | char *result; 167 | char *r; 168 | const unsigned char *cp; 169 | size_t outlen; 170 | unsigned i; 171 | /* 172 | * If the input string is NULL, return an empty string. 173 | */ 174 | if (string == NULL) { 175 | result = Malloc(1); 176 | result[0] = '\0'; 177 | return result; 178 | } 179 | /* 180 | * Determine required size of output string. 181 | */ 182 | if (!size) 183 | size = strlen((const char *) string); 184 | 185 | outlen = size; 186 | cp = string; 187 | for (i=0; iai_addr, sizeof(sa_in)); 346 | memcpy(&(addr->v4), &sa_in.sin_addr, sizeof(struct in_addr)); 347 | } else { /* Must be AF_INET6 */ 348 | memcpy(&sa_in6, res->ai_addr, sizeof(sa_in6)); 349 | memcpy(&(addr->v6), &sa_in6.sin6_addr, sizeof(struct in6_addr)); 350 | } 351 | 352 | freeaddrinfo(res); 353 | 354 | *error_msg = NULL; 355 | return addr; 356 | } 357 | 358 | /* 359 | * my_ntoa -- IPv6 compatible inet_ntoa replacement 360 | * 361 | * Inputs: 362 | * 363 | * addr The IP address (either IPv4 or IPv6) 364 | * 365 | * Returns: 366 | * 367 | * Pointer to the string representation of the IP address. 368 | */ 369 | const char * 370 | my_ntoa(ip_address addr, int ipv6_flag) { 371 | static char ip_str[MAXLINE]; 372 | const char *cp; 373 | 374 | if (ipv6_flag) 375 | cp = inet_ntop(AF_INET6, &addr.v6, ip_str, MAXLINE); 376 | else 377 | cp = inet_ntop(AF_INET, &addr.v4, ip_str, MAXLINE); 378 | 379 | return cp; 380 | } 381 | 382 | /* 383 | * str_to_bandwidth -- Convert a bandwidth string to unsigned integer 384 | * 385 | * Inputs: 386 | * 387 | * bandwidth_string The bandwidth string to convert 388 | * 389 | * Returns: 390 | * 391 | * The bandwidth in bits per second as an unsigned integer 392 | */ 393 | unsigned 394 | str_to_bandwidth(const char *bandwidth_string) { 395 | char *bandwidth_str; 396 | size_t bandwidth_len; 397 | unsigned value; 398 | int multiplier=1; 399 | int end_char; 400 | 401 | bandwidth_str=dupstr(bandwidth_string); /* Writable copy */ 402 | bandwidth_len=strlen(bandwidth_str); 403 | end_char = bandwidth_str[bandwidth_len-1]; 404 | if (!isdigit(end_char)) { /* End character is not a digit */ 405 | bandwidth_str[bandwidth_len-1] = '\0'; /* Remove last character */ 406 | switch (end_char) { 407 | case 'M': 408 | case 'm': 409 | multiplier = 1000000; 410 | break; 411 | case 'K': 412 | case 'k': 413 | multiplier = 1000; 414 | break; 415 | default: 416 | err_msg("ERROR: Unknown bandwidth multiplier character: \"%c\"", 417 | end_char); 418 | break; 419 | } 420 | } 421 | value=Strtoul(bandwidth_str, 10); 422 | free(bandwidth_str); 423 | return multiplier * value; 424 | } 425 | 426 | /* 427 | * str_to_interval -- Convert an interval string to unsigned integer 428 | * 429 | * Inputs: 430 | * 431 | * interval_string The interval string to convert 432 | * 433 | * Returns: 434 | * 435 | * The interval in microsecons as an unsigned integer 436 | */ 437 | unsigned 438 | str_to_interval(const char *interval_string) { 439 | char *interval_str; 440 | size_t interval_len; 441 | unsigned value; 442 | int multiplier=1000; 443 | int end_char; 444 | 445 | interval_str=dupstr(interval_string); /* Writable copy */ 446 | interval_len=strlen(interval_str); 447 | end_char = interval_str[interval_len-1]; 448 | if (!isdigit(end_char)) { /* End character is not a digit */ 449 | interval_str[interval_len-1] = '\0'; /* Remove last character */ 450 | switch (end_char) { 451 | case 'U': 452 | case 'u': 453 | multiplier = 1; 454 | break; 455 | case 'S': 456 | case 's': 457 | multiplier = 1000000; 458 | break; 459 | default: 460 | err_msg("ERROR: Unknown interval multiplier character: \"%c\"", 461 | end_char); 462 | break; 463 | } 464 | } 465 | value=Strtoul(interval_str, 10); 466 | free(interval_str); 467 | return multiplier * value; 468 | } 469 | 470 | /* 471 | * dupstr -- duplicate a string 472 | * 473 | * Inputs: 474 | * 475 | * str The string to duplcate 476 | * 477 | * Returns: 478 | * 479 | * A pointer to the duplicate string. 480 | * 481 | * This is a replacement for the common but non-standard "strdup" 482 | * function. 483 | * 484 | * The returned pointer points to Malloc'ed memory, which must be 485 | * free'ed by the caller. 486 | */ 487 | char * 488 | dupstr(const char *str) { 489 | char *cp; 490 | size_t len; 491 | 492 | len = strlen(str) + 1; /* Allow space for terminating NULL */ 493 | cp = Malloc(len); 494 | strlcpy(cp, str, len); 495 | return cp; 496 | } 497 | -------------------------------------------------------------------------------- /wrappers.c: -------------------------------------------------------------------------------- 1 | /* 2 | * The TCP Scanner (tcp-scan) is Copyright (C) 2003-2008 Roy Hills, 3 | * NTA Monitor Ltd. 4 | * 5 | * This file is part of tcp-scan. 6 | * 7 | * tcp-scan 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 | * tcp-scan 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 tcp-scan. If not, see . 19 | * 20 | * Author: Roy Hills 21 | * Date: 8 November 2003 22 | * 23 | * This file contains wrapper functions for system and library calls that 24 | * are not expected to fail. If they do fail, then it calls err_sys to 25 | * print a diagnostic and terminate the program. This removed the tedious 26 | * "if ((function()) == NULL) err_sys("function");" logic thus making the 27 | * code easier to read. 28 | * 29 | * The wrapper functions have the same name as the system or library function 30 | * but with an initial capital letter. E.g. Gethostbyname(). This convention 31 | * if from Richard Steven's UNIX Network Programming book. 32 | * 33 | */ 34 | 35 | #include "tcp-scan.h" 36 | 37 | /* 38 | * We omit the timezone arg from this wrapper since it's obsolete and we never 39 | * use it. 40 | */ 41 | int Gettimeofday(struct timeval *tv) { 42 | int result; 43 | 44 | result = gettimeofday(tv, NULL); 45 | 46 | if (result != 0) 47 | err_sys("gettimeofday"); 48 | 49 | return result; 50 | } 51 | 52 | void *Malloc(size_t size) { 53 | void *result; 54 | 55 | result = malloc(size); 56 | 57 | if (result == NULL) 58 | err_sys("malloc"); 59 | 60 | return result; 61 | } 62 | 63 | void *Realloc(void *ptr, size_t size) { 64 | void *result; 65 | 66 | result=realloc(ptr, size); 67 | 68 | if (result == NULL) 69 | err_sys("realloc"); 70 | 71 | return result; 72 | } 73 | 74 | unsigned long int Strtoul(const char *nptr, int base) { 75 | char *endptr; 76 | unsigned long int result; 77 | 78 | result=strtoul(nptr, &endptr, base); 79 | if (endptr == nptr) /* No digits converted */ 80 | err_msg("ERROR: \"%s\" is not a valid numeric value", nptr); 81 | if (*endptr != '\0' && !isspace((unsigned char)*endptr)) 82 | err_msg("ERROR: \"%s\" is not a valid numeric value", nptr); 83 | 84 | return result; 85 | } 86 | 87 | long int Strtol(const char *nptr, int base) { 88 | char *endptr; 89 | long int result; 90 | 91 | result=strtol(nptr, &endptr, base); 92 | if (endptr == nptr) /* No digits converted */ 93 | err_msg("ERROR: \"%s\" is not a valid numeric value", nptr); 94 | if (*endptr != '\0' && !isspace((unsigned char)*endptr)) 95 | err_msg("ERROR: \"%s\" is not a valid numeric value", nptr); 96 | 97 | return result; 98 | } 99 | 100 | /* 101 | * my_lookupdev() is adapted from pcap_lookupdev() which is depreciated 102 | * in libpcap 1.9.0 and later. 103 | */ 104 | char * 105 | my_lookupdev(char *errbuf) 106 | { 107 | pcap_if_t *alldevs; 108 | 109 | #ifndef IF_NAMESIZE 110 | #define IF_NAMESIZE 8192 111 | #endif 112 | 113 | static char device[IF_NAMESIZE + 1]; 114 | char *ret; 115 | 116 | if (pcap_findalldevs(&alldevs, errbuf) == -1) 117 | return (NULL); 118 | 119 | if (alldevs == NULL || (alldevs->flags & PCAP_IF_LOOPBACK)) { 120 | /* 121 | * There are no devices on the list, or the first device 122 | * on the list is a loopback device, which means there 123 | * are no non-loopback devices on the list. This means 124 | * we can't return any device. 125 | */ 126 | (void)strlcpy(errbuf, "no suitable device found", PCAP_ERRBUF_SIZE); 127 | ret = NULL; 128 | } else { 129 | /* 130 | * Return the name of the first device on the list. 131 | */ 132 | (void)strlcpy(device, alldevs->name, sizeof(device)); 133 | ret = device; 134 | } 135 | 136 | pcap_freealldevs(alldevs); 137 | return (ret); 138 | } 139 | --------------------------------------------------------------------------------