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