Don't restart ioctl(2) calls automatically
[iolib.git] / src / sockets / address.lisp
blobd5b1fcf9c3956ed340cb3dff25523c56412ba96f
1 ;;;; -*- Mode: Lisp; Syntax: ANSI-Common-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-storage->sockaddr (ss)
77 (with-foreign-slots ((family) ss sockaddr-storage)
78 (switch (family :test #'=)
79 (af-inet (sockaddr-in->sockaddr ss))
80 (af-inet6 (sockaddr-in6->sockaddr ss))
81 (af-local (sockaddr-un->sockaddr ss)))))
83 (defun sockaddr->sockaddr-storage (ss sockaddr &optional (port 0))
84 (etypecase sockaddr
85 (ipv4-address (make-sockaddr-in ss (address-name sockaddr) port))
86 (ipv6-address (make-sockaddr-in6 ss (address-name sockaddr) port))
87 (local-address (make-sockaddr-un ss (address-name sockaddr)
88 (abstract-address-p sockaddr)))))
90 (defun sockaddr-size (ss)
91 (with-foreign-slots ((family) ss sockaddr-storage)
92 (switch (family :test #'=)
93 (af-inet size-of-sockaddr-in)
94 (af-inet6 size-of-sockaddr-in6)
95 (af-local size-of-sockaddr-un))))
97 ;;;; Conversion functions
99 (defun integer-to-dotted (integer)
100 "Convert an (UNSIGNED-BYTE 32) IPv4 address to a dotted string."
101 (check-type integer ub32 "an '(unsigned-byte 32)")
102 (let ((*print-pretty* nil) (*print-base* 10))
103 (format nil "~A.~A.~A.~A"
104 (ldb (byte 8 24) integer)
105 (ldb (byte 8 16) integer)
106 (ldb (byte 8 8) integer)
107 (ldb (byte 8 0) integer))))
109 (defun dotted-to-vector (address)
110 "Convert a dotted IPv4 address to a (SIMPLE-ARRAY (UNSIGNED-BYTE 8) 4)."
111 (check-type address string "a string")
112 (let ((addr (make-array 4 :element-type 'ub8 :initial-element 0))
113 (split (split-sequence #\. address :count 5)))
114 (flet ((set-array-value (index str)
115 (setf (aref addr index)
116 (ensure-number str :type 'ub8))))
117 (let ((len (length split)))
118 (unless (<= 1 len 4)
119 (error 'parse-error))
120 (set-array-value 3 (nth (1- len) split))
121 (loop :for n :in split
122 :for index :below (1- len)
123 :do (set-array-value index n))))
124 (values addr)))
126 (defun dotted-to-integer (address)
127 "Convert a dotted IPv4 address to an (UNSIGNED-BYTE 32)."
128 (vector-to-integer (dotted-to-vector address)))
130 (defun vector-to-dotted (vector)
131 "Convert an 4-element vector to a dotted string."
132 (coercef vector 'ipv4-array)
133 (let ((*print-pretty* nil) (*print-base* 10))
134 (with-output-to-string (s)
135 (princ (aref vector 0) s) (princ #\. s)
136 (princ (aref vector 1) s) (princ #\. s)
137 (princ (aref vector 2) s) (princ #\. s)
138 (princ (aref vector 3) s))))
140 ;;; TODO: add tests against inet_pton(). Optimize if necessary.
141 ;;; <http://java.sun.com/javase/6/docs/api/java/net/Inet6Address.html#format>
142 (defun colon-separated-to-vector (string)
143 "Convert a colon-separated IPv6 address to a (SIMPLE-ARRAY (UNSIGNED-BYTE 16) 8)."
144 (check-type string string "a string")
145 (when (< (length string) 2)
146 (error 'parse-error))
147 (flet ((handle-trailing-and-leading-colons (string)
148 (let ((start 0)
149 (end (length string))
150 (start-i 0)
151 (trailing-colon-p nil)
152 (tokens-from-leading-or-trailing-zeros 0))
153 (when (char= #\: (char string 0))
154 (incf start)
155 (unless (char= #\: (char string 1))
156 (setq start-i 1)
157 (setq tokens-from-leading-or-trailing-zeros 1)))
158 (when (char= #\: (char string (- end 1)))
159 (setq trailing-colon-p t)
160 (unless (char= #\: (char string (- end 2)))
161 (incf tokens-from-leading-or-trailing-zeros))
162 (decf end))
163 (values start end start-i trailing-colon-p
164 tokens-from-leading-or-trailing-zeros)))
165 (emptyp (string)
166 (= 0 (length string)))
167 ;; we need to use this instead of dotted-to-vector because
168 ;; abbreviated IPv4 addresses are invalid in this context.
169 (ipv4-string-to-ub16-list (string)
170 (let ((tokens (split-sequence #\. string)))
171 (when (= (length tokens) 4)
172 (let ((ipv4 (map 'vector
173 (lambda (string)
174 (let ((x (ignore-errors
175 (parse-integer string))))
176 (if (or (null x) (not (<= 0 x #xff)))
177 (error 'parse-error)
178 x)))
179 tokens)))
180 (list (dpb (aref ipv4 0) (byte 8 8) (aref ipv4 1))
181 (dpb (aref ipv4 2) (byte 8 8) (aref ipv4 3)))))))
182 (parse-hex-ub16 (string)
183 (ensure-number string :type 'ub16 :radix 16)))
184 (multiple-value-bind (start end start-i trailing-colon-p extra-tokens)
185 (handle-trailing-and-leading-colons string)
186 (let* ((vector (make-array 8 :element-type 'ub16 :initial-element 0))
187 (tokens (split-sequence #\: string :start start :end end))
188 (empty-tokens (count-if #'emptyp tokens))
189 (token-count (+ (length tokens) extra-tokens)))
190 (unless trailing-colon-p
191 (let ((ipv4 (ipv4-string-to-ub16-list (lastcar tokens))))
192 (when ipv4
193 (incf token-count)
194 (setq tokens (nconc (butlast tokens) ipv4)))))
195 (when (or (> token-count 8) (> empty-tokens 1)
196 (and (zerop empty-tokens) (/= token-count 8)))
197 (error 'parse-error))
198 (loop for i from start-i and token in tokens do
199 (cond
200 ((integerp token) (setf (aref vector i) token))
201 ((emptyp token) (incf i (- 8 token-count)))
202 (t (setf (aref vector i) (parse-hex-ub16 token)))))
203 vector))))
205 (defun ipv4-on-ipv6-mapped-vector-p (vector)
206 (and (dotimes (i 5 t)
207 (when (plusp (aref vector i))
208 (return nil)))
209 (= (aref vector 5) #xffff)))
211 (defun princ-ipv4-on-ipv6-mapped-address (vector s)
212 (princ "::ffff:" s)
213 (let ((*print-base* 10) (*print-pretty* nil))
214 (princ (ldb (byte 8 8) (aref vector 6)) s) (princ #\. s)
215 (princ (ldb (byte 8 0) (aref vector 6)) s) (princ #\. s)
216 (princ (ldb (byte 8 8) (aref vector 7)) s) (princ #\. s)
217 (princ (ldb (byte 8 0) (aref vector 7)) s)))
219 (defun vector-to-colon-separated (vector &optional (case :downcase))
220 "Convert an (SIMPLE-ARRAY (UNSIGNED-BYTE 16) 8) to a colon-separated IPv6
221 address. CASE may be :DOWNCASE or :UPCASE."
222 (coercef vector 'ipv6-array)
223 (check-type case (member :upcase :downcase) "either :UPCASE or :DOWNCASE")
224 (let ((s (make-string-output-stream)))
225 (flet ((find-zeros ()
226 (let ((start (position 0 vector :start 1 :end 7)))
227 (when start
228 (values start
229 (position-if #'plusp vector :start start :end 7)))))
230 (princ-subvec (start end)
231 (loop :for i :from start :below end
232 :do (princ (aref vector i) s) (princ #\: s))))
233 (cond
234 ((ipv4-on-ipv6-mapped-vector-p vector)
235 (princ-ipv4-on-ipv6-mapped-address vector s))
237 (let ((*print-base* 16) (*print-pretty* nil))
238 (when (plusp (aref vector 0)) (princ (aref vector 0) s))
239 (princ #\: s)
240 (multiple-value-bind (start end) (find-zeros)
241 (cond (start (princ-subvec 1 start)
242 (princ #\: s)
243 (when end (princ-subvec end 7)))
244 (t (princ-subvec 1 7))))
245 (when (plusp (aref vector 7)) (princ (aref vector 7) s))))))
246 (let ((str (get-output-stream-string s)))
247 (ecase case
248 (:downcase (nstring-downcase str))
249 (:upcase (nstring-upcase str))))))
251 (defmacro ignore-parse-errors (&body body)
252 ;; return first value only
253 `(values (ignore-some-conditions (parse-error) ,@body)))
255 (defun string-address-to-vector (address)
256 "Convert a string address (dotted or colon-separated) to a vector address.
257 If the string is not a valid address, return NIL."
258 (or (ignore-parse-errors (dotted-to-vector address))
259 (ignore-parse-errors (colon-separated-to-vector address))))
261 (defun address-to-vector (address)
262 "Convert any representation of an internet address to a vector.
263 Allowed inputs are: unsigned 32-bit integers, strings, vectors
264 and INET-ADDRESS objects. If the address is valid, two values
265 are returned: the vector and the address type (:IPV4 or IPV6),
266 otherwise NIL is returned."
267 (let (vector addr-type)
268 (typecase address
269 (number (and (ignore-parse-errors
270 (setf vector (integer-to-vector address)))
271 (setf addr-type :ipv4)))
272 (string (cond
273 ((ignore-parse-errors (setf vector (dotted-to-vector address)))
274 (setf addr-type :ipv4))
275 ((ignore-parse-errors
276 (setf vector (colon-separated-to-vector address)))
277 (setf addr-type :ipv6))))
278 ((vector * 4) (and (ignore-parse-errors
279 (setf vector (coerce address 'ipv4-array)))
280 (setf addr-type :ipv4)))
281 ((vector * 8) (and (ignore-parse-errors
282 (setf vector (coerce address 'ipv6-array)))
283 (setf addr-type :ipv6)))
284 (ipv4-address (setf vector (copy-seq (address-name address))
285 addr-type :ipv4))
286 (ipv6-address (setf vector (copy-seq (address-name address))
287 addr-type :ipv6)))
288 (when vector
289 (values vector addr-type))))
291 (defun ensure-address (address &key (family :internet) abstract (errorp t))
292 "If FAMILY is :LOCAL, a LOCAL-ADDRESS is instantiated with
293 ADDRESS as its NAME slot. If FAMILY is :INTERNET, an appropriate
294 subtype of INET-ADDRESS is instantiated after guessing the
295 address type through ADDRESS-TO-VECTOR. If the address is invalid
296 and ERRORP is not NIL, then a CL:PARSE-ERROR is signalled,
297 otherwise NIL is returned.
299 When ADDRESS is already an instance of the ADDRESS class, a check
300 is made to see if it matches the FAMILY argument and it is
301 returned unmodified."
302 (ecase family
303 (:internet
304 (typecase address
305 (address (cond
306 (errorp
307 (check-type address inet-address "an INET address"))
308 ((not (typep address 'inet-address))
309 (return* nil)))
310 address)
311 (t (let ((vector (address-to-vector address)))
312 (cond
313 (vector (make-address vector))
314 (errorp (error 'parse-error)))))))
315 (:local
316 (etypecase address
317 (string (make-instance 'local-address :name address :abstract abstract))
318 (address (cond
319 (errorp
320 (check-type address local-address "a local address"))
321 ((not (typep address 'local-address))
322 (return* nil)))
323 address)))))
325 ;;;; Print Methods
327 (defgeneric address-to-string (address)
328 (:documentation "Returns a textual presentation of ADDRESS."))
330 (defmethod address-to-string ((address ipv4-address))
331 (vector-to-dotted (address-name address)))
333 (defmethod address-to-string ((address ipv6-address))
334 (vector-to-colon-separated (address-name address)))
336 (defmethod address-to-string ((address local-address))
337 (format nil "~:[~;@~]~S" (abstract-address-p address)
338 (address-name address)))
340 (defmethod print-object ((address inet-address) stream)
341 (let ((namestring (address-to-string address)))
342 (if *print-escape*
343 (format stream "#/~S/~A" 'ip namestring)
344 (write-string namestring stream))))
346 (defmethod print-object ((address local-address) stream)
347 (print-unreadable-object (address stream :type nil :identity nil)
348 (format stream "Unix socket address: ~A"
349 (address-to-string address))))
351 ;;;; Reader Macro
353 (define-literal-reader ip (stream)
354 (loop :with sstr := (make-string-output-stream)
355 :for char := (read-char stream nil nil)
356 :while char
357 :do (cond ((or (digit-char-p char 16)
358 (member char '(#\. #\:) :test #'char=))
359 (write-char char sstr))
361 (unread-char char stream)
362 (loop-finish)))
363 :finally (return (or (ensure-address (get-output-stream-string sstr)
364 :errorp nil)
365 (error 'reader-error :stream stream)))))
367 ;;;; Equality Methods
369 (defun vector-equal (v1 v2)
370 (and (= (length v1) (length v2))
371 (every #'eql v1 v2)))
373 (defgeneric address= (addr1 addr2)
374 (:documentation "Returns T if both arguments are the same socket address."))
376 (defmethod address= ((addr1 inet-address) (addr2 inet-address))
377 (vector-equal (address-name addr1) (address-name addr2)))
379 (defmethod address= ((addr1 local-address) (addr2 local-address))
380 (equal (address-name addr1) (address-name addr2)))
382 (defun address-equal-p (addr1 addr2 &optional (family :internet))
383 "Returns T if both arguments are designators for the same socket address."
384 (address= (ensure-address addr1 :family family)
385 (ensure-address addr2 :family family)))
387 ;;;; Copy Methods
389 (defgeneric copy-address (address)
390 (:documentation
391 "Returns a copy of ADDRESS which is ADDRESS= to the original."))
393 (defmethod copy-address ((addr ipv4-address))
394 (make-instance 'ipv4-address :name (copy-seq (address-name addr))))
396 (defmethod copy-address ((addr ipv6-address))
397 (make-instance 'ipv6-address :name (copy-seq (address-name addr))))
399 (defmethod copy-address ((addr local-address))
400 (make-instance 'local-address
401 :name (copy-seq (address-name addr))
402 :abstract (abstract-address-p addr)))
404 (defun map-ipv4-address-to-ipv6 (address)
405 "Returns an IPv6 address by mapping ADDRESS onto it."
406 (make-instance 'ipv6-address
407 :name (map-ipv4-vector-to-ipv6 (address-name address))))
409 (defun map-ipv6-address-to-ipv4 (address)
410 "Extracts the IPv4 part of an IPv6-mapped IPv4 address.
411 Signals an error if ADDRESS is not an IPv6-mapped IPv4 address."
412 (assert (ipv6-ipv4-mapped-p address) (address)
413 "Not an IPv6-mapped IPv4 address: ~A" address)
414 (make-instance 'ipv4-address
415 :name (map-ipv6-vector-to-ipv4 (address-name address))))
417 ;;;; Constructor
419 (defun make-address (name)
420 "Constructs an ADDRESS object. NAME should be of type
421 IPV4-ARRAY, IPV6-ARRAY or STRING in which case an instance of
422 IPV4-ADDRESS, IPV6-ADDRESS or LOCAL-ADDRESS, respectively, will
423 be created. Otherwise, a TYPE-ERROR is signalled. See also
424 ENSURE-ADDRESS."
425 (cond
426 ((ignore-errors (coercef name 'ipv4-array))
427 (make-instance 'ipv4-address :name name))
428 ((ignore-errors (coercef name 'ipv6-array))
429 (make-instance 'ipv6-address :name name))
430 ((stringp name) (make-instance 'local-address :name name))
431 (t (error 'type-error :datum name
432 :expected-type '(or string ipv4-array ipv6-array)))))