Make sure that OPEN-STREAM-P works on stream sockets.
[iolib.git] / src / sockets / address.lisp
blob6633434c0331c70cfa8ceee448b7f93ebdbb9007
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-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 (isys:sizeof 'sockaddr-in))
94 (af-inet6 (isys:sizeof 'sockaddr-in6))
95 (af-local (isys:sizeof '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 ;; we need to use this instead of dotted-to-vector because
166 ;; abbreviated IPv4 addresses are invalid in this context.
167 (ipv4-string-to-ub16-list (string)
168 (let ((tokens (split-sequence #\. string)))
169 (when (= (length tokens) 4)
170 (let ((ipv4 (map 'vector
171 (lambda (string)
172 (let ((x (ignore-errors
173 (parse-integer string))))
174 (if (or (null x) (not (<= 0 x #xff)))
175 (error 'parse-error)
176 x)))
177 tokens)))
178 (list (dpb (aref ipv4 0) (byte 8 8) (aref ipv4 1))
179 (dpb (aref ipv4 2) (byte 8 8) (aref ipv4 3)))))))
180 (parse-hex-ub16 (string)
181 (ensure-number string :type 'ub16 :radix 16)))
182 (multiple-value-bind (start end start-i trailing-colon-p extra-tokens)
183 (handle-trailing-and-leading-colons string)
184 (let* ((vector (make-array 8 :element-type 'ub16 :initial-element 0))
185 (tokens (split-sequence #\: string :start start :end end))
186 (empty-tokens (count-if #'emptyp tokens))
187 (token-count (+ (length tokens) extra-tokens)))
188 (unless trailing-colon-p
189 (let ((ipv4 (ipv4-string-to-ub16-list (lastcar tokens))))
190 (when ipv4
191 (incf token-count)
192 (setq tokens (nconc (butlast tokens) ipv4)))))
193 (when (or (> token-count 8) (> empty-tokens 1)
194 (and (zerop empty-tokens) (/= token-count 8)))
195 (error 'parse-error))
196 (loop for i from start-i and token in tokens do
197 (cond
198 ((integerp token) (setf (aref vector i) token))
199 ((emptyp token) (incf i (- 8 token-count)))
200 (t (setf (aref vector i) (parse-hex-ub16 token)))))
201 vector))))
203 (defun ipv4-on-ipv6-mapped-vector-p (vector)
204 (and (dotimes (i 5 t)
205 (when (plusp (aref vector i))
206 (return nil)))
207 (= (aref vector 5) #xffff)))
209 (defun princ-ipv4-on-ipv6-mapped-address (vector s)
210 (princ "::ffff:" s)
211 (let ((*print-base* 10) (*print-pretty* nil))
212 (princ (ldb (byte 8 8) (aref vector 6)) s) (princ #\. s)
213 (princ (ldb (byte 8 0) (aref vector 6)) s) (princ #\. s)
214 (princ (ldb (byte 8 8) (aref vector 7)) s) (princ #\. s)
215 (princ (ldb (byte 8 0) (aref vector 7)) s)))
217 (defun vector-to-colon-separated (vector &optional (case :downcase))
218 "Convert an (SIMPLE-ARRAY (UNSIGNED-BYTE 16) 8) to a colon-separated IPv6
219 address. CASE may be :DOWNCASE or :UPCASE."
220 (coercef vector 'ipv6-array)
221 (check-type case (member :upcase :downcase) "either :UPCASE or :DOWNCASE")
222 (let ((s (make-string-output-stream)))
223 (flet ((find-zeros ()
224 (let ((start (position 0 vector :start 1 :end 7)))
225 (when start
226 (values start
227 (position-if #'plusp vector :start start :end 7)))))
228 (princ-subvec (start end)
229 (loop :for i :from start :below end
230 :do (princ (aref vector i) s) (princ #\: s))))
231 (cond
232 ((ipv4-on-ipv6-mapped-vector-p vector)
233 (princ-ipv4-on-ipv6-mapped-address vector s))
235 (let ((*print-base* 16) (*print-pretty* nil))
236 (when (plusp (aref vector 0)) (princ (aref vector 0) s))
237 (princ #\: s)
238 (multiple-value-bind (start end) (find-zeros)
239 (cond (start (princ-subvec 1 start)
240 (princ #\: s)
241 (when end (princ-subvec end 7)))
242 (t (princ-subvec 1 7))))
243 (when (plusp (aref vector 7)) (princ (aref vector 7) s))))))
244 (let ((str (get-output-stream-string s)))
245 (ecase case
246 (:downcase (nstring-downcase str))
247 (:upcase (nstring-upcase str))))))
249 (defmacro ignore-parse-errors (&body body)
250 ;; return first value only
251 `(values (ignore-some-conditions (parse-error) ,@body)))
253 (defun string-address-to-vector (address)
254 "Convert a string address (dotted or colon-separated) to a vector address.
255 If the string is not a valid address, return NIL."
256 (or (ignore-parse-errors (dotted-to-vector address))
257 (ignore-parse-errors (colon-separated-to-vector address))))
259 (defun address-to-vector (address)
260 "Convert any representation of an internet address to a vector.
261 Allowed inputs are: unsigned 32-bit integers, strings, vectors
262 and INET-ADDRESS objects. If the address is valid, two values
263 are returned: the vector and the address type (:IPV4 or IPV6),
264 otherwise NIL is returned."
265 (let (vector addr-type)
266 (typecase address
267 (number (and (ignore-parse-errors
268 (setf vector (integer-to-vector address)))
269 (setf addr-type :ipv4)))
270 (string (cond
271 ((ignore-parse-errors (setf vector (dotted-to-vector address)))
272 (setf addr-type :ipv4))
273 ((ignore-parse-errors
274 (setf vector (colon-separated-to-vector address)))
275 (setf addr-type :ipv6))))
276 ((vector * 4) (and (ignore-parse-errors
277 (setf vector (coerce address 'ipv4-array)))
278 (setf addr-type :ipv4)))
279 ((vector * 8) (and (ignore-parse-errors
280 (setf vector (coerce address 'ipv6-array)))
281 (setf addr-type :ipv6)))
282 (ipv4-address (setf vector (copy-seq (address-name address))
283 addr-type :ipv4))
284 (ipv6-address (setf vector (copy-seq (address-name address))
285 addr-type :ipv6)))
286 (when vector
287 (values vector addr-type))))
289 (defun ensure-address (address &key (family :internet) abstract (errorp t))
290 "If FAMILY is :LOCAL, a LOCAL-ADDRESS is instantiated with
291 ADDRESS as its NAME slot. If FAMILY is :INTERNET, an appropriate
292 subtype of INET-ADDRESS is instantiated after guessing the
293 address type through ADDRESS-TO-VECTOR. If the address is invalid
294 and ERRORP is not NIL, then a CL:PARSE-ERROR is signalled,
295 otherwise NIL is returned.
297 When ADDRESS is already an instance of the ADDRESS class, a check
298 is made to see if it matches the FAMILY argument and it is
299 returned unmodified."
300 (ecase family
301 (:internet
302 (typecase address
303 (address (cond
304 (errorp
305 (check-type address inet-address "an INET address"))
306 ((not (typep address 'inet-address))
307 (return* nil)))
308 address)
309 (t (let ((vector (address-to-vector address)))
310 (cond
311 (vector (make-address vector))
312 (errorp (error 'parse-error)))))))
313 (:local
314 (etypecase address
315 (string (make-instance 'local-address :name address :abstract abstract))
316 (address (cond
317 (errorp
318 (check-type address local-address "a local address"))
319 ((not (typep address 'local-address))
320 (return* nil)))
321 address)))))
323 ;;;; Print Methods
325 (defgeneric address-to-string (address)
326 (:documentation "Returns a textual presentation of ADDRESS."))
328 (defmethod address-to-string ((address ipv4-address))
329 (vector-to-dotted (address-name address)))
331 (defmethod address-to-string ((address ipv6-address))
332 (vector-to-colon-separated (address-name address)))
334 (defmethod address-to-string ((address local-address))
335 (format nil "~:[~;@~]~S" (abstract-address-p address)
336 (address-name address)))
338 (defmethod print-object ((address inet-address) stream)
339 (let ((namestring (address-to-string address)))
340 (if (or *print-readably* *print-escape*)
341 (format stream "#/~S/~A" 'ip namestring)
342 (write-string namestring stream))))
344 (defmethod print-object ((address local-address) stream)
345 (print-unreadable-object (address stream :type nil :identity nil)
346 (format stream "Unix socket address: ~A"
347 (address-to-string address))))
349 ;;;; Reader Macro
351 (define-literal-reader ip (stream)
352 (loop :with sstr := (make-string-output-stream)
353 :for char := (read-char stream nil nil)
354 :while char
355 :do (cond ((or (digit-char-p char 16)
356 (member char '(#\. #\:) :test #'char=))
357 (write-char char sstr))
359 (unread-char char stream)
360 (loop-finish)))
361 :finally (return (or (ensure-address (get-output-stream-string sstr)
362 :errorp nil)
363 (error 'reader-error :stream stream)))))
365 ;;;; Equality Methods
367 (defun vector-equal (v1 v2)
368 (and (= (length v1) (length v2))
369 (every #'eql v1 v2)))
371 (defgeneric address= (addr1 addr2)
372 (:documentation "Returns T if both arguments are the same socket address."))
374 (defmethod address= ((addr1 inet-address) (addr2 inet-address))
375 (vector-equal (address-name addr1) (address-name addr2)))
377 (defmethod address= ((addr1 local-address) (addr2 local-address))
378 (equal (address-name addr1) (address-name addr2)))
380 (defun address-equal-p (addr1 addr2 &optional (family :internet))
381 "Returns T if both arguments are designators for the same socket address."
382 (address= (ensure-address addr1 :family family)
383 (ensure-address addr2 :family family)))
385 ;;;; Copy Methods
387 (defgeneric copy-address (address)
388 (:documentation
389 "Returns a copy of ADDRESS which is ADDRESS= to the original."))
391 (defmethod copy-address ((addr ipv4-address))
392 (make-instance 'ipv4-address :name (copy-seq (address-name addr))))
394 (defmethod copy-address ((addr ipv6-address))
395 (make-instance 'ipv6-address :name (copy-seq (address-name addr))))
397 (defmethod copy-address ((addr local-address))
398 (make-instance 'local-address
399 :name (copy-seq (address-name addr))
400 :abstract (abstract-address-p addr)))
402 (defun map-ipv4-address-to-ipv6 (address)
403 "Returns an IPv6 address by mapping ADDRESS onto it."
404 (make-instance 'ipv6-address
405 :name (map-ipv4-vector-to-ipv6 (address-name address))))
407 (defun map-ipv6-address-to-ipv4 (address)
408 "Extracts the IPv4 part of an IPv6-mapped IPv4 address.
409 Signals an error if ADDRESS is not an IPv6-mapped IPv4 address."
410 (assert (ipv6-ipv4-mapped-p address) (address)
411 "Not an IPv6-mapped IPv4 address: ~A" address)
412 (make-instance 'ipv4-address
413 :name (map-ipv6-vector-to-ipv4 (address-name address))))
415 ;;;; Constructor
417 (defun make-address (name)
418 "Constructs an ADDRESS object. NAME should be of type
419 IPV4-ARRAY, IPV6-ARRAY or STRING in which case an instance of
420 IPV4-ADDRESS, IPV6-ADDRESS or LOCAL-ADDRESS, respectively, will
421 be created. Otherwise, a TYPE-ERROR is signalled. See also
422 ENSURE-ADDRESS."
423 (cond
424 ((ignore-errors (coercef name 'ipv4-array))
425 (make-instance 'ipv4-address :name name))
426 ((ignore-errors (coercef name 'ipv6-array))
427 (make-instance 'ipv6-address :name name))
428 ((stringp name) (make-instance 'local-address :name name))
429 (t (error 'type-error :datum name
430 :expected-type '(or string ipv4-array ipv6-array)))))