0.8.12.51:
[sbcl.git] / contrib / sb-bsd-sockets / sockets.lisp
1 (in-package "SB-BSD-SOCKETS")
2
3 ;;;; Methods, classes, functions for sockets.  Protocol-specific stuff
4 ;;;; is deferred to inet.lisp, unix.lisp, etc
5
6 #|| <h2>SOCKETs</h2>
7
8 |#
9
10 (eval-when (:load-toplevel :compile-toplevel :execute)
11 (defclass socket ()
12   ((file-descriptor :initarg :descriptor
13                     :reader socket-file-descriptor)
14    (family :initform (error "No socket family") :reader socket-family)
15    (protocol :initarg :protocol :reader socket-protocol)
16    (type  :initarg :type :reader socket-type)
17    (stream))))
18   
19 (defmethod print-object ((object socket) stream)
20   (print-unreadable-object (object stream :type t :identity t)
21                            (princ "descriptor " stream)
22                            (princ (slot-value object 'file-descriptor) stream)))
23
24
25 (defmethod shared-initialize :after ((socket socket) slot-names
26                                      &key protocol type
27                                      &allow-other-keys)
28   (let* ((proto-num
29           (cond ((and protocol (keywordp protocol))
30                  (get-protocol-by-name (string-downcase (symbol-name protocol))))
31                 (protocol protocol)
32                 (t 0)))
33          (fd (or (and (slot-boundp socket 'file-descriptor)
34                       (socket-file-descriptor socket))
35                  (sockint::socket (socket-family socket)
36                                   (ecase type
37                                     ((:datagram) sockint::sock-dgram)
38                                     ((:stream) sockint::sock-stream))
39                                   proto-num))))
40       (if (= fd -1) (socket-error "socket"))
41       (setf (slot-value socket 'file-descriptor) fd
42             (slot-value socket 'protocol) proto-num
43             (slot-value socket 'type) type)
44       (sb-ext:finalize socket (lambda () (sockint::close fd)))))
45
46 \f
47
48 (defgeneric make-sockaddr-for (socket &optional sockaddr &rest address)
49   (:documentation "Return a Socket Address object suitable for use with SOCKET.
50 When SOCKADDR is passed, it is used instead of a new object."))
51
52 (defgeneric free-sockaddr-for (socket sockaddr)
53   (:documentation "Deallocate a Socket Address object that was
54 created for SOCKET."))
55
56 (defmacro with-sockaddr-for ((socket sockaddr &optional sockaddr-args) &body body)
57   `(let ((,sockaddr (apply #'make-sockaddr-for ,socket nil ,sockaddr-args)))
58      (unwind-protect (progn ,@body)
59        (free-sockaddr-for ,socket ,sockaddr))))
60
61 ;; we deliberately redesign the "bind" interface: instead of passing a
62 ;; sockaddr_something as second arg, we pass the elements of one as
63 ;; multiple arguments.
64
65 (defgeneric socket-bind (socket &rest address)
66   (:documentation "Bind SOCKET to ADDRESS, which may vary according to
67 socket family.  For the INET family, pass ADDRESS and PORT as two
68 arguments; for FILE address family sockets, pass the filename string.
69 See also bind(2)"))
70
71 (defmethod socket-bind ((socket socket)
72                         &rest address)
73   (with-sockaddr-for (socket sockaddr address)
74     (if (= (sockint::bind (socket-file-descriptor socket)
75                           sockaddr
76                           (size-of-sockaddr socket))
77            -1)
78         (socket-error "bind"))))
79
80 \f
81 (defgeneric socket-accept (socket)
82   (:documentation "Perform the accept(2) call, returning a
83 newly-created connected socket and the peer address as multiple
84 values"))
85   
86 (defmethod socket-accept ((socket socket))
87   (with-sockaddr-for (socket sockaddr)
88     (let ((fd (sockint::accept (socket-file-descriptor socket)
89                                sockaddr
90                                (size-of-sockaddr socket))))
91       (cond
92         ((and (= fd -1) (= sockint::EAGAIN (sb-unix::get-errno)))
93          nil)
94         ((= fd -1) (socket-error "accept"))
95         (t (apply #'values
96                   (let ((s (make-instance (class-of socket)
97                               :type (socket-type socket)
98                               :protocol (socket-protocol socket)
99                               :descriptor fd)))
100                     (sb-ext:finalize s (lambda () (sockint::close fd))))
101                   (multiple-value-list (bits-of-sockaddr socket sockaddr))))))))
102     
103 (defgeneric socket-connect (socket &rest address)
104   (:documentation "Perform the connect(2) call to connect SOCKET to a
105   remote PEER.  No useful return value."))
106
107 (defmethod socket-connect ((socket socket) &rest peer)
108   (with-sockaddr-for (socket sockaddr peer)
109     (if (= (sockint::connect (socket-file-descriptor socket)
110                              sockaddr
111                              (size-of-sockaddr socket))
112            -1)
113         (socket-error "connect"))))
114
115 (defgeneric socket-peername (socket)
116   (:documentation "Return the socket's peer; depending on the address
117   family this may return multiple values"))
118   
119 (defmethod socket-peername ((socket socket))
120   (with-sockaddr-for (socket sockaddr)
121     (when (= (sockint::getpeername (socket-file-descriptor socket)
122                                     sockaddr
123                                     (size-of-sockaddr socket))
124              -1)
125       (socket-error "getpeername"))
126     (bits-of-sockaddr socket sockaddr)))
127
128 (defgeneric socket-name (socket)
129   (:documentation "Return the address (as vector of bytes) and port
130   that the socket is bound to, as multiple values."))
131
132 (defmethod socket-name ((socket socket))
133   (with-sockaddr-for (socket sockaddr)
134     (when (= (sockint::getsockname (socket-file-descriptor socket)
135                                    sockaddr
136                                    (size-of-sockaddr socket))
137              -1)
138       (socket-error "getsockname"))
139     (bits-of-sockaddr socket sockaddr)))
140
141
142 ;;; There are a whole bunch of interesting things you can do with a
143 ;;; socket that don't really map onto "do stream io", especially in
144 ;;; CL which has no portable concept of a "short read".  socket-receive
145 ;;; allows us to read from an unconnected socket into a buffer, and
146 ;;; to learn who the sender of the packet was
147
148 (defgeneric socket-receive (socket buffer length
149                             &key
150                             oob peek waitall element-type)
151   (:documentation "Read LENGTH octets from SOCKET into BUFFER (or a freshly-consed buffer if
152 NIL), using recvfrom(2).  If LENGTH is NIL, the length of BUFFER is
153 used, so at least one of these two arguments must be non-NIL.  If
154 BUFFER is supplied, it had better be of an element type one octet wide.
155 Returns the buffer, its length, and the address of the peer
156 that sent it, as multiple values.  On datagram sockets, sets MSG_TRUNC
157 so that the actual packet length is returned even if the buffer was too
158 small"))
159   
160 (defmethod socket-receive ((socket socket) buffer length
161                            &key
162                            oob peek waitall
163                            (element-type 'character))
164   (with-sockaddr-for (socket sockaddr)
165     (let ((flags
166            (logior (if oob sockint::MSG-OOB 0)
167                    (if peek sockint::MSG-PEEK 0)
168                    (if waitall sockint::MSG-WAITALL 0)
169                    #+linux sockint::MSG-NOSIGNAL ;don't send us SIGPIPE
170                    (if (eql (socket-type socket) :datagram)
171                        sockint::msg-TRUNC 0))))
172       (unless (or buffer length)
173         (error "Must supply at least one of BUFFER or LENGTH"))
174       (unless length
175         (setf length (length buffer)))
176       (unless buffer
177         (setf buffer (make-array length :element-type element-type)))
178       (let ((copy-buffer (sb-alien:make-alien (array sb-alien:unsigned 1) length)))
179         (unwind-protect
180             (sb-alien:with-alien ((sa-len (array (sb-alien:unsigned 32) 2)))
181               (setf (sb-alien:deref sa-len 0) (size-of-sockaddr socket))
182               (let ((len
183                      (sockint::recvfrom (socket-file-descriptor socket)
184                                         copy-buffer
185                                         length
186                                         flags
187                                         sockaddr
188                                         (sb-alien:cast sa-len (* integer)))))
189                 (cond
190                   ((and (= len -1) (= sockint::EAGAIN (sb-unix::get-errno))) nil)
191                   ((= len -1) (socket-error "recvfrom"))
192                   (t (loop for i from 0 below len
193                            do (setf (elt buffer i) (sb-alien:deref copy-buffer i)))
194                      (apply #'values buffer len (multiple-value-list
195                                                  (bits-of-sockaddr socket sockaddr)))))))
196           (sb-alien:free-alien copy-buffer))))))
197
198
199
200 (defgeneric socket-listen (socket backlog)
201   (:documentation "Mark SOCKET as willing to accept incoming connections.  BACKLOG
202 defines the maximum length that the queue of pending connections may
203 grow to before new connection attempts are refused.  See also listen(2)"))
204
205 (defmethod socket-listen ((socket socket) backlog)
206   (let ((r (sockint::listen (socket-file-descriptor socket) backlog)))
207     (if (= r -1)
208         (socket-error "listen"))))
209
210 (defgeneric socket-close (socket)
211   (:documentation "Close SOCKET.  May throw any kind of error that write(2) would have
212 thrown.  If SOCKET-MAKE-STREAM has been called, calls CLOSE on that
213 stream instead"))
214
215 (defmethod socket-close ((socket socket))
216   ;; the close(2) manual page has all kinds of warning about not
217   ;; checking the return value of close, on the grounds that an
218   ;; earlier write(2) might have returned successfully w/o actually
219   ;; writing the stuff to disk.  It then goes on to define the only
220   ;; possible error return as EBADF (fd isn't a valid open file
221   ;; descriptor).  Presumably this is an oversight and we could also
222   ;; get anything that write(2) would have given us.
223
224   ;; note that if you have a socket _and_ a stream on the same fd, 
225   ;; the socket will avoid doing anything to close the fd in case
226   ;; the stream has done it already - if so, it may have been
227   ;; reassigned to some other file, and closing it would be bad
228
229   (let ((fd (socket-file-descriptor socket)))
230     (cond ((eql fd -1) ; already closed
231            nil)
232           ((slot-boundp socket 'stream)
233            (close (slot-value socket 'stream)) ;; closes fd
234            (setf (slot-value socket 'file-descriptor) -1)
235            (slot-makunbound socket 'stream))
236           (t
237            (sb-ext:cancel-finalization socket)
238            (handler-case
239                (if (= (sockint::close fd) -1)
240                    (socket-error "close"))
241              (bad-file-descriptor-error (c) (declare (ignore c)) nil)
242              (:no-error (c)  (declare (ignore c)) nil))))))
243
244     
245 (defgeneric socket-make-stream (socket  &rest args)
246     (:documentation "Find or create a STREAM that can be used for IO
247 on SOCKET (which must be connected).  ARGS are passed onto
248 SB-SYS:MAKE-FD-STREAM."))
249
250 (defmethod socket-make-stream ((socket socket)  &rest args)
251   (let ((stream
252          (and (slot-boundp socket 'stream) (slot-value socket 'stream))))
253     (unless stream
254       (setf stream (apply #'sb-sys:make-fd-stream
255                           (socket-file-descriptor socket)
256                           :name "a constant string"
257                           args))
258       (setf (slot-value socket 'stream) stream)
259       (sb-ext:cancel-finalization socket))
260     stream))
261
262 \f
263
264 ;;; Error handling
265
266 (define-condition socket-error (error)
267   ((errno :initform nil
268           :initarg :errno  
269           :reader socket-error-errno) 
270    (symbol :initform nil :initarg :symbol :reader socket-error-symbol)
271    (syscall  :initform "outer space" :initarg :syscall :reader socket-error-syscall))
272   (:report (lambda (c s)
273              (let ((num (socket-error-errno c)))
274                (format s "Socket error in \"~A\": ~A (~A)"
275                        (socket-error-syscall c)
276                        (or (socket-error-symbol c) (socket-error-errno c))
277                        #+cmu (sb-unix:get-unix-error-msg num)
278                        #+sbcl (sb-int:strerror num))))))
279
280 ;;; watch out for slightly hacky symbol punning: we use both the value
281 ;;; and the symbol-name of sockint::efoo
282
283 (defmacro define-socket-condition (symbol name)
284   `(progn
285      (define-condition ,name (socket-error)
286        ((symbol :reader socket-error-symbol :initform (quote ,symbol))))
287      (export ',name)
288      (push (cons ,symbol (quote ,name)) *conditions-for-errno*)))
289
290 (defparameter *conditions-for-errno* nil)
291 ;;; this needs the rest of the list adding to it, really.  They also
292 ;;; need symbols to be added to constants.ccon
293 ;;; I haven't yet thought of a non-kludgey way of keeping all this in
294 ;;; the same place
295 (define-socket-condition sockint::EADDRINUSE address-in-use-error)
296 (define-socket-condition sockint::EAGAIN interrupted-error)
297 (define-socket-condition sockint::EBADF bad-file-descriptor-error)
298 (define-socket-condition sockint::ECONNREFUSED connection-refused-error)
299 (define-socket-condition sockint::ETIMEDOUT operation-timeout-error)
300 (define-socket-condition sockint::EINTR interrupted-error)
301 (define-socket-condition sockint::EINVAL invalid-argument-error)
302 (define-socket-condition sockint::ENOBUFS no-buffers-error)
303 (define-socket-condition sockint::ENOMEM out-of-memory-error)
304 (define-socket-condition sockint::EOPNOTSUPP operation-not-supported-error)
305 (define-socket-condition sockint::EPERM operation-not-permitted-error)
306 (define-socket-condition sockint::EPROTONOSUPPORT protocol-not-supported-error)
307 (define-socket-condition sockint::ESOCKTNOSUPPORT socket-type-not-supported-error)
308 (define-socket-condition sockint::ENETUNREACH network-unreachable-error)
309
310
311 (defun condition-for-errno (err)
312   (or (cdr (assoc err *conditions-for-errno* :test #'eql)) 'socket-error))
313       
314 #+cmu
315 (defun socket-error (where)
316   ;; Peter's debian/x86 cmucl packages (and sbcl, derived from them)
317   ;; use a direct syscall interface, and have to call UNIX-GET-ERRNO
318   ;; to update the value that unix-errno looks at.  On other CMUCL
319   ;; ports, (UNIX-GET-ERRNO) is not needed and doesn't exist
320   (when (fboundp 'unix::unix-get-errno) (unix::unix-get-errno))
321   (let ((condition (condition-for-errno sb-unix:unix-errno)))
322     (error condition :errno sb-unix:unix-errno  :syscall where)))
323
324 #+sbcl
325 (defun socket-error (where)
326   (let* ((errno  (sb-unix::get-errno))
327          (condition (condition-for-errno errno)))
328     (error condition :errno errno  :syscall where)))
329
330
331 (defgeneric bits-of-sockaddr (socket sockaddr)
332   (:documentation "Return protocol-dependent bits of parameter
333 SOCKADDR, e.g. the Host/Port if SOCKET is an inet socket."))
334
335 (defgeneric size-of-sockaddr (socket)
336   (:documentation "Return the size of a sockaddr object for SOCKET."))