5 ;;; Network (numbering) tools
7 ;;; (c) 2006 Straylight/Edgeware
10 ;;;----- Licensing notice ---------------------------------------------------
12 ;;; This program is free software; you can redistribute it and/or modify
13 ;;; it under the terms of the GNU General Public License as published by
14 ;;; the Free Software Foundation; either version 2 of the License, or
15 ;;; (at your option) any later version.
17 ;;; This program is distributed in the hope that it will be useful,
18 ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;;; GNU General Public License for more details.
22 ;;; You should have received a copy of the GNU General Public License
23 ;;; along with this program; if not, write to the Free Software Foundation,
24 ;;; Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
26 ;;;--------------------------------------------------------------------------
30 (:use #:common-lisp #:mdw.base #:mdw.str #:collect)
31 (:export #:ipaddr #:string-ipaddr #:ipaddr-byte #:ipaddr-string #:ipaddrp
32 #:integer-netmask #:ipmask #:ipmask-cidl-slash #:make-ipnet
33 #:string-ipnet #:ipnet #:ipnet-net #:ipnet-mask #:with-ipnet
34 #:ipnet-pretty #:ipnet-string #:ipnet-broadcast #:ipnet-hosts
35 #:ipnet-host #:ipaddr-networkp #:ipnet-subnetp
36 #:ipnet-changeable-bytes
37 #:host-find #:host-create #:defhost #:parse-ipaddr
38 #:resolve-hostname #:canonify-hostname
39 #:net #:net-find #:net-get-as-ipnet #:net-create #:defnet
40 #:net-next-host #:net-host))
44 ;;;--------------------------------------------------------------------------
48 "Return 2^N - 1: i.e., a mask of N set bits."
52 "The type of unsigned 32-bit values."
56 "The type of IP (version 4) addresses."
59 ;;;--------------------------------------------------------------------------
60 ;;; Various random utilities.
62 (defun count-low-zero-bits (n)
63 "Return the number of low-order zero bits in the integer N."
69 ;;;--------------------------------------------------------------------------
70 ;;; Simple messing with IP addresses.
72 (defun string-ipaddr (str &key (start 0) (end nil))
73 "Parse STR as an IP address in dotted-quad form and return the integer
74 equivalent. STR may be anything at all: it's converted as if by
75 `stringify'. The START and END arguments may be used to parse out a
77 (setf str (stringify str))
79 (setf end (length str)))
80 (let ((addr 0) (noct 0))
82 (let* ((pos (position #\. str :start start :end end))
83 (i (parse-integer str :start start :end (or pos end))))
85 (error "IP address octet out of range"))
86 (setf addr (+ (* addr 256) i))
90 (setf start (1+ pos))))
92 (error "Wrong number of octets in IP address"))
95 (defun ipaddr-byte (ip n)
96 "Return byte N (from most significant downwards) of an IP address."
98 (logand #xff (ash ip (* -8 (- 3 n)))))
100 (defun ipaddr-string (ip)
101 "Transform the address IP into a string in dotted-quad form."
102 (check-type ip ipaddr)
103 (join-strings #\. (collecting ()
105 (collect (ipaddr-byte ip i))))))
108 "Answer true if IP is a valid IP address in integer form."
112 "Convert IP to an IP address. If it's an integer, return it unchanged;
113 otherwise convert by `string-ipaddr'."
116 (t (string-ipaddr ip))))
118 ;;;--------------------------------------------------------------------------
121 (defun integer-netmask (i)
122 "Given an integer I, return a netmask with its I top bits set."
123 (- (ash 1 32) (ash 1 (- 32 i))))
126 "Transform IP into a netmask. If it's a small integer then it's converted
127 by `integer-netmask'; if nil, then all-bits-set; otherwise convert using
131 ((integer 0 32) (integer-netmask ip))
134 (defun ipmask-cidl-slash (mask)
135 "Given a netmask MASK, return an integer N such that (integer-netmask N) =
136 MASK, or nil if this is impossible."
138 (when (= mask (integer-netmask i))
141 ;;;--------------------------------------------------------------------------
142 ;;; Networks: pairing an address and netmask.
144 (defun make-ipnet (net mask)
145 "Construct an IP-network object given the NET and MASK; these are
146 transformed as though by `ipaddr' and `ipmask'."
147 (let ((net (ipaddr net))
148 (mask (ipmask mask)))
149 (cons (logand net mask) mask)))
151 (defun string-ipnet (str &key (start 0) (end nil))
152 "Parse an IP-network from the string STR."
153 (setf str (stringify str))
154 (unless end (setf end (length str)))
155 (let ((sl (position #\/ str :start start :end end)))
157 (make-ipnet (parse-ipaddr (subseq str start sl))
158 (if (find #\. str :start (1+ sl) :end end)
159 (string-ipaddr str :start (1+ sl) :end end)
160 (integer-netmask (parse-integer str
163 (make-ipnet (parse-ipaddr (subseq str start end))
164 (integer-netmask 32)))))
167 "Construct an IP-network object from the given argument. A number of forms
170 * ADDR -- a single address (equivalent to ADDR 32)
171 * (NET . MASK|nil) -- a single-object representation.
172 * IPNET -- return an equivalent (`equal', not necessarily `eql')
174 (cond ((or (stringp net) (symbolp net)) (string-ipnet net))
175 (t (apply #'make-ipnet (pairify net 32)))))
177 (defun ipnet-net (ipn)
178 "Return the base network address of IPN."
181 (defun ipnet-mask (ipn)
182 "Return the netmask of IPN."
185 (defmacro with-ipnet ((net mask) ipn &body body)
186 "Evaluate BODY with NET and MASK bound to the base address and netmask of
187 IPN. Either NET or MASK (or, less usefully, both) may be nil if not
191 (let (,@(and net `((,net (ipnet-net ,tmp))))
192 ,@(and mask `((,mask (ipnet-mask ,tmp)))))
195 (defun ipnet-pretty (ipn)
196 "Convert IPN to a pretty cons-cell form."
197 (with-ipnet (net mask) ipn
198 (cons (ipaddr-string net)
199 (or (ipmask-cidl-slash mask) (ipaddr-string mask)))))
201 (defun ipnet-string (ipn)
202 "Convert IPN to a string."
203 (with-ipnet (net mask) ipn
206 (or (ipmask-cidl-slash mask) (ipaddr-string mask)))))
208 (defun ipnet-broadcast (ipn)
209 "Return the broadcast address for the network IPN."
210 (with-ipnet (net mask) ipn
211 (logior net (logxor (mask 32) mask))))
213 (defun ipnet-hosts (ipn)
214 "Return the number of available addresses in network IPN."
215 (ash 1 (- 32 (logcount (ipnet-mask ipn)))))
217 (defun ipnet-host (ipn host)
218 "Return the address of the given HOST in network IPN. This works even with
219 a non-contiguous netmask."
220 (check-type host u32)
221 (with-ipnet (net mask) ipn
222 (let ((i 0) (m 1) (a net) (h host))
225 (error "Host index ~D out of range for network ~A"
226 host (ipnet-pretty ipn)))
232 (setf a (logior a (logand m h)))
233 (setf h (logandc2 h m))))
237 (defun ipaddr-networkp (ip ipn)
238 "Returns true if address IP is within network IPN."
239 (with-ipnet (net mask) ipn
240 (= net (logand ip mask))))
242 (defun ipnet-subnetp (ipn subn)
243 "Returns true if SUBN is a (non-strict) subnet of IPN."
244 (with-ipnet (net mask) ipn
245 (with-ipnet (subnet submask) subn
246 (and (= net (logand subnet mask))
247 (= submask (logior mask submask))))))
249 (defun ipnet-changeable-bytes (mask)
250 "Answers how many low-order bytes of MASK are (entirely or partially)
251 changeable. This is used when constructing reverse zones."
253 (when (/= (ipaddr-byte mask i) 255)
256 ;;;--------------------------------------------------------------------------
259 (defun resolve-hostname (name)
260 "Resolve a hostname to an IP address using the DNS, or return nil."
261 #+cmu (let ((he (ext:lookup-host-entry name)))
263 (ext:host-entry-addr he)))
267 (defun canonify-hostname (name)
268 "Resolve a hostname to canonical form using the DNS, or return nil."
269 #+cmu (let ((he (ext:lookup-host-entry name)))
271 (ext:host-entry-name he)))
274 ;;;--------------------------------------------------------------------------
275 ;;; Host names and specifiers.
277 (defun parse-ipaddr (addr)
278 "Convert the string ADDR into an IP address: tries all sorts of things:
280 (NET [INDEX]) index a network: NET is a network name defined by
281 defnet; INDEX is an index or one of the special
282 symbols understood by net-host, and defaults to :next
284 INTEGER an integer IP address
286 IPADDR an IP address in dotted-quad form
288 HOST a host name defined by defhost
290 DNSNAME a name string to look up in the DNS"
295 (net-host (or (net-find net)
296 (error "Network ~A not found" net))
298 ((ipaddrp addr) addr)
300 (setf addr (string-downcase (stringify addr)))
302 (and (plusp (length addr))
303 (digit-char-p (char addr 0))
304 (string-ipaddr addr))
305 (resolve-hostname (stringify addr))
306 (error "Host name ~A unresolvable" addr)))))
308 (defvar *hosts* (make-hash-table :test #'equal)
309 "The table of known hostnames.")
311 (defun host-find (name)
312 "Find a host by NAME."
313 (gethash (string-downcase (stringify name)) *hosts*))
315 (defun (setf host-find) (addr name)
316 "Make NAME map to ADDR (must be an ipaddr in integer form)."
317 (setf (gethash (string-downcase (stringify name)) *hosts*) addr))
319 (defun host-create (name addr)
320 "Make host NAME map to ADDR (anything acceptable to parse-ipaddr)."
321 (setf (host-find name) (parse-ipaddr addr)))
323 (defmacro defhost (name addr)
324 "Main host definition macro. Neither NAME nor ADDR is evaluated."
326 (host-create ',name ',addr)
329 ;;;--------------------------------------------------------------------------
330 ;;; Network names and specifiers.
332 (defstruct (net (:predicate netp))
333 "A network structure. Slots:
335 NAME The network's name, as a string
336 IPNET The network base address and mask
337 HOSTS Number of hosts in the network
338 NEXT Index of the next unassigned host"
344 (defvar *networks* (make-hash-table :test #'equal)
345 "The table of known networks.")
347 (defun net-find (name)
348 "Find a network by NAME."
349 (gethash (string-downcase (stringify name)) *networks*))
351 (defun (setf net-find) (net name)
352 "Make NAME map to NET."
353 (setf (gethash (string-downcase (stringify name)) *networks*) net))
355 (defun net-get-as-ipnet (form)
356 "Transform FORM into an ipnet. FORM may be a network name, or something
357 acceptable to the ipnet function."
358 (let ((net (net-find form)))
359 (if net (net-ipnet net)
362 (defun process-net-form (root addr subnets)
363 "Unpack a net-form. The return value is a list of entries, each of which
364 is a list of the form (NAME ADDR MASK). The first entry is merely repeats
365 the given ROOT and ADDR arguments (unpacking ADDR into separate network
366 address and mask). The SUBNETS are then processed: they are a list of
367 items of the form (NAME NUM-HOSTS . SUBNETS), where NAME names the subnet,
368 NUM-HOSTS is the number of hosts in it, and SUBNETS are its sub-subnets in
369 the same form. An error is signalled if a net's subnets use up more hosts
370 than the net has to start with."
371 (labels ((frob (subnets limit finger)
373 (destructuring-bind (name size &rest subs) (car subnets)
374 (when (> (count-low-zero-bits size)
375 (count-low-zero-bits finger))
376 (error "Bad subnet size for ~A." name))
377 (when (> (+ finger size) limit)
378 (error "Subnet ~A out of range." name))
380 (list (list name finger (- (ash 1 32) size))))
381 (frob subs (+ finger size) finger)
382 (frob (cdr subnets) limit (+ finger size)))))))
383 (let ((ipn (ipnet addr)))
384 (with-ipnet (net mask) ipn
385 (unless (ipmask-cidl-slash mask)
386 (error "Bad mask for subnet form."))
387 (cons (list root net mask)
388 (frob subnets (+ net (ipnet-hosts ipn) 1) net))))))
390 (defun net-create (name net)
391 "Construct a new network called NAME and add it to the map. The ARGS
392 describe the new network, in a form acceptable to the ipnet function."
393 (let ((ipn (ipnet net)))
394 (setf (net-find name)
395 (make-net :name (string-downcase (stringify name))
397 :hosts (ipnet-hosts ipn)
400 (defmacro defnet (name net &rest subnets)
401 "Main network definition macro. None of the arguments is evaluated."
403 ,@(loop for (name addr mask) in (process-net-form name net subnets)
404 collect `(net-create ',name '(,addr . ,mask)))
407 (defun net-next-host (net)
408 "Given a NET, return the IP address (as integer) of the next available
409 address in the network."
410 (unless (< (net-next net) (net-hosts net))
411 (error "No more hosts left in network ~A" (net-name net)))
412 (let ((next (net-next net)))
413 (incf (net-next net))
414 (net-host net next)))
416 (defun net-host (net host)
417 "Return the given HOST on the NEXT. HOST may be an index (in range, of
418 course), or one of the keywords:
420 :NEXT next host, as by net-next-host
421 :NET network base address
422 :BROADCAST network broadcast address"
424 (:next (net-next-host net))
425 (:net (ipnet-net (net-ipnet net)))
426 (:broadcast (ipnet-broadcast (net-ipnet net)))
427 (t (ipnet-host (net-ipnet net) host))))
429 ;;;----- That's all, folks --------------------------------------------------