2 ###############################################################################
4 # libloc - A library to determine the location of someone on the Internet #
6 # Copyright (C) 2017 IPFire Development Team <info@ipfire.org> #
8 # This library is free software; you can redistribute it and/or #
9 # modify it under the terms of the GNU Lesser General Public #
10 # License as published by the Free Software Foundation; either #
11 # version 2.1 of the License, or (at your option) any later version. #
13 # This library 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 GNU #
16 # Lesser General Public License for more details. #
18 ###############################################################################
28 # Load our location module
32 def _(singular
, plural
=None, n
=None):
34 return gettext
.dngettext("libloc", singular
, plural
, n
)
36 return gettext
.dgettext("libloc", singular
)
40 class OutputFormatter(object):
41 def __init__(self
, ns
):
50 def __exit__(self
, type, value
, tb
):
56 if "country_code" in self
.ns
:
57 return "networks_country_%s" % self
.ns
.country_code
[0]
59 elif "asn" in self
.ns
:
60 return "networks_AS%s" % self
.ns
.asn
[0]
68 def network(self
, network
):
72 class IpsetOutputFormatter(OutputFormatter
):
77 print("create %s hash:net family inet hashsize 1024 maxelem 65536" % self
.name
)
79 def network(self
, network
):
80 print("add %s %s" % (self
.name
, network
))
83 class NftablesOutputFormatter(OutputFormatter
):
88 print("define %s = {" % self
.name
)
93 def network(self
, network
):
94 print(" %s," % network
)
97 class XTGeoIPOutputFormatter(OutputFormatter
):
99 Formats the output in that way, that it can be loaded by
100 the xt_geoip kernel module from xtables-addons.
102 def network(self
, network
):
103 n
= ipaddress
.ip_network("%s" % network
)
105 for address
in (n
.network_address
, n
.broadcast_address
):
106 bytes
= socket
.inet_pton(
107 socket
.AF_INET6
if address
.version
== 6 else socket
.AF_INET
,
116 "ipset" : IpsetOutputFormatter
,
117 "list" : OutputFormatter
,
118 "nftables" : NftablesOutputFormatter
,
119 "xt_geoip" : XTGeoIPOutputFormatter
,
123 parser
= argparse
.ArgumentParser(
124 description
=_("Location Database Command Line Interface"),
126 subparsers
= parser
.add_subparsers()
128 # Global configuration flags
129 parser
.add_argument("--debug", action
="store_true",
130 help=_("Enable debug output"))
133 parser
.add_argument("--version", action
="version",
134 version
="%%(prog)s %s" % location
.__version
__)
137 parser
.add_argument("--database", "-d",
138 default
="@databasedir@/database.db", help=_("Path to database"),
141 # lookup an IP address
142 lookup
= subparsers
.add_parser("lookup",
143 help=_("Lookup one or multiple IP addresses"),
145 lookup
.add_argument("address", nargs
="+")
146 lookup
.set_defaults(func
=self
.handle_lookup
)
149 get_as
= subparsers
.add_parser("get-as",
150 help=_("Get information about one or multiple Autonomous Systems"),
152 get_as
.add_argument("asn", nargs
="+")
153 get_as
.set_defaults(func
=self
.handle_get_as
)
156 search_as
= subparsers
.add_parser("search-as",
157 help=_("Search for Autonomous Systems that match the string"),
159 search_as
.add_argument("query", nargs
=1)
160 search_as
.set_defaults(func
=self
.handle_search_as
)
162 # List all networks in an AS
163 list_networks_by_as
= subparsers
.add_parser("list-networks-by-as",
164 help=_("Lists all networks in an AS"),
166 list_networks_by_as
.add_argument("asn", nargs
=1, type=int)
167 list_networks_by_as
.add_argument("--output-format",
168 choices
=self
.output_formats
.keys(), default
="list")
169 list_networks_by_as
.set_defaults(func
=self
.handle_list_networks_by_as
)
171 # List all networks in a country
172 list_networks_by_cc
= subparsers
.add_parser("list-networks-by-cc",
173 help=_("Lists all networks in a country"),
175 list_networks_by_cc
.add_argument("country_code", nargs
=1)
176 list_networks_by_cc
.add_argument("--output-format",
177 choices
=self
.output_formats
.keys(), default
="list")
178 list_networks_by_cc
.set_defaults(func
=self
.handle_list_networks_by_cc
)
180 args
= parser
.parse_args()
182 # Print usage if no action was given
183 if not "func" in args
:
190 # Parse command line arguments
191 args
= self
.parse_cli()
195 db
= location
.Database(args
.database
)
196 except FileNotFoundError
as e
:
197 sys
.stderr
.write("location-query: Could not open database %s: %s\n" \
198 % (args
.database
, e
))
202 ret
= args
.func(db
, args
)
204 # Return with exit code
208 # Otherwise just exit
211 def handle_lookup(self
, db
, ns
):
214 for address
in ns
.address
:
216 n
= db
.lookup(address
)
218 print(_("Invalid IP address: %s") % address
, file=sys
.stderr
)
227 print(_("Nothing found for %(address)s") % args
, file=sys
.stderr
)
231 # Try to retrieve the AS if we have an AS number
235 # If we have found an AS we will print it in the message
241 print(_("%(address)s belongs to %(network)s which is a part of %(as)s") % args
)
244 print(_("%(address)s belongs to %(network)s") % args
)
248 def handle_get_as(self
, db
, ns
):
250 Gets information about Autonomous Systems
258 print(_("Invalid ASN: %s") % asn
, file=sys
.stderr
)
262 # Fetch AS from database
267 print(_("Could not find AS%s") % asn
, file=sys
.stderr
)
271 print(_("AS%(asn)s belongs to %(name)s") % { "asn" : a
.number
, "name" : a
.name
})
275 def handle_search_as(self
, db
, ns
):
276 for query
in ns
.query
:
277 # Print all matches ASes
278 for a
in db
.search_as(query
):
281 def __get_output_formatter(self
, ns
):
283 cls
= self
.output_formats
[ns
.output_format
]
285 cls
= OutputFormatter
289 def handle_list_networks_by_as(self
, db
, ns
):
290 with self
.__get
_output
_formatter
(ns
) as f
:
292 # Print all matching networks
293 for n
in db
.search_networks(asn
=asn
):
296 def handle_list_networks_by_cc(self
, db
, ns
):
297 with self
.__get
_output
_formatter
(ns
) as f
:
298 for country_code
in ns
.country_code
:
299 # Print all matching networks
300 for n
in db
.search_networks(country_code
=country_code
):
305 # Run the command line interface