1 import Data.List (intercalate, intersperse)
2 import System.Exit (exitFailure)
3 import Text.Regex.Posix
17 -- A regular expression that matches a non-address character.
18 non_addr_char :: String
19 non_addr_char = "[^\\.0-9]"
22 -- Add non_addr_chars on either side of the given String. This
23 -- prevents (for example) the regex '127.0.0.1' from matching
25 addr_barrier :: String -> String
26 addr_barrier x = non_addr_char ++ x ++ non_addr_char
29 -- The magic happens here. We take a CIDR String as an argument, and
30 -- return the equivalent regular expression. We do this as follows:
32 -- 1. Compute the minimum possible value of each octet.
33 -- 2. Compute the maximum possible value of each octet.
34 -- 3. Generate a regex matching every value between those min and
36 -- 4. Join the regexes from step 3 with regexes matching periods.
37 -- 5. Stick an address boundary on either side of the result.
38 --cidr_to_regex :: String -> String
39 cidr_to_regex :: Cidr.Cidr -> String
41 addr_barrier (intercalate "\\." [range1, range2, range3, range4])
43 range1 = numeric_range min1 max1
44 range2 = numeric_range min2 max2
45 range3 = numeric_range min3 max3
46 range4 = numeric_range min4 max4
47 min1 = min_first_octet cidr
48 min2 = min_second_octet cidr
49 min3 = min_third_octet cidr
50 min4 = min_fourth_octet cidr
51 max1 = max_first_octet cidr
52 max2 = max_second_octet cidr
53 max3 = max_third_octet cidr
54 max4 = max_fourth_octet cidr
57 -- Will return True if the passed String is in CIDR notation, False
59 is_valid_cidr :: String -> Bool
60 is_valid_cidr cidr = cidr =~ "([0-9]{1,3}\\.){3}[0-9]{1,3}/[0-9]{1,2}"
63 -- Take a list of Strings, and return a regular expression matching
65 alternate :: [String] -> String
66 alternate terms = "(" ++ (concat (intersperse "|" terms)) ++ ")"
69 -- Take two Ints as parameters, and return a regex matching any
70 -- integer between them (inclusive).
71 numeric_range :: Int -> Int -> String
73 alternate (map show [lower..upper])
79 -- Take a CIDR String, and exitFailure if it's invalid.
80 validate_or_die :: String -> IO ()
81 validate_or_die cidr = do
82 if (is_valid_cidr cidr)
86 putStrLn "Error: not valid CIDR notation."
93 let cidr_strings = lines input
94 mapM validate_or_die cidr_strings
95 let cidrs = map Cidr.from_string cidr_strings
96 let regexes = map cidr_to_regex cidrs
97 putStrLn $ alternate regexes