1 (in-package "SB-BSD-SOCKETS")
3 ;;;; Methods, classes, functions for sockets. Protocol-specific stuff
4 ;;;; is deferred to inet.lisp, unix.lisp, etc
6 (eval-when (:load-toplevel :compile-toplevel :execute)
9 ((file-descriptor :initarg :descriptor
10 :reader socket-file-descriptor)
11 (family :initform (error "No socket family")
12 :reader socket-family)
13 (protocol :initarg :protocol
14 :reader socket-protocol
15 :documentation "Protocol used by the socket. If a
16 keyword, the symbol-name of the keyword will be passed to
17 GET-PROTOCOL-BY-NAME downcased, and the returned value used as
18 protocol. Other values are used as-is.")
21 :documentation "Type of the socket: :STREAM or :DATAGRAM.")
23 (:documentation "Common base class of all sockets, not meant to be
24 directly instantiated.")))
26 (defmethod print-object ((object socket) stream)
27 (print-unreadable-object (object stream :type t :identity t)
28 (format stream "~@[~A, ~]~@[peer: ~A, ~]fd: ~A"
29 (socket-namestring object)
30 (socket-peerstring object)
31 (slot-value object 'file-descriptor))))
33 (defgeneric socket-namestring (socket))
35 (defmethod socket-namestring (socket)
38 (defgeneric socket-peerstring (socket))
40 (defmethod socket-peerstring (socket)
43 (defmethod shared-initialize :after ((socket socket) slot-names
47 (cond ((and protocol (keywordp protocol))
48 (get-protocol-by-name (string-downcase (symbol-name protocol))))
51 (fd (or (and (slot-boundp socket 'file-descriptor)
52 (socket-file-descriptor socket))
53 (sockint::socket (socket-family socket)
55 ((:datagram) sockint::sock-dgram)
56 ((:stream) sockint::sock-stream))
58 (if (= fd -1) (socket-error "socket"))
59 (setf (slot-value socket 'file-descriptor) fd
60 (slot-value socket 'protocol) proto-num
61 (slot-value socket 'type) type)
62 (sb-ext:finalize socket (lambda () (sockint::close fd)))))
66 (defgeneric make-sockaddr-for (socket &optional sockaddr &rest address)
67 (:documentation "Return a Socket Address object suitable for use with SOCKET.
68 When SOCKADDR is passed, it is used instead of a new object."))
70 (defgeneric free-sockaddr-for (socket sockaddr)
71 (:documentation "Deallocate a Socket Address object that was
72 created for SOCKET."))
74 (defmacro with-sockaddr-for ((socket sockaddr &optional sockaddr-args) &body body)
75 `(let ((,sockaddr (apply #'make-sockaddr-for ,socket nil ,sockaddr-args)))
76 (unwind-protect (progn ,@body)
77 (free-sockaddr-for ,socket ,sockaddr))))
79 ;; we deliberately redesign the "bind" interface: instead of passing a
80 ;; sockaddr_something as second arg, we pass the elements of one as
81 ;; multiple arguments.
83 (defgeneric socket-bind (socket &rest address)
84 (:documentation "Bind SOCKET to ADDRESS, which may vary according to
85 socket family. For the INET family, pass ADDRESS and PORT as two
86 arguments; for FILE address family sockets, pass the filename string.
89 (defmethod socket-bind ((socket socket)
91 (with-sockaddr-for (socket sockaddr address)
92 (if (= (sockint::bind (socket-file-descriptor socket)
94 (size-of-sockaddr socket))
96 (socket-error "bind"))))
99 (defgeneric socket-accept (socket)
100 (:documentation "Perform the accept(2) call, returning a
101 newly-created connected socket and the peer address as multiple
104 (defmethod socket-accept ((socket socket))
105 (with-sockaddr-for (socket sockaddr)
106 (let ((fd (sockint::accept (socket-file-descriptor socket)
108 (size-of-sockaddr socket))))
111 (member (sb-unix::get-errno)
112 (list sockint::EAGAIN sockint::EINTR)))
114 ((= fd -1) (socket-error "accept"))
116 (let ((s (make-instance (class-of socket)
117 :type (socket-type socket)
118 :protocol (socket-protocol socket)
120 (sb-ext:finalize s (lambda () (sockint::close fd))))
121 (multiple-value-list (bits-of-sockaddr socket sockaddr))))))))
123 (defgeneric socket-connect (socket &rest address)
124 (:documentation "Perform the connect(2) call to connect SOCKET to a
125 remote PEER. No useful return value."))
127 (defmethod socket-connect ((socket socket) &rest peer)
128 (with-sockaddr-for (socket sockaddr peer)
129 (if (= (sockint::connect (socket-file-descriptor socket)
131 (size-of-sockaddr socket))
133 (socket-error "connect"))))
135 (defgeneric socket-peername (socket)
136 (:documentation "Return the socket's peer; depending on the address
137 family this may return multiple values"))
139 (defmethod socket-peername ((socket socket))
140 (with-sockaddr-for (socket sockaddr)
141 (when (= (sockint::getpeername (socket-file-descriptor socket)
143 (size-of-sockaddr socket))
145 (socket-error "getpeername"))
146 (bits-of-sockaddr socket sockaddr)))
148 (defgeneric socket-name (socket)
149 (:documentation "Return the address (as vector of bytes) and port
150 that the socket is bound to, as multiple values."))
152 (defmethod socket-name ((socket socket))
153 (with-sockaddr-for (socket sockaddr)
154 (when (= (sockint::getsockname (socket-file-descriptor socket)
156 (size-of-sockaddr socket))
158 (socket-error "getsockname"))
159 (bits-of-sockaddr socket sockaddr)))
162 ;;; There are a whole bunch of interesting things you can do with a
163 ;;; socket that don't really map onto "do stream io", especially in
164 ;;; CL which has no portable concept of a "short read". socket-receive
165 ;;; allows us to read from an unconnected socket into a buffer, and
166 ;;; to learn who the sender of the packet was
168 (defgeneric socket-receive (socket buffer length
170 oob peek waitall dontwait element-type)
172 "Read LENGTH octets from SOCKET into BUFFER (or a freshly-consed
173 buffer if NIL), using recvfrom(2). If LENGTH is NIL, the length of
174 BUFFER is used, so at least one of these two arguments must be
175 non-NIL. If BUFFER is supplied, it had better be of an element type
176 one octet wide. Returns the buffer, its length, and the address of the
177 peer that sent it, as multiple values. On datagram sockets, sets
178 MSG_TRUNC so that the actual packet length is returned even if the
179 buffer was too small."))
181 (defmethod socket-receive ((socket socket) buffer length
183 oob peek waitall dontwait
184 (element-type 'character))
185 (with-sockaddr-for (socket sockaddr)
187 (logior (if oob sockint::MSG-OOB 0)
188 (if peek sockint::MSG-PEEK 0)
189 (if waitall sockint::MSG-WAITALL 0)
190 (if dontwait sockint::MSG-DONTWAIT 0)
191 #+linux sockint::MSG-NOSIGNAL ;don't send us SIGPIPE
192 (if (eql (socket-type socket) :datagram)
193 sockint::msg-TRUNC 0))))
194 (unless (or buffer length)
195 (error "Must supply at least one of BUFFER or LENGTH"))
197 (setf length (length buffer)))
198 (when buffer (setf element-type (array-element-type buffer)))
199 (unless (or (subtypep element-type 'character)
200 (subtypep element-type 'integer))
201 (error "Buffer element-type must be either a character or an integer subtype."))
203 (setf buffer (make-array length :element-type element-type)))
204 ;; really big FIXME: This whole copy-buffer thing is broken.
205 ;; doesn't support characters more than 8 bits wide, or integer
206 ;; types that aren't (unsigned-byte 8).
207 (let ((copy-buffer (sb-alien:make-alien (array (sb-alien:unsigned 8) 1) length)))
209 (sb-alien:with-alien ((sa-len sockint::socklen-t (size-of-sockaddr socket)))
211 (sockint::recvfrom (socket-file-descriptor socket)
216 (sb-alien:addr sa-len))))
219 (member (sb-unix::get-errno)
220 (list sockint::EAGAIN sockint::EINTR)))
222 ((= len -1) (socket-error "recvfrom"))
223 (t (loop for i from 0 below len
224 do (setf (elt buffer i)
226 ((or (eql element-type 'character) (eql element-type 'base-char))
227 (code-char (sb-alien:deref (sb-alien:deref copy-buffer) i)))
228 (t (sb-alien:deref (sb-alien:deref copy-buffer) i)))))
229 (apply #'values buffer len (multiple-value-list
230 (bits-of-sockaddr socket sockaddr)))))))
231 (sb-alien:free-alien copy-buffer))))))
233 (defmacro with-vector-sap ((name vector) &body body)
234 `(sb-sys:with-pinned-objects (,vector)
235 (let ((,name (sb-sys:vector-sap ,vector)))
238 (defgeneric socket-send (socket buffer length
242 oob eor dontroute dontwait nosignal
243 #+linux confirm #+linux more)
245 "Send LENGTH octets from BUFFER into SOCKET, using sendto(2). If BUFFER
246 is a string, it will converted to octets according to EXTERNAL-FORMAT. If
247 LENGTH is NIL, the length of the octet buffer is used. The format of ADDRESS
248 depends on the socket type (for example for INET domain sockets it would
249 be a list of an IP address and a port). If no socket address is provided,
250 send(2) will be called instead. Returns the number of octets written."))
252 (defmethod socket-send ((socket socket) buffer length
255 (external-format :default)
256 oob eor dontroute dontwait nosignal
257 #+linux confirm #+linux more)
259 (logior (if oob sockint::MSG-OOB 0)
260 (if eor sockint::MSG-EOR 0)
261 (if dontroute sockint::MSG-DONTROUTE 0)
262 (if dontwait sockint::MSG-DONTWAIT 0)
263 #-darwin (if nosignal sockint::MSG-NOSIGNAL 0)
264 #+linux (if confirm sockint::MSG-CONFIRM 0)
265 #+linux (if more sockint::MSG-MORE 0)))
266 (buffer (etypecase buffer
268 (sb-ext:string-to-octets buffer
269 :external-format external-format
270 :null-terminate nil))
271 ((simple-array (unsigned-byte 8))
273 ((array (unsigned-byte 8))
274 (make-array (length buffer)
275 :element-type '(unsigned-byte 8)
276 :initial-contents buffer))))
277 (len (with-vector-sap (buffer-sap buffer)
279 (setf length (length buffer)))
281 (with-sockaddr-for (socket sockaddr address)
282 (sb-alien:with-alien ((sa-len sockint::socklen-t
283 (size-of-sockaddr socket)))
284 (sockint::sendto (socket-file-descriptor socket)
290 (sockint::send (socket-file-descriptor socket)
296 (member (sb-unix::get-errno)
297 (list sockint::EAGAIN sockint::EINTR)))
300 (socket-error "sendto"))
303 (defgeneric socket-listen (socket backlog)
304 (:documentation "Mark SOCKET as willing to accept incoming connections. BACKLOG
305 defines the maximum length that the queue of pending connections may
306 grow to before new connection attempts are refused. See also listen(2)"))
308 (defmethod socket-listen ((socket socket) backlog)
309 (let ((r (sockint::listen (socket-file-descriptor socket) backlog)))
311 (socket-error "listen"))))
313 (defgeneric socket-open-p (socket)
314 (:documentation "Return true if SOCKET is open; otherwise, return false.")
315 (:method ((socket t)) (error 'type-error
316 :datum socket :expected-type 'socket)))
318 (defmethod socket-open-p ((socket socket))
319 (if (slot-boundp socket 'stream)
320 (open-stream-p (slot-value socket 'stream))
321 (/= -1 (socket-file-descriptor socket))))
323 (defgeneric socket-close (socket &key abort)
325 "Close SOCKET, unless it was already closed.
327 If SOCKET-MAKE-STREAM has been called, calls CLOSE using ABORT on that stream.
328 Otherwise closes the socket file descriptor using close(2)."))
330 (defmethod socket-close ((socket socket) &key abort)
331 ;; the close(2) manual page has all kinds of warning about not
332 ;; checking the return value of close, on the grounds that an
333 ;; earlier write(2) might have returned successfully w/o actually
334 ;; writing the stuff to disk. It then goes on to define the only
335 ;; possible error return as EBADF (fd isn't a valid open file
336 ;; descriptor). Presumably this is an oversight and we could also
337 ;; get anything that write(2) would have given us.
339 ;; note that if you have a socket _and_ a stream on the same fd,
340 ;; the socket will avoid doing anything to close the fd in case
341 ;; the stream has done it already - if so, it may have been
342 ;; reassigned to some other file, and closing it would be bad
343 (let ((fd (socket-file-descriptor socket)))
344 (flet ((drop-it (&optional streamp)
345 (setf (slot-value socket 'file-descriptor) -1)
347 (slot-makunbound socket 'stream)
348 (sb-ext:cancel-finalization socket))
353 ((slot-boundp socket 'stream)
354 (close (slot-value socket 'stream) :abort abort)
355 ;; Don't do this if there was an error from CLOSE -- the stream is
360 (when (minusp (sockint::close fd))
361 (socket-error "close"))
362 (bad-file-descriptor-error ()
368 (defgeneric socket-make-stream (socket &key input output
369 element-type external-format
372 (:documentation "Find or create a STREAM that can be used for IO on
373 SOCKET \(which must be connected\). Specify whether the stream is for
374 INPUT, OUTPUT, or both \(it is an error to specify neither\). ELEMENT-TYPE
375 and EXTERNAL-FORMAT are as per OPEN. TIMEOUT specifies a read timeout
378 (defmethod socket-make-stream ((socket socket)
380 (element-type 'character)
382 (external-format :default)
385 "Default method for SOCKET objects. An ELEMENT-TYPE of :DEFAULT will
386 construct a bivalent stream. Acceptable values for BUFFERING are :FULL, :LINE
387 and :NONE. Streams will have no TIMEOUT by default. If AUTO-CLOSE is true, the
388 underlying OS socket is automatically closed after the stream and the socket
389 have been garbage collected.
391 The stream for SOCKET will be cached, and a second invocation of this method
392 will return the same stream. This may lead to oddities if this function is
393 invoked with inconsistent arguments \(e.g., one might request an input stream
394 and get an output stream in response\)."
396 (and (slot-boundp socket 'stream) (slot-value socket 'stream))))
398 (setf stream (sb-sys:make-fd-stream
399 (socket-file-descriptor socket)
400 :name (format nil "socket~@[ ~A~]~@[, peer: ~A~]"
401 (socket-namestring socket)
402 (socket-peerstring socket))
406 :element-type element-type
408 :external-format external-format
410 :auto-close auto-close)))
411 (setf (slot-value socket 'stream) stream)
412 (sb-ext:cancel-finalization socket)
419 (define-condition socket-error (error)
420 ((errno :initform nil
422 :reader socket-error-errno)
423 (symbol :initform nil :initarg :symbol :reader socket-error-symbol)
424 (syscall :initform "outer space" :initarg :syscall :reader socket-error-syscall))
425 (:report (lambda (c s)
426 (let ((num (socket-error-errno c)))
427 (format s "Socket error in \"~A\": ~A (~A)"
428 (socket-error-syscall c)
429 (or (socket-error-symbol c) (socket-error-errno c))
430 #+cmu (sb-unix:get-unix-error-msg num)
431 #+sbcl (sb-int:strerror num)))))
432 (:documentation "Common base class of socket related conditions."))
434 ;;; watch out for slightly hacky symbol punning: we use both the value
435 ;;; and the symbol-name of sockint::efoo
437 (defmacro define-socket-condition (symbol name)
439 (define-condition ,name (socket-error)
440 ((symbol :reader socket-error-symbol :initform (quote ,symbol))))
442 (push (cons ,symbol (quote ,name)) *conditions-for-errno*)))
444 (defparameter *conditions-for-errno* nil)
445 ;;; this needs the rest of the list adding to it, really. They also
446 ;;; need symbols to be added to constants.ccon
447 ;;; I haven't yet thought of a non-kludgey way of keeping all this in
449 (define-socket-condition sockint::EADDRINUSE address-in-use-error)
450 (define-socket-condition sockint::EAGAIN interrupted-error)
451 (define-socket-condition sockint::EBADF bad-file-descriptor-error)
452 (define-socket-condition sockint::ECONNREFUSED connection-refused-error)
453 (define-socket-condition sockint::ETIMEDOUT operation-timeout-error)
454 (define-socket-condition sockint::EINTR interrupted-error)
455 (define-socket-condition sockint::EINVAL invalid-argument-error)
456 (define-socket-condition sockint::ENOBUFS no-buffers-error)
457 (define-socket-condition sockint::ENOMEM out-of-memory-error)
458 (define-socket-condition sockint::EOPNOTSUPP operation-not-supported-error)
459 (define-socket-condition sockint::EPERM operation-not-permitted-error)
460 (define-socket-condition sockint::EPROTONOSUPPORT protocol-not-supported-error)
461 (define-socket-condition sockint::ESOCKTNOSUPPORT socket-type-not-supported-error)
462 (define-socket-condition sockint::ENETUNREACH network-unreachable-error)
463 (define-socket-condition sockint::ENOTCONN not-connected-error)
465 (defun condition-for-errno (err)
466 (or (cdr (assoc err *conditions-for-errno* :test #'eql)) 'socket-error))
469 (defun socket-error (where)
470 ;; Peter's debian/x86 cmucl packages (and sbcl, derived from them)
471 ;; use a direct syscall interface, and have to call UNIX-GET-ERRNO
472 ;; to update the value that unix-errno looks at. On other CMUCL
473 ;; ports, (UNIX-GET-ERRNO) is not needed and doesn't exist
474 (when (fboundp 'unix::unix-get-errno) (unix::unix-get-errno))
475 (let ((condition (condition-for-errno sb-unix:unix-errno)))
476 (error condition :errno sb-unix:unix-errno :syscall where)))
479 (defun socket-error (where)
480 ;; FIXME: Our Texinfo documentation extracter need at least his to spit
481 ;; out the signature. Real documentation would be better...
483 (let* ((errno (sb-unix::get-errno))
484 (condition (condition-for-errno errno)))
485 (error condition :errno errno :syscall where)))
488 (defgeneric bits-of-sockaddr (socket sockaddr)
489 (:documentation "Return protocol-dependent bits of parameter
490 SOCKADDR, e.g. the Host/Port if SOCKET is an inet socket."))
492 (defgeneric size-of-sockaddr (socket)
493 (:documentation "Return the size of a sockaddr object for SOCKET."))