a45796b0c283c8ff40e4a8390614f3da89b20fde
[iolib.git] / src / sockets / address.lisp
bloba45796b0c283c8ff40e4a8390614f3da89b20fde
1 ;;;; -*- Mode: Lisp; indent-tabs-mode: nil -*-
2 ;;;
3 ;;; --- IP address classes and main methods.
4 ;;;
6 (in-package :iolib.sockets)
8 ;;;; Class Definitions
10 (defclass address ()
11 ((name :initarg :name :reader address-name :type vector))
12 (:documentation "Base class for all socket address classes."))
14 (defclass inet-address (address) ()
15 (:documentation "Base class for IPv4 and IPv6 addresses."))
17 (defclass ipv4-address (inet-address) ()
18 (:documentation "IPv4 address. Its low-level representation
19 can be accessed as vector of type IPV4-ARRAY through the
20 ADDRESS-NAME reader."))
22 (defclass ipv6-address (inet-address) ()
23 (:documentation "IPv6 address. Its low-level representation
24 can be accessed as vector of type IPV6-ARRAY through the
25 ADDRESS-NAME reader."))
27 (defclass local-address (address)
28 ((abstract :initform nil :initarg :abstract
29 :reader abstract-address-p :type boolean))
30 (:documentation "UNIX socket address."))
31 (unset-method-docstring #'abstract-address-p () '(local-address))
32 (set-function-docstring 'abstract-address-p "Return T if ADDRESS is a LOCAL-ADDRESS that lives in the abstract namespace.")
34 (defmethod initialize-instance :after ((address local-address) &key)
35 (with-slots (name) address
36 (etypecase name
37 (string t)
38 (pathname (setf name (namestring name))))))
40 (defmethod make-load-form ((address inet-address) &optional env)
41 (declare (ignore env))
42 `(make-instance ,(class-of address)
43 :name ,(address-name address)))
45 (defmethod make-load-form ((address local-address) &optional env)
46 (declare (ignore env))
47 `(make-instance ,(class-of address)
48 :name ,(address-name address)
49 :abstract ,(abstract-address-p address)))
51 ;;;; Conversion functions for SOCKADDR_* structs
53 (defun sockaddr-in->sockaddr (sin)
54 (with-foreign-slots ((addr port) sin sockaddr-in)
55 (values (make-instance 'ipv4-address
56 :name (integer-to-vector (ntohl addr)))
57 (ntohs port))))
59 (defun sockaddr-in6->sockaddr (sin6)
60 (with-foreign-slots ((addr port) sin6 sockaddr-in6)
61 (values (make-instance 'ipv6-address
62 :name (in6-addr-to-ipv6-array addr))
63 (ntohs port))))
65 (defun parse-un-path (path)
66 (foreign-string-to-lisp path :max-chars (1- unix-path-max)))
68 (defun sockaddr-un->sockaddr (sun)
69 (with-foreign-slots ((path) sun sockaddr-un)
70 (multiple-value-bind (name abstract)
71 (if (zerop (mem-aref path :uint8 0))
72 (values (parse-un-path (inc-pointer path 1)) t)
73 (values (parse-un-path path) nil))
74 (make-instance 'local-address :name name :abstract abstract))))
76 (defun sockaddr-nl->sockaddr (snl)
77 (with-foreign-slots ((groups port) snl sockaddr-nl)
78 (values (make-instance 'netlink-address :multicast-groups groups)
79 port)))
81 (defun sockaddr-storage->sockaddr (ss)
82 (with-foreign-slots ((family) ss sockaddr-storage)
83 (switch (family :test #'=)
84 (af-inet (sockaddr-in->sockaddr ss))
85 (af-inet6 (sockaddr-in6->sockaddr ss))
86 (af-local (sockaddr-un->sockaddr ss))
87 (af-netlink (sockaddr-nl->sockaddr ss)))))
89 (defun sockaddr->sockaddr-storage (ss sockaddr &optional (port 0))
90 (etypecase sockaddr
91 (ipv4-address (make-sockaddr-in ss (address-name sockaddr) port))
92 (ipv6-address (make-sockaddr-in6 ss (address-name sockaddr) port))
93 (local-address (make-sockaddr-un ss (address-name sockaddr)
94 (abstract-address-p sockaddr)))
95 (netlink-address (make-sockaddr-nl ss (multicast-groups sockaddr) port))))
97 (defun sockaddr-size (ss)
98 (with-foreign-slots ((family) ss sockaddr-storage)
99 (switch (family :test #'=)
100 (af-inet (isys:sizeof 'sockaddr-in))
101 (af-inet6 (isys:sizeof 'sockaddr-in6))
102 (af-local (isys:sizeof 'sockaddr-un))
103 (af-netlink (isys:sizeof 'sockaddr-nl)))))
105 ;;;; Conversion functions
107 (defun integer-to-dotted (integer)
108 "Convert an (UNSIGNED-BYTE 32) IPv4 address to a dotted string."
109 (check-type integer ub32 "an '(unsigned-byte 32)")
110 (let ((*print-pretty* nil) (*print-base* 10))
111 (format nil "~A.~A.~A.~A"
112 (ldb (byte 8 24) integer)
113 (ldb (byte 8 16) integer)
114 (ldb (byte 8 8) integer)
115 (ldb (byte 8 0) integer))))
117 (defun dotted-to-vector (address)
118 "Convert a dotted IPv4 address to a (SIMPLE-ARRAY (UNSIGNED-BYTE 8) 4)."
119 (check-type address string "a string")
120 (let ((addr (make-array 4 :element-type 'ub8 :initial-element 0))
121 (split (split-sequence #\. address :count 5)))
122 (flet ((set-array-value (index str)
123 (setf (aref addr index)
124 (ensure-number str :type 'ub8))))
125 (let ((len (length split)))
126 (unless (<= 1 len 4)
127 (error 'parse-error))
128 (set-array-value 3 (nth (1- len) split))
129 (loop :for n :in split
130 :for index :below (1- len)
131 :do (set-array-value index n))))
132 (values addr)))
134 (defun dotted-to-integer (address)
135 "Convert a dotted IPv4 address to an (UNSIGNED-BYTE 32)."
136 (vector-to-integer (dotted-to-vector address)))
138 (defun vector-to-dotted (vector)
139 "Convert an 4-element vector to a dotted string."
140 (coercef vector 'ipv4-array)
141 (let ((*print-pretty* nil) (*print-base* 10))
142 (with-output-to-string (s)
143 (princ (aref vector 0) s) (princ #\. s)
144 (princ (aref vector 1) s) (princ #\. s)
145 (princ (aref vector 2) s) (princ #\. s)
146 (princ (aref vector 3) s))))
148 ;;; TODO: add tests against inet_pton(). Optimize if necessary.
149 ;;; <http://java.sun.com/javase/6/docs/api/java/net/Inet6Address.html#format>
150 (defun colon-separated-to-vector (string)
151 "Convert a colon-separated IPv6 address to a (SIMPLE-ARRAY (UNSIGNED-BYTE 16) 8)."
152 (check-type string string "a string")
153 (when (< (length string) 2)
154 (error 'parse-error))
155 (flet ((handle-trailing-and-leading-colons (string)
156 (let ((start 0)
157 (end (length string))
158 (start-i 0)
159 (trailing-colon-p nil)
160 (tokens-from-leading-or-trailing-zeros 0))
161 (when (char= #\: (char string 0))
162 (incf start)
163 (unless (char= #\: (char string 1))
164 (setq start-i 1)
165 (setq tokens-from-leading-or-trailing-zeros 1)))
166 (when (char= #\: (char string (- end 1)))
167 (setq trailing-colon-p t)
168 (unless (char= #\: (char string (- end 2)))
169 (incf tokens-from-leading-or-trailing-zeros))
170 (decf end))
171 (values start end start-i trailing-colon-p
172 tokens-from-leading-or-trailing-zeros)))
173 ;; we need to use this instead of dotted-to-vector because
174 ;; abbreviated IPv4 addresses are invalid in this context.
175 (ipv4-string-to-ub16-list (string)
176 (let ((tokens (split-sequence #\. string)))
177 (when (= (length tokens) 4)
178 (let ((ipv4 (map 'vector
179 (lambda (string)
180 (let ((x (ignore-errors
181 (parse-integer string))))
182 (if (or (null x) (not (<= 0 x #xff)))
183 (error 'parse-error)
184 x)))
185 tokens)))
186 (list (dpb (aref ipv4 0) (byte 8 8) (aref ipv4 1))
187 (dpb (aref ipv4 2) (byte 8 8) (aref ipv4 3)))))))
188 (parse-hex-ub16 (string)
189 (ensure-number string :type 'ub16 :radix 16)))
190 (multiple-value-bind (start end start-i trailing-colon-p extra-tokens)
191 (handle-trailing-and-leading-colons string)
192 (let* ((vector (make-array 8 :element-type 'ub16 :initial-element 0))
193 (tokens (split-sequence #\: string :start start :end end))
194 (empty-tokens (count-if #'emptyp tokens))
195 (token-count (+ (length tokens) extra-tokens)))
196 (unless trailing-colon-p
197 (let ((ipv4 (ipv4-string-to-ub16-list (lastcar tokens))))
198 (when ipv4
199 (incf token-count)
200 (setq tokens (nconc (butlast tokens) ipv4)))))
201 (when (or (> token-count 8) (> empty-tokens 1)
202 (and (zerop empty-tokens) (/= token-count 8)))
203 (error 'parse-error))
204 (loop for i from start-i and token in tokens do
205 (cond
206 ((integerp token) (setf (aref vector i) token))
207 ((emptyp token) (incf i (- 8 token-count)))
208 (t (setf (aref vector i) (parse-hex-ub16 token)))))
209 vector))))
211 (defun ipv4-on-ipv6-mapped-vector-p (vector)
212 (and (dotimes (i 5 t)
213 (when (plusp (aref vector i))
214 (return nil)))
215 (= (aref vector 5) #xffff)))
217 (defun princ-ipv4-on-ipv6-mapped-address (vector s)
218 (princ "::ffff:" s)
219 (let ((*print-base* 10) (*print-pretty* nil))
220 (princ (ldb (byte 8 8) (aref vector 6)) s) (princ #\. s)
221 (princ (ldb (byte 8 0) (aref vector 6)) s) (princ #\. s)
222 (princ (ldb (byte 8 8) (aref vector 7)) s) (princ #\. s)
223 (princ (ldb (byte 8 0) (aref vector 7)) s)))
225 (defun vector-to-colon-separated (vector &optional (case :downcase))
226 "Convert an (SIMPLE-ARRAY (UNSIGNED-BYTE 16) 8) to a colon-separated IPv6
227 address. CASE may be :DOWNCASE or :UPCASE."
228 (coercef vector 'ipv6-array)
229 (check-type case (member :upcase :downcase) "either :UPCASE or :DOWNCASE")
230 (let ((s (make-string-output-stream)))
231 (flet ((find-zeros ()
232 (let ((start (position 0 vector :start 1 :end 7)))
233 (when start
234 (values start
235 (position-if #'plusp vector :start start :end 7)))))
236 (princ-subvec (start end)
237 (loop :for i :from start :below end
238 :do (princ (aref vector i) s) (princ #\: s))))
239 (cond
240 ((ipv4-on-ipv6-mapped-vector-p vector)
241 (princ-ipv4-on-ipv6-mapped-address vector s))
243 (let ((*print-base* 16) (*print-pretty* nil))
244 (when (plusp (aref vector 0)) (princ (aref vector 0) s))
245 (princ #\: s)
246 (multiple-value-bind (start end) (find-zeros)
247 (cond (start (princ-subvec 1 start)
248 (princ #\: s)
249 (when end (princ-subvec end 7)))
250 (t (princ-subvec 1 7))))
251 (when (plusp (aref vector 7)) (princ (aref vector 7) s))))))
252 (let ((str (get-output-stream-string s)))
253 (ecase case
254 (:downcase (nstring-downcase str))
255 (:upcase (nstring-upcase str))))))
257 (defmacro ignore-parse-errors (&body body)
258 ;; return first value only
259 `(values (ignore-some-conditions (parse-error) ,@body)))
261 (defun string-address-to-vector (address)
262 "Convert a string address (dotted or colon-separated) to a vector address.
263 If the string is not a valid address, return NIL."
264 (or (ignore-parse-errors (dotted-to-vector address))
265 (ignore-parse-errors (colon-separated-to-vector address))))
267 (defun address-to-vector (address)
268 "Convert any representation of an internet address to a vector.
269 Allowed inputs are: unsigned 32-bit integers, strings, vectors
270 and INET-ADDRESS objects. If the address is valid, two values
271 are returned: the vector and the address type (:IPV4 or IPV6),
272 otherwise NIL is returned."
273 (let (vector addr-type)
274 (typecase address
275 (number (and (ignore-parse-errors
276 (setf vector (integer-to-vector address)))
277 (setf addr-type :ipv4)))
278 (string (cond
279 ((ignore-parse-errors (setf vector (dotted-to-vector address)))
280 (setf addr-type :ipv4))
281 ((ignore-parse-errors
282 (setf vector (colon-separated-to-vector address)))
283 (setf addr-type :ipv6))))
284 ((vector * 4) (and (ignore-parse-errors
285 (setf vector (coerce address 'ipv4-array)))
286 (setf addr-type :ipv4)))
287 ((vector * 8) (and (ignore-parse-errors
288 (setf vector (coerce address 'ipv6-array)))
289 (setf addr-type :ipv6)))
290 (ipv4-address (setf vector (copy-seq (address-name address))
291 addr-type :ipv4))
292 (ipv6-address (setf vector (copy-seq (address-name address))
293 addr-type :ipv6)))
294 (when vector
295 (values vector addr-type))))
297 (defun ensure-address (address &key (family :internet) abstract (errorp t))
298 "If FAMILY is :LOCAL, a LOCAL-ADDRESS is instantiated with
299 ADDRESS as its NAME slot. If FAMILY is :INTERNET, an appropriate
300 subtype of INET-ADDRESS is instantiated after guessing the
301 address type through ADDRESS-TO-VECTOR. If the address is invalid
302 and ERRORP is not NIL, then a CL:PARSE-ERROR is signalled,
303 otherwise NIL is returned.
305 When ADDRESS is already an instance of the ADDRESS class, a check
306 is made to see if it matches the FAMILY argument and it is
307 returned unmodified."
308 (ecase family
309 (:internet
310 (typecase address
311 (address (cond
312 (errorp
313 (check-type address inet-address "an INET address"))
314 ((not (typep address 'inet-address))
315 (return* nil)))
316 address)
317 (t (let ((vector (address-to-vector address)))
318 (cond
319 (vector (make-address vector))
320 (errorp (error 'parse-error)))))))
321 (:local
322 (etypecase address
323 (string (make-instance 'local-address :name address :abstract abstract))
324 (address (cond
325 (errorp
326 (check-type address local-address "a local address"))
327 ((not (typep address 'local-address))
328 (return* nil)))
329 address)))))
331 ;;;; Print Methods
333 (defgeneric address-to-string (address)
334 (:documentation "Returns a textual presentation of ADDRESS."))
336 (defmethod address-to-string ((address ipv4-address))
337 (vector-to-dotted (address-name address)))
339 (defmethod address-to-string ((address ipv6-address))
340 (vector-to-colon-separated (address-name address)))
342 (defmethod address-to-string ((address local-address))
343 (format nil "~:[~;@~]~S" (abstract-address-p address)
344 (address-name address)))
346 (defmethod print-object ((address inet-address) stream)
347 (let ((namestring (address-to-string address)))
348 (if (or *print-readably* *print-escape*)
349 (format stream "#/~S/~A" 'ip namestring)
350 (write-string namestring stream))))
352 (defmethod print-object ((address local-address) stream)
353 (print-unreadable-object (address stream :type nil :identity nil)
354 (format stream "Unix socket address: ~A"
355 (address-to-string address))))
357 ;;;; Reader Macro
359 (define-literal-reader ip (stream)
360 (loop :with sstr := (make-string-output-stream)
361 :for char := (read-char stream nil nil)
362 :while char
363 :do (cond ((or (digit-char-p char 16)
364 (member char '(#\. #\:) :test #'char=))
365 (write-char char sstr))
367 (unread-char char stream)
368 (loop-finish)))
369 :finally (return (or (ensure-address (get-output-stream-string sstr)
370 :errorp nil)
371 (error 'reader-error :stream stream)))))
373 ;;;; Equality Methods
375 (defun vector-equal (v1 v2)
376 (and (= (length v1) (length v2))
377 (every #'eql v1 v2)))
379 (defgeneric address= (addr1 addr2)
380 (:documentation "Returns T if both arguments are the same socket address."))
382 (defmethod address= ((addr1 inet-address) (addr2 inet-address))
383 (vector-equal (address-name addr1) (address-name addr2)))
385 (defmethod address= ((addr1 local-address) (addr2 local-address))
386 (equal (address-name addr1) (address-name addr2)))
388 (defun address-equal-p (addr1 addr2 &optional (family :internet))
389 "Returns T if both arguments are designators for the same socket address."
390 (address= (ensure-address addr1 :family family)
391 (ensure-address addr2 :family family)))
393 ;;;; Copy Methods
395 (defgeneric copy-address (address)
396 (:documentation
397 "Returns a copy of ADDRESS which is ADDRESS= to the original."))
399 (defmethod copy-address ((addr ipv4-address))
400 (make-instance 'ipv4-address :name (copy-seq (address-name addr))))
402 (defmethod copy-address ((addr ipv6-address))
403 (make-instance 'ipv6-address :name (copy-seq (address-name addr))))
405 (defmethod copy-address ((addr local-address))
406 (make-instance 'local-address
407 :name (copy-seq (address-name addr))
408 :abstract (abstract-address-p addr)))
410 (defun map-ipv4-address-to-ipv6 (address)
411 "Returns an IPv6 address by mapping ADDRESS onto it."
412 (make-instance 'ipv6-address
413 :name (map-ipv4-vector-to-ipv6 (address-name address))))
415 (defun map-ipv6-address-to-ipv4 (address)
416 "Extracts the IPv4 part of an IPv6-mapped IPv4 address.
417 Signals an error if ADDRESS is not an IPv6-mapped IPv4 address."
418 (assert (ipv6-ipv4-mapped-p address) (address)
419 "Not an IPv6-mapped IPv4 address: ~A" address)
420 (make-instance 'ipv4-address
421 :name (map-ipv6-vector-to-ipv4 (address-name address))))
423 ;;;; Constructor
425 (defun make-address (name)
426 "Constructs an ADDRESS object. NAME should be of type
427 IPV4-ARRAY, IPV6-ARRAY or STRING in which case an instance of
428 IPV4-ADDRESS, IPV6-ADDRESS or LOCAL-ADDRESS, respectively, will
429 be created. Otherwise, a TYPE-ERROR is signalled. See also
430 ENSURE-ADDRESS."
431 (cond
432 ((ignore-errors (coercef name 'ipv4-array))
433 (make-instance 'ipv4-address :name name))
434 ((ignore-errors (coercef name 'ipv6-array))
435 (make-instance 'ipv6-address :name name))
436 ((stringp name) (make-instance 'local-address :name name))
437 (t (error 'type-error :datum name
438 :expected-type '(or string ipv4-array ipv6-array)))))