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 ;;; Winsock is different w.r.t errno
10 (defun socket-errno ()
11 "Get socket error code, usually from errno, but see #+win32."
12 #+win32 (sockint::wsa-get-last-error)
13 #-win32 (sb-unix::get-errno))
16 ((file-descriptor :initarg :descriptor
17 :reader socket-file-descriptor)
18 (family :initform (error "No socket family")
19 :reader socket-family)
20 (protocol :initarg :protocol
21 :reader socket-protocol
22 :documentation "Protocol used by the socket. If a
23 keyword, the symbol-name of the keyword will be passed to
24 GET-PROTOCOL-BY-NAME downcased, and the returned value used as
25 protocol. Other values are used as-is.")
28 :documentation "Type of the socket: :STREAM or :DATAGRAM.")
30 (non-blocking-p :type (member t nil) :initform nil)
32 (:documentation "Common base class of all sockets, not meant to be
33 directly instantiated.")))
35 (defmethod print-object ((object socket) stream)
36 (print-unreadable-object (object stream :type t :identity t)
37 (format stream "~@[~A, ~]~@[peer: ~A, ~]fd: ~A"
38 (socket-namestring object)
39 (socket-peerstring object)
40 (slot-value object 'file-descriptor))))
42 (defgeneric socket-namestring (socket))
44 (defmethod socket-namestring (socket)
47 (defgeneric socket-peerstring (socket))
49 (defmethod socket-peerstring (socket)
52 (defmethod shared-initialize :after ((socket socket) slot-names
56 (cond ((and protocol (keywordp protocol))
57 (get-protocol-by-name (string-downcase (symbol-name protocol))))
60 (fd (or (and (slot-boundp socket 'file-descriptor)
61 (socket-file-descriptor socket))
62 (sockint::socket (socket-family socket)
64 ((:datagram) sockint::sock-dgram)
65 ((:stream) sockint::sock-stream))
67 (if (= fd -1) (socket-error "socket"))
68 (setf (slot-value socket 'file-descriptor) fd
69 (slot-value socket 'protocol) proto-num
70 (slot-value socket 'type) type)
71 (sb-ext:finalize socket (lambda () (sockint::close fd))
76 (defgeneric make-sockaddr-for (socket &optional sockaddr &rest address)
77 (:documentation "Return a Socket Address object suitable for use with SOCKET.
78 When SOCKADDR is passed, it is used instead of a new object."))
80 (defgeneric free-sockaddr-for (socket sockaddr)
81 (:documentation "Deallocate a Socket Address object that was
82 created for SOCKET."))
84 (defmacro with-sockaddr-for ((socket sockaddr &optional sockaddr-args) &body body)
85 `(let ((,sockaddr (apply #'make-sockaddr-for ,socket nil ,sockaddr-args)))
86 (unwind-protect (progn ,@body)
87 (free-sockaddr-for ,socket ,sockaddr))))
89 ;; we deliberately redesign the "bind" interface: instead of passing a
90 ;; sockaddr_something as second arg, we pass the elements of one as
91 ;; multiple arguments.
93 (defgeneric socket-bind (socket &rest address)
94 (:documentation "Bind SOCKET to ADDRESS, which may vary according to
95 socket family. For the INET family, pass ADDRESS and PORT as two
96 arguments; for FILE address family sockets, pass the filename string.
99 (defmethod socket-bind ((socket socket)
101 (with-sockaddr-for (socket sockaddr address)
102 (if (= (sockint::bind (socket-file-descriptor socket)
104 (size-of-sockaddr socket))
106 (socket-error "bind"))))
109 (defgeneric socket-accept (socket)
110 (:documentation "Perform the accept(2) call, returning a
111 newly-created connected socket and the peer address as multiple
114 (defmethod socket-accept ((socket socket))
115 (with-sockaddr-for (socket sockaddr)
116 (let ((fd (sockint::accept (socket-file-descriptor socket)
118 (size-of-sockaddr socket))))
121 (member (socket-errno)
122 (list sockint::EAGAIN sockint::EINTR)))
124 ((= fd -1) (socket-error "accept"))
126 (let ((s (make-instance (class-of socket)
127 :type (socket-type socket)
128 :protocol (socket-protocol socket)
130 (sb-ext:finalize s (lambda () (sockint::close fd))
132 (multiple-value-list (bits-of-sockaddr socket sockaddr))))))))
134 (defgeneric socket-connect (socket &rest address)
135 (:documentation "Perform the connect(2) call to connect SOCKET to a
136 remote PEER. No useful return value."))
138 (defmethod socket-connect ((socket socket) &rest peer)
139 (with-sockaddr-for (socket sockaddr peer)
140 (if (= (sockint::connect (socket-file-descriptor socket)
142 (size-of-sockaddr socket))
144 (socket-error "connect"))))
146 (defgeneric socket-peername (socket)
147 (:documentation "Return the socket's peer; depending on the address
148 family this may return multiple values"))
150 (defmethod socket-peername ((socket socket))
151 (with-sockaddr-for (socket sockaddr)
152 (when (= (sockint::getpeername (socket-file-descriptor socket)
154 (size-of-sockaddr socket))
156 (socket-error "getpeername"))
157 (bits-of-sockaddr socket sockaddr)))
159 (defgeneric socket-name (socket)
160 (:documentation "Return the address (as vector of bytes) and port
161 that the socket is bound to, as multiple values."))
163 (defmethod socket-name ((socket socket))
164 (with-sockaddr-for (socket sockaddr)
165 (when (= (sockint::getsockname (socket-file-descriptor socket)
167 (size-of-sockaddr socket))
169 (socket-error "getsockname"))
170 (bits-of-sockaddr socket sockaddr)))
173 ;;; There are a whole bunch of interesting things you can do with a
174 ;;; socket that don't really map onto "do stream io", especially in
175 ;;; CL which has no portable concept of a "short read". socket-receive
176 ;;; allows us to read from an unconnected socket into a buffer, and
177 ;;; to learn who the sender of the packet was
179 (defgeneric socket-receive (socket buffer length
181 oob peek waitall dontwait element-type)
183 "Read LENGTH octets from SOCKET into BUFFER (or a freshly-consed
184 buffer if NIL), using recvfrom(2). If LENGTH is NIL, the length of
185 BUFFER is used, so at least one of these two arguments must be
186 non-NIL. If BUFFER is supplied, it had better be of an element type
187 one octet wide. Returns the buffer, its length, and the address of the
188 peer that sent it, as multiple values. On datagram sockets, sets
189 MSG_TRUNC so that the actual packet length is returned even if the
190 buffer was too small."))
192 (defmethod socket-receive ((socket socket) buffer length
194 oob peek waitall dontwait
195 (element-type 'character))
196 (with-sockaddr-for (socket sockaddr)
198 (logior (if oob sockint::MSG-OOB 0)
199 (if peek sockint::MSG-PEEK 0)
200 (if waitall sockint::MSG-WAITALL 0)
201 (if dontwait sockint::MSG-DONTWAIT 0)
202 #+linux sockint::MSG-NOSIGNAL ;don't send us SIGPIPE
203 (if (eql (socket-type socket) :datagram)
204 sockint::msg-TRUNC 0))))
205 (unless (or buffer length)
206 (error "Must supply at least one of BUFFER or LENGTH"))
208 (setf length (length buffer)))
209 (when buffer (setf element-type (array-element-type buffer)))
210 (unless (or (subtypep element-type 'character)
211 (subtypep element-type 'integer))
212 (error "Buffer element-type must be either a character or an integer subtype."))
214 (setf buffer (make-array length :element-type element-type)))
215 ;; really big FIXME: This whole copy-buffer thing is broken.
216 ;; doesn't support characters more than 8 bits wide, or integer
217 ;; types that aren't (unsigned-byte 8).
218 (let ((copy-buffer (sb-alien:make-alien (array (sb-alien:unsigned 8) 1) length)))
220 (sb-alien:with-alien ((sa-len sockint::socklen-t (size-of-sockaddr socket)))
222 (sockint::recvfrom (socket-file-descriptor socket)
227 (sb-alien:addr sa-len))))
230 (member (socket-errno)
231 (list sockint::EAGAIN sockint::EINTR)))
233 ((= len -1) (socket-error "recvfrom"))
234 (t (loop for i from 0 below (min len length)
235 do (setf (elt buffer i)
237 ((or (eql element-type 'character) (eql element-type 'base-char))
238 (code-char (sb-alien:deref (sb-alien:deref copy-buffer) i)))
239 (t (sb-alien:deref (sb-alien:deref copy-buffer) i)))))
240 (apply #'values buffer len (multiple-value-list
241 (bits-of-sockaddr socket sockaddr)))))))
242 (sb-alien:free-alien copy-buffer))))))
244 (defmacro with-vector-sap ((name vector) &body body)
245 `(sb-sys:with-pinned-objects (,vector)
246 (let ((,name (sb-sys:vector-sap ,vector)))
249 (defgeneric socket-send (socket buffer length
253 oob eor dontroute dontwait nosignal
254 #+linux confirm #+linux more)
256 "Send LENGTH octets from BUFFER into SOCKET, using sendto(2). If BUFFER
257 is a string, it will converted to octets according to EXTERNAL-FORMAT. If
258 LENGTH is NIL, the length of the octet buffer is used. The format of ADDRESS
259 depends on the socket type (for example for INET domain sockets it would
260 be a list of an IP address and a port). If no socket address is provided,
261 send(2) will be called instead. Returns the number of octets written."))
263 (defmethod socket-send ((socket socket) buffer length
266 (external-format :default)
267 oob eor dontroute dontwait nosignal
268 #+linux confirm #+linux more)
270 (logior (if oob sockint::MSG-OOB 0)
271 (if eor sockint::MSG-EOR 0)
272 (if dontroute sockint::MSG-DONTROUTE 0)
273 (if dontwait sockint::MSG-DONTWAIT 0)
274 #-darwin (if nosignal sockint::MSG-NOSIGNAL 0)
275 #+linux (if confirm sockint::MSG-CONFIRM 0)
276 #+linux (if more sockint::MSG-MORE 0)))
277 (buffer (etypecase buffer
279 (sb-ext:string-to-octets buffer
280 :external-format external-format
281 :null-terminate nil))
282 ((simple-array (unsigned-byte 8))
284 ((array (unsigned-byte 8))
285 (make-array (length buffer)
286 :element-type '(unsigned-byte 8)
287 :initial-contents buffer))))
288 (len (with-vector-sap (buffer-sap buffer)
290 (setf length (length buffer)))
292 (with-sockaddr-for (socket sockaddr address)
293 (sb-alien:with-alien ((sa-len sockint::socklen-t
294 (size-of-sockaddr socket)))
295 (sockint::sendto (socket-file-descriptor socket)
301 (sockint::send (socket-file-descriptor socket)
307 (member (socket-errno)
308 (list sockint::EAGAIN sockint::EINTR)))
311 (socket-error "sendto"))
314 (defgeneric socket-listen (socket backlog)
315 (:documentation "Mark SOCKET as willing to accept incoming connections. BACKLOG
316 defines the maximum length that the queue of pending connections may
317 grow to before new connection attempts are refused. See also listen(2)"))
319 (defmethod socket-listen ((socket socket) backlog)
320 (let ((r (sockint::listen (socket-file-descriptor socket) backlog)))
322 (socket-error "listen"))))
324 (defgeneric socket-open-p (socket)
325 (:documentation "Return true if SOCKET is open; otherwise, return false.")
326 (:method ((socket t)) (error 'type-error
327 :datum socket :expected-type 'socket)))
329 (defmethod socket-open-p ((socket socket))
330 (if (slot-boundp socket 'stream)
331 (open-stream-p (slot-value socket 'stream))
332 (/= -1 (socket-file-descriptor socket))))
334 (defgeneric socket-close (socket &key abort)
336 "Close SOCKET, unless it was already closed.
338 If SOCKET-MAKE-STREAM has been called, calls CLOSE using ABORT on that stream.
339 Otherwise closes the socket file descriptor using close(2)."))
341 (defmethod socket-close ((socket socket) &key abort)
342 ;; the close(2) manual page has all kinds of warning about not
343 ;; checking the return value of close, on the grounds that an
344 ;; earlier write(2) might have returned successfully w/o actually
345 ;; writing the stuff to disk. It then goes on to define the only
346 ;; possible error return as EBADF (fd isn't a valid open file
347 ;; descriptor). Presumably this is an oversight and we could also
348 ;; get anything that write(2) would have given us.
350 ;; note that if you have a socket _and_ a stream on the same fd,
351 ;; the socket will avoid doing anything to close the fd in case
352 ;; the stream has done it already - if so, it may have been
353 ;; reassigned to some other file, and closing it would be bad
354 (let ((fd (socket-file-descriptor socket)))
355 (flet ((drop-it (&optional streamp)
356 (setf (slot-value socket 'file-descriptor) -1)
358 (slot-makunbound socket 'stream)
359 (sb-ext:cancel-finalization socket))
364 ((slot-boundp socket 'stream)
365 (close (slot-value socket 'stream) :abort abort)
366 ;; Don't do this if there was an error from CLOSE -- the stream is
371 (when (minusp (sockint::close fd))
372 (socket-error "close"))
373 (bad-file-descriptor-error ()
379 (defgeneric socket-make-stream (socket &key input output
380 element-type external-format
383 (:documentation "Find or create a STREAM that can be used for IO on
384 SOCKET \(which must be connected\). Specify whether the stream is for
385 INPUT, OUTPUT, or both \(it is an error to specify neither\). ELEMENT-TYPE
386 and EXTERNAL-FORMAT are as per OPEN. TIMEOUT specifies a read timeout
389 (defmethod socket-make-stream ((socket socket)
391 (element-type 'character)
393 (external-format :default)
397 "Default method for SOCKET objects.
399 ELEMENT-TYPE defaults to CHARACTER, to construct a bivalent stream,
400 capable of both binary and character IO use :DEFAULT.
402 Acceptable values for BUFFERING are :FULL, :LINE and :NONE, default
403 is :FULL, ie. output is buffered till it is explicitly flushed using
404 CLOSE or FINISH-OUTPUT. (FORCE-OUTPUT forces some output to be
405 flushed: to ensure all buffered output is flused use FINISH-OUTPUT.)
407 Streams have no TIMEOUT by default. If one is provided, it is the
408 number of seconds the system will at most wait for input to appear on
409 the socket stream when trying to read from it.
411 If AUTO-CLOSE is true, the underlying OS socket is automatically
412 closed after the stream and the socket have been garbage collected.
415 If SERVE-EVENTS is true, blocking IO on the socket will dispatch to
416 the recursive event loop. Default is false.
418 The stream for SOCKET will be cached, and a second invocation of this
419 method will return the same stream. This may lead to oddities if this
420 function is invoked with inconsistent arguments \(e.g., one might
421 request an input stream and get an output stream in response\)."
423 (and (slot-boundp socket 'stream) (slot-value socket 'stream))))
425 (setf stream (sb-sys:make-fd-stream
426 (socket-file-descriptor socket)
427 :name (format nil "socket~@[ ~A~]~@[, peer: ~A~]"
428 (socket-namestring socket)
429 (socket-peerstring socket))
433 :element-type element-type
435 :external-format external-format
437 :auto-close auto-close
438 :serve-events (and serve-events #+win32 nil)))
439 (setf (slot-value socket 'stream) stream))
440 (sb-ext:cancel-finalization socket)
447 (define-condition socket-error (error)
448 ((errno :initform nil
450 :reader socket-error-errno)
451 (symbol :initform nil :initarg :symbol :reader socket-error-symbol)
452 (syscall :initform "outer space" :initarg :syscall :reader socket-error-syscall))
453 (:report (lambda (c s)
454 (let ((num (socket-error-errno c)))
455 (format s "Socket error in \"~A\": ~A (~A)"
456 (socket-error-syscall c)
457 (or (socket-error-symbol c) (socket-error-errno c))
458 #+cmu (sb-unix:get-unix-error-msg num)
460 #+win32 (sb-win32::get-last-error-message num)
461 #-win32 (sb-int:strerror num)))))
462 (:documentation "Common base class of socket related conditions."))
464 ;;; watch out for slightly hacky symbol punning: we use both the value
465 ;;; and the symbol-name of sockint::efoo
467 (defmacro define-socket-condition (symbol name)
469 (define-condition ,name (socket-error)
470 ((symbol :reader socket-error-symbol :initform (quote ,symbol))))
472 (push (cons ,symbol (quote ,name)) *conditions-for-errno*)))
474 (defparameter *conditions-for-errno* nil)
475 ;;; this needs the rest of the list adding to it, really. They also
476 ;;; need symbols to be added to constants.ccon
477 ;;; I haven't yet thought of a non-kludgey way of keeping all this in
479 (define-socket-condition sockint::EADDRINUSE address-in-use-error)
480 (define-socket-condition sockint::EAGAIN interrupted-error)
481 (define-socket-condition sockint::EBADF bad-file-descriptor-error)
482 (define-socket-condition sockint::ECONNREFUSED connection-refused-error)
483 (define-socket-condition sockint::ETIMEDOUT operation-timeout-error)
484 (define-socket-condition sockint::EINTR interrupted-error)
485 (define-socket-condition sockint::EINVAL invalid-argument-error)
486 (define-socket-condition sockint::ENOBUFS no-buffers-error)
487 (define-socket-condition sockint::ENOMEM out-of-memory-error)
488 (define-socket-condition sockint::EOPNOTSUPP operation-not-supported-error)
489 (define-socket-condition sockint::EPERM operation-not-permitted-error)
490 (define-socket-condition sockint::EPROTONOSUPPORT protocol-not-supported-error)
491 (define-socket-condition sockint::ESOCKTNOSUPPORT socket-type-not-supported-error)
492 (define-socket-condition sockint::ENETUNREACH network-unreachable-error)
493 (define-socket-condition sockint::ENOTCONN not-connected-error)
495 (defun condition-for-errno (err)
496 (or (cdr (assoc err *conditions-for-errno* :test #'eql)) 'socket-error))
499 (defun socket-error (where)
500 ;; Peter's debian/x86 cmucl packages (and sbcl, derived from them)
501 ;; use a direct syscall interface, and have to call UNIX-GET-ERRNO
502 ;; to update the value that unix-errno looks at. On other CMUCL
503 ;; ports, (UNIX-GET-ERRNO) is not needed and doesn't exist
504 (when (fboundp 'unix::unix-get-errno) (unix::unix-get-errno))
505 (let ((condition (condition-for-errno sb-unix:unix-errno)))
506 (error condition :errno sb-unix:unix-errno :syscall where)))
509 (defun socket-error (where)
510 ;; FIXME: Our Texinfo documentation extracter need at least his to spit
511 ;; out the signature. Real documentation would be better...
513 (let* ((errno (socket-errno))
514 (condition (condition-for-errno errno)))
515 (error condition :errno errno :syscall where)))
518 (defgeneric bits-of-sockaddr (socket sockaddr)
519 (:documentation "Return protocol-dependent bits of parameter
520 SOCKADDR, e.g. the Host/Port if SOCKET is an inet socket."))
522 (defgeneric size-of-sockaddr (socket)
523 (:documentation "Return the size of a sockaddr object for SOCKET."))