chiark / gitweb /
net: Fix misspelt export entry.
[zone] / net.lisp
1 ;;; -*-lisp-*-
2 ;;;
3 ;;; $Id$
4 ;;;
5 ;;; Network (numbering) tools
6 ;;;
7 ;;; (c) 2006 Straylight/Edgeware
8 ;;;
9
10 ;;;----- Licensing notice ---------------------------------------------------
11 ;;;
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.
16 ;;; 
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.
21 ;;; 
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.
25
26 ;;;--------------------------------------------------------------------------
27 ;;; Packaging.
28
29 (defpackage #:net
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))
41
42 (in-package #:net)
43
44 ;;;--------------------------------------------------------------------------
45 ;;; Basic types.
46
47 (defun mask (n)
48   "Return 2^N - 1: i.e., a mask of N set bits."
49   (1- (ash 1 n)))
50
51 (deftype u32 ()
52   "The type of unsigned 32-bit values."
53   '(unsigned-byte 32))
54
55 (deftype ipaddr ()
56   "The type of IP (version 4) addresses."
57   'u32)
58
59 ;;;--------------------------------------------------------------------------
60 ;;; Various random utilities.
61
62 (defun count-low-zero-bits (n)
63   "Return the number of low-order zero bits in the integer N."
64   (if (zerop n) nil
65       (loop for i from 0
66             until (logbitp i n)
67             finally (return i))))
68
69 ;;;--------------------------------------------------------------------------
70 ;;; Simple messing with IP addresses.
71
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
76    substring."
77   (setf str (stringify str))
78   (unless end
79     (setf end (length str)))
80   (let ((addr 0) (noct 0))
81     (loop
82       (let* ((pos (position #\. str :start start :end end))
83              (i (parse-integer str :start start :end (or pos end))))
84         (unless (<= 0 i 256)
85           (error "IP address octet out of range"))
86         (setf addr (+ (* addr 256) i))
87         (incf noct)
88         (unless pos
89           (return))
90         (setf start (1+ pos))))
91     (unless (= noct 4)
92       (error "Wrong number of octets in IP address"))
93     addr))
94
95 (defun ipaddr-byte (ip n)
96   "Return byte N (from most significant downwards) of an IP address."
97   (assert (<= 0 n 3))
98   (logand #xff (ash ip (* -8 (- 3 n)))))
99
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 ()
104                       (dotimes (i 4)
105                         (collect (ipaddr-byte ip i))))))
106
107 (defun ipaddrp (ip)
108   "Answer true if IP is a valid IP address in integer form."
109   (typep ip 'ipaddr))
110
111 (defun ipaddr (ip)
112   "Convert IP to an IP address.  If it's an integer, return it unchanged;
113    otherwise convert by `string-ipaddr'."
114   (typecase ip
115     (ipaddr ip)
116     (t (string-ipaddr ip))))
117
118 ;;;--------------------------------------------------------------------------
119 ;;; Netmasks.
120
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))))
124
125 (defun ipmask (ip)
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
128    `ipaddr'."
129   (typecase ip
130     (null (mask 32))
131     ((integer 0 32) (integer-netmask ip))
132     (t (ipaddr ip))))
133
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."
137   (dotimes (i 33)
138     (when (= mask (integer-netmask i))
139       (return i))))
140
141 ;;;--------------------------------------------------------------------------
142 ;;; Networks: pairing an address and netmask.
143
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)))
150
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)))
156     (if sl
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
161                                                         :start (1+ sl)
162                                                         :end end))))
163         (make-ipnet (parse-ipaddr (subseq str start end))
164                     (integer-netmask 32)))))
165
166 (defun ipnet (net)
167   "Construct an IP-network object from the given argument.  A number of forms
168    are acceptable:
169
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')
173        version."
174   (cond ((or (stringp net) (symbolp net)) (string-ipnet net))
175         (t (apply #'make-ipnet (pairify net 32)))))
176
177 (defun ipnet-net (ipn)
178   "Return the base network address of IPN."
179   (car ipn))
180
181 (defun ipnet-mask (ipn)
182   "Return the netmask of IPN."
183   (cdr ipn))
184
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
188    wanted."
189   (with-gensyms tmp
190     `(let ((,tmp ,ipn))
191        (let (,@(and net `((,net (ipnet-net ,tmp))))
192              ,@(and mask `((,mask (ipnet-mask ,tmp)))))
193          ,@body))))
194
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)))))
200
201 (defun ipnet-string (ipn)
202   "Convert IPN to a string."
203   (with-ipnet (net mask) ipn
204     (format nil "~A/~A"
205             (ipaddr-string net)
206             (or (ipmask-cidl-slash mask) (ipaddr-string mask)))))
207
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))))
212
213 (defun ipnet-hosts (ipn)
214   "Return the number of available addresses in network IPN."
215   (ash 1 (- 32 (logcount (ipnet-mask ipn)))))
216
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))
223       (loop
224         (when (>= i 32)
225           (error "Host index ~D out of range for network ~A"
226                  host (ipnet-pretty ipn)))
227         (cond ((zerop h)
228                (return a))
229               ((logbitp i mask)
230                (setf h (ash h 1)))
231               (t
232                (setf a (logior a (logand m h)))
233                (setf h (logandc2 h m))))
234         (setf m (ash m 1))
235         (incf i)))))
236
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))))
241
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))))))
248
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."
252   (dotimes (i 4 4)
253     (when (/= (ipaddr-byte mask i) 255)
254       (return (- 4 i)))))
255
256 ;;;--------------------------------------------------------------------------
257 ;;; Name resolution.
258
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)))
262           (and he
263                (ext:host-entry-addr he)))
264   #-cmu nil
265 )
266
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)))
270           (and he
271                (ext:host-entry-name he)))
272   #-cmu nil)
273
274 ;;;--------------------------------------------------------------------------
275 ;;; Host names and specifiers.
276
277 (defun parse-ipaddr (addr)
278   "Convert the string ADDR into an IP address: tries all sorts of things:
279
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
283
284    INTEGER              an integer IP address
285
286    IPADDR               an IP address in dotted-quad form
287
288    HOST                 a host name defined by defhost
289
290    DNSNAME              a name string to look up in the DNS"
291   (cond ((listp addr)
292          (destructuring-bind
293              (net host)
294              (pairify addr :next)
295            (net-host (or (net-find net)
296                          (error "Network ~A not found" net))
297                      host)))
298         ((ipaddrp addr) addr)
299         (t
300          (setf addr (string-downcase (stringify addr)))
301          (or (host-find 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)))))
307
308 (defvar *hosts* (make-hash-table :test #'equal)
309   "The table of known hostnames.")
310
311 (defun host-find (name)
312   "Find a host by NAME."
313   (gethash (string-downcase (stringify name)) *hosts*))
314
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))
318
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)))
322
323 (defmacro defhost (name addr)
324   "Main host definition macro.  Neither NAME nor ADDR is evaluated."
325   `(progn
326      (host-create ',name ',addr)
327      ',name))
328
329 ;;;--------------------------------------------------------------------------
330 ;;; Network names and specifiers.
331
332 (defstruct (net (:predicate netp))
333   "A network structure.  Slots:
334
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"
339   name
340   ipnet
341   hosts
342   next)
343
344 (defvar *networks* (make-hash-table :test #'equal)
345   "The table of known networks.")
346
347 (defun net-find (name)
348   "Find a network by NAME."
349   (gethash (string-downcase (stringify name)) *networks*))
350
351 (defun (setf net-find) (net name)
352   "Make NAME map to NET."
353   (setf (gethash (string-downcase (stringify name)) *networks*) net))
354
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)
360         (ipnet form))))
361
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)
372              (when subnets
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))
379                  (append (and 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))))))
389
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))
396                     :ipnet ipn
397                     :hosts (ipnet-hosts ipn)
398                     :next 1))))
399
400 (defmacro defnet (name net &rest subnets)
401   "Main network definition macro.  None of the arguments is evaluated."
402   `(progn
403     ,@(loop for (name addr mask) in (process-net-form name net subnets)
404             collect `(net-create ',name '(,addr . ,mask)))
405     ',name))
406
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)))
415
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:
419
420    :NEXT       next host, as by net-next-host
421    :NET        network base address
422    :BROADCAST  network broadcast address"
423   (case host
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))))
428
429 ;;;----- That's all, folks --------------------------------------------------