├── COPYING ├── ChangeLog ├── Makefile ├── README ├── grepcidr.1 └── grepcidr.c /COPYING: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc. 5 | 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Library General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | -------------------------------------------------------------------------------- /ChangeLog: -------------------------------------------------------------------------------- 1 | Version 2.991 2 | ============ 3 | 4 | - Add -D for partial range matching 5 | - Fix minor bugs 6 | - More extensive debugging info incuded with -DDEBUG 7 | 8 | Version 2.99 9 | ============ 10 | 11 | - Add -C to match CIDR ranges in the input 12 | 13 | Version 2.98 14 | =========== 15 | 16 | - Make 0.0.0.0/0 work 17 | - Replace fgets() with getline() so it can handle arbitrary line 18 | lengths in non-mmap files 19 | - Twiddle state machine so ::::ffff:1.2.3.4 and ::::1 are recognized 20 | as IPv6 21 | - Match IPv6 after 8 groups so 1:2:3:4:5:6:7:8:junk works 22 | - Fix bug that allowed oversize values in first v6 group 23 | - Peek after last colon in low group so 1::2:junk works 24 | 25 | Version 2.97 26 | =========== 27 | 28 | - Quick flag doesn't recognize v4 with dots before or after, to limit 29 | false matches in rDNS names 30 | 31 | Version 2.96 32 | =========== 33 | 34 | - New -s flag to stop comlaints about sloppy (misaligned CIDRs) 35 | - CIDRs now always properly bit aligned, even if the base address wasn't 36 | - Minor bug fixes 37 | 38 | Version 2.95 39 | =========== 40 | 41 | - Rewritten to use a faster state machine recognizer and mapped files, 42 | about 3 times faster overall, no speed penalty for matching through 43 | the whole line 44 | - Handles both IPv4 and IPv6 patterns 45 | - Better error checking 46 | - Handle multiple input files 47 | 48 | Version 1.3 49 | =========== 50 | - Much faster than past versions due to binary search of patterns 51 | - Decreased memory usage 52 | - Applied search improvements suggested by Dick Wesseling 53 | - Now supports IP ranges as well as CIDR format 54 | - Improved usage to be more grep-like (e.g. filename on command line) 55 | - Now uses grep-like exit code (0=ok, 1=no match, 2=error) 56 | 57 | 58 | Version 1.2 59 | =========== 60 | - Improved algorithm for faster processing with large number of patterns 61 | (approx. 50 times as fast on test set, with specs from diverse regions) 62 | 63 | 64 | version 1.1 65 | =========== 66 | - New algorithm has increased speed by about 2.4 times! 67 | - Added -c (count) option, like grep 68 | - Reduced memory usage in case loading large files (-f) 69 | - Added simple Makefile 70 | 71 | 72 | version 1.0 73 | =========== 74 | - First public release 75 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # 2 | # Makefile for grepcidr 3 | # 4 | 5 | # Set to where you'd like grepcidr installed 6 | INSTALLDIR=/usr/local/bin 7 | 8 | # Set to your favorite C compiler and flags 9 | # with GCC, -O3 makes a lot of difference 10 | # -DDEBUG=1 prints out hex versions of IPs and matches 11 | 12 | CFLAGS=-O3 -Wall -pedantic 13 | #CFLAGS=-g -Wall -pedantic -DDEBUG=1 14 | TFILES=COPYING ChangeLog Makefile README grepcidr.1 grepcidr.c 15 | DIR!=basename ${PWD} 16 | 17 | # End of settable values 18 | 19 | all: grepcidr 20 | 21 | grepcidr: grepcidr.c 22 | $(CC) $(CFLAGS) -o grepcidr grepcidr.c 23 | 24 | install: grepcidr 25 | cp grepcidr $(INSTALLDIR) 26 | 27 | clean: 28 | rm -f grepcidr 29 | 30 | tar: 31 | cd ..; tar cvjf ${DIR}.tjz ${TFILES:C%^%${DIR}/%} 32 | -------------------------------------------------------------------------------- /README: -------------------------------------------------------------------------------- 1 | grepcidr 2.991 - Filter IP addresses matching IPv4 and IPv6 CIDR specification 2 | Parts Copyright (C) 2004-2005 Jem E. Berkes 3 | http://www.pc-tools.net/unix/grepcidr/ 4 | 5 | Revised by John Levine Dec 2013-Oct 2015, who makes 6 | no copyright claims to the modifications. 7 | 8 | PURPOSE 9 | ------- 10 | grepcidr can be used to filter a list of IP addresses against one or more 11 | Classless Inter-Domain Routing (CIDR) specifications, or arbitrary networks 12 | specified by an address range. As with grep, there are options to invert 13 | matching and load patterns from a file. grepcidr is capable of comparing 14 | thousands or even millions of IPs to networks with little memory usage and 15 | in reasonable computation time. 16 | 17 | grepcidr has endless uses in network software, including: mail filtering and 18 | processing, network security, log analysis, and many custom applications. 19 | 20 | COMPILING & INSTALLING 21 | ---------------------- 22 | Edit Makefile to customize the build. Then, 23 | make 24 | make install 25 | 26 | 27 | COMMAND USAGE 28 | ------------- 29 | Usage: 30 | grepcidr [-V] [-cCDvhais] PATTERN [FILE ...] 31 | grepcidr [-V] [-V] [-cCDvhais] [-e PATTERN | -f FILE] [FILE ...] 32 | 33 | -V Show software version 34 | -a Anchor matches to beginning of line, otherwise match anywhere 35 | -c Display count of the lines that would have been shown, instead of showing them 36 | -C Parse CIDR ranges in input and only match if a search term encompasses the entire range. 37 | -D Parse CIDR ranges in input and match if a search term matches any part of the range. 38 | -v Invert the sense of matching, to select non-matching IP addresses 39 | -e Specify pattern(s) on command-line 40 | -f Obtain CIDR and range pattern(s) from file 41 | -i Ignore patterns that are not valid CIDRs or ranges 42 | -h Do not print filenames when matching multiple files 43 | 44 | PATTERN specified on the command line may contain multiple patterns 45 | separated by whitespace or commas. For long lists of network patterns, 46 | specify a -f FILE to load where each line contains one pattern. Comment 47 | lines starting with # are ignored, as are comments following white space 48 | after a pattern. Use -i to ignore invalid pattern lines. 49 | 50 | Each pattern, whether on the command line or inside a file, may be: 51 | CIDR format a.b.c.d/xx or aa:bb::cc::dd/xx 52 | IP range a.b.c.d-e.f.g.h 53 | Single IP a.b.c.d or aa:bb:cc::dd 54 | 55 | IPv6 addresses can be written in any format including embedded IPv4. 56 | The zero address :: is accepted as a pattern but does not match in 57 | files. (Use regular grep if that's what you're looking for,) It does 58 | not accept IPv6 ranges, since few people use them. 59 | 60 | Grepcidr uses a state machine to look for IP addresses in the input, 61 | and a binary search to match addresses against patterns. Its speed is 62 | roughly O(N) in the size of the input, and O(log N) in the number of 63 | patterns. A prepass over the patterns merges adjacent and overlapping 64 | patterns so there is negligle speed penalty for matching, e.g. 65 | 1.2.2.0/24 and 1.2.3.0/24 rather than 1.2.2.0/23. 66 | 67 | Input files are mapped into memory if possible, so the state machine 68 | can make one pass over the whole file. If mapping fails, it reads the 69 | input a line at a time. 70 | 71 | EXAMPLES 72 | -------- 73 | 74 | grepcidr -f ournetworks blocklist > abuse.log 75 | Find our customers that show up in blocklists 76 | 77 | grepcidr 127.0.0.0/8,::1 iplog 78 | Searches for any localnet IP addresses inside the iplog file 79 | 80 | grepcidr "192.168.0.1-192.168.10.13" iplog 81 | Searches for IPs matching indicated range in the iplog file 82 | 83 | script | grepcidr -ivf whitelist > blacklist 84 | Create a blacklist, with whitelisted networks removed (inverse) 85 | 86 | grepcidr -if list1 list2 87 | Cross-reference two lists, outputs IPs common to both lists 88 | -------------------------------------------------------------------------------- /grepcidr.1: -------------------------------------------------------------------------------- 1 | .TH "GREPCIDR" "1" 2 | .SH "NAME" 3 | grepcidr \(em Filter IP addresses matching IPv4 and IPv6 address specifications 4 | .SH "SYNOPSIS" 5 | .PP 6 | \fBgrepcidr\fR [\fB-V\fP] [\fB-cCDvahisq\fP] \fIPATTERN\fP [\fIFILE ...\fP] 7 | .PP 8 | \fBgrepcidr\fR [\fB-V\fP] [\fB-cCDvahisq\fP] [\fB-e \fIPATTERN\fR\fP | \fB-f \fIFILE\fP] [\fIFILE ...\fP] 9 | .SH "DESCRIPTION" 10 | .PP 11 | \fBgrepcidr\fR can be used to filter a list of IP addresses and ranges against one or more 12 | IPv4 and IPv6 address ranges. As with grep, there are options to invert 13 | matching and load patterns from a file. grepcidr is designed to scale well, 14 | and handle large numbers of patterns and large input files efficiently. 15 | This version uses a completely rewritten parser that is typically two or three times 16 | faster than previous versions. 17 | .\" 18 | .SH "OPTIONS" 19 | .IP "\fB-V\fP" 10 20 | Show software version 21 | .IP "\fB-c\fP" 10 22 | Display count of the lines that otherwise would have been printed 23 | .IP "\fB-v\fP" 10 24 | Invert the sense of matching, to select lines with IPs that don't match any pattern 25 | .IP "\fB-a\fP" 10 26 | (anchor) Only match addresses that occur at the beginning of a line 27 | .IP "\fB-e\fP" 10 28 | Specify pattern(s) as an argument 29 | .IP "\fB-f\fP" 10 30 | Obtain pattern(s) from a file 31 | .IP "\fB-h\fP" 10 32 | Do not print file names with matched lines 33 | .IP "\fB-i\fP" 10 34 | Ignore bad patterns 35 | .IP "\fB-s\fP" 10 36 | (Sloppy) Don't complain about misaligned CIDR ranges. 37 | .IP "\fB-C\fP" 10 38 | Parse CIDR ranges in input and match if a search term covers the entire range. 39 | .IP "\fB-D\fP" 10 40 | Parse CIDR ranges in input and match if a search term covers any of the range. 41 | .IP "\fB-q\fP" 10 42 | (Quick) Ignore IPv4 addresses that are followed by a dot. 43 | .SH "USAGE NOTES" 44 | .PP 45 | PATTERN specified on the command line may contain multiple patterns 46 | separated by whitespace or commas. For long lists of network patterns, 47 | use \fB-f\fP to load a file where each line contains one pattern. Comment 48 | lines starting with # are ignored. 49 | In a file, each pattern can be followed by a space and comments. 50 | .PP 51 | Each pattern, whether on the command line or inside a file, may be: 52 | .PP 53 | .nf 54 | a.b.c.d/xx (IPv4 CIDR range) 55 | a.b.c.d-e.f.g.h (IPv4 range) 56 | a.b.c.d (Single IPv4 address) 57 | ab:cd::ef (Single IPv6 address) 58 | ab:cd::ef/xx (IPv6 CIDR range) 59 | ab::cd:a.b.c.d (IPv4 address embedded in IPv6) 60 | .fi 61 | .PP 62 | Invalid patterns are ignored with the \fB-i\fP flag, which can be useful for 63 | using files of IPs or CIDRs as patterns that also contain other material. 64 | CIDRs are always properly aligned even if the base address wasn't, e.g., 65 | 12.34.56.78/24 is treated as 12.34.56.0/24, 66 | and 1234:5678::abcd/64 is treated as 1234:5678::0/64. 67 | Complaints about misaligned CIDRs can be suppressed with \fB-s\fP. 68 | .SH COMPATIBILITY 69 | .PP 70 | In version 2.9 \fBgrepcidr\fR normally searches for IP addresses anywhere 71 | on the input line. 72 | It uses a reasonable but ad-hoc parser to look for the begining of an address. 73 | This can cause unexpected results in some cases, e.g. ab:c12.34.56.78 will not 74 | match as an IPv4 address because ab:c12 looks like the beginning of an IPv6 75 | address. 76 | Addresses written as IPv6 embedded IPv4 addresses will match either the IPv4 77 | or IPv6 address pattern, e.g. ::ffff:12.34.56.78 will match both ::ffff:0/96 and 12.34.0.0/16. 78 | .PP 79 | Even though :: is a valid way to write a zero IPv6 address, grepcidr won't match it. 80 | (If that's what you want, use regular grep.) 81 | It will match 0:: or ::0.0.0.0 or 0::0 or or any other form. 82 | .PP 83 | Normallly grepcidr will match every string that looks like 84 | an IPv4 address, so in 1.2.3.4.5.6.7.8 it will match 85 | both 1.2.3.4 and 5.6.7.8. 86 | The \fB-q\fP option ignores addresses preceded or followed by a dot, 87 | which avoids false matches in some contexts. 88 | .PP 89 | Use the \fB-a\fP option to look for addresses only at the 90 | start of the line, optionally preceded by whitespace. 91 | This type of search is stricter, but not significantly faster. 92 | .PP 93 | Note that \fB-v\fP outputs only lines that do contain IP addresses, but do not match 94 | any of the patterns. 95 | .PP 96 | If there is more than one file named on the command line, each matched line 97 | is preceded by the file name unless the \fR-h\fP flag is set. 98 | .SH "EXAMPLES" 99 | .PP 100 | \fI\fBgrepcidr\fR \-f ournetworks blacklist > abuse.log\fP 101 | .PP 102 | Find customers (CIDR ranges in file) that appear in blacklist 103 | .PP 104 | \fI\fBgrepcidr\fR 127.0.0.0/8,::1 iplog\fP 105 | .PP 106 | Searches for any localnet IP addresses inside the iplog file 107 | .PP 108 | \fI\fBgrepcidr\fR "192.168.0.1-192.168.10.13" iplog\fP 109 | .br 110 | \fI\fBgrepcidr\fR "2001:3def:1234::/48" iplog\fP 111 | .PP 112 | Searches for IPs matching indicated range in the iplog file 113 | .PP 114 | \fI\fBscript\fR | \fBgrepcidr\fR \-vf whitelist > blacklist\fP 115 | .PP 116 | Create a blacklist, with whitelisted networks removed (inverse) 117 | .PP 118 | \fI\fBgrepcidr\fR \-f list1 list2\fP 119 | .PP 120 | Cross-reference two lists, outputs IPs common to both lists 121 | .SH "EXIT STATUS" 122 | .PP 123 | As with grep: the exit status is 0 if matching IPs are found, and 1 124 | if not found. If an error occurred the exit status is 2. 125 | .SH "AUTHOR" 126 | .PP 127 | This software is based on software written by Jem Berkes , 128 | extensively rewritten by John Levine . 129 | Permission is granted to copy, distribute and/or modify this document under 130 | the terms of the GNU General Public License, Version 2 or any later version 131 | published by the Free Software Foundation. 132 | -------------------------------------------------------------------------------- /grepcidr.c: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | grepcidr 2.99 - Filter IP addresses matching IPv4 and IPv6 CIDR specification 4 | Parts copyright (C) 2004, 2005 Jem E. Berkes 5 | www.sysdesign.ca 6 | Somewhat rewritten by John Levine 7 | 8 | This program is free software; you can redistribute it and/or modify 9 | it under the terms of the GNU General Public License as published by 10 | the Free Software Foundation; either version 2 of the License, or 11 | (at your option) any later version. 12 | 13 | This program is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | GNU General Public License for more details. 17 | 18 | You should have received a copy of the GNU General Public License 19 | along with this program; if not, write to the Free Software 20 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 21 | $Header: /Users/johnl/grepcidr-2.991/RCS/grepcidr.c,v 1.5 2015/10/25 15:11:06 johnl Exp $ 22 | */ 23 | 24 | 25 | #define _WITH_GETLINE /* hint for FreeBSD */ 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include 34 | #include 35 | 36 | #define EXIT_OK 0 37 | #define EXIT_NOMATCH 1 38 | #define EXIT_ERROR 2 39 | 40 | #define TXT_VERSION "grepcidr 2.991\nParts copyright (C) 2004, 2005 Jem E. Berkes \n" 41 | #define TXT_USAGE "Usage:\n" \ 42 | "\tgrepcidr [-V] [-cCDvhais] PATTERN [FILE...]\n" \ 43 | "\tgrepcidr [-V] [-cCDvhais] [-e PATTERN | -f FILE] [FILE...]\n" 44 | #define MAXFIELD 512 45 | #define TOKEN_SEPS "\t,\r\n" /* so user can specify multiple patterns on command line */ 46 | #define INIT_NETWORKS 8192 47 | 48 | /* 49 | Specifies a network. Whether originally in CIDR format (IP/mask) 50 | or a range of IPs (IP_start-IP_end), spec is converted to a range. 51 | The range is min to max (32-bit or 128 bit IPs) inclusive. 52 | */ 53 | struct netspec 54 | { 55 | unsigned int min; 56 | unsigned int max; 57 | }; 58 | 59 | typedef struct v6addr { unsigned char a[16]; } v6addr; 60 | 61 | /* redefine this if your memcmp is slow, but it probably isn't */ 62 | #define v6cmp(a1, a2) memcmp((a1).a,(a2).a,16) 63 | 64 | struct netspec6 65 | { 66 | v6addr min; 67 | v6addr max; 68 | }; 69 | 70 | /* Global variables */ 71 | static unsigned int npatterns = 0; /* total patterns in array */ 72 | static unsigned int n6patterns = 0; /* total patterns in v6 array */ 73 | static unsigned int capacity = 0; /* current capacity of array */ 74 | static unsigned int capacity6 = 0; /* current capacity of v6 array */ 75 | static struct netspec* array = NULL; /* array of patterns, network specs */ 76 | static struct netspec6* array6 = NULL; /* array of patterns, v6 network specs */ 77 | static unsigned int counting = 0; /* when non-zero, counts matches */ 78 | static int invert = 0; /* flag for inverted mode */ 79 | static int anchor = 0; /* anchor matches at beginning of line */ 80 | static int nonames = 0; /* don't show filenames */ 81 | static int nmatch = 0; /* count of matches for exit code */ 82 | static int igbadpat = 0; /* ignore bad patterns */ 83 | static int sloppy = 0; /* don't complain about sloppy CIDR */ 84 | static int cidrsearch = 0; /* parse and match CIDR in haystack */ 85 | static int didrsearch = 0; /* match CIDR if overlaps with haystack */ 86 | static int quick = 0; /* quick match, ignore v4 with dots before or after */ 87 | 88 | static void scan_block(char *bp, size_t blen, const char *fn); 89 | static void scan_read(FILE *f, const char *fn); 90 | static int applymask6(const v6addr ahi, int size, struct netspec6 *spec); 91 | 92 | /* for getline */ 93 | char *linep = NULL; 94 | size_t linesize; 95 | 96 | /* 97 | Insert new spec inside array of network spec 98 | Dynamically grow array buffer as needed 99 | */ 100 | void array_insert(struct netspec* newspec) 101 | { 102 | /* Initial array allocation */ 103 | if(!array) { 104 | capacity = INIT_NETWORKS; 105 | array = (struct netspec*) malloc(capacity*sizeof(struct netspec)); 106 | if(!array) { 107 | perror("Out of memory"); 108 | exit(EXIT_ERROR); 109 | } 110 | } 111 | if (npatterns == capacity) 112 | { 113 | capacity *= 2; 114 | array = (struct netspec *)realloc(array, capacity*sizeof(struct netspec)); 115 | if(!array) { 116 | perror("Out of memory"); 117 | exit(EXIT_ERROR); 118 | } 119 | } 120 | array[npatterns++] = *newspec; 121 | } 122 | 123 | void array_insert6(struct netspec6* newspec) 124 | { 125 | /* Initial array allocation */ 126 | if(!array6) { 127 | capacity6 = INIT_NETWORKS; 128 | array6 = (struct netspec6*) malloc(capacity6*sizeof(struct netspec6)); 129 | if(!array6) { 130 | perror("Out of memory"); 131 | exit(EXIT_ERROR); 132 | } 133 | } 134 | if (n6patterns == capacity6) 135 | { 136 | capacity6 *= 2; 137 | array6 = (struct netspec6 *)realloc(array6, capacity6*sizeof(struct netspec6)); 138 | if(!array6) { 139 | perror("Out of memory"); 140 | exit(EXIT_ERROR); 141 | } 142 | } 143 | array6[n6patterns++] = *newspec; 144 | } 145 | 146 | /* 147 | Given string, fills in the struct netspec (must be allocated) 148 | Accept CIDR IP/mask format or IP_start-IP_end range. 149 | Returns true (nonzero) on success, false (zero) on failure. 150 | */ 151 | int net_parse(const char* line, struct netspec* spec) 152 | { 153 | unsigned int minip = 0, maxip = 0; 154 | unsigned int octet = 0; 155 | unsigned int size = 0; /* if using CIDR IP/mask format */ 156 | unsigned int mask; 157 | char *p; 158 | enum iscan { 159 | I_BEG = 0, /* beginning of line */ 160 | I_IP1, /* first octet*/ 161 | I_IP1D, /* dot after first octet */ 162 | I_IP2, /* second octet */ 163 | I_IP2D, /* dot after second octet */ 164 | I_IP3, /* third octet */ 165 | I_IP3D, /* dot after third octet */ 166 | I_IP4, /* fourth octet */ 167 | I_MIP1, /* first octet of max IP */ 168 | I_MIP1D, /* dot after first octet */ 169 | I_MIP2, /* second octet */ 170 | I_MIP2D, /* dot after second octet */ 171 | I_MIP3, /* third octet */ 172 | I_MIP3D, /* dot after third octet */ 173 | I_MIP4, /* fourth octet */ 174 | I_PIP, /* post first IP */ 175 | I_MASK, /* scanning a mask */ 176 | I_PD /* post dash */ 177 | 178 | } state; 179 | state = I_BEG; 180 | for(p = (char *)line;;) { 181 | int ch = *p++; 182 | 183 | switch(state) { 184 | case I_BEG: 185 | if(isspace(ch)) 186 | continue; 187 | if(isdigit(ch)) { /* start a potential IP */ 188 | octet = ch-'0'; 189 | state = I_IP1; 190 | continue; 191 | } 192 | break; 193 | 194 | case I_IP1: /* in an IP address */ 195 | case I_IP2: 196 | case I_IP3: 197 | 198 | case I_MIP1: /* in a second IP address */ 199 | case I_MIP2: 200 | case I_MIP3: 201 | if(isdigit(ch)) { 202 | octet = octet*10 + ch-'0'; 203 | continue; 204 | } 205 | if(ch == '.') { 206 | if(octet > 255) { /* not a real address */ 207 | return 0; 208 | } 209 | maxip <<= 8; 210 | maxip += octet; 211 | state++; /* corresponding dot state */ 212 | continue; 213 | } 214 | /* otherwise, wasn't a full IP */ 215 | return 0; 216 | 217 | case I_IP1D: /* saw dot after an octet */ 218 | case I_IP2D: 219 | case I_IP3D: 220 | 221 | case I_MIP1D: /* saw dot after an octet */ 222 | case I_MIP2D: 223 | case I_MIP3D: 224 | if(isdigit(ch)) { 225 | octet = ch-'0'; 226 | state++; /* next octet state */ 227 | continue; 228 | } 229 | return 0; /* wasn't an IP */ 230 | 231 | case I_IP4: /* in last octet */ 232 | if(isdigit(ch)) { 233 | octet = octet*10 + ch-'0'; 234 | continue; 235 | } 236 | 237 | /* OK, we have the IP */ 238 | if(octet > 255) { /* not a real address */ 239 | return 0; 240 | } 241 | maxip <<= 8; 242 | maxip += octet; 243 | minip = maxip; /* until we see otherwise */ 244 | if(!ch) break; /* end of string */ 245 | if(ch == '/') 246 | state = I_MASK; 247 | else if(ch == '-') 248 | state = I_PD; 249 | else 250 | state = I_PIP; 251 | continue; 252 | 253 | case I_MIP4: /* in last octet of range max*/ 254 | if(isdigit(ch)) { 255 | octet = octet*10 + ch-'0'; 256 | continue; 257 | } 258 | 259 | /* OK, we have the IP */ 260 | if(octet > 255) { /* not a real address */ 261 | return 0; 262 | } 263 | maxip <<= 8; 264 | maxip += octet; 265 | if(ch && !isspace(ch)) 266 | return 0; /* junk at end */ 267 | break; 268 | 269 | case I_PIP: 270 | if(ch == '/') 271 | state = I_MASK; 272 | else if(ch == '-') 273 | state = I_PD; 274 | else if(!ch) 275 | break; /* single IP with spaces after it */ 276 | else if(!isspace(ch)) 277 | return 0; /* junk */ 278 | continue; 279 | case I_PD: 280 | if(isspace(ch)) 281 | continue; 282 | if(!isdigit(ch)) 283 | return 0; /* junk */ 284 | octet = ch-'0'; 285 | state = I_MIP1; 286 | continue; 287 | 288 | case I_MASK: /* CIDR mask size */ 289 | if(isdigit(ch)) { 290 | size = size*10 + ch-'0'; 291 | continue; 292 | } 293 | if(ch && !isspace(ch)) 294 | return 0; /* junk at end */ 295 | if(size > 32) 296 | return 0; /* not a reasonable cidr */ 297 | mask = (1L<<(32-size))-1; 298 | if(maxip&mask && !sloppy) 299 | fprintf(stderr, "Invalid cidr: %s\n", line); 300 | minip &= ~mask; /* force to CIDR boundary */ 301 | maxip |= mask; 302 | 303 | break; 304 | } 305 | if(ch && !isspace(ch)) return 0; /* crud at end of address */ 306 | break; 307 | } 308 | /* got something, return it */ 309 | spec->min = minip; 310 | spec->max = maxip; 311 | #if DEBUG 312 | if(getenv("RANGES"))printf("range %08x - %08x\n", minip, maxip); 313 | #endif /* DEBUG */ 314 | if(minip > maxip) 315 | fprintf(stderr, "Backward range: %s\n", line); 316 | return 1; 317 | } 318 | 319 | /* 320 | * parse IPv6 address or CIDR 321 | * no ranges, since they don't seem popular 322 | * This should handle the full syntax in RFC 4291 sec 2.2 and 2.3 323 | */ 324 | /* turn a hex digit to a value, has to be a hex digit */ 325 | #define xtod(c) ((c<='9')?(c-'0'):((c&15)+9)) 326 | 327 | int net_parse6(const char* line, struct netspec6* spec) 328 | { 329 | v6addr ahi; /* high part of address */ 330 | v6addr alo; /* low part of address */ 331 | int nhi = 0; /* how many bytes in ahi */ 332 | int nlo = 0; /* how many bytes in alo */ 333 | int octet = -1; /* current v4 octet, -1 means not an octet */ 334 | unsigned int chunk = 0; /* current 16 bit chunk */ 335 | int size = -1; 336 | enum sv6 { 337 | V_BEG = 0, /* beginning of string */ 338 | V_HCH, /* in a hi chunk */ 339 | V_HC1, /* hi, seen one colon */ 340 | V_HC2, /* hi, seen two colons */ 341 | V_LCH, /* in a low chunk */ 342 | V_LC1, /* seen a low colon */ 343 | V_IC1, /* seen initial colon */ 344 | V_EIP1D, /* dot after first octet of embedded IPv4 */ 345 | V_EIP2, /* second octet */ 346 | V_EIP2D, /* dot after second octet */ 347 | V_EIP3, /* third octet */ 348 | V_EIP3D, /* dot after third octet */ 349 | V_EIP4, /* fourth octet */ 350 | V_SIZE /* CIDR size */ 351 | } state; 352 | char *p = (char *)line; 353 | 354 | state = 0; 355 | 356 | for(;;) { 357 | int ch = *p++; 358 | 359 | switch(state) { 360 | case V_BEG: 361 | if(isspace(ch)) continue; 362 | if(isxdigit(ch)) { /* first chunk can't be v4 */ 363 | chunk = xtod(ch); 364 | state = V_HCH; 365 | continue; 366 | } 367 | if(ch == ':') { 368 | state = V_IC1; 369 | continue; 370 | } 371 | return 0; /* not an IP */ 372 | 373 | case V_IC1: /* leading colon must be two colons */ 374 | if(ch == ':') { 375 | state = V_HC2; 376 | continue; 377 | } 378 | return 0; /* not an IP */ 379 | 380 | case V_HCH: 381 | if(isxdigit(ch)) { 382 | chunk = (chunk<<4)+xtod(ch); 383 | if(isdigit(ch)) { 384 | if(octet >= 0) octet = octet*10 + ch-'1'; 385 | } else 386 | octet = -1; /* not v4 */ 387 | continue; 388 | } 389 | /* finish the current chunk */ 390 | 391 | if(ch == '.') { 392 | if(nhi == 12 && octet >= 0 && octet <= 255) { /* embedded v4 */ 393 | ahi.a[nhi++] = octet; 394 | state = V_EIP1D; 395 | continue; 396 | } 397 | return 0; /* not an IP */ 398 | } 399 | 400 | if(nhi > 14) return 0; /* too many chunks */ 401 | ahi.a[nhi++] = chunk >> 8; /* big-endian for memcmp() */ 402 | ahi.a[nhi++] = chunk & 255; 403 | if(ch == ':') { 404 | state = V_HC1; 405 | continue; 406 | } 407 | if(ch == '/') { 408 | state = V_SIZE; 409 | continue; 410 | } 411 | break; /* end of the number */ 412 | 413 | case V_HC1: 414 | if(isxdigit(ch)) { 415 | chunk = xtod(ch); 416 | if(isdigit(ch)) 417 | octet = chunk; 418 | else 419 | octet = -1; 420 | state = V_HCH; 421 | continue; 422 | } 423 | if(ch == ':') { 424 | state = V_HC2; 425 | continue; 426 | } 427 | return 0; /* not an IP */ 428 | 429 | case V_HC2: 430 | if(isxdigit(ch)) { /* two colons and digit, start low half */ 431 | chunk = xtod(ch); 432 | if(isdigit(ch)) 433 | octet = chunk; 434 | else 435 | octet = -1; 436 | state = V_LCH; 437 | continue; 438 | } 439 | if(ch == '/') { 440 | state = V_SIZE; 441 | continue; 442 | } 443 | break; /* end of only high half */ 444 | 445 | case V_LCH: 446 | if(isxdigit(ch)) { 447 | chunk = (chunk<<4)+xtod(ch); 448 | if(isdigit(ch)) { 449 | if(octet >= 0) octet = octet*10 + ch-'0'; 450 | } else 451 | octet = -1; /* not v4 */ 452 | continue; 453 | } 454 | /* finish the current chunk */ 455 | if(ch == '.') { 456 | if((nhi+nlo) < 12 457 | && octet >= 0 && octet <= 255) { /* embedded v4 */ 458 | /* move all into ahi */ 459 | memset(ahi.a+nhi, 0, 12-(nhi+nlo)); 460 | if(nlo) { 461 | memcpy(ahi.a+12-nlo, alo.a, nlo); 462 | nlo = 0; 463 | } 464 | nhi = 12; 465 | ahi.a[nhi++] = octet; 466 | state = V_EIP1D; 467 | continue; 468 | } 469 | return 0; /* not an embedded v4 */ 470 | } 471 | 472 | if((nhi+nlo) > 12) return 0; /* too many chunks */ 473 | if(chunk > 0xffff) return 0; /* too big for a chunk */ 474 | alo.a[nlo++] = chunk >> 8; /* big-endian for memcmp() */ 475 | alo.a[nlo++] = chunk & 255; 476 | if(ch == ':') { 477 | state = V_LC1; 478 | continue; 479 | } 480 | if(ch == '/') { 481 | state = V_SIZE; 482 | continue; 483 | } 484 | break; /* end of the number */ 485 | 486 | case V_LC1: 487 | if(isxdigit(ch)) { 488 | chunk = xtod(ch); 489 | if(isdigit(ch)) 490 | octet = chunk; 491 | else 492 | octet = -1; 493 | state = V_LCH; 494 | continue; 495 | } 496 | return 0; /* trailing junk, not an IP */ 497 | 498 | case V_EIP1D: /* dot after first octet of embedded IPv4 */ 499 | case V_EIP2D: /* dot after second octet */ 500 | case V_EIP3D: /* dot after third octet */ 501 | if(isdigit(ch)) { 502 | octet = ch-'0'; 503 | state++; 504 | continue; 505 | } 506 | return 0; /* not an IP */ 507 | 508 | case V_EIP2: /* second octet */ 509 | case V_EIP3: /* third octet */ 510 | if(isdigit(ch)) { 511 | octet = octet*10 + ch-'0'; 512 | continue; 513 | } 514 | if(ch == '.') { 515 | if(octet > 255) return 0; /* not an IP */ 516 | ahi.a[nhi++] = octet; 517 | state++; 518 | continue; 519 | } 520 | return 0; /* not an IP */ 521 | 522 | case V_EIP4: /* fourth octet */ 523 | if(isdigit(ch)) { 524 | octet = octet*10 + ch-'0'; 525 | continue; 526 | } 527 | if(octet > 255) break; /* not an IP */ 528 | ahi.a[nhi++] = octet; 529 | if(ch == '/') { 530 | state = V_SIZE; 531 | continue; 532 | } 533 | break; /* four octets, we're done */ 534 | 535 | case V_SIZE: 536 | if(isdigit(ch)) { 537 | if (size < 0) size = 0; 538 | size = size*10 + ch-'0'; 539 | continue; 540 | } 541 | if(size < 0 || size > 128) return 0; /* no digits or junk at the end */ 542 | break; 543 | } 544 | break; 545 | /* accept if \0 or space after an item */ 546 | if(ch && !isspace(ch)) return 0; /* crud in the item */ 547 | } 548 | 549 | /* combine ahi and alo */ 550 | if(nlo && (nhi+nlo) >= 16) return 0; /* too many chunks */ 551 | if((nhi+nlo) < 16) 552 | memset(ahi.a+nhi, 0, 16-(nhi+nlo)); 553 | if(nlo)memcpy(ahi.a+16-nlo, alo.a, nlo); 554 | if (!applymask6(ahi, size, spec) && !sloppy) { 555 | p = strchr(line, '\n'); 556 | if(p) *p = 0; /* just a string */ 557 | fprintf(stderr, "Bad cidr range: %s\n", line); 558 | } 559 | return 1; 560 | } 561 | 562 | /* Return 0 (softfail) if bits were set in host part of CIDR address */ 563 | static int applymask6(const v6addr ahi, int size, struct netspec6 *spec) 564 | { 565 | int badbits = 0; /* bits already set, bad CIDR */ 566 | assert(size >= 0 && size <= 128); 567 | 568 | spec->min = spec->max = ahi; 569 | 570 | if(size >= 0) { /* set low bits for the range */ 571 | /* and also check that they were already zero */ 572 | int nbits = size&7; /* bits within a byte */ 573 | int nbytes = size >> 3; 574 | 575 | if(nbits) { 576 | int mask = 255>>nbits; 577 | 578 | if(ahi.a[nbytes]&mask) badbits = 1; 579 | spec->min.a[nbytes] &= 255-mask; 580 | spec->max.a[nbytes] |= mask; 581 | nbytes++; 582 | } 583 | while(nbytes < 16) { 584 | if(ahi.a[nbytes]) badbits = 1; 585 | spec->min.a[nbytes] = 0; 586 | spec->max.a[nbytes] = 255; 587 | nbytes++; 588 | } 589 | } 590 | return !badbits; 591 | } 592 | 593 | /* Compare two netspecs, for sorting. Comparison is done on minimum of range */ 594 | int netsort(const void* a, const void* b) 595 | { 596 | unsigned int c1 = ((struct netspec*)a)->min; 597 | unsigned int c2 = ((struct netspec*)b)->min; 598 | if (c1 < c2) return -1; 599 | if (c1 > c2) return +1; 600 | 601 | c1 = ((struct netspec*)a)->max; 602 | c2 = ((struct netspec*)b)->max; 603 | if (c1 < c2) return -1; 604 | if (c1 > c2) return +1; 605 | return 0; 606 | } 607 | 608 | int netsort6(const void* a, const void* b) 609 | { 610 | int r; 611 | v6addr *c1 = &((struct netspec6*)a)->min; 612 | v6addr *c2 = &((struct netspec6*)b)->min; 613 | r = v6cmp(*c1, *c2); 614 | if(r != 0) return r; 615 | 616 | c1 = &((struct netspec6*)a)->max; 617 | c2 = &((struct netspec6*)b)->max; 618 | return v6cmp(*c1, *c2); 619 | } 620 | 621 | int main(int argc, char* argv[]) 622 | { 623 | static char shortopts[] = "acCDe:f:iqsvV"; 624 | char* pat_filename = NULL; /* filename containing patterns */ 625 | char* pat_strings = NULL; /* pattern strings on command line */ 626 | int foundopt; 627 | 628 | if (argc == 1) 629 | { 630 | fprintf(stderr, TXT_USAGE); 631 | return EXIT_ERROR; 632 | } 633 | 634 | while ((foundopt = getopt(argc, argv, shortopts)) != -1) 635 | { 636 | switch (foundopt) 637 | { 638 | case 'V': 639 | puts(TXT_VERSION); 640 | return EXIT_ERROR; 641 | 642 | case 'c': 643 | counting = 1; 644 | break; 645 | 646 | case 'v': 647 | invert = 1; 648 | break; 649 | 650 | case 'h': 651 | nonames = 1; 652 | break; 653 | 654 | case 'a': 655 | anchor = 1; 656 | break; 657 | 658 | case 'i': 659 | igbadpat = 1; 660 | break; 661 | 662 | case 'q': 663 | quick = 1; 664 | break; 665 | 666 | case 's': 667 | sloppy = 1; 668 | break; 669 | 670 | case 'D': 671 | didrsearch = 1; 672 | /* fall through */ 673 | 674 | case 'C': 675 | cidrsearch = 1; 676 | break; 677 | 678 | case 'e': 679 | pat_strings = optarg; 680 | break; 681 | 682 | case 'f': 683 | pat_filename = optarg; 684 | break; 685 | 686 | default: 687 | fprintf(stderr, TXT_USAGE); 688 | return EXIT_ERROR; 689 | } 690 | } 691 | if (!pat_filename && !pat_strings) 692 | { 693 | if (optind < argc) 694 | pat_strings = argv[optind++]; 695 | else 696 | { 697 | fprintf(stderr, "Specify PATTERN or -f FILE to read patterns from\n"); 698 | return EXIT_ERROR; 699 | } 700 | } 701 | 702 | /* Load patterns defining networks */ 703 | if (pat_filename) 704 | { 705 | FILE* data = fopen(pat_filename, "r"); 706 | if (data) 707 | { 708 | while (getline(&linep, &linesize, data) > 0) 709 | { 710 | if (*linep != '#') { 711 | if(strchr(linep, ':')) { 712 | struct netspec6 spec6; 713 | 714 | if(net_parse6(linep, &spec6)) 715 | array_insert6(&spec6); 716 | else if(!igbadpat) 717 | fprintf(stderr, "Not a pattern: %s", linep); 718 | } else { 719 | struct netspec spec; 720 | 721 | if (net_parse(linep, &spec)) 722 | array_insert(&spec); 723 | else if(!igbadpat) 724 | fprintf(stderr, "Not a pattern: %s", linep); 725 | } 726 | } 727 | } 728 | fclose(data); 729 | } 730 | else 731 | { 732 | perror(pat_filename); 733 | return EXIT_ERROR; 734 | } 735 | } 736 | if (pat_strings) 737 | { 738 | char* token = strtok(pat_strings, TOKEN_SEPS); 739 | while (token) 740 | { 741 | if(strchr(token, ':')) { 742 | struct netspec6 spec6; 743 | 744 | if(net_parse6(token, &spec6)) 745 | array_insert6(&spec6); 746 | else if(!igbadpat) 747 | fprintf(stderr, "Not a pattern: %s\n", token); 748 | } else { 749 | struct netspec spec; 750 | 751 | if (net_parse(token, &spec)) 752 | array_insert(&spec); 753 | else if(!igbadpat) 754 | fprintf(stderr, "Not a pattern: %s\n", token); 755 | } 756 | token = strtok(NULL, TOKEN_SEPS); 757 | } 758 | } 759 | 760 | if(!npatterns && !n6patterns) { 761 | fprintf(stderr, "No patterns to match\n"); 762 | return EXIT_ERROR; 763 | } 764 | 765 | /* Prepare array for rapid searching */ 766 | if(npatterns) { 767 | struct netspec *inp, *outp; 768 | #if DEBUG 769 | char *dnp; 770 | if((dnp = getenv("PRESORT4")) != 0) { 771 | FILE *f = fopen(dnp, "w"); 772 | struct netspec *p; 773 | for(p = array; p < array+npatterns; p++) 774 | fprintf(f, "%d.%d.%d.%d-%d.%d.%d.%d\n", p->min>>24, 775 | (p->min>>16)&255, (p->min>>8)&255, p->min&255, 776 | p->max>>24, (p->max>>16)&255, (p->max>>8)&255, p->max&255); 777 | fclose(f); 778 | } 779 | #endif /* DEBUG */ 780 | qsort(array, npatterns, sizeof(struct netspec), netsort); 781 | #if DEBUG 782 | if((dnp = getenv("POSTSORT4")) != 0) { 783 | FILE *f = fopen(dnp, "w"); 784 | struct netspec *p; 785 | for(p = array; p < array+npatterns; p++) 786 | fprintf(f, "%d.%d.%d.%d-%d.%d.%d.%d\n", p->min>>24, 787 | (p->min>>16)&255, (p->min>>8)&255, p->min&255, 788 | p->max>>24, (p->max>>16)&255, (p->max>>8)&255, p->max&255); 789 | fclose(f); 790 | } 791 | #endif /* DEBUG */ 792 | 793 | /* combine overlapping ranges 794 | * outp is clean so far, inp is checked for overlap 795 | */ 796 | outp = array; 797 | for (inp = array+1; inp < array+npatterns; inp++) 798 | { 799 | if (inp->max <= outp->max) 800 | continue; /* contained within previous range, ignore */ 801 | 802 | if(inp->min <= outp->max) { /* overlapping ranges, combine */ 803 | outp->max = inp->max; 804 | continue; 805 | } 806 | if(++outp < inp) 807 | *outp = *inp; /* move down due to previously combined or ignored */ 808 | } 809 | npatterns = outp-array+1; /* adjusted count after combinations */ 810 | #if DEBUG 811 | if((dnp = getenv("POSTMERGE4")) != 0) { 812 | FILE *f = fopen(dnp, "w"); 813 | struct netspec *p; 814 | for(p = array; p < array+npatterns; p++) 815 | fprintf(f, "%d.%d.%d.%d-%d.%d.%d.%d\n", p->min>>24, 816 | (p->min>>16)&255, (p->min>>8)&255, p->min&255, 817 | p->max>>24, (p->max>>16)&255, (p->max>>8)&255, p->max&255); 818 | fclose(f); 819 | } 820 | #endif /* DEBUG */ 821 | } 822 | if(n6patterns) { 823 | struct netspec6 *inp, *outp; 824 | 825 | qsort(array6, n6patterns, sizeof(struct netspec6), netsort6); 826 | 827 | /* combine overlapping ranges 828 | * outp is clean so far, inp is checked for overlap 829 | */ 830 | outp = array6; 831 | for (inp = array6+1; inp < array6+n6patterns; inp++) 832 | { 833 | if (v6cmp(inp->max, outp->max) <= 0) 834 | continue; /* contained within previous range, ignore */ 835 | 836 | if(v6cmp(inp->min, outp->max)<=0) { /* overlapping ranges, combine */ 837 | outp->max = inp->max; 838 | continue; 839 | } 840 | if(++outp < inp) 841 | *outp = *inp; /* move down due to previously combined or ignored */ 842 | } 843 | n6patterns = outp-array6+1; /* adjusted count after combinations */ 844 | } 845 | 846 | # if DEBUG 847 | { /* DEBUG */ 848 | int i,n; 849 | for(n = 0; n < n6patterns; n++) { 850 | printf("min %d:", n); 851 | for(i = 0; i<16; i++) printf(" %02x", array6[n].min.a[i]); 852 | printf("\nmax %d:",n); 853 | for(i = 0; i<16; i++) printf(" %02x", array6[n].max.a[i]); 854 | printf("\n"); 855 | } 856 | } 857 | # endif /* DEBUG */ 858 | if (optind >= argc) { 859 | scan_read(stdin, NULL); 860 | } else { 861 | if(optind+1 >= argc) nonames = 1; /* just one file, no name */ 862 | 863 | while(optind < argc) { 864 | char *fn = argv[optind++]; 865 | FILE *f = fopen(fn, "r"); 866 | char *fmap; 867 | size_t flen; 868 | struct stat statbuf; 869 | 870 | if(!f) { 871 | perror(fn); 872 | return EXIT_ERROR; 873 | } 874 | if(fstat(fileno(f), &statbuf) != 0 || (statbuf.st_mode&S_IFMT)!= S_IFREG ) { 875 | scan_read(f, fn); /* can't stat or not a normal file, fall back to read */ 876 | fclose(f); 877 | continue; 878 | } 879 | flen = statbuf.st_size; 880 | if(flen == 0) { 881 | fclose(f); /* empty file, forget it */ 882 | continue; 883 | } 884 | 885 | fmap = mmap(NULL, flen, PROT_READ, MAP_SHARED, fileno(f), (off_t)0); 886 | if(fmap == MAP_FAILED) { 887 | perror("map failed"); 888 | scan_read(f, fn); /* can't map, fall back to read */ 889 | fclose(f); 890 | continue; 891 | } 892 | 893 | scan_block(fmap, flen, fn); 894 | munmap(fmap, flen); 895 | fclose(f); 896 | } 897 | } 898 | 899 | /* Cleanup */ 900 | if (counting) 901 | printf("%u\n", nmatch); 902 | if (nmatch) 903 | return EXIT_OK; 904 | else 905 | return EXIT_NOMATCH; 906 | } 907 | 908 | /* scan a line at a time */ 909 | static void scan_read(FILE *f, const char *fn) 910 | { 911 | ssize_t len; 912 | 913 | while((len = getline(&linep, &linesize, f)) > 0) 914 | scan_block(linep, len, fn); 915 | } 916 | 917 | static int netmatch(const struct netspec ip4); 918 | static int netmatch6(const struct netspec6 ip6); 919 | 920 | /* scan some text, must be whole lines 921 | * generally either one line or the whole file 922 | * bp: pointer to buffer 923 | * blen: length of buffer 924 | * fn: filename for printing 925 | * This should handle the full V6 syntax in RFC 4291 sec 2.2 and 2.3 except for 926 | * :: for a zero address 927 | * strings of colons may confuse it 928 | */ 929 | static void scan_block(char *bp, size_t blen, const char *fn) 930 | { 931 | enum sscan { 932 | S_BEG = 0, /* beginning of line */ 933 | S_SC, /* scan for IP */ 934 | S_NSC, /* saw a dot, scan for non-digit */ 935 | S_IP1, /* first octet or maybe first v6 chunk*/ 936 | S_IP1D, /* dot after first octet */ 937 | S_IP2, /* second octet */ 938 | S_IP2D, /* dot after second octet */ 939 | S_IP3, /* third octet */ 940 | S_IP3D, /* dot after third octet */ 941 | S_IP4, /* fourth octet */ 942 | S_V4SZ, /* v4 cidr prefix */ 943 | S_HCH, /* in a hi v6 chunk */ 944 | S_HC1, /* hi, seen one colon */ 945 | S_HC2, /* hi, seen two colons */ 946 | S_LCH, /* in a low chunk */ 947 | S_LC1, /* seen a low colon */ 948 | S_IC1, /* seen initial colon */ 949 | S_EIP1D, /* dot after first octet in embedded v4 */ 950 | S_EIP2, /* second octet */ 951 | S_EIP2D, /* dot after second octet */ 952 | S_EIP3, /* third octet */ 953 | S_EIP3D, /* dot after third octet */ 954 | S_EIP4, /* fourth octet */ 955 | S_V6SZ, /* v6 cidr prefix */ 956 | S_SCNL, /* scan for new line */ 957 | S_SCNLP /* scan for new line and print line */ 958 | } state; 959 | enum sscan snext = anchor?S_SCNL:S_SC; /* state after not an IP */ 960 | 961 | char *p = bp; /* current character */ 962 | char *plim = bp+blen; /* end of buffer */ 963 | char *lp = bp; /* beginning of current line */ 964 | unsigned int ip4 = 0; /* IPv4 value */ 965 | int octet = 0; /* current octet */ 966 | int size = -1; /* CIDR size */ 967 | v6addr ahi; /* high part of address */ 968 | v6addr alo; /* low part of address */ 969 | struct netspec range4; /* IPv4 address or range */ 970 | struct netspec6 range6; /* IPv6 address or range */ 971 | int nhi = 0; /* how many bytes in ahi */ 972 | int nlo = 0; /* how many bytes in alo */ 973 | unsigned int chunk = 0; /* current 16 bit chunk */ 974 | int seenone = 0; /* seen an address on this line, for -v */ 975 | 976 | state = S_BEG; 977 | for(p = bp; p < plim;) { 978 | int ch = *p++; 979 | 980 | switch(state) { 981 | case S_BEG: /* beginning of line */ 982 | lp = p-1; 983 | seenone = 0; 984 | /* skip leading spaces */ 985 | while(p < plim && (ch == ' ' || ch == '\t')) 986 | ch = *p++; 987 | /* fall through */ 988 | 989 | case S_SC: /* normal scanning */ 990 | if(isdigit(ch)) { /* start a potential IP of either type */ 991 | ip4 = 0; 992 | state = S_IP1; 993 | nhi = nlo = 0; 994 | octet = chunk = ch-'0'; 995 | continue; 996 | } else if(isxdigit(ch)) { 997 | state = S_HCH; 998 | nhi = nlo = 0; 999 | octet = -1; /* hex, not v4 */ 1000 | chunk = xtod(ch); 1001 | continue; 1002 | } else if(ch == ':') { 1003 | state = S_IC1; 1004 | continue; 1005 | } else if(quick && ch == '.') { 1006 | state = S_NSC; 1007 | continue; 1008 | } 1009 | break; 1010 | 1011 | case S_NSC: /* ignore crud after a dot */ 1012 | if(isdigit(ch) || ch == '.') 1013 | continue; 1014 | state = S_SC; 1015 | break; 1016 | 1017 | case S_IC1: /* initial colon must be two colons and lo part */ 1018 | if(ch == ':') { 1019 | nhi = nlo = 0; 1020 | state = S_HC2; 1021 | continue; 1022 | } 1023 | /* rescan as normal in case it was 1024 | * a random colon before an IP 1025 | */ 1026 | state = S_SC; 1027 | p--; 1028 | continue; 1029 | 1030 | case S_HCH: /* high v6 chunk */ 1031 | if(isxdigit(ch)) { 1032 | chunk = (chunk<<4) + xtod(ch); 1033 | if(isdigit(ch)) 1034 | octet = octet*10 + ch-'0'; /* in case it turns out to be v4 */ 1035 | else 1036 | octet = -1; /* hex, can't be v4 */ 1037 | continue; 1038 | } 1039 | /* finish the current chunk */ 1040 | if(ch == '.' && nhi < 14 && octet >= 0) { /* possible v4 address, is it embedded? */ 1041 | if(octet > 255) { /* not a real address */ 1042 | break; 1043 | } 1044 | /* is it embedded? */ 1045 | if(nhi == 12) { 1046 | ahi.a[nhi++] = octet; 1047 | state = S_EIP1D; 1048 | continue; 1049 | } 1050 | /* v6 address was too short, 1051 | * must be a regular v4 address 1052 | */ 1053 | ip4 = octet; 1054 | state = S_IP1D; /* corresponding dot state */ 1055 | continue; 1056 | } 1057 | if(chunk > 0xffff) 1058 | break; /* value too big */ 1059 | if(nhi < 16) { /* if too long, keep parsing to avoid strange matches */ 1060 | ahi.a[nhi++] = chunk >> 8; /* big-endian for memcmp() */ 1061 | ahi.a[nhi++] = chunk & 255; 1062 | } 1063 | if(ch == ':') { 1064 | state = S_HC1; 1065 | continue; 1066 | } 1067 | /* was it full address? */ 1068 | if(nhi == 16) { 1069 | if(!n6patterns) break; /* no v6 patterns */ 1070 | if(cidrsearch && ch == '/') { 1071 | size = 0; 1072 | state = S_V6SZ; 1073 | continue; 1074 | } 1075 | seenone = 1; 1076 | range6.min = range6.max = ahi; 1077 | if(!netmatch6(range6)) 1078 | break; /* didn't match */ 1079 | state = S_SCNLP; 1080 | goto scnlp; /* in case it was a \n */ 1081 | } 1082 | break; /* partial address, not an IP */ 1083 | 1084 | case S_HC1: /* colon separator in hi part */ 1085 | if(isxdigit(ch)) { 1086 | chunk = xtod(ch); 1087 | if(isdigit(ch)) 1088 | octet = ch-'0'; 1089 | else 1090 | octet = -1; 1091 | state = S_HCH; 1092 | continue; 1093 | } 1094 | if(ch == ':') { /* two colons, might be end or lo part can follow */ 1095 | state = S_HC2; 1096 | continue; 1097 | } 1098 | break; /* not an IP */ 1099 | 1100 | case S_HC2: /* seen high:: might be end or might be low chunk */ 1101 | if(isxdigit(ch)) { /* two colons and digit, start low chunks */ 1102 | chunk = xtod(ch); 1103 | if(isdigit(ch)) 1104 | octet = chunk; 1105 | else 1106 | octet = -1; 1107 | state = S_LCH; 1108 | continue; 1109 | } 1110 | 1111 | /* high part only, check it */ 1112 | if(!nhi) { 1113 | if(ch == ':') /* string of possibly leading colons */ 1114 | continue; 1115 | break; /* don't match :: as zero address */ 1116 | } 1117 | if(!n6patterns) break; /* no v6 patterns */ 1118 | memset(ahi.a+nhi, 0, 16-nhi); /* zero low bytes */ 1119 | if(cidrsearch && ch == '/') { 1120 | size = 0; 1121 | state = S_V6SZ; 1122 | continue; 1123 | } else 1124 | size = -1; 1125 | 1126 | seenone = 1; 1127 | range6.min = range6.max = ahi; 1128 | if(!netmatch6(range6)) 1129 | break; /* didn't match */ 1130 | state = S_SCNLP; 1131 | goto scnlp; /* in case it was a \n */ 1132 | 1133 | case S_V6SZ: 1134 | if(isdigit(ch)) { 1135 | if (size >= 0) 1136 | size = size*10 + ch-'0'; 1137 | if(size > 128) /* gobble up the rest */ 1138 | size = -1; 1139 | continue; 1140 | } 1141 | if(!n6patterns) break; /* no v6 patterns */ 1142 | seenone = 1; 1143 | if (size < 0) size = 0; /* ignore bad prefix */ 1144 | /* TODO: check badbits? naah */ 1145 | applymask6(ahi, size, &range6); 1146 | if(!netmatch6(range6)) 1147 | break; /* didn't match */ 1148 | state = S_SCNLP; 1149 | goto scnlp; /* in case it was a \n */ 1150 | 1151 | case S_LCH: /* low chunk */ 1152 | if(isxdigit(ch)) { 1153 | chunk = (chunk<<4)+xtod(ch); 1154 | if(isdigit(ch)) 1155 | octet = octet*10 + ch-'0'; /* in case it turns out to be v4 */ 1156 | else 1157 | octet = -1; 1158 | continue; 1159 | } 1160 | /* finish the current chunk */ 1161 | if(ch == '.' && octet >= 0 && octet <= 255) { /* maybe a v4 address */ 1162 | if((nhi+nlo) < 12) { /* embedded v4 */ 1163 | /* move all into ahi */ 1164 | memset(ahi.a+nhi, 0, 12-(nhi+nlo)); 1165 | if(nlo) 1166 | memcpy(ahi.a+12-nlo, alo.a, nlo); 1167 | nhi = 12; 1168 | ahi.a[nhi++] = octet; 1169 | state = S_EIP1D; 1170 | continue; 1171 | } 1172 | } 1173 | /* doesn't look like an octet, or too 1174 | * long to be embedded, treat as 1175 | * likely v6 1176 | */ 1177 | if(chunk > 0xffff) break; /* too big for a chunk */ 1178 | if(nlo < 16) { /* keep parsing overlong to avoid strange results */ 1179 | alo.a[nlo++] = chunk >> 8; /* big-endian for memcmp() */ 1180 | alo.a[nlo++] = chunk & 255; 1181 | } 1182 | if(ch == ':') { 1183 | state = S_LC1; 1184 | continue; 1185 | } 1186 | /* end of lo part, check it */ 1187 | if(!n6patterns) break; /* no v6 patterns */ 1188 | if((nhi+nlo) >= 14) break; /* too many chunks. not an IP */ 1189 | memset(ahi.a+nhi, 0, 16-(nhi+nlo)); /* combine hi and lo parts */ 1190 | memcpy(ahi.a+(16-nlo), alo.a, nlo); 1191 | if(cidrsearch && ch == '/') { 1192 | state = S_V6SZ; 1193 | size = 0; 1194 | continue; 1195 | } 1196 | seenone = 1; 1197 | range6.min = range6.max = ahi; 1198 | if(!netmatch6(range6)) 1199 | break; /* didn't match */ 1200 | state = S_SCNLP; 1201 | goto scnlp; /* in case it was a \n */ 1202 | 1203 | case S_LC1: /* seen a colon after a low chunk */ 1204 | if(isxdigit(ch)) { 1205 | chunk = xtod(ch); 1206 | if(isdigit(ch)) 1207 | octet = chunk; 1208 | else 1209 | octet = -1; 1210 | state = S_LCH; 1211 | continue; 1212 | } 1213 | break; /* trailing junk, not an IP */ 1214 | 1215 | case S_IP1: /* in an IP address, don't know yet which kind */ 1216 | if(isxdigit(ch)) { 1217 | chunk = (chunk<<4) + xtod(ch); 1218 | if(!isdigit(ch)) { 1219 | state = S_HCH; /* doesn't look like a v4 address */ 1220 | octet = -1; 1221 | continue; 1222 | } 1223 | } else if(ch == ':') { 1224 | /* finish the current chunk, 1225 | * which must be chunk 0 */ 1226 | ahi.a[nhi++] = chunk >> 8; /* big-endian for memcmp() */ 1227 | ahi.a[nhi++] = chunk & 255; 1228 | state = S_HC1; 1229 | continue; 1230 | } 1231 | /* fall through */ 1232 | case S_IP2: 1233 | case S_IP3: 1234 | if(isdigit(ch)) { 1235 | octet = octet*10 + ch-'0'; 1236 | continue; 1237 | } 1238 | if(ch == '.') { 1239 | if(octet > 255) { /* not a real address */ 1240 | break; 1241 | } 1242 | ip4 <<= 8; 1243 | ip4 += octet; 1244 | state++; /* corresponding dot state */ 1245 | continue; 1246 | } 1247 | /* otherwise, wasn't a full IP */ 1248 | break; 1249 | 1250 | case S_IP1D: /* saw dot after an octet */ 1251 | case S_IP2D: 1252 | case S_IP3D: 1253 | case S_EIP1D: /* saw dot after an embedded octet */ 1254 | case S_EIP2D: 1255 | case S_EIP3D: 1256 | if(isdigit(ch)) { 1257 | octet = ch-'0'; 1258 | state++; /* next digit state */ 1259 | continue; 1260 | } 1261 | break; /* wasn't an IP */ 1262 | 1263 | case S_IP4: /* in last octet */ 1264 | if(isdigit(ch)) { 1265 | octet = octet*10 + ch-'0'; 1266 | continue; 1267 | } 1268 | /* OK, we have the IP */ 1269 | if(quick && ch == '.') { /* seen crud, skip it */ 1270 | state = S_NSC; 1271 | continue; 1272 | } 1273 | if(octet > 255) { /* not a real address */ 1274 | break; 1275 | } 1276 | ip4 <<= 8; 1277 | ip4 += octet; 1278 | if(!npatterns) break; /* no v4 patterns */ 1279 | if(cidrsearch && ch == '/') { 1280 | state = S_V4SZ; 1281 | size = 0; 1282 | continue; 1283 | } 1284 | seenone = 1; 1285 | range4.min = range4.max = ip4; 1286 | if(!netmatch(range4)) 1287 | break; /* didn't match */ 1288 | state = S_SCNLP; 1289 | goto scnlp; /* in case it was a \n */ 1290 | 1291 | case S_V4SZ: /* cidr size */ 1292 | if(isdigit(ch)) { 1293 | if (size >= 0) 1294 | size = size*10 + ch-'0'; 1295 | if(size > 32) /* gobble up the rest */ 1296 | size = -1; 1297 | continue; 1298 | } 1299 | seenone = 1; 1300 | range4.min = range4.max = ip4; 1301 | if(size >= 0) { /* ignore bad prefix */ 1302 | int mask = (1L<<(32-size))-1; 1303 | range4.min &= ~mask; /* force to CIDR boundary */ 1304 | range4.max |= mask; 1305 | } 1306 | if(!netmatch(range4)) 1307 | break; /* didn't match */ 1308 | state = S_SCNLP; 1309 | goto scnlp; /* in case it was a \n */ 1310 | 1311 | case S_EIP2: /* in embedded octet */ 1312 | case S_EIP3: 1313 | if(isdigit(ch)) { 1314 | octet = octet*10 + ch-'0'; 1315 | continue; 1316 | } 1317 | if(ch == '.') { 1318 | if(octet > 255) { /* not a real address */ 1319 | break; 1320 | } 1321 | ahi.a[nhi++] = octet; 1322 | state++; /* corresponding dot state */ 1323 | continue; 1324 | } 1325 | /* otherwise, wasn't a full IP */ 1326 | break; 1327 | 1328 | case S_EIP4: /* in last embedded octet */ 1329 | if(isdigit(ch)) { 1330 | octet = octet*10 + ch-'0'; 1331 | continue; 1332 | } 1333 | /* OK, we have the IP */ 1334 | if(quick && ch == '.') { /* seen crud, skip it */ 1335 | state = S_NSC; 1336 | continue; 1337 | } 1338 | if(octet > 255) { /* not a real address */ 1339 | break; 1340 | } 1341 | /* no CIDR allowed with IPv4 embedded in IPv6 */ 1342 | ahi.a[nhi++] = octet; 1343 | seenone = 1; 1344 | if(n6patterns) { 1345 | range6.min = range6.max = ahi; 1346 | if(netmatch6(range6)) { /* try a v6 pattern */ 1347 | state = S_SCNLP; 1348 | goto scnlp; /* in case it was a \n */ 1349 | } 1350 | } 1351 | /* get the v4 address as an int and try 1352 | * that */ 1353 | ip4 = (ahi.a[12]<<24)|(ahi.a[13]<<16)|(ahi.a[14]<<8)|ahi.a[15]; 1354 | if(cidrsearch && ch == '/') { 1355 | state = S_V4SZ; 1356 | size = 0; 1357 | continue; 1358 | } 1359 | range4.min = range4.max = ip4; 1360 | if(!npatterns || !netmatch(range4)) 1361 | break; /* didn't match */ 1362 | 1363 | state = S_SCNLP; 1364 | /* fall through, in case it was a \n */ 1365 | 1366 | scnlp: 1367 | case S_SCNLP: /* print this line */ 1368 | /* HACK scan the rest of the line fast */ 1369 | while(ch != '\n' && p < plim) 1370 | ch = *p++; 1371 | 1372 | if(ch == '\n') { 1373 | if(!invert) { 1374 | nmatch++; 1375 | if(!counting) { 1376 | if(fn && !nonames) 1377 | printf("%s:", fn); 1378 | fwrite(lp, 1, p-lp, stdout); 1379 | } 1380 | } 1381 | state = S_BEG; 1382 | } 1383 | continue; 1384 | 1385 | case S_SCNL: 1386 | /* HACK scan the rest of the line fast */ 1387 | while(ch != '\n' && p < plim) 1388 | ch = *p++; 1389 | break; 1390 | } 1391 | /* default action if it wasn't an IP */ 1392 | if(ch == '\n') { 1393 | if(invert && seenone) { /* -v prints or counts lines with IPs that didn't match */ 1394 | nmatch++; 1395 | if(!counting) { 1396 | if(fn && !nonames) 1397 | printf("%s:", fn); 1398 | fwrite(lp, 1, p-lp, stdout); 1399 | } 1400 | } 1401 | state = S_BEG; 1402 | } else 1403 | state = snext; 1404 | continue; 1405 | 1406 | } 1407 | } /* scan_block */ 1408 | 1409 | /* 1410 | * binary range search for a value 1411 | */ 1412 | static int 1413 | netmatch(const struct netspec ip4) 1414 | { 1415 | int minx = 0; 1416 | int maxx = npatterns-1; 1417 | int tryx = 0; 1418 | 1419 | # if DEBUG 1420 | { /* DEBUG */ 1421 | 1422 | assert(npatterns); /* don't call this if there are no v4 patterns */ 1423 | printf("match: %x %d.%d.%d.%d-%x %d.%d.%d.%d\n", ip4.min, ip4.min>>24, 1424 | (ip4.min>>16)&255, (ip4.min>>8)&255, ip4.min&255, 1425 | ip4.max, ip4.max>>24, (ip4.max>>16)&255, (ip4.max>>8)&255, ip4.max&255); 1426 | } 1427 | # endif 1428 | /* make sure it's in range */ 1429 | if(ip4.max < array[0].min || ip4.min > array[maxx].max) return 0; 1430 | 1431 | while(minx <= maxx) { 1432 | tryx = (minx+maxx)/2; 1433 | # if DEBUG 1434 | if(getenv("TRY")) printf("try %d:%d -> %d %x %x\n", minx, maxx, tryx, array[tryx].min, array[tryx].max); 1435 | # endif 1436 | 1437 | if(ip4.max < array[tryx].min) { 1438 | maxx = tryx-1; 1439 | continue; 1440 | } 1441 | if(ip4.min > array[tryx].max) { 1442 | minx = tryx+1; 1443 | continue; 1444 | } 1445 | break; /* gee, we may have found it */ 1446 | } 1447 | 1448 | if(ip4.min >= array[tryx].min && ip4.max <= array[tryx].max) return 1; /* target in pattern */ 1449 | if(didrsearch) { /* look for overlap */ 1450 | if(ip4.min <= array[tryx].min && ip4.max >= array[tryx].max) return 1; /* pattern in target */ 1451 | if(ip4.min >= array[tryx].min && ip4.min <= array[tryx].max) return 1; /* base of target in pattern */ 1452 | if(ip4.max >= array[tryx].min && ip4.max <= array[tryx].max) return 1; /* end of target in pattern */ 1453 | } 1454 | return 0; /* not in the current entry */ 1455 | } 1456 | 1457 | static int 1458 | netmatch6(const struct netspec6 ip6) 1459 | { 1460 | int minx = 0; 1461 | int maxx = n6patterns-1; 1462 | int tryx = 0; 1463 | 1464 | # if DEBUG 1465 | { /* DEBUG */ 1466 | int i; 1467 | 1468 | assert(n6patterns); /* don't call this if there are no v6 patterns */ 1469 | printf("match:"); 1470 | for(i = 0; i<16; i++) printf(" %02x", ip6.min.a[i]); 1471 | printf("-"); 1472 | for(i = 0; i<16; i++) printf(" %02x", ip6.max.a[i]); 1473 | printf("\n"); 1474 | } 1475 | # endif 1476 | /* make sure it's in range */ 1477 | if(v6cmp(ip6.max, array6[0].min) < 0 || v6cmp(ip6.min, array6[maxx].max) > 0) return 0; 1478 | 1479 | while(minx <= maxx) { 1480 | tryx = (minx+maxx)/2; 1481 | 1482 | if(v6cmp(ip6.min, array6[tryx].min)<0) { 1483 | maxx = tryx-1; 1484 | continue; 1485 | } 1486 | if(v6cmp(ip6.min, array6[tryx].max)>0) { 1487 | minx = tryx+1; 1488 | continue; 1489 | } 1490 | break; /* gee, we may have found it */ 1491 | } 1492 | 1493 | # if DEBUG 1494 | { /* DEBUG */ 1495 | int i; 1496 | 1497 | assert(n6patterns); /* don't call this if there are no v6 patterns */ 1498 | printf("candidate: %d/%d", minx, maxx); 1499 | for(i = 0; i<16; i++) printf(" %02x", array6[minx].min.a[i]); 1500 | printf("-"); 1501 | for(i = 0; i<16; i++) printf(" %02x", array6[minx].max.a[i]); 1502 | printf("\n"); 1503 | } 1504 | # endif 1505 | 1506 | if(v6cmp(ip6.min, array6[tryx].min) >= 0 && v6cmp(ip6.max, array6[tryx].max) <= 0) return 1; /* target in pattern */ 1507 | if(didrsearch) { 1508 | if(v6cmp(ip6.min, array6[tryx].min) <= 0 && v6cmp(ip6.max, array6[tryx].max) >= 0) return 1; /* pattern in target */ 1509 | if(v6cmp(ip6.min, array6[tryx].min) >= 0 && v6cmp(ip6.min, array6[tryx].max) <= 0) return 1; /* base in pattern */ 1510 | if(v6cmp(ip6.max, array6[tryx].min) >= 0 && v6cmp(ip6.max, array6[tryx].max) <= 0) return 1; /* end in target */ 1511 | } 1512 | return 0; /* not in the current entry */ 1513 | } 1514 | --------------------------------------------------------------------------------