sb-bsd-sockets: Implement NON-BLOCKING-MODE on Windows
[sbcl.git] / contrib / sb-bsd-sockets / name-service.lisp
1 (in-package :sb-bsd-sockets)
2
3 (defclass host-ent ()
4   ((name :initarg :name :reader host-ent-name
5          :documentation "The name of the host")
6    ;; Deliberately not documented, since this isn't very useful,
7    ;; and the data isn't available when using getaddrinfo(). Unfortunately
8    ;; it is exported.
9    (aliases :initarg :aliases :reader host-ent-aliases)
10    ;; presently always AF_INET. Not exported.
11    (address-type :initarg :type :reader host-ent-address-type)
12    (addresses :initarg :addresses :reader host-ent-addresses
13               :documentation "A list of addresses for this host."))
14   (:documentation "This class represents the results of an address lookup."))
15
16 (defgeneric host-ent-address (host-ent)
17   (:documentation "Returns some valid address for HOST-ENT."))
18
19 (defmethod host-ent-address ((host-ent host-ent))
20   (car (host-ent-addresses host-ent)))
21
22 (defun make-host-ent (h &optional errno)
23   (when (sb-alien:null-alien h)
24     (name-service-error "gethostbyname" errno))
25   (let* ((length (sockint::hostent-length h))
26          (aliases (loop for i = 0 then (1+ i)
27                         for al = (sb-alien:deref (sockint::hostent-aliases h) i)
28                         while al
29                         collect al))
30          (addresses
31           (loop for i = 0 then (1+ i)
32                 for ad = (sb-alien:deref (sockint::hostent-addresses h) i)
33                 until (sb-alien:null-alien ad)
34                 collect (ecase (sockint::hostent-type h)
35                           (#.sockint::af-inet
36                            ;; CLH: Work around x86-64 darwin bug here.
37                            ;; The length is reported as 8, when it should be 4.
38                            ;; FIXME: this is rumored to be fixed in 10.5
39                            #+(and darwin x86-64)
40                            (progn
41                              (assert (or (= length 4) (= length 8)))
42                              (naturalize-unsigned-byte-8-array ad 4))
43                            #-(and darwin x86-64)
44                            (progn
45                              (assert (= length 4))
46                              (naturalize-unsigned-byte-8-array ad length)))
47                           #-win32
48                           (#.sockint::af-local
49                            (sb-alien:cast ad sb-alien:c-string))))))
50     (make-instance 'host-ent
51                    :name (sockint::hostent-name h)
52                    :type (sockint::hostent-type h)
53                    :aliases aliases
54                    :addresses addresses)))
55
56 (defun naturalize-unsigned-byte-8-array (array length)
57   (let ((addr (make-array 4 :element-type '(unsigned-byte 8))))
58     (dotimes (i length)
59       (setf (elt addr i) (sb-alien:deref array i)))
60     addr))
61
62 ;;; Resolving
63
64 #-sb-bsd-sockets-addrinfo
65 (sb-ext:defglobal **gethostby-lock** (sb-thread:make-mutex :name "gethostby lock"))
66
67 (defun get-host-by-name (host-name)
68   "Returns a HOST-ENT instance for HOST-NAME or signals a NAME-SERVICE-ERROR.
69 HOST-NAME may also be an IP address in dotted quad notation or some other
70 weird stuff - see gethostbyname(3) or getaddrinfo(3) for the details."
71   #+sb-bsd-sockets-addrinfo
72   (get-address-info host-name)
73   #-sb-bsd-sockets-addrinfo
74   (sb-thread::with-system-mutex (**gethostby-lock** :allow-with-interrupts t)
75     (make-host-ent (sockint::gethostbyname host-name))))
76
77 (defun get-host-by-address (address)
78   "Returns a HOST-ENT instance for ADDRESS, which should be a vector of
79  (integer 0 255), or signals a NAME-SERVICE-ERROR.  See gethostbyaddr(3)
80  or gethostinfo(3) for details."
81   #+sb-bsd-sockets-addrinfo
82   (get-name-info address)
83   #-sb-bsd-sockets-addrinfo
84   (sb-thread::with-system-mutex (**gethostby-lock** :allow-with-interrupts t)
85     (sockint::with-in-addr packed-addr ()
86       (let ((addr-vector (coerce address 'vector)))
87         (loop for i from 0 below (length addr-vector)
88               do (setf (sb-alien:deref (sockint::in-addr-addr packed-addr) i)
89                        (elt addr-vector i)))
90         (make-host-ent (sockint::gethostbyaddr packed-addr
91                                                4
92                                                sockint::af-inet))))))
93
94 ;;; Emulate the above two functions with getaddrinfo / getnameinfo
95
96 #+sb-bsd-sockets-addrinfo
97 (defun get-address-info (node)
98   (sb-alien:with-alien ((buf (sb-alien:array (* sockint::addrinfo) 1)))
99     (let* ((res (sb-alien:addr (sb-alien:deref buf 0)))
100            (err (sockint::getaddrinfo node nil nil res)))
101       (if (zerop err)
102           (let ((host-ent (make-instance 'host-ent
103                                          :name node
104                                          :type sockint::af-inet
105                                          :aliases nil
106                                          :addresses nil)))
107             (loop for sap = (sb-alien:deref res) then (sockint::addrinfo-next info)
108                   until (sb-alien::null-alien sap)
109                   for info = (sb-alien:cast sap (* sockint::addrinfo))
110                   ;; Only handle AF_INET currently.
111                   do (when (eq (sockint::addrinfo-family info) sockint::af-inet)
112                        (let* ((sockaddr (sockint::addrinfo-addr info))
113                               (address (sockint::sockaddr-in-addr sockaddr)))
114                          ;; The same effective result can be multiple time
115                          ;; in the list, with different socktypes. Only record
116                          ;; each address once.
117                          (setf (slot-value host-ent 'addresses)
118                                (adjoin (naturalize-unsigned-byte-8-array address
119                                                                          4)
120                                        (host-ent-addresses host-ent)
121                                        :test 'equalp)))))
122             (sockint::freeaddrinfo (sb-alien:deref res))
123             host-ent)
124           (addrinfo-error "getaddrinfo" err)))))
125
126 (defconstant ni-max-host 1025)
127
128 #+sb-bsd-sockets-addrinfo
129 (defun get-name-info (address)
130   (assert (= (length address) 4))
131   (sockint::with-sockaddr-in sockaddr ()
132     (sb-alien:with-alien ((host-buf (array char #.ni-max-host)))
133       #+darwin (setf (sockint::sockaddr-in-len sockaddr) 16)
134       (setf (sockint::sockaddr-in-family sockaddr) sockint::af-inet)
135       (dotimes (i 4)
136         (setf (sb-alien:deref (sockint::sockaddr-in-addr sockaddr) i)
137               (aref address i)))
138       (let ((err (sockint::getnameinfo (sb-alien:alien-sap sockaddr)
139                                        (sb-alien:alien-size sockint::sockaddr-in :bytes)
140                                        (sb-alien:cast host-buf (* char)) ni-max-host
141                                        nil 0
142                                        sockint::ni-namereqd)))
143         (if (zerop err)
144             (make-instance 'host-ent
145                            :name (sb-alien::c-string-to-string
146                                   (sb-alien:alien-sap host-buf)
147                                   (sb-impl::default-external-format)
148                                   'character)
149                            :type sockint::af-inet
150                            :aliases nil
151                            :addresses (list address))
152             (addrinfo-error "getnameinfo" err))))))
153
154 ;;; Error handling
155
156 (defvar *name-service-errno* 0
157   "The value of h_errno, after it's been fetched from Unix-land by calling
158 GET-NAME-SERVICE-ERRNO")
159
160 (defun name-service-error (where &optional errno)
161   ;; There was a dummy docstring here for the texinfo extractor, but I
162   ;; see no reason for this to be documented in the manual, and removed
163   ;; it. -- JES
164   (let ((*name-service-errno* (get-name-service-errno errno)))
165     ;; Comment next to NETDB_INTERNAL in netdb.h says "See errno.".
166     ;; This special case treatment hasn't actually been tested yet.
167     (if (and #-win32 (= *name-service-errno* sockint::NETDB-INTERNAL))
168         (socket-error where)
169         (let ((condition
170                (condition-for-name-service-errno *name-service-errno*)))
171           (error condition :errno *name-service-errno* :syscall where)))))
172
173 (defun addrinfo-error (where error-code)
174   (let ((condition (condition-for-name-service-error-code error-code)))
175     (error condition :error-code error-code :syscall where)))
176
177 (define-condition name-service-error (error)
178   ((errno :initform nil :initarg :errno :reader name-service-error-errno)
179    (error-code :initform nil :initarg :error-code
180                :reader name-service-error-error-code)
181    (symbol :initform nil :initarg :symbol :reader name-service-error-symbol)
182    (syscall :initform "an unknown location" :initarg :syscall :reader name-service-error-syscall))
183   (:report (lambda (c s)
184              (let* ((errno (name-service-error-errno c))
185                     (error-code (name-service-error-error-code c)))
186                (format s "Name service error in \"~A\": ~A (~A)"
187                        (name-service-error-syscall c)
188                        (or (name-service-error-symbol c)
189                            errno
190                            error-code)
191                        (get-name-service-error-message errno error-code))))))
192
193 (defparameter *conditions-for-name-service-errno* nil)
194 ;; getaddrinfo and getnameinfo return an error code, rather than using
195 ;; h_errno.  While on Linux there's no overlap between their possible
196 ;; values, this doesn't seem to be guaranteed on all systems.
197 (defparameter *conditions-for-name-service-error-code* nil)
198
199 ;; Define a special name-service-error for variour error cases, and associate
200 ;; them with the matching h_errno / error code.
201 (defmacro define-name-service-condition (errno-symbol error-code-symbol name)
202   `(progn
203      (define-condition ,name (name-service-error)
204        ((errno-symbol :reader name-service-error-errno-symbol
205                       :initform (quote ,errno-symbol))
206         (error-code-symbol :reader name-service-error-error-code-symbol
207                            :initform (quote ,error-code-symbol))))
208      (push (cons ,errno-symbol (quote ,name))
209            *conditions-for-name-service-errno*)
210      #+sb-bsd-sockets-addrinfo
211      (push (cons ,error-code-symbol (quote ,name))
212            *conditions-for-name-service-error-code*)))
213
214 #-win32
215 (define-name-service-condition
216     sockint::NETDB-INTERNAL
217     nil ;; Doesn't map directly to any getaddrinfo error code
218     netdb-internal-error)
219 #-win32
220 (define-name-service-condition
221     sockint::NETDB-SUCCESS
222     nil ;; Doesn't map directly to any getaddrinfo error code
223     netdb-success-error)
224 (define-name-service-condition
225     sockint::HOST-NOT-FOUND
226     sockint::EAI-NONAME
227     host-not-found-error)
228 (define-name-service-condition
229     sockint::TRY-AGAIN
230     sockint::EAI-AGAIN
231     try-again-error)
232 (define-name-service-condition
233     sockint::NO-RECOVERY
234     sockint::EAI-FAIL
235     no-recovery-error)
236 (define-name-service-condition
237     ;; Also defined as NO-DATA, with the same value
238     sockint::NO-ADDRESS
239     ;; getaddrinfo() as of RFC 3493 can no longer distinguish between
240     ;; host no found and address not found
241     nil
242     no-address-error)
243
244 (defun condition-for-name-service-errno (err)
245   (or (cdr (assoc err *conditions-for-name-service-errno* :test #'eql))
246       'name-service-error))
247
248 (defun condition-for-name-service-error-code (err)
249   (or (cdr (assoc err *conditions-for-name-service-error-code* :test #'eql))
250       'name-service-error))
251
252 (defun get-name-service-errno (&optional errno)
253   (setf *name-service-errno*
254         (or errno
255             (sb-alien:alien-funcall
256              #-win32
257              (sb-alien:extern-alien "get_h_errno" (function integer))
258              #+win32
259              (sb-alien:extern-alien "WSAGetLastError" (function integer))))))
260
261 (defun get-name-service-error-message (errno error-code)
262   #-win32
263   (if errno
264       (sockint::h-strerror errno)
265       (sockint::gai-strerror error-code)))