1 /*-
2 * SPDX-License-Identifier: BSD-3-Clause
3 *
4 * Copyright (c) 1982, 1986, 1988, 1990, 1993
5 * The Regents of the University of California.
6 * Copyright (c) 2004 The FreeBSD Foundation
7 * Copyright (c) 2004-2008 Robert N. M. Watson
8 * All rights reserved.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
33 *
34 * @(#)uipc_socket.c 8.3 (Berkeley) 4/15/94
35 */
36
37 /*
38 * Comments on the socket life cycle:
39 *
40 * soalloc() sets of socket layer state for a socket, called only by
41 * socreate() and sonewconn(). Socket layer private.
42 *
43 * sodealloc() tears down socket layer state for a socket, called only by
44 * sofree() and sonewconn(). Socket layer private.
45 *
46 * pru_attach() associates protocol layer state with an allocated socket;
47 * called only once, may fail, aborting socket allocation. This is called
48 * from socreate() and sonewconn(). Socket layer private.
49 *
50 * pru_detach() disassociates protocol layer state from an attached socket,
51 * and will be called exactly once for sockets in which pru_attach() has
52 * been successfully called. If pru_attach() returned an error,
53 * pru_detach() will not be called. Socket layer private.
54 *
55 * pru_abort() and pru_close() notify the protocol layer that the last
56 * consumer of a socket is starting to tear down the socket, and that the
57 * protocol should terminate the connection. Historically, pru_abort() also
58 * detached protocol state from the socket state, but this is no longer the
59 * case.
60 *
61 * socreate() creates a socket and attaches protocol state. This is a public
62 * interface that may be used by socket layer consumers to create new
63 * sockets.
64 *
65 * sonewconn() creates a socket and attaches protocol state. This is a
66 * public interface that may be used by protocols to create new sockets when
67 * a new connection is received and will be available for accept() on a
68 * listen socket.
69 *
70 * soclose() destroys a socket after possibly waiting for it to disconnect.
71 * This is a public interface that socket consumers should use to close and
72 * release a socket when done with it.
73 *
74 * soabort() destroys a socket without waiting for it to disconnect (used
75 * only for incoming connections that are already partially or fully
76 * connected). This is used internally by the socket layer when clearing
77 * listen socket queues (due to overflow or close on the listen socket), but
78 * is also a public interface protocols may use to abort connections in
79 * their incomplete listen queues should they no longer be required. Sockets
80 * placed in completed connection listen queues should not be aborted for
81 * reasons described in the comment above the soclose() implementation. This
82 * is not a general purpose close routine, and except in the specific
83 * circumstances described here, should not be used.
84 *
85 * sofree() will free a socket and its protocol state if all references on
86 * the socket have been released, and is the public interface to attempt to
87 * free a socket when a reference is removed. This is a socket layer private
88 * interface.
89 *
90 * NOTE: In addition to socreate() and soclose(), which provide a single
91 * socket reference to the consumer to be managed as required, there are two
92 * calls to explicitly manage socket references, soref(), and sorele().
93 * Currently, these are generally required only when transitioning a socket
94 * from a listen queue to a file descriptor, in order to prevent garbage
95 * collection of the socket at an untimely moment. For a number of reasons,
96 * these interfaces are not preferred, and should be avoided.
97 *
98 * NOTE: With regard to VNETs the general rule is that callers do not set
99 * curvnet. Exceptions to this rule include soabort(), sodisconnect(),
100 * sofree() (and with that sorele(), sotryfree()), as well as sonewconn()
101 * and sorflush(), which are usually called from a pre-set VNET context.
102 * sopoll() currently does not need a VNET context to be set.
103 */
104
105 #include <sys/cdefs.h>
106 #include "opt_inet.h"
107 #include "opt_inet6.h"
108 #include "opt_kern_tls.h"
109 #include "opt_ktrace.h"
110 #include "opt_sctp.h"
111
112 #include <sys/param.h>
113 #include <sys/systm.h>
114 #include <sys/capsicum.h>
115 #include <sys/fcntl.h>
116 #include <sys/limits.h>
117 #include <sys/lock.h>
118 #include <sys/mac.h>
119 #include <sys/malloc.h>
120 #include <sys/mbuf.h>
121 #include <sys/mutex.h>
122 #include <sys/domain.h>
123 #include <sys/file.h> /* for struct knote */
124 #include <sys/hhook.h>
125 #include <sys/kernel.h>
126 #include <sys/khelp.h>
127 #include <sys/kthread.h>
128 #include <sys/ktls.h>
129 #include <sys/event.h>
130 #include <sys/eventhandler.h>
131 #include <sys/poll.h>
132 #include <sys/proc.h>
133 #include <sys/protosw.h>
134 #include <sys/sbuf.h>
135 #include <sys/socket.h>
136 #include <sys/socketvar.h>
137 #include <sys/resourcevar.h>
138 #include <net/route.h>
139 #include <sys/sched.h>
140 #include <sys/signalvar.h>
141 #include <sys/smp.h>
142 #include <sys/stat.h>
143 #include <sys/sx.h>
144 #include <sys/sysctl.h>
145 #include <sys/taskqueue.h>
146 #include <sys/uio.h>
147 #include <sys/un.h>
148 #include <sys/unpcb.h>
149 #include <sys/jail.h>
150 #include <sys/syslog.h>
151 #include <netinet/in.h>
152 #include <netinet/in_pcb.h>
153 #include <netinet/tcp.h>
154
155 #include <net/vnet.h>
156
157 #include <security/mac/mac_framework.h>
158 #include <security/mac/mac_internal.h>
159
160 #include <vm/uma.h>
161
162 #ifdef COMPAT_FREEBSD32
163 #include <sys/mount.h>
164 #include <sys/sysent.h>
165 #include <compat/freebsd32/freebsd32.h>
166 #endif
167
168 static int soreceive_generic_locked(struct socket *so,
169 struct sockaddr **psa, struct uio *uio, struct mbuf **mp,
170 struct mbuf **controlp, int *flagsp);
171 static int soreceive_rcvoob(struct socket *so, struct uio *uio,
172 int flags);
173 static int soreceive_stream_locked(struct socket *so, struct sockbuf *sb,
174 struct sockaddr **psa, struct uio *uio, struct mbuf **mp,
175 struct mbuf **controlp, int flags);
176 static int sosend_generic_locked(struct socket *so, struct sockaddr *addr,
177 struct uio *uio, struct mbuf *top, struct mbuf *control,
178 int flags, struct thread *td);
179 static void so_rdknl_lock(void *);
180 static void so_rdknl_unlock(void *);
181 static void so_rdknl_assert_lock(void *, int);
182 static void so_wrknl_lock(void *);
183 static void so_wrknl_unlock(void *);
184 static void so_wrknl_assert_lock(void *, int);
185
186 static void filt_sordetach(struct knote *kn);
187 static int filt_soread(struct knote *kn, long hint);
188 static void filt_sowdetach(struct knote *kn);
189 static int filt_sowrite(struct knote *kn, long hint);
190 static int filt_soempty(struct knote *kn, long hint);
191 static int inline hhook_run_socket(struct socket *so, void *hctx, int32_t h_id);
192 fo_kqfilter_t soo_kqfilter;
193
194 static const struct filterops soread_filtops = {
195 .f_isfd = 1,
196 .f_detach = filt_sordetach,
197 .f_event = filt_soread,
198 };
199 static const struct filterops sowrite_filtops = {
200 .f_isfd = 1,
201 .f_detach = filt_sowdetach,
202 .f_event = filt_sowrite,
203 };
204 static const struct filterops soempty_filtops = {
205 .f_isfd = 1,
206 .f_detach = filt_sowdetach,
207 .f_event = filt_soempty,
208 };
209
210 so_gen_t so_gencnt; /* generation count for sockets */
211
212 MALLOC_DEFINE(M_SONAME, "soname", "socket name");
213 MALLOC_DEFINE(M_PCB, "pcb", "protocol control block");
214
215 #define VNET_SO_ASSERT(so) \
216 VNET_ASSERT(curvnet != NULL, \
217 ("%s:%d curvnet is NULL, so=%p", __func__, __LINE__, (so)));
218
219 VNET_DEFINE(struct hhook_head *, socket_hhh[HHOOK_SOCKET_LAST + 1]);
220 #define V_socket_hhh VNET(socket_hhh)
221
222 #ifdef COMPAT_FREEBSD32
223 #ifdef __amd64__
224 /* off_t has 4-byte alignment on i386 but not on other 32-bit platforms. */
225 #define __splice32_packed __packed
226 #else
227 #define __splice32_packed
228 #endif
229 struct splice32 {
230 int32_t sp_fd;
231 int64_t sp_max;
232 struct timeval32 sp_idle;
233 } __splice32_packed;
234 #undef __splice32_packed
235 #endif
236
237 /*
238 * Limit on the number of connections in the listen queue waiting
239 * for accept(2).
240 * NB: The original sysctl somaxconn is still available but hidden
241 * to prevent confusion about the actual purpose of this number.
242 */
243 VNET_DEFINE_STATIC(u_int, somaxconn) = SOMAXCONN;
244 #define V_somaxconn VNET(somaxconn)
245
246 static int
sysctl_somaxconn(SYSCTL_HANDLER_ARGS)247 sysctl_somaxconn(SYSCTL_HANDLER_ARGS)
248 {
249 int error;
250 u_int val;
251
252 val = V_somaxconn;
253 error = sysctl_handle_int(oidp, &val, 0, req);
254 if (error || !req->newptr )
255 return (error);
256
257 /*
258 * The purpose of the UINT_MAX / 3 limit, is so that the formula
259 * 3 * sol_qlimit / 2
260 * below, will not overflow.
261 */
262
263 if (val < 1 || val > UINT_MAX / 3)
264 return (EINVAL);
265
266 V_somaxconn = val;
267 return (0);
268 }
269 SYSCTL_PROC(_kern_ipc, OID_AUTO, soacceptqueue,
270 CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_MPSAFE | CTLFLAG_VNET, 0, sizeof(u_int),
271 sysctl_somaxconn, "IU",
272 "Maximum listen socket pending connection accept queue size");
273 SYSCTL_PROC(_kern_ipc, KIPC_SOMAXCONN, somaxconn,
274 CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_SKIP | CTLFLAG_MPSAFE | CTLFLAG_VNET, 0,
275 sizeof(u_int), sysctl_somaxconn, "IU",
276 "Maximum listen socket pending connection accept queue size (compat)");
277
278 static u_int numopensockets;
279 static int
sysctl_numopensockets(SYSCTL_HANDLER_ARGS)280 sysctl_numopensockets(SYSCTL_HANDLER_ARGS)
281 {
282 u_int val;
283
284 #ifdef VIMAGE
285 if(!IS_DEFAULT_VNET(curvnet))
286 val = curvnet->vnet_sockcnt;
287 else
288 #endif
289 val = numopensockets;
290 return (sysctl_handle_int(oidp, &val, 0, req));
291 }
292 SYSCTL_PROC(_kern_ipc, OID_AUTO, numopensockets,
293 CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE | CTLFLAG_VNET, 0, sizeof(u_int),
294 sysctl_numopensockets, "IU", "Number of open sockets");
295
296 /*
297 * so_global_mtx protects so_gencnt, numopensockets, and the per-socket
298 * so_gencnt field.
299 */
300 static struct mtx so_global_mtx;
301 MTX_SYSINIT(so_global_mtx, &so_global_mtx, "so_glabel", MTX_DEF);
302
303 /*
304 * General IPC sysctl name space, used by sockets and a variety of other IPC
305 * types.
306 */
307 SYSCTL_NODE(_kern, KERN_IPC, ipc, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
308 "IPC");
309
310 /*
311 * Initialize the socket subsystem and set up the socket
312 * memory allocator.
313 */
314 static uma_zone_t socket_zone;
315 int maxsockets;
316
317 static void
socket_zone_change(void * tag)318 socket_zone_change(void *tag)
319 {
320
321 maxsockets = uma_zone_set_max(socket_zone, maxsockets);
322 }
323
324 static int splice_init_state;
325 static struct sx splice_init_lock;
326 SX_SYSINIT(splice_init_lock, &splice_init_lock, "splice_init");
327
328 static SYSCTL_NODE(_kern_ipc, OID_AUTO, splice, CTLFLAG_RW, 0,
329 "Settings relating to the SO_SPLICE socket option");
330
331 static bool splice_receive_stream = true;
332 SYSCTL_BOOL(_kern_ipc_splice, OID_AUTO, receive_stream, CTLFLAG_RWTUN,
333 &splice_receive_stream, 0,
334 "Use soreceive_stream() for stream splices");
335
336 static uma_zone_t splice_zone;
337 static struct proc *splice_proc;
338 struct splice_wq {
339 struct mtx mtx;
340 STAILQ_HEAD(, so_splice) head;
341 bool running;
342 } __aligned(CACHE_LINE_SIZE);
343 static struct splice_wq *splice_wq;
344 static uint32_t splice_index = 0;
345
346 static void so_splice_timeout(void *arg, int pending);
347 static void so_splice_xfer(struct so_splice *s);
348 static int so_unsplice(struct socket *so, bool timeout);
349
350 static void
splice_work_thread(void * ctx)351 splice_work_thread(void *ctx)
352 {
353 struct splice_wq *wq = ctx;
354 struct so_splice *s, *s_temp;
355 STAILQ_HEAD(, so_splice) local_head;
356 int cpu;
357
358 cpu = wq - splice_wq;
359 if (bootverbose)
360 printf("starting so_splice worker thread for CPU %d\n", cpu);
361
362 for (;;) {
363 mtx_lock(&wq->mtx);
364 while (STAILQ_EMPTY(&wq->head)) {
365 wq->running = false;
366 mtx_sleep(wq, &wq->mtx, 0, "-", 0);
367 wq->running = true;
368 }
369 STAILQ_INIT(&local_head);
370 STAILQ_CONCAT(&local_head, &wq->head);
371 STAILQ_INIT(&wq->head);
372 mtx_unlock(&wq->mtx);
373 STAILQ_FOREACH_SAFE(s, &local_head, next, s_temp) {
374 mtx_lock(&s->mtx);
375 CURVNET_SET(s->src->so_vnet);
376 so_splice_xfer(s);
377 CURVNET_RESTORE();
378 }
379 }
380 }
381
382 static void
so_splice_dispatch_async(struct so_splice * sp)383 so_splice_dispatch_async(struct so_splice *sp)
384 {
385 struct splice_wq *wq;
386 bool running;
387
388 wq = &splice_wq[sp->wq_index];
389 mtx_lock(&wq->mtx);
390 STAILQ_INSERT_TAIL(&wq->head, sp, next);
391 running = wq->running;
392 mtx_unlock(&wq->mtx);
393 if (!running)
394 wakeup(wq);
395 }
396
397 void
so_splice_dispatch(struct so_splice * sp)398 so_splice_dispatch(struct so_splice *sp)
399 {
400 mtx_assert(&sp->mtx, MA_OWNED);
401
402 if (sp->state != SPLICE_IDLE) {
403 mtx_unlock(&sp->mtx);
404 } else {
405 sp->state = SPLICE_QUEUED;
406 mtx_unlock(&sp->mtx);
407 so_splice_dispatch_async(sp);
408 }
409 }
410
411 static int
splice_zinit(void * mem,int size __unused,int flags __unused)412 splice_zinit(void *mem, int size __unused, int flags __unused)
413 {
414 struct so_splice *s;
415
416 s = (struct so_splice *)mem;
417 mtx_init(&s->mtx, "so_splice", NULL, MTX_DEF);
418 return (0);
419 }
420
421 static void
splice_zfini(void * mem,int size)422 splice_zfini(void *mem, int size)
423 {
424 struct so_splice *s;
425
426 s = (struct so_splice *)mem;
427 mtx_destroy(&s->mtx);
428 }
429
430 static int
splice_init(void)431 splice_init(void)
432 {
433 struct thread *td;
434 int error, i, state;
435
436 state = atomic_load_acq_int(&splice_init_state);
437 if (__predict_true(state > 0))
438 return (0);
439 if (state < 0)
440 return (ENXIO);
441 sx_xlock(&splice_init_lock);
442 if (splice_init_state != 0) {
443 sx_xunlock(&splice_init_lock);
444 return (0);
445 }
446
447 splice_zone = uma_zcreate("splice", sizeof(struct so_splice), NULL,
448 NULL, splice_zinit, splice_zfini, UMA_ALIGN_CACHE, 0);
449
450 splice_wq = mallocarray(mp_maxid + 1, sizeof(*splice_wq), M_TEMP,
451 M_WAITOK | M_ZERO);
452
453 /*
454 * Initialize the workqueues to run the splice work. We create a
455 * work queue for each CPU.
456 */
457 CPU_FOREACH(i) {
458 STAILQ_INIT(&splice_wq[i].head);
459 mtx_init(&splice_wq[i].mtx, "splice work queue", NULL, MTX_DEF);
460 }
461
462 /* Start kthreads for each workqueue. */
463 error = 0;
464 CPU_FOREACH(i) {
465 error = kproc_kthread_add(splice_work_thread, &splice_wq[i],
466 &splice_proc, &td, 0, 0, "so_splice", "thr_%d", i);
467 if (error) {
468 printf("Can't add so_splice thread %d error %d\n",
469 i, error);
470 break;
471 }
472
473 /*
474 * It's possible to create loops with SO_SPLICE; ensure that
475 * worker threads aren't able to starve the system too easily.
476 */
477 thread_lock(td);
478 sched_prio(td, PUSER);
479 thread_unlock(td);
480 }
481
482 splice_init_state = error != 0 ? -1 : 1;
483 sx_xunlock(&splice_init_lock);
484
485 return (error);
486 }
487
488 /*
489 * Lock a pair of socket's I/O locks for splicing. Avoid blocking while holding
490 * one lock in order to avoid potential deadlocks in case there is some other
491 * code path which acquires more than one I/O lock at a time.
492 */
493 static void
splice_lock_pair(struct socket * so_src,struct socket * so_dst)494 splice_lock_pair(struct socket *so_src, struct socket *so_dst)
495 {
496 int error;
497
498 for (;;) {
499 error = SOCK_IO_SEND_LOCK(so_dst, SBL_WAIT | SBL_NOINTR);
500 KASSERT(error == 0,
501 ("%s: failed to lock send I/O lock: %d", __func__, error));
502 error = SOCK_IO_RECV_LOCK(so_src, 0);
503 KASSERT(error == 0 || error == EWOULDBLOCK,
504 ("%s: failed to lock recv I/O lock: %d", __func__, error));
505 if (error == 0)
506 break;
507 SOCK_IO_SEND_UNLOCK(so_dst);
508
509 error = SOCK_IO_RECV_LOCK(so_src, SBL_WAIT | SBL_NOINTR);
510 KASSERT(error == 0,
511 ("%s: failed to lock recv I/O lock: %d", __func__, error));
512 error = SOCK_IO_SEND_LOCK(so_dst, 0);
513 KASSERT(error == 0 || error == EWOULDBLOCK,
514 ("%s: failed to lock send I/O lock: %d", __func__, error));
515 if (error == 0)
516 break;
517 SOCK_IO_RECV_UNLOCK(so_src);
518 }
519 }
520
521 static void
splice_unlock_pair(struct socket * so_src,struct socket * so_dst)522 splice_unlock_pair(struct socket *so_src, struct socket *so_dst)
523 {
524 SOCK_IO_RECV_UNLOCK(so_src);
525 SOCK_IO_SEND_UNLOCK(so_dst);
526 }
527
528 /*
529 * Move data from the source to the sink. Assumes that both of the relevant
530 * socket I/O locks are held.
531 */
532 static int
so_splice_xfer_data(struct socket * so_src,struct socket * so_dst,off_t max,ssize_t * lenp)533 so_splice_xfer_data(struct socket *so_src, struct socket *so_dst, off_t max,
534 ssize_t *lenp)
535 {
536 struct uio uio;
537 struct mbuf *m;
538 struct sockbuf *sb_src, *sb_dst;
539 ssize_t len;
540 long space;
541 int error, flags;
542
543 SOCK_IO_RECV_ASSERT_LOCKED(so_src);
544 SOCK_IO_SEND_ASSERT_LOCKED(so_dst);
545
546 error = 0;
547 m = NULL;
548 memset(&uio, 0, sizeof(uio));
549
550 sb_src = &so_src->so_rcv;
551 sb_dst = &so_dst->so_snd;
552
553 space = sbspace(sb_dst);
554 if (space < 0)
555 space = 0;
556 len = MIN(max, MIN(space, sbavail(sb_src)));
557 if (len == 0) {
558 SOCK_RECVBUF_LOCK(so_src);
559 if ((sb_src->sb_state & SBS_CANTRCVMORE) != 0)
560 error = EPIPE;
561 SOCK_RECVBUF_UNLOCK(so_src);
562 } else {
563 flags = MSG_DONTWAIT;
564 uio.uio_resid = len;
565 if (splice_receive_stream && sb_src->sb_tls_info == NULL) {
566 error = soreceive_stream_locked(so_src, sb_src, NULL,
567 &uio, &m, NULL, flags);
568 } else {
569 error = soreceive_generic_locked(so_src, NULL,
570 &uio, &m, NULL, &flags);
571 }
572 if (error != 0 && m != NULL) {
573 m_freem(m);
574 m = NULL;
575 }
576 }
577 if (m != NULL) {
578 len -= uio.uio_resid;
579 error = sosend_generic_locked(so_dst, NULL, NULL, m, NULL,
580 MSG_DONTWAIT, curthread);
581 } else if (error == 0) {
582 len = 0;
583 SOCK_SENDBUF_LOCK(so_dst);
584 if ((sb_dst->sb_state & SBS_CANTSENDMORE) != 0)
585 error = EPIPE;
586 SOCK_SENDBUF_UNLOCK(so_dst);
587 }
588 if (error == 0)
589 *lenp = len;
590 return (error);
591 }
592
593 /*
594 * Transfer data from the source to the sink.
595 */
596 static void
so_splice_xfer(struct so_splice * sp)597 so_splice_xfer(struct so_splice *sp)
598 {
599 struct socket *so_src, *so_dst;
600 off_t max;
601 ssize_t len;
602 int error;
603
604 mtx_assert(&sp->mtx, MA_OWNED);
605 KASSERT(sp->state == SPLICE_QUEUED || sp->state == SPLICE_CLOSING,
606 ("so_splice_xfer: invalid state %d", sp->state));
607 KASSERT(sp->max != 0, ("so_splice_xfer: max == 0"));
608
609 if (sp->state == SPLICE_CLOSING) {
610 /* Userspace asked us to close the splice. */
611 goto closing;
612 }
613
614 sp->state = SPLICE_RUNNING;
615 so_src = sp->src;
616 so_dst = sp->dst;
617 max = sp->max > 0 ? sp->max - so_src->so_splice_sent : OFF_MAX;
618 if (max < 0)
619 max = 0;
620
621 /*
622 * Lock the sockets in order to block userspace from doing anything
623 * sneaky. If an error occurs or one of the sockets can no longer
624 * transfer data, we will automatically unsplice.
625 */
626 mtx_unlock(&sp->mtx);
627 splice_lock_pair(so_src, so_dst);
628
629 error = so_splice_xfer_data(so_src, so_dst, max, &len);
630
631 mtx_lock(&sp->mtx);
632
633 /*
634 * Update our stats while still holding the socket locks. This
635 * synchronizes with getsockopt(SO_SPLICE), see the comment there.
636 */
637 if (error == 0) {
638 KASSERT(len >= 0, ("%s: len %zd < 0", __func__, len));
639 so_src->so_splice_sent += len;
640 }
641 splice_unlock_pair(so_src, so_dst);
642
643 switch (sp->state) {
644 case SPLICE_CLOSING:
645 closing:
646 sp->state = SPLICE_CLOSED;
647 wakeup(sp);
648 mtx_unlock(&sp->mtx);
649 break;
650 case SPLICE_RUNNING:
651 if (error != 0 ||
652 (sp->max > 0 && so_src->so_splice_sent >= sp->max)) {
653 sp->state = SPLICE_EXCEPTION;
654 soref(so_src);
655 mtx_unlock(&sp->mtx);
656 (void)so_unsplice(so_src, false);
657 sorele(so_src);
658 } else {
659 /*
660 * Locklessly check for additional bytes in the source's
661 * receive buffer and queue more work if possible. We
662 * may end up queuing needless work, but that's ok, and
663 * if we race with a thread inserting more data into the
664 * buffer and observe sbavail() == 0, the splice mutex
665 * ensures that splice_push() will queue more work for
666 * us.
667 */
668 if (sbavail(&so_src->so_rcv) > 0 &&
669 sbspace(&so_dst->so_snd) > 0) {
670 sp->state = SPLICE_QUEUED;
671 mtx_unlock(&sp->mtx);
672 so_splice_dispatch_async(sp);
673 } else {
674 sp->state = SPLICE_IDLE;
675 mtx_unlock(&sp->mtx);
676 }
677 }
678 break;
679 default:
680 __assert_unreachable();
681 }
682 }
683
684 static void
socket_hhook_register(int subtype)685 socket_hhook_register(int subtype)
686 {
687
688 if (hhook_head_register(HHOOK_TYPE_SOCKET, subtype,
689 &V_socket_hhh[subtype],
690 HHOOK_NOWAIT|HHOOK_HEADISINVNET) != 0)
691 printf("%s: WARNING: unable to register hook\n", __func__);
692 }
693
694 static void
socket_hhook_deregister(int subtype)695 socket_hhook_deregister(int subtype)
696 {
697
698 if (hhook_head_deregister(V_socket_hhh[subtype]) != 0)
699 printf("%s: WARNING: unable to deregister hook\n", __func__);
700 }
701
702 static void
socket_init(void * tag)703 socket_init(void *tag)
704 {
705
706 socket_zone = uma_zcreate("socket", sizeof(struct socket), NULL, NULL,
707 NULL, NULL, UMA_ALIGN_PTR, 0);
708 maxsockets = uma_zone_set_max(socket_zone, maxsockets);
709 uma_zone_set_warning(socket_zone, "kern.ipc.maxsockets limit reached");
710 EVENTHANDLER_REGISTER(maxsockets_change, socket_zone_change, NULL,
711 EVENTHANDLER_PRI_FIRST);
712 }
713 SYSINIT(socket, SI_SUB_PROTO_DOMAININIT, SI_ORDER_ANY, socket_init, NULL);
714
715 static void
socket_vnet_init(const void * unused __unused)716 socket_vnet_init(const void *unused __unused)
717 {
718 int i;
719
720 /* We expect a contiguous range */
721 for (i = 0; i <= HHOOK_SOCKET_LAST; i++)
722 socket_hhook_register(i);
723 }
724 VNET_SYSINIT(socket_vnet_init, SI_SUB_PROTO_DOMAININIT, SI_ORDER_ANY,
725 socket_vnet_init, NULL);
726
727 static void
socket_vnet_uninit(const void * unused __unused)728 socket_vnet_uninit(const void *unused __unused)
729 {
730 int i;
731
732 for (i = 0; i <= HHOOK_SOCKET_LAST; i++)
733 socket_hhook_deregister(i);
734 }
735 VNET_SYSUNINIT(socket_vnet_uninit, SI_SUB_PROTO_DOMAININIT, SI_ORDER_ANY,
736 socket_vnet_uninit, NULL);
737
738 /*
739 * Initialise maxsockets. This SYSINIT must be run after
740 * tunable_mbinit().
741 */
742 static void
init_maxsockets(void * ignored)743 init_maxsockets(void *ignored)
744 {
745
746 TUNABLE_INT_FETCH("kern.ipc.maxsockets", &maxsockets);
747 maxsockets = imax(maxsockets, maxfiles);
748 }
749 SYSINIT(param, SI_SUB_TUNABLES, SI_ORDER_ANY, init_maxsockets, NULL);
750
751 /*
752 * Sysctl to get and set the maximum global sockets limit. Notify protocols
753 * of the change so that they can update their dependent limits as required.
754 */
755 static int
sysctl_maxsockets(SYSCTL_HANDLER_ARGS)756 sysctl_maxsockets(SYSCTL_HANDLER_ARGS)
757 {
758 int error, newmaxsockets;
759
760 newmaxsockets = maxsockets;
761 error = sysctl_handle_int(oidp, &newmaxsockets, 0, req);
762 if (error == 0 && req->newptr && newmaxsockets != maxsockets) {
763 if (newmaxsockets > maxsockets &&
764 newmaxsockets <= maxfiles) {
765 maxsockets = newmaxsockets;
766 EVENTHANDLER_INVOKE(maxsockets_change);
767 } else
768 error = EINVAL;
769 }
770 return (error);
771 }
772 SYSCTL_PROC(_kern_ipc, OID_AUTO, maxsockets,
773 CTLTYPE_INT | CTLFLAG_RWTUN | CTLFLAG_NOFETCH | CTLFLAG_MPSAFE,
774 &maxsockets, 0, sysctl_maxsockets, "IU",
775 "Maximum number of sockets available");
776
777 /*
778 * Socket operation routines. These routines are called by the routines in
779 * sys_socket.c or from a system process, and implement the semantics of
780 * socket operations by switching out to the protocol specific routines.
781 */
782
783 /*
784 * Get a socket structure from our zone, and initialize it. Note that it
785 * would probably be better to allocate socket and PCB at the same time, but
786 * I'm not convinced that all the protocols can be easily modified to do
787 * this.
788 *
789 * soalloc() returns a socket with a ref count of 0.
790 */
791 static struct socket *
soalloc(struct vnet * vnet)792 soalloc(struct vnet *vnet)
793 {
794 struct socket *so;
795
796 so = uma_zalloc(socket_zone, M_NOWAIT | M_ZERO);
797 if (so == NULL)
798 return (NULL);
799 #ifdef MAC
800 if (mac_socket_init(so, M_NOWAIT) != 0) {
801 uma_zfree(socket_zone, so);
802 return (NULL);
803 }
804 #endif
805 if (khelp_init_osd(HELPER_CLASS_SOCKET, &so->osd)) {
806 uma_zfree(socket_zone, so);
807 return (NULL);
808 }
809
810 /*
811 * The socket locking protocol allows to lock 2 sockets at a time,
812 * however, the first one must be a listening socket. WITNESS lacks
813 * a feature to change class of an existing lock, so we use DUPOK.
814 */
815 mtx_init(&so->so_lock, "socket", NULL, MTX_DEF | MTX_DUPOK);
816 mtx_init(&so->so_snd_mtx, "so_snd", NULL, MTX_DEF);
817 mtx_init(&so->so_rcv_mtx, "so_rcv", NULL, MTX_DEF);
818 so->so_rcv.sb_sel = &so->so_rdsel;
819 so->so_snd.sb_sel = &so->so_wrsel;
820 sx_init(&so->so_snd_sx, "so_snd_sx");
821 sx_init(&so->so_rcv_sx, "so_rcv_sx");
822 TAILQ_INIT(&so->so_snd.sb_aiojobq);
823 TAILQ_INIT(&so->so_rcv.sb_aiojobq);
824 TASK_INIT(&so->so_snd.sb_aiotask, 0, soaio_snd, so);
825 TASK_INIT(&so->so_rcv.sb_aiotask, 0, soaio_rcv, so);
826 #ifdef VIMAGE
827 VNET_ASSERT(vnet != NULL, ("%s:%d vnet is NULL, so=%p",
828 __func__, __LINE__, so));
829 so->so_vnet = vnet;
830 #endif
831 /* We shouldn't need the so_global_mtx */
832 if (hhook_run_socket(so, NULL, HHOOK_SOCKET_CREATE)) {
833 /* Do we need more comprehensive error returns? */
834 uma_zfree(socket_zone, so);
835 return (NULL);
836 }
837 mtx_lock(&so_global_mtx);
838 so->so_gencnt = ++so_gencnt;
839 ++numopensockets;
840 #ifdef VIMAGE
841 vnet->vnet_sockcnt++;
842 #endif
843 mtx_unlock(&so_global_mtx);
844
845 return (so);
846 }
847
848 /*
849 * Free the storage associated with a socket at the socket layer, tear down
850 * locks, labels, etc. All protocol state is assumed already to have been
851 * torn down (and possibly never set up) by the caller.
852 */
853 void
sodealloc(struct socket * so)854 sodealloc(struct socket *so)
855 {
856
857 KASSERT(so->so_count == 0, ("sodealloc(): so_count %d", so->so_count));
858 KASSERT(so->so_pcb == NULL, ("sodealloc(): so_pcb != NULL"));
859
860 mtx_lock(&so_global_mtx);
861 so->so_gencnt = ++so_gencnt;
862 --numopensockets; /* Could be below, but faster here. */
863 #ifdef VIMAGE
864 VNET_ASSERT(so->so_vnet != NULL, ("%s:%d so_vnet is NULL, so=%p",
865 __func__, __LINE__, so));
866 so->so_vnet->vnet_sockcnt--;
867 #endif
868 mtx_unlock(&so_global_mtx);
869 #ifdef MAC
870 mac_socket_destroy(so);
871 #endif
872 hhook_run_socket(so, NULL, HHOOK_SOCKET_CLOSE);
873
874 khelp_destroy_osd(&so->osd);
875 if (SOLISTENING(so)) {
876 if (so->sol_accept_filter != NULL)
877 accept_filt_setopt(so, NULL);
878 } else {
879 if (so->so_rcv.sb_hiwat)
880 (void)chgsbsize(so->so_cred->cr_uidinfo,
881 &so->so_rcv.sb_hiwat, 0, RLIM_INFINITY);
882 if (so->so_snd.sb_hiwat)
883 (void)chgsbsize(so->so_cred->cr_uidinfo,
884 &so->so_snd.sb_hiwat, 0, RLIM_INFINITY);
885 sx_destroy(&so->so_snd_sx);
886 sx_destroy(&so->so_rcv_sx);
887 mtx_destroy(&so->so_snd_mtx);
888 mtx_destroy(&so->so_rcv_mtx);
889 }
890 crfree(so->so_cred);
891 mtx_destroy(&so->so_lock);
892 uma_zfree(socket_zone, so);
893 }
894
895 /*
896 * socreate returns a socket with a ref count of 1 and a file descriptor
897 * reference. The socket should be closed with soclose().
898 */
899 int
socreate(int dom,struct socket ** aso,int type,int proto,struct ucred * cred,struct thread * td)900 socreate(int dom, struct socket **aso, int type, int proto,
901 struct ucred *cred, struct thread *td)
902 {
903 struct protosw *prp;
904 struct socket *so;
905 int error;
906
907 /*
908 * XXX: divert(4) historically abused PF_INET. Keep this compatibility
909 * shim until all applications have been updated.
910 */
911 if (__predict_false(dom == PF_INET && type == SOCK_RAW &&
912 proto == IPPROTO_DIVERT)) {
913 dom = PF_DIVERT;
914 printf("%s uses obsolete way to create divert(4) socket\n",
915 td->td_proc->p_comm);
916 }
917
918 prp = pffindproto(dom, type, proto);
919 if (prp == NULL) {
920 /* No support for domain. */
921 if (pffinddomain(dom) == NULL)
922 return (EAFNOSUPPORT);
923 /* No support for socket type. */
924 if (proto == 0 && type != 0)
925 return (EPROTOTYPE);
926 return (EPROTONOSUPPORT);
927 }
928
929 MPASS(prp->pr_attach);
930
931 if ((prp->pr_flags & PR_CAPATTACH) == 0) {
932 if (CAP_TRACING(td))
933 ktrcapfail(CAPFAIL_PROTO, &proto);
934 if (IN_CAPABILITY_MODE(td))
935 return (ECAPMODE);
936 }
937
938 if (prison_check_af(cred, prp->pr_domain->dom_family) != 0)
939 return (EPROTONOSUPPORT);
940
941 so = soalloc(CRED_TO_VNET(cred));
942 if (so == NULL)
943 return (ENOBUFS);
944
945 so->so_type = type;
946 so->so_cred = crhold(cred);
947 if ((prp->pr_domain->dom_family == PF_INET) ||
948 (prp->pr_domain->dom_family == PF_INET6) ||
949 (prp->pr_domain->dom_family == PF_ROUTE))
950 so->so_fibnum = td->td_proc->p_fibnum;
951 else
952 so->so_fibnum = 0;
953 so->so_proto = prp;
954 #ifdef MAC
955 mac_socket_create(cred, so);
956 #endif
957 knlist_init(&so->so_rdsel.si_note, so, so_rdknl_lock, so_rdknl_unlock,
958 so_rdknl_assert_lock);
959 knlist_init(&so->so_wrsel.si_note, so, so_wrknl_lock, so_wrknl_unlock,
960 so_wrknl_assert_lock);
961 if ((prp->pr_flags & PR_SOCKBUF) == 0) {
962 so->so_snd.sb_mtx = &so->so_snd_mtx;
963 so->so_rcv.sb_mtx = &so->so_rcv_mtx;
964 }
965 /*
966 * Auto-sizing of socket buffers is managed by the protocols and
967 * the appropriate flags must be set in the pru_attach function.
968 */
969 CURVNET_SET(so->so_vnet);
970 error = prp->pr_attach(so, proto, td);
971 CURVNET_RESTORE();
972 if (error) {
973 sodealloc(so);
974 return (error);
975 }
976 soref(so);
977 *aso = so;
978 return (0);
979 }
980
981 #ifdef REGRESSION
982 static int regression_sonewconn_earlytest = 1;
983 SYSCTL_INT(_regression, OID_AUTO, sonewconn_earlytest, CTLFLAG_RW,
984 ®ression_sonewconn_earlytest, 0, "Perform early sonewconn limit test");
985 #endif
986
987 static int sooverprio = LOG_DEBUG;
988 SYSCTL_INT(_kern_ipc, OID_AUTO, sooverprio, CTLFLAG_RW,
989 &sooverprio, 0, "Log priority for listen socket overflows: 0..7 or -1 to disable");
990
991 static struct timeval overinterval = { 60, 0 };
992 SYSCTL_TIMEVAL_SEC(_kern_ipc, OID_AUTO, sooverinterval, CTLFLAG_RW,
993 &overinterval,
994 "Delay in seconds between warnings for listen socket overflows");
995
996 /*
997 * When an attempt at a new connection is noted on a socket which supports
998 * accept(2), the protocol has two options:
999 * 1) Call legacy sonewconn() function, which would call protocol attach
1000 * method, same as used for socket(2).
1001 * 2) Call solisten_clone(), do attach that is specific to a cloned connection,
1002 * and then call solisten_enqueue().
1003 *
1004 * Note: the ref count on the socket is 0 on return.
1005 */
1006 struct socket *
solisten_clone(struct socket * head)1007 solisten_clone(struct socket *head)
1008 {
1009 struct sbuf descrsb;
1010 struct socket *so;
1011 int len, overcount;
1012 u_int qlen;
1013 const char localprefix[] = "local:";
1014 char descrbuf[SUNPATHLEN + sizeof(localprefix)];
1015 #if defined(INET6)
1016 char addrbuf[INET6_ADDRSTRLEN];
1017 #elif defined(INET)
1018 char addrbuf[INET_ADDRSTRLEN];
1019 #endif
1020 bool dolog, over;
1021
1022 SOLISTEN_LOCK(head);
1023 over = (head->sol_qlen > 3 * head->sol_qlimit / 2);
1024 #ifdef REGRESSION
1025 if (regression_sonewconn_earlytest && over) {
1026 #else
1027 if (over) {
1028 #endif
1029 head->sol_overcount++;
1030 dolog = (sooverprio >= 0) &&
1031 !!ratecheck(&head->sol_lastover, &overinterval);
1032
1033 /*
1034 * If we're going to log, copy the overflow count and queue
1035 * length from the listen socket before dropping the lock.
1036 * Also, reset the overflow count.
1037 */
1038 if (dolog) {
1039 overcount = head->sol_overcount;
1040 head->sol_overcount = 0;
1041 qlen = head->sol_qlen;
1042 }
1043 SOLISTEN_UNLOCK(head);
1044
1045 if (dolog) {
1046 /*
1047 * Try to print something descriptive about the
1048 * socket for the error message.
1049 */
1050 sbuf_new(&descrsb, descrbuf, sizeof(descrbuf),
1051 SBUF_FIXEDLEN);
1052 switch (head->so_proto->pr_domain->dom_family) {
1053 #if defined(INET) || defined(INET6)
1054 #ifdef INET
1055 case AF_INET:
1056 #endif
1057 #ifdef INET6
1058 case AF_INET6:
1059 if (head->so_proto->pr_domain->dom_family ==
1060 AF_INET6 ||
1061 (sotoinpcb(head)->inp_inc.inc_flags &
1062 INC_ISIPV6)) {
1063 ip6_sprintf(addrbuf,
1064 &sotoinpcb(head)->inp_inc.inc6_laddr);
1065 sbuf_printf(&descrsb, "[%s]", addrbuf);
1066 } else
1067 #endif
1068 {
1069 #ifdef INET
1070 inet_ntoa_r(
1071 sotoinpcb(head)->inp_inc.inc_laddr,
1072 addrbuf);
1073 sbuf_cat(&descrsb, addrbuf);
1074 #endif
1075 }
1076 sbuf_printf(&descrsb, ":%hu (proto %u)",
1077 ntohs(sotoinpcb(head)->inp_inc.inc_lport),
1078 head->so_proto->pr_protocol);
1079 break;
1080 #endif /* INET || INET6 */
1081 case AF_UNIX:
1082 sbuf_cat(&descrsb, localprefix);
1083 if (sotounpcb(head)->unp_addr != NULL)
1084 len =
1085 sotounpcb(head)->unp_addr->sun_len -
1086 offsetof(struct sockaddr_un,
1087 sun_path);
1088 else
1089 len = 0;
1090 if (len > 0)
1091 sbuf_bcat(&descrsb,
1092 sotounpcb(head)->unp_addr->sun_path,
1093 len);
1094 else
1095 sbuf_cat(&descrsb, "(unknown)");
1096 break;
1097 }
1098
1099 /*
1100 * If we can't print something more specific, at least
1101 * print the domain name.
1102 */
1103 if (sbuf_finish(&descrsb) != 0 ||
1104 sbuf_len(&descrsb) <= 0) {
1105 sbuf_clear(&descrsb);
1106 sbuf_cat(&descrsb,
1107 head->so_proto->pr_domain->dom_name ?:
1108 "unknown");
1109 sbuf_finish(&descrsb);
1110 }
1111 KASSERT(sbuf_len(&descrsb) > 0,
1112 ("%s: sbuf creation failed", __func__));
1113 /*
1114 * Preserve the historic listen queue overflow log
1115 * message, that starts with "sonewconn:". It has
1116 * been known to sysadmins for years and also test
1117 * sys/kern/sonewconn_overflow checks for it.
1118 */
1119 if (head->so_cred == 0) {
1120 log(LOG_PRI(sooverprio),
1121 "sonewconn: pcb %p (%s): "
1122 "Listen queue overflow: %i already in "
1123 "queue awaiting acceptance (%d "
1124 "occurrences)\n", head->so_pcb,
1125 sbuf_data(&descrsb),
1126 qlen, overcount);
1127 } else {
1128 log(LOG_PRI(sooverprio),
1129 "sonewconn: pcb %p (%s): "
1130 "Listen queue overflow: "
1131 "%i already in queue awaiting acceptance "
1132 "(%d occurrences), euid %d, rgid %d, jail %s\n",
1133 head->so_pcb, sbuf_data(&descrsb), qlen,
1134 overcount, head->so_cred->cr_uid,
1135 head->so_cred->cr_rgid,
1136 head->so_cred->cr_prison ?
1137 head->so_cred->cr_prison->pr_name :
1138 "not_jailed");
1139 }
1140 sbuf_delete(&descrsb);
1141
1142 overcount = 0;
1143 }
1144
1145 return (NULL);
1146 }
1147 SOLISTEN_UNLOCK(head);
1148 VNET_ASSERT(head->so_vnet != NULL, ("%s: so %p vnet is NULL",
1149 __func__, head));
1150 so = soalloc(head->so_vnet);
1151 if (so == NULL) {
1152 log(LOG_DEBUG, "%s: pcb %p: New socket allocation failure: "
1153 "limit reached or out of memory\n",
1154 __func__, head->so_pcb);
1155 return (NULL);
1156 }
1157 so->so_listen = head;
1158 so->so_type = head->so_type;
1159 /*
1160 * POSIX is ambiguous on what options an accept(2)ed socket should
1161 * inherit from the listener. Words "create a new socket" may be
1162 * interpreted as not inheriting anything. Best programming practice
1163 * for application developers is to not rely on such inheritance.
1164 * FreeBSD had historically inherited all so_options excluding
1165 * SO_ACCEPTCONN, which virtually means all SOL_SOCKET level options,
1166 * including those completely irrelevant to a new born socket. For
1167 * compatibility with older versions we will inherit a list of
1168 * meaningful options.
1169 */
1170 so->so_options = head->so_options & (SO_KEEPALIVE | SO_DONTROUTE |
1171 SO_LINGER | SO_OOBINLINE | SO_NOSIGPIPE);
1172 so->so_linger = head->so_linger;
1173 so->so_state = head->so_state;
1174 so->so_fibnum = head->so_fibnum;
1175 so->so_proto = head->so_proto;
1176 so->so_cred = crhold(head->so_cred);
1177 #ifdef MAC
1178 mac_socket_newconn(head, so);
1179 #endif
1180 knlist_init(&so->so_rdsel.si_note, so, so_rdknl_lock, so_rdknl_unlock,
1181 so_rdknl_assert_lock);
1182 knlist_init(&so->so_wrsel.si_note, so, so_wrknl_lock, so_wrknl_unlock,
1183 so_wrknl_assert_lock);
1184 VNET_SO_ASSERT(head);
1185 if (soreserve(so, head->sol_sbsnd_hiwat, head->sol_sbrcv_hiwat)) {
1186 sodealloc(so);
1187 log(LOG_DEBUG, "%s: pcb %p: soreserve() failed\n",
1188 __func__, head->so_pcb);
1189 return (NULL);
1190 }
1191 so->so_rcv.sb_lowat = head->sol_sbrcv_lowat;
1192 so->so_snd.sb_lowat = head->sol_sbsnd_lowat;
1193 so->so_rcv.sb_timeo = head->sol_sbrcv_timeo;
1194 so->so_snd.sb_timeo = head->sol_sbsnd_timeo;
1195 so->so_rcv.sb_flags = head->sol_sbrcv_flags & SB_AUTOSIZE;
1196 so->so_snd.sb_flags = head->sol_sbsnd_flags & SB_AUTOSIZE;
1197 if ((so->so_proto->pr_flags & PR_SOCKBUF) == 0) {
1198 so->so_snd.sb_mtx = &so->so_snd_mtx;
1199 so->so_rcv.sb_mtx = &so->so_rcv_mtx;
1200 }
1201
1202 return (so);
1203 }
1204
1205 /* Connstatus may be 0, or SS_ISCONFIRMING, or SS_ISCONNECTED. */
1206 struct socket *
1207 sonewconn(struct socket *head, int connstatus)
1208 {
1209 struct socket *so;
1210
1211 if ((so = solisten_clone(head)) == NULL)
1212 return (NULL);
1213
1214 if (so->so_proto->pr_attach(so, 0, NULL) != 0) {
1215 sodealloc(so);
1216 log(LOG_DEBUG, "%s: pcb %p: pr_attach() failed\n",
1217 __func__, head->so_pcb);
1218 return (NULL);
1219 }
1220
1221 (void)solisten_enqueue(so, connstatus);
1222
1223 return (so);
1224 }
1225
1226 /*
1227 * Enqueue socket cloned by solisten_clone() to the listen queue of the
1228 * listener it has been cloned from.
1229 *
1230 * Return 'true' if socket landed on complete queue, otherwise 'false'.
1231 */
1232 bool
1233 solisten_enqueue(struct socket *so, int connstatus)
1234 {
1235 struct socket *head = so->so_listen;
1236
1237 MPASS(refcount_load(&so->so_count) == 0);
1238 refcount_init(&so->so_count, 1);
1239
1240 SOLISTEN_LOCK(head);
1241 if (head->sol_accept_filter != NULL)
1242 connstatus = 0;
1243 so->so_state |= connstatus;
1244 soref(head); /* A socket on (in)complete queue refs head. */
1245 if (connstatus) {
1246 TAILQ_INSERT_TAIL(&head->sol_comp, so, so_list);
1247 so->so_qstate = SQ_COMP;
1248 head->sol_qlen++;
1249 solisten_wakeup(head); /* unlocks */
1250 return (true);
1251 } else {
1252 /*
1253 * Keep removing sockets from the head until there's room for
1254 * us to insert on the tail. In pre-locking revisions, this
1255 * was a simple if(), but as we could be racing with other
1256 * threads and soabort() requires dropping locks, we must
1257 * loop waiting for the condition to be true.
1258 */
1259 while (head->sol_incqlen > head->sol_qlimit) {
1260 struct socket *sp;
1261
1262 sp = TAILQ_FIRST(&head->sol_incomp);
1263 TAILQ_REMOVE(&head->sol_incomp, sp, so_list);
1264 head->sol_incqlen--;
1265 SOCK_LOCK(sp);
1266 sp->so_qstate = SQ_NONE;
1267 sp->so_listen = NULL;
1268 SOCK_UNLOCK(sp);
1269 sorele_locked(head); /* does SOLISTEN_UNLOCK, head stays */
1270 soabort(sp);
1271 SOLISTEN_LOCK(head);
1272 }
1273 TAILQ_INSERT_TAIL(&head->sol_incomp, so, so_list);
1274 so->so_qstate = SQ_INCOMP;
1275 head->sol_incqlen++;
1276 SOLISTEN_UNLOCK(head);
1277 return (false);
1278 }
1279 }
1280
1281 #if defined(SCTP) || defined(SCTP_SUPPORT)
1282 /*
1283 * Socket part of sctp_peeloff(). Detach a new socket from an
1284 * association. The new socket is returned with a reference.
1285 *
1286 * XXXGL: reduce copy-paste with solisten_clone().
1287 */
1288 struct socket *
1289 sopeeloff(struct socket *head)
1290 {
1291 struct socket *so;
1292
1293 VNET_ASSERT(head->so_vnet != NULL, ("%s:%d so_vnet is NULL, head=%p",
1294 __func__, __LINE__, head));
1295 so = soalloc(head->so_vnet);
1296 if (so == NULL) {
1297 log(LOG_DEBUG, "%s: pcb %p: New socket allocation failure: "
1298 "limit reached or out of memory\n",
1299 __func__, head->so_pcb);
1300 return (NULL);
1301 }
1302 so->so_type = head->so_type;
1303 so->so_options = head->so_options;
1304 so->so_linger = head->so_linger;
1305 so->so_state = (head->so_state & SS_NBIO) | SS_ISCONNECTED;
1306 so->so_fibnum = head->so_fibnum;
1307 so->so_proto = head->so_proto;
1308 so->so_cred = crhold(head->so_cred);
1309 #ifdef MAC
1310 mac_socket_newconn(head, so);
1311 #endif
1312 knlist_init(&so->so_rdsel.si_note, so, so_rdknl_lock, so_rdknl_unlock,
1313 so_rdknl_assert_lock);
1314 knlist_init(&so->so_wrsel.si_note, so, so_wrknl_lock, so_wrknl_unlock,
1315 so_wrknl_assert_lock);
1316 VNET_SO_ASSERT(head);
1317 if (soreserve(so, head->so_snd.sb_hiwat, head->so_rcv.sb_hiwat)) {
1318 sodealloc(so);
1319 log(LOG_DEBUG, "%s: pcb %p: soreserve() failed\n",
1320 __func__, head->so_pcb);
1321 return (NULL);
1322 }
1323 if ((*so->so_proto->pr_attach)(so, 0, NULL)) {
1324 sodealloc(so);
1325 log(LOG_DEBUG, "%s: pcb %p: pru_attach() failed\n",
1326 __func__, head->so_pcb);
1327 return (NULL);
1328 }
1329 so->so_rcv.sb_lowat = head->so_rcv.sb_lowat;
1330 so->so_snd.sb_lowat = head->so_snd.sb_lowat;
1331 so->so_rcv.sb_timeo = head->so_rcv.sb_timeo;
1332 so->so_snd.sb_timeo = head->so_snd.sb_timeo;
1333 so->so_rcv.sb_flags |= head->so_rcv.sb_flags & SB_AUTOSIZE;
1334 so->so_snd.sb_flags |= head->so_snd.sb_flags & SB_AUTOSIZE;
1335 if ((so->so_proto->pr_flags & PR_SOCKBUF) == 0) {
1336 so->so_snd.sb_mtx = &so->so_snd_mtx;
1337 so->so_rcv.sb_mtx = &so->so_rcv_mtx;
1338 }
1339
1340 soref(so);
1341
1342 return (so);
1343 }
1344 #endif /* SCTP */
1345
1346 int
1347 sobind(struct socket *so, struct sockaddr *nam, struct thread *td)
1348 {
1349 int error;
1350
1351 CURVNET_SET(so->so_vnet);
1352 error = so->so_proto->pr_bind(so, nam, td);
1353 CURVNET_RESTORE();
1354 return (error);
1355 }
1356
1357 int
1358 sobindat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
1359 {
1360 int error;
1361
1362 CURVNET_SET(so->so_vnet);
1363 error = so->so_proto->pr_bindat(fd, so, nam, td);
1364 CURVNET_RESTORE();
1365 return (error);
1366 }
1367
1368 /*
1369 * solisten() transitions a socket from a non-listening state to a listening
1370 * state, but can also be used to update the listen queue depth on an
1371 * existing listen socket. The protocol will call back into the sockets
1372 * layer using solisten_proto_check() and solisten_proto() to check and set
1373 * socket-layer listen state. Call backs are used so that the protocol can
1374 * acquire both protocol and socket layer locks in whatever order is required
1375 * by the protocol.
1376 *
1377 * Protocol implementors are advised to hold the socket lock across the
1378 * socket-layer test and set to avoid races at the socket layer.
1379 */
1380 int
1381 solisten(struct socket *so, int backlog, struct thread *td)
1382 {
1383 int error;
1384
1385 CURVNET_SET(so->so_vnet);
1386 error = so->so_proto->pr_listen(so, backlog, td);
1387 CURVNET_RESTORE();
1388 return (error);
1389 }
1390
1391 /*
1392 * Prepare for a call to solisten_proto(). Acquire all socket buffer locks in
1393 * order to interlock with socket I/O.
1394 */
1395 int
1396 solisten_proto_check(struct socket *so)
1397 {
1398 SOCK_LOCK_ASSERT(so);
1399
1400 if ((so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING |
1401 SS_ISDISCONNECTING)) != 0)
1402 return (EINVAL);
1403
1404 /*
1405 * Sleeping is not permitted here, so simply fail if userspace is
1406 * attempting to transmit or receive on the socket. This kind of
1407 * transient failure is not ideal, but it should occur only if userspace
1408 * is misusing the socket interfaces.
1409 */
1410 if (!sx_try_xlock(&so->so_snd_sx))
1411 return (EAGAIN);
1412 if (!sx_try_xlock(&so->so_rcv_sx)) {
1413 sx_xunlock(&so->so_snd_sx);
1414 return (EAGAIN);
1415 }
1416 mtx_lock(&so->so_snd_mtx);
1417 mtx_lock(&so->so_rcv_mtx);
1418
1419 /* Interlock with soo_aio_queue() and KTLS. */
1420 if (!SOLISTENING(so)) {
1421 bool ktls;
1422
1423 #ifdef KERN_TLS
1424 ktls = so->so_snd.sb_tls_info != NULL ||
1425 so->so_rcv.sb_tls_info != NULL;
1426 #else
1427 ktls = false;
1428 #endif
1429 if (ktls ||
1430 (so->so_snd.sb_flags & (SB_AIO | SB_AIO_RUNNING)) != 0 ||
1431 (so->so_rcv.sb_flags & (SB_AIO | SB_AIO_RUNNING)) != 0) {
1432 solisten_proto_abort(so);
1433 return (EINVAL);
1434 }
1435 }
1436
1437 return (0);
1438 }
1439
1440 /*
1441 * Undo the setup done by solisten_proto_check().
1442 */
1443 void
1444 solisten_proto_abort(struct socket *so)
1445 {
1446 mtx_unlock(&so->so_snd_mtx);
1447 mtx_unlock(&so->so_rcv_mtx);
1448 sx_xunlock(&so->so_snd_sx);
1449 sx_xunlock(&so->so_rcv_sx);
1450 }
1451
1452 void
1453 solisten_proto(struct socket *so, int backlog)
1454 {
1455 int sbrcv_lowat, sbsnd_lowat;
1456 u_int sbrcv_hiwat, sbsnd_hiwat;
1457 short sbrcv_flags, sbsnd_flags;
1458 sbintime_t sbrcv_timeo, sbsnd_timeo;
1459
1460 SOCK_LOCK_ASSERT(so);
1461 KASSERT((so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING |
1462 SS_ISDISCONNECTING)) == 0,
1463 ("%s: bad socket state %p", __func__, so));
1464
1465 if (SOLISTENING(so))
1466 goto listening;
1467
1468 /*
1469 * Change this socket to listening state.
1470 */
1471 sbrcv_lowat = so->so_rcv.sb_lowat;
1472 sbsnd_lowat = so->so_snd.sb_lowat;
1473 sbrcv_hiwat = so->so_rcv.sb_hiwat;
1474 sbsnd_hiwat = so->so_snd.sb_hiwat;
1475 sbrcv_flags = so->so_rcv.sb_flags;
1476 sbsnd_flags = so->so_snd.sb_flags;
1477 sbrcv_timeo = so->so_rcv.sb_timeo;
1478 sbsnd_timeo = so->so_snd.sb_timeo;
1479
1480 #ifdef MAC
1481 mac_socketpeer_label_free(so->so_peerlabel);
1482 #endif
1483
1484 sbdestroy(so, SO_SND);
1485 sbdestroy(so, SO_RCV);
1486
1487 #ifdef INVARIANTS
1488 bzero(&so->so_rcv,
1489 sizeof(struct socket) - offsetof(struct socket, so_rcv));
1490 #endif
1491
1492 so->sol_sbrcv_lowat = sbrcv_lowat;
1493 so->sol_sbsnd_lowat = sbsnd_lowat;
1494 so->sol_sbrcv_hiwat = sbrcv_hiwat;
1495 so->sol_sbsnd_hiwat = sbsnd_hiwat;
1496 so->sol_sbrcv_flags = sbrcv_flags;
1497 so->sol_sbsnd_flags = sbsnd_flags;
1498 so->sol_sbrcv_timeo = sbrcv_timeo;
1499 so->sol_sbsnd_timeo = sbsnd_timeo;
1500
1501 so->sol_qlen = so->sol_incqlen = 0;
1502 TAILQ_INIT(&so->sol_incomp);
1503 TAILQ_INIT(&so->sol_comp);
1504
1505 so->sol_accept_filter = NULL;
1506 so->sol_accept_filter_arg = NULL;
1507 so->sol_accept_filter_str = NULL;
1508
1509 so->sol_upcall = NULL;
1510 so->sol_upcallarg = NULL;
1511
1512 so->so_options |= SO_ACCEPTCONN;
1513
1514 listening:
1515 if (backlog < 0 || backlog > V_somaxconn)
1516 backlog = V_somaxconn;
1517 so->sol_qlimit = backlog;
1518
1519 mtx_unlock(&so->so_snd_mtx);
1520 mtx_unlock(&so->so_rcv_mtx);
1521 sx_xunlock(&so->so_snd_sx);
1522 sx_xunlock(&so->so_rcv_sx);
1523 }
1524
1525 /*
1526 * Wakeup listeners/subsystems once we have a complete connection.
1527 * Enters with lock, returns unlocked.
1528 */
1529 void
1530 solisten_wakeup(struct socket *sol)
1531 {
1532
1533 if (sol->sol_upcall != NULL)
1534 (void )sol->sol_upcall(sol, sol->sol_upcallarg, M_NOWAIT);
1535 else {
1536 selwakeuppri(&sol->so_rdsel, PSOCK);
1537 KNOTE_LOCKED(&sol->so_rdsel.si_note, 0);
1538 }
1539 SOLISTEN_UNLOCK(sol);
1540 wakeup_one(&sol->sol_comp);
1541 if ((sol->so_state & SS_ASYNC) && sol->so_sigio != NULL)
1542 pgsigio(&sol->so_sigio, SIGIO, 0);
1543 }
1544
1545 /*
1546 * Return single connection off a listening socket queue. Main consumer of
1547 * the function is kern_accept4(). Some modules, that do their own accept
1548 * management also use the function. The socket reference held by the
1549 * listen queue is handed to the caller.
1550 *
1551 * Listening socket must be locked on entry and is returned unlocked on
1552 * return.
1553 * The flags argument is set of accept4(2) flags and ACCEPT4_INHERIT.
1554 */
1555 int
1556 solisten_dequeue(struct socket *head, struct socket **ret, int flags)
1557 {
1558 struct socket *so;
1559 int error;
1560
1561 SOLISTEN_LOCK_ASSERT(head);
1562
1563 while (!(head->so_state & SS_NBIO) && TAILQ_EMPTY(&head->sol_comp) &&
1564 head->so_error == 0) {
1565 error = msleep(&head->sol_comp, SOCK_MTX(head), PSOCK | PCATCH,
1566 "accept", 0);
1567 if (error != 0) {
1568 SOLISTEN_UNLOCK(head);
1569 return (error);
1570 }
1571 }
1572 if (head->so_error) {
1573 error = head->so_error;
1574 head->so_error = 0;
1575 } else if ((head->so_state & SS_NBIO) && TAILQ_EMPTY(&head->sol_comp))
1576 error = EWOULDBLOCK;
1577 else
1578 error = 0;
1579 if (error) {
1580 SOLISTEN_UNLOCK(head);
1581 return (error);
1582 }
1583 so = TAILQ_FIRST(&head->sol_comp);
1584 SOCK_LOCK(so);
1585 KASSERT(so->so_qstate == SQ_COMP,
1586 ("%s: so %p not SQ_COMP", __func__, so));
1587 head->sol_qlen--;
1588 so->so_qstate = SQ_NONE;
1589 so->so_listen = NULL;
1590 TAILQ_REMOVE(&head->sol_comp, so, so_list);
1591 if (flags & ACCEPT4_INHERIT)
1592 so->so_state |= (head->so_state & SS_NBIO);
1593 else
1594 so->so_state |= (flags & SOCK_NONBLOCK) ? SS_NBIO : 0;
1595 SOCK_UNLOCK(so);
1596 sorele_locked(head);
1597
1598 *ret = so;
1599 return (0);
1600 }
1601
1602 static struct so_splice *
1603 so_splice_alloc(off_t max)
1604 {
1605 struct so_splice *sp;
1606
1607 sp = uma_zalloc(splice_zone, M_WAITOK);
1608 sp->src = NULL;
1609 sp->dst = NULL;
1610 sp->max = max > 0 ? max : -1;
1611 do {
1612 sp->wq_index = atomic_fetchadd_32(&splice_index, 1) %
1613 (mp_maxid + 1);
1614 } while (CPU_ABSENT(sp->wq_index));
1615 sp->state = SPLICE_INIT;
1616 TIMEOUT_TASK_INIT(taskqueue_thread, &sp->timeout, 0, so_splice_timeout,
1617 sp);
1618 return (sp);
1619 }
1620
1621 static void
1622 so_splice_free(struct so_splice *sp)
1623 {
1624 KASSERT(sp->state == SPLICE_CLOSED,
1625 ("so_splice_free: sp %p not closed", sp));
1626 uma_zfree(splice_zone, sp);
1627 }
1628
1629 static void
1630 so_splice_timeout(void *arg, int pending __unused)
1631 {
1632 struct so_splice *sp;
1633
1634 sp = arg;
1635 (void)so_unsplice(sp->src, true);
1636 }
1637
1638 /*
1639 * Splice the output from so to the input of so2.
1640 */
1641 static int
1642 so_splice(struct socket *so, struct socket *so2, struct splice *splice)
1643 {
1644 struct so_splice *sp;
1645 int error;
1646
1647 if (splice->sp_max < 0)
1648 return (EINVAL);
1649 /* Handle only TCP for now; TODO: other streaming protos */
1650 if (so->so_proto->pr_protocol != IPPROTO_TCP ||
1651 so2->so_proto->pr_protocol != IPPROTO_TCP)
1652 return (EPROTONOSUPPORT);
1653 if (so->so_vnet != so2->so_vnet)
1654 return (EINVAL);
1655
1656 /* so_splice_xfer() assumes that we're using these implementations. */
1657 KASSERT(so->so_proto->pr_sosend == sosend_generic,
1658 ("so_splice: sosend not sosend_generic"));
1659 KASSERT(so2->so_proto->pr_soreceive == soreceive_generic ||
1660 so2->so_proto->pr_soreceive == soreceive_stream,
1661 ("so_splice: soreceive not soreceive_generic/stream"));
1662
1663 sp = so_splice_alloc(splice->sp_max);
1664 so->so_splice_sent = 0;
1665 sp->src = so;
1666 sp->dst = so2;
1667
1668 error = 0;
1669 SOCK_LOCK(so);
1670 if (SOLISTENING(so))
1671 error = EINVAL;
1672 else if ((so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING)) == 0)
1673 error = ENOTCONN;
1674 else if (so->so_splice != NULL)
1675 error = EBUSY;
1676 if (error != 0) {
1677 SOCK_UNLOCK(so);
1678 uma_zfree(splice_zone, sp);
1679 return (error);
1680 }
1681 SOCK_RECVBUF_LOCK(so);
1682 if (so->so_rcv.sb_tls_info != NULL) {
1683 SOCK_RECVBUF_UNLOCK(so);
1684 SOCK_UNLOCK(so);
1685 uma_zfree(splice_zone, sp);
1686 return (EINVAL);
1687 }
1688 so->so_rcv.sb_flags |= SB_SPLICED;
1689 so->so_splice = sp;
1690 soref(so);
1691 SOCK_RECVBUF_UNLOCK(so);
1692 SOCK_UNLOCK(so);
1693
1694 error = 0;
1695 SOCK_LOCK(so2);
1696 if (SOLISTENING(so2))
1697 error = EINVAL;
1698 else if ((so2->so_state & (SS_ISCONNECTED | SS_ISCONNECTING)) == 0)
1699 error = ENOTCONN;
1700 else if (so2->so_splice_back != NULL)
1701 error = EBUSY;
1702 if (error != 0) {
1703 SOCK_UNLOCK(so2);
1704 so_unsplice(so, false);
1705 return (error);
1706 }
1707 SOCK_SENDBUF_LOCK(so2);
1708 if (so->so_snd.sb_tls_info != NULL) {
1709 SOCK_SENDBUF_UNLOCK(so2);
1710 SOCK_UNLOCK(so2);
1711 so_unsplice(so, false);
1712 return (EINVAL);
1713 }
1714 so2->so_snd.sb_flags |= SB_SPLICED;
1715 so2->so_splice_back = sp;
1716 soref(so2);
1717 mtx_lock(&sp->mtx);
1718 SOCK_SENDBUF_UNLOCK(so2);
1719 SOCK_UNLOCK(so2);
1720
1721 if (splice->sp_idle.tv_sec != 0 || splice->sp_idle.tv_usec != 0) {
1722 taskqueue_enqueue_timeout_sbt(taskqueue_thread, &sp->timeout,
1723 tvtosbt(splice->sp_idle), 0, C_PREL(4));
1724 }
1725
1726 /*
1727 * Transfer any data already present in the socket buffer.
1728 */
1729 KASSERT(sp->state == SPLICE_INIT,
1730 ("so_splice: splice %p state %d", sp, sp->state));
1731 sp->state = SPLICE_QUEUED;
1732 so_splice_xfer(sp);
1733 return (0);
1734 }
1735
1736 static int
1737 so_unsplice(struct socket *so, bool timeout)
1738 {
1739 struct socket *so2;
1740 struct so_splice *sp;
1741 bool drain, so2rele;
1742
1743 /*
1744 * First unset SB_SPLICED and hide the splice structure so that
1745 * wakeup routines will stop enqueuing work. This also ensures that
1746 * a only a single thread will proceed with the unsplice.
1747 */
1748 SOCK_LOCK(so);
1749 if (SOLISTENING(so)) {
1750 SOCK_UNLOCK(so);
1751 return (EINVAL);
1752 }
1753 SOCK_RECVBUF_LOCK(so);
1754 if ((so->so_rcv.sb_flags & SB_SPLICED) == 0) {
1755 SOCK_RECVBUF_UNLOCK(so);
1756 SOCK_UNLOCK(so);
1757 return (ENOTCONN);
1758 }
1759 sp = so->so_splice;
1760 mtx_lock(&sp->mtx);
1761 if (sp->state == SPLICE_INIT) {
1762 /*
1763 * A splice is in the middle of being set up.
1764 */
1765 mtx_unlock(&sp->mtx);
1766 SOCK_RECVBUF_UNLOCK(so);
1767 SOCK_UNLOCK(so);
1768 return (ENOTCONN);
1769 }
1770 mtx_unlock(&sp->mtx);
1771 so->so_rcv.sb_flags &= ~SB_SPLICED;
1772 so->so_splice = NULL;
1773 SOCK_RECVBUF_UNLOCK(so);
1774 SOCK_UNLOCK(so);
1775
1776 so2 = sp->dst;
1777 SOCK_LOCK(so2);
1778 KASSERT(!SOLISTENING(so2), ("%s: so2 is listening", __func__));
1779 SOCK_SENDBUF_LOCK(so2);
1780 KASSERT(sp->state == SPLICE_INIT ||
1781 (so2->so_snd.sb_flags & SB_SPLICED) != 0,
1782 ("%s: so2 is not spliced", __func__));
1783 KASSERT(sp->state == SPLICE_INIT ||
1784 so2->so_splice_back == sp,
1785 ("%s: so_splice_back != sp", __func__));
1786 so2->so_snd.sb_flags &= ~SB_SPLICED;
1787 so2rele = so2->so_splice_back != NULL;
1788 so2->so_splice_back = NULL;
1789 SOCK_SENDBUF_UNLOCK(so2);
1790 SOCK_UNLOCK(so2);
1791
1792 /*
1793 * No new work is being enqueued. The worker thread might be
1794 * splicing data right now, in which case we want to wait for it to
1795 * finish before proceeding.
1796 */
1797 mtx_lock(&sp->mtx);
1798 switch (sp->state) {
1799 case SPLICE_QUEUED:
1800 case SPLICE_RUNNING:
1801 sp->state = SPLICE_CLOSING;
1802 while (sp->state == SPLICE_CLOSING)
1803 msleep(sp, &sp->mtx, PSOCK, "unsplice", 0);
1804 break;
1805 case SPLICE_INIT:
1806 case SPLICE_IDLE:
1807 case SPLICE_EXCEPTION:
1808 sp->state = SPLICE_CLOSED;
1809 break;
1810 default:
1811 __assert_unreachable();
1812 }
1813 if (!timeout) {
1814 drain = taskqueue_cancel_timeout(taskqueue_thread, &sp->timeout,
1815 NULL) != 0;
1816 } else {
1817 drain = false;
1818 }
1819 mtx_unlock(&sp->mtx);
1820 if (drain)
1821 taskqueue_drain_timeout(taskqueue_thread, &sp->timeout);
1822
1823 /*
1824 * Now we hold the sole reference to the splice structure.
1825 * Clean up: signal userspace and release socket references.
1826 */
1827 sorwakeup(so);
1828 CURVNET_SET(so->so_vnet);
1829 sorele(so);
1830 sowwakeup(so2);
1831 if (so2rele)
1832 sorele(so2);
1833 CURVNET_RESTORE();
1834 so_splice_free(sp);
1835 return (0);
1836 }
1837
1838 /*
1839 * Free socket upon release of the very last reference.
1840 */
1841 static void
1842 sofree(struct socket *so)
1843 {
1844 struct protosw *pr = so->so_proto;
1845
1846 SOCK_LOCK_ASSERT(so);
1847 KASSERT(refcount_load(&so->so_count) == 0,
1848 ("%s: so %p has references", __func__, so));
1849 KASSERT(SOLISTENING(so) || so->so_qstate == SQ_NONE,
1850 ("%s: so %p is on listen queue", __func__, so));
1851 KASSERT(SOLISTENING(so) || (so->so_rcv.sb_flags & SB_SPLICED) == 0,
1852 ("%s: so %p rcvbuf is spliced", __func__, so));
1853 KASSERT(SOLISTENING(so) || (so->so_snd.sb_flags & SB_SPLICED) == 0,
1854 ("%s: so %p sndbuf is spliced", __func__, so));
1855 KASSERT(so->so_splice == NULL && so->so_splice_back == NULL,
1856 ("%s: so %p has spliced data", __func__, so));
1857
1858 SOCK_UNLOCK(so);
1859
1860 if (so->so_dtor != NULL)
1861 so->so_dtor(so);
1862
1863 VNET_SO_ASSERT(so);
1864 if ((pr->pr_flags & PR_RIGHTS) && !SOLISTENING(so)) {
1865 MPASS(pr->pr_domain->dom_dispose != NULL);
1866 (*pr->pr_domain->dom_dispose)(so);
1867 }
1868 if (pr->pr_detach != NULL)
1869 pr->pr_detach(so);
1870
1871 /*
1872 * From this point on, we assume that no other references to this
1873 * socket exist anywhere else in the stack. Therefore, no locks need
1874 * to be acquired or held.
1875 */
1876 if (!(pr->pr_flags & PR_SOCKBUF) && !SOLISTENING(so)) {
1877 sbdestroy(so, SO_SND);
1878 sbdestroy(so, SO_RCV);
1879 }
1880 seldrain(&so->so_rdsel);
1881 seldrain(&so->so_wrsel);
1882 knlist_destroy(&so->so_rdsel.si_note);
1883 knlist_destroy(&so->so_wrsel.si_note);
1884 sodealloc(so);
1885 }
1886
1887 /*
1888 * Release a reference on a socket while holding the socket lock.
1889 * Unlocks the socket lock before returning.
1890 */
1891 void
1892 sorele_locked(struct socket *so)
1893 {
1894 SOCK_LOCK_ASSERT(so);
1895 if (refcount_release(&so->so_count))
1896 sofree(so);
1897 else
1898 SOCK_UNLOCK(so);
1899 }
1900
1901 /*
1902 * Close a socket on last file table reference removal. Initiate disconnect
1903 * if connected. Free socket when disconnect complete.
1904 *
1905 * This function will sorele() the socket. Note that soclose() may be called
1906 * prior to the ref count reaching zero. The actual socket structure will
1907 * not be freed until the ref count reaches zero.
1908 */
1909 int
1910 soclose(struct socket *so)
1911 {
1912 struct accept_queue lqueue;
1913 int error = 0;
1914 bool listening, last __diagused;
1915
1916 CURVNET_SET(so->so_vnet);
1917 funsetown(&so->so_sigio);
1918 if (so->so_state & SS_ISCONNECTED) {
1919 if ((so->so_state & SS_ISDISCONNECTING) == 0) {
1920 error = sodisconnect(so);
1921 if (error) {
1922 if (error == ENOTCONN)
1923 error = 0;
1924 goto drop;
1925 }
1926 }
1927
1928 if ((so->so_options & SO_LINGER) != 0 && so->so_linger != 0) {
1929 if ((so->so_state & SS_ISDISCONNECTING) &&
1930 (so->so_state & SS_NBIO))
1931 goto drop;
1932 while (so->so_state & SS_ISCONNECTED) {
1933 error = tsleep(&so->so_timeo,
1934 PSOCK | PCATCH, "soclos",
1935 so->so_linger * hz);
1936 if (error)
1937 break;
1938 }
1939 }
1940 }
1941
1942 drop:
1943 if (so->so_proto->pr_close != NULL)
1944 so->so_proto->pr_close(so);
1945
1946 SOCK_LOCK(so);
1947 if ((listening = SOLISTENING(so))) {
1948 struct socket *sp;
1949
1950 TAILQ_INIT(&lqueue);
1951 TAILQ_SWAP(&lqueue, &so->sol_incomp, socket, so_list);
1952 TAILQ_CONCAT(&lqueue, &so->sol_comp, so_list);
1953
1954 so->sol_qlen = so->sol_incqlen = 0;
1955
1956 TAILQ_FOREACH(sp, &lqueue, so_list) {
1957 SOCK_LOCK(sp);
1958 sp->so_qstate = SQ_NONE;
1959 sp->so_listen = NULL;
1960 SOCK_UNLOCK(sp);
1961 last = refcount_release(&so->so_count);
1962 KASSERT(!last, ("%s: released last reference for %p",
1963 __func__, so));
1964 }
1965 }
1966 sorele_locked(so);
1967 if (listening) {
1968 struct socket *sp, *tsp;
1969
1970 TAILQ_FOREACH_SAFE(sp, &lqueue, so_list, tsp)
1971 soabort(sp);
1972 }
1973 CURVNET_RESTORE();
1974 return (error);
1975 }
1976
1977 /*
1978 * soabort() is used to abruptly tear down a connection, such as when a
1979 * resource limit is reached (listen queue depth exceeded), or if a listen
1980 * socket is closed while there are sockets waiting to be accepted.
1981 *
1982 * This interface is tricky, because it is called on an unreferenced socket,
1983 * and must be called only by a thread that has actually removed the socket
1984 * from the listen queue it was on. Likely this thread holds the last
1985 * reference on the socket and soabort() will proceed with sofree(). But
1986 * it might be not the last, as the sockets on the listen queues are seen
1987 * from the protocol side.
1988 *
1989 * This interface will call into the protocol code, so must not be called
1990 * with any socket locks held. Protocols do call it while holding their own
1991 * recursible protocol mutexes, but this is something that should be subject
1992 * to review in the future.
1993 *
1994 * Usually socket should have a single reference left, but this is not a
1995 * requirement. In the past, when we have had named references for file
1996 * descriptor and protocol, we asserted that none of them are being held.
1997 */
1998 void
1999 soabort(struct socket *so)
2000 {
2001
2002 VNET_SO_ASSERT(so);
2003
2004 if (so->so_proto->pr_abort != NULL)
2005 so->so_proto->pr_abort(so);
2006 SOCK_LOCK(so);
2007 sorele_locked(so);
2008 }
2009
2010 int
2011 soaccept(struct socket *so, struct sockaddr **nam)
2012 {
2013 int error;
2014
2015 CURVNET_SET(so->so_vnet);
2016 error = so->so_proto->pr_accept(so, nam);
2017 CURVNET_RESTORE();
2018 return (error);
2019 }
2020
2021 int
2022 soconnect(struct socket *so, struct sockaddr *nam, struct thread *td)
2023 {
2024
2025 return (soconnectat(AT_FDCWD, so, nam, td));
2026 }
2027
2028 int
2029 soconnectat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
2030 {
2031 int error;
2032
2033 CURVNET_SET(so->so_vnet);
2034
2035 /*
2036 * If protocol is connection-based, can only connect once.
2037 * Otherwise, if connected, try to disconnect first. This allows
2038 * user to disconnect by connecting to, e.g., a null address.
2039 *
2040 * Note, this check is racy and may need to be re-evaluated at the
2041 * protocol layer.
2042 */
2043 if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
2044 ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
2045 (error = sodisconnect(so)))) {
2046 error = EISCONN;
2047 } else {
2048 /*
2049 * Prevent accumulated error from previous connection from
2050 * biting us.
2051 */
2052 so->so_error = 0;
2053 if (fd == AT_FDCWD) {
2054 error = so->so_proto->pr_connect(so, nam, td);
2055 } else {
2056 error = so->so_proto->pr_connectat(fd, so, nam, td);
2057 }
2058 }
2059 CURVNET_RESTORE();
2060
2061 return (error);
2062 }
2063
2064 int
2065 soconnect2(struct socket *so1, struct socket *so2)
2066 {
2067 int error;
2068
2069 CURVNET_SET(so1->so_vnet);
2070 error = so1->so_proto->pr_connect2(so1, so2);
2071 CURVNET_RESTORE();
2072 return (error);
2073 }
2074
2075 int
2076 sodisconnect(struct socket *so)
2077 {
2078 int error;
2079
2080 if ((so->so_state & SS_ISCONNECTED) == 0)
2081 return (ENOTCONN);
2082 if (so->so_state & SS_ISDISCONNECTING)
2083 return (EALREADY);
2084 VNET_SO_ASSERT(so);
2085 error = so->so_proto->pr_disconnect(so);
2086 return (error);
2087 }
2088
2089 int
2090 sosend_dgram(struct socket *so, struct sockaddr *addr, struct uio *uio,
2091 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
2092 {
2093 long space;
2094 ssize_t resid;
2095 int clen = 0, error, dontroute;
2096
2097 KASSERT(so->so_type == SOCK_DGRAM, ("sosend_dgram: !SOCK_DGRAM"));
2098 KASSERT(so->so_proto->pr_flags & PR_ATOMIC,
2099 ("sosend_dgram: !PR_ATOMIC"));
2100
2101 if (uio != NULL)
2102 resid = uio->uio_resid;
2103 else
2104 resid = top->m_pkthdr.len;
2105 /*
2106 * In theory resid should be unsigned. However, space must be
2107 * signed, as it might be less than 0 if we over-committed, and we
2108 * must use a signed comparison of space and resid. On the other
2109 * hand, a negative resid causes us to loop sending 0-length
2110 * segments to the protocol.
2111 */
2112 if (resid < 0) {
2113 error = EINVAL;
2114 goto out;
2115 }
2116
2117 dontroute =
2118 (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0;
2119 if (td != NULL)
2120 td->td_ru.ru_msgsnd++;
2121 if (control != NULL)
2122 clen = control->m_len;
2123
2124 SOCKBUF_LOCK(&so->so_snd);
2125 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
2126 SOCKBUF_UNLOCK(&so->so_snd);
2127 error = EPIPE;
2128 goto out;
2129 }
2130 if (so->so_error) {
2131 error = so->so_error;
2132 so->so_error = 0;
2133 SOCKBUF_UNLOCK(&so->so_snd);
2134 goto out;
2135 }
2136 if ((so->so_state & SS_ISCONNECTED) == 0) {
2137 /*
2138 * `sendto' and `sendmsg' is allowed on a connection-based
2139 * socket if it supports implied connect. Return ENOTCONN if
2140 * not connected and no address is supplied.
2141 */
2142 if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
2143 (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
2144 if ((so->so_state & SS_ISCONFIRMING) == 0 &&
2145 !(resid == 0 && clen != 0)) {
2146 SOCKBUF_UNLOCK(&so->so_snd);
2147 error = ENOTCONN;
2148 goto out;
2149 }
2150 } else if (addr == NULL) {
2151 if (so->so_proto->pr_flags & PR_CONNREQUIRED)
2152 error = ENOTCONN;
2153 else
2154 error = EDESTADDRREQ;
2155 SOCKBUF_UNLOCK(&so->so_snd);
2156 goto out;
2157 }
2158 }
2159
2160 /*
2161 * Do we need MSG_OOB support in SOCK_DGRAM? Signs here may be a
2162 * problem and need fixing.
2163 */
2164 space = sbspace(&so->so_snd);
2165 if (flags & MSG_OOB)
2166 space += 1024;
2167 space -= clen;
2168 SOCKBUF_UNLOCK(&so->so_snd);
2169 if (resid > space) {
2170 error = EMSGSIZE;
2171 goto out;
2172 }
2173 if (uio == NULL) {
2174 resid = 0;
2175 if (flags & MSG_EOR)
2176 top->m_flags |= M_EOR;
2177 } else {
2178 /*
2179 * Copy the data from userland into a mbuf chain.
2180 * If no data is to be copied in, a single empty mbuf
2181 * is returned.
2182 */
2183 top = m_uiotombuf(uio, M_WAITOK, space, max_hdr,
2184 (M_PKTHDR | ((flags & MSG_EOR) ? M_EOR : 0)));
2185 if (top == NULL) {
2186 error = EFAULT; /* only possible error */
2187 goto out;
2188 }
2189 space -= resid - uio->uio_resid;
2190 resid = uio->uio_resid;
2191 }
2192 KASSERT(resid == 0, ("sosend_dgram: resid != 0"));
2193 /*
2194 * XXXRW: Frobbing SO_DONTROUTE here is even worse without sblock
2195 * than with.
2196 */
2197 if (dontroute) {
2198 SOCK_LOCK(so);
2199 so->so_options |= SO_DONTROUTE;
2200 SOCK_UNLOCK(so);
2201 }
2202 /*
2203 * XXX all the SBS_CANTSENDMORE checks previously done could be out
2204 * of date. We could have received a reset packet in an interrupt or
2205 * maybe we slept while doing page faults in uiomove() etc. We could
2206 * probably recheck again inside the locking protection here, but
2207 * there are probably other places that this also happens. We must
2208 * rethink this.
2209 */
2210 VNET_SO_ASSERT(so);
2211 error = so->so_proto->pr_send(so, (flags & MSG_OOB) ? PRUS_OOB :
2212 /*
2213 * If the user set MSG_EOF, the protocol understands this flag and
2214 * nothing left to send then use PRU_SEND_EOF instead of PRU_SEND.
2215 */
2216 ((flags & MSG_EOF) &&
2217 (so->so_proto->pr_flags & PR_IMPLOPCL) &&
2218 (resid <= 0)) ?
2219 PRUS_EOF :
2220 /* If there is more to send set PRUS_MORETOCOME */
2221 (flags & MSG_MORETOCOME) ||
2222 (resid > 0 && space > 0) ? PRUS_MORETOCOME : 0,
2223 top, addr, control, td);
2224 if (dontroute) {
2225 SOCK_LOCK(so);
2226 so->so_options &= ~SO_DONTROUTE;
2227 SOCK_UNLOCK(so);
2228 }
2229 clen = 0;
2230 control = NULL;
2231 top = NULL;
2232 out:
2233 if (top != NULL)
2234 m_freem(top);
2235 if (control != NULL)
2236 m_freem(control);
2237 return (error);
2238 }
2239
2240 /*
2241 * Send on a socket. If send must go all at once and message is larger than
2242 * send buffering, then hard error. Lock against other senders. If must go
2243 * all at once and not enough room now, then inform user that this would
2244 * block and do nothing. Otherwise, if nonblocking, send as much as
2245 * possible. The data to be sent is described by "uio" if nonzero, otherwise
2246 * by the mbuf chain "top" (which must be null if uio is not). Data provided
2247 * in mbuf chain must be small enough to send all at once.
2248 *
2249 * Returns nonzero on error, timeout or signal; callers must check for short
2250 * counts if EINTR/ERESTART are returned. Data and control buffers are freed
2251 * on return.
2252 */
2253 static int
2254 sosend_generic_locked(struct socket *so, struct sockaddr *addr, struct uio *uio,
2255 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
2256 {
2257 long space;
2258 ssize_t resid;
2259 int clen = 0, error, dontroute;
2260 int atomic = sosendallatonce(so) || top;
2261 int pr_send_flag;
2262 #ifdef KERN_TLS
2263 struct ktls_session *tls;
2264 int tls_enq_cnt, tls_send_flag;
2265 uint8_t tls_rtype;
2266
2267 tls = NULL;
2268 tls_rtype = TLS_RLTYPE_APP;
2269 #endif
2270
2271 SOCK_IO_SEND_ASSERT_LOCKED(so);
2272
2273 if (uio != NULL)
2274 resid = uio->uio_resid;
2275 else if ((top->m_flags & M_PKTHDR) != 0)
2276 resid = top->m_pkthdr.len;
2277 else
2278 resid = m_length(top, NULL);
2279 /*
2280 * In theory resid should be unsigned. However, space must be
2281 * signed, as it might be less than 0 if we over-committed, and we
2282 * must use a signed comparison of space and resid. On the other
2283 * hand, a negative resid causes us to loop sending 0-length
2284 * segments to the protocol.
2285 *
2286 * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
2287 * type sockets since that's an error.
2288 */
2289 if (resid < 0 || (so->so_type == SOCK_STREAM && (flags & MSG_EOR))) {
2290 error = EINVAL;
2291 goto out;
2292 }
2293
2294 dontroute =
2295 (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
2296 (so->so_proto->pr_flags & PR_ATOMIC);
2297 if (td != NULL)
2298 td->td_ru.ru_msgsnd++;
2299 if (control != NULL)
2300 clen = control->m_len;
2301
2302 #ifdef KERN_TLS
2303 tls_send_flag = 0;
2304 tls = ktls_hold(so->so_snd.sb_tls_info);
2305 if (tls != NULL) {
2306 if (tls->mode == TCP_TLS_MODE_SW)
2307 tls_send_flag = PRUS_NOTREADY;
2308
2309 if (control != NULL) {
2310 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
2311
2312 if (clen >= sizeof(*cm) &&
2313 cm->cmsg_type == TLS_SET_RECORD_TYPE) {
2314 tls_rtype = *((uint8_t *)CMSG_DATA(cm));
2315 clen = 0;
2316 m_freem(control);
2317 control = NULL;
2318 atomic = 1;
2319 }
2320 }
2321
2322 if (resid == 0 && !ktls_permit_empty_frames(tls)) {
2323 error = EINVAL;
2324 goto out;
2325 }
2326 }
2327 #endif
2328
2329 restart:
2330 do {
2331 SOCKBUF_LOCK(&so->so_snd);
2332 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
2333 SOCKBUF_UNLOCK(&so->so_snd);
2334 error = EPIPE;
2335 goto out;
2336 }
2337 if (so->so_error) {
2338 error = so->so_error;
2339 so->so_error = 0;
2340 SOCKBUF_UNLOCK(&so->so_snd);
2341 goto out;
2342 }
2343 if ((so->so_state & SS_ISCONNECTED) == 0) {
2344 /*
2345 * `sendto' and `sendmsg' is allowed on a connection-
2346 * based socket if it supports implied connect.
2347 * Return ENOTCONN if not connected and no address is
2348 * supplied.
2349 */
2350 if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
2351 (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
2352 if ((so->so_state & SS_ISCONFIRMING) == 0 &&
2353 !(resid == 0 && clen != 0)) {
2354 SOCKBUF_UNLOCK(&so->so_snd);
2355 error = ENOTCONN;
2356 goto out;
2357 }
2358 } else if (addr == NULL) {
2359 SOCKBUF_UNLOCK(&so->so_snd);
2360 if (so->so_proto->pr_flags & PR_CONNREQUIRED)
2361 error = ENOTCONN;
2362 else
2363 error = EDESTADDRREQ;
2364 goto out;
2365 }
2366 }
2367 space = sbspace(&so->so_snd);
2368 if (flags & MSG_OOB)
2369 space += 1024;
2370 if ((atomic && resid > so->so_snd.sb_hiwat) ||
2371 clen > so->so_snd.sb_hiwat) {
2372 SOCKBUF_UNLOCK(&so->so_snd);
2373 error = EMSGSIZE;
2374 goto out;
2375 }
2376 if (space < resid + clen &&
2377 (atomic || space < so->so_snd.sb_lowat || space < clen)) {
2378 if ((so->so_state & SS_NBIO) ||
2379 (flags & (MSG_NBIO | MSG_DONTWAIT)) != 0) {
2380 SOCKBUF_UNLOCK(&so->so_snd);
2381 error = EWOULDBLOCK;
2382 goto out;
2383 }
2384 error = sbwait(so, SO_SND);
2385 SOCKBUF_UNLOCK(&so->so_snd);
2386 if (error)
2387 goto out;
2388 goto restart;
2389 }
2390 SOCKBUF_UNLOCK(&so->so_snd);
2391 space -= clen;
2392 do {
2393 if (uio == NULL) {
2394 resid = 0;
2395 if (flags & MSG_EOR)
2396 top->m_flags |= M_EOR;
2397 #ifdef KERN_TLS
2398 if (tls != NULL) {
2399 ktls_frame(top, tls, &tls_enq_cnt,
2400 tls_rtype);
2401 tls_rtype = TLS_RLTYPE_APP;
2402 }
2403 #endif
2404 } else {
2405 /*
2406 * Copy the data from userland into a mbuf
2407 * chain. If resid is 0, which can happen
2408 * only if we have control to send, then
2409 * a single empty mbuf is returned. This
2410 * is a workaround to prevent protocol send
2411 * methods to panic.
2412 */
2413 #ifdef KERN_TLS
2414 if (tls != NULL) {
2415 top = m_uiotombuf(uio, M_WAITOK, space,
2416 tls->params.max_frame_len,
2417 M_EXTPG |
2418 ((flags & MSG_EOR) ? M_EOR : 0));
2419 if (top != NULL) {
2420 ktls_frame(top, tls,
2421 &tls_enq_cnt, tls_rtype);
2422 }
2423 tls_rtype = TLS_RLTYPE_APP;
2424 } else
2425 #endif
2426 top = m_uiotombuf(uio, M_WAITOK, space,
2427 (atomic ? max_hdr : 0),
2428 (atomic ? M_PKTHDR : 0) |
2429 ((flags & MSG_EOR) ? M_EOR : 0));
2430 if (top == NULL) {
2431 error = EFAULT; /* only possible error */
2432 goto out;
2433 }
2434 space -= resid - uio->uio_resid;
2435 resid = uio->uio_resid;
2436 }
2437 if (dontroute) {
2438 SOCK_LOCK(so);
2439 so->so_options |= SO_DONTROUTE;
2440 SOCK_UNLOCK(so);
2441 }
2442 /*
2443 * XXX all the SBS_CANTSENDMORE checks previously
2444 * done could be out of date. We could have received
2445 * a reset packet in an interrupt or maybe we slept
2446 * while doing page faults in uiomove() etc. We
2447 * could probably recheck again inside the locking
2448 * protection here, but there are probably other
2449 * places that this also happens. We must rethink
2450 * this.
2451 */
2452 VNET_SO_ASSERT(so);
2453
2454 pr_send_flag = (flags & MSG_OOB) ? PRUS_OOB :
2455 /*
2456 * If the user set MSG_EOF, the protocol understands
2457 * this flag and nothing left to send then use
2458 * PRU_SEND_EOF instead of PRU_SEND.
2459 */
2460 ((flags & MSG_EOF) &&
2461 (so->so_proto->pr_flags & PR_IMPLOPCL) &&
2462 (resid <= 0)) ?
2463 PRUS_EOF :
2464 /* If there is more to send set PRUS_MORETOCOME. */
2465 (flags & MSG_MORETOCOME) ||
2466 (resid > 0 && space > 0) ? PRUS_MORETOCOME : 0;
2467
2468 #ifdef KERN_TLS
2469 pr_send_flag |= tls_send_flag;
2470 #endif
2471
2472 error = so->so_proto->pr_send(so, pr_send_flag, top,
2473 addr, control, td);
2474
2475 if (dontroute) {
2476 SOCK_LOCK(so);
2477 so->so_options &= ~SO_DONTROUTE;
2478 SOCK_UNLOCK(so);
2479 }
2480
2481 #ifdef KERN_TLS
2482 if (tls != NULL && tls->mode == TCP_TLS_MODE_SW) {
2483 if (error != 0) {
2484 m_freem(top);
2485 top = NULL;
2486 } else {
2487 soref(so);
2488 ktls_enqueue(top, so, tls_enq_cnt);
2489 }
2490 }
2491 #endif
2492 clen = 0;
2493 control = NULL;
2494 top = NULL;
2495 if (error)
2496 goto out;
2497 } while (resid && space > 0);
2498 } while (resid);
2499
2500 out:
2501 #ifdef KERN_TLS
2502 if (tls != NULL)
2503 ktls_free(tls);
2504 #endif
2505 if (top != NULL)
2506 m_freem(top);
2507 if (control != NULL)
2508 m_freem(control);
2509 return (error);
2510 }
2511
2512 int
2513 sosend_generic(struct socket *so, struct sockaddr *addr, struct uio *uio,
2514 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
2515 {
2516 int error;
2517
2518 error = SOCK_IO_SEND_LOCK(so, SBLOCKWAIT(flags));
2519 if (error)
2520 return (error);
2521 error = sosend_generic_locked(so, addr, uio, top, control, flags, td);
2522 SOCK_IO_SEND_UNLOCK(so);
2523 return (error);
2524 }
2525
2526 /*
2527 * Send to a socket from a kernel thread.
2528 *
2529 * XXXGL: in almost all cases uio is NULL and the mbuf is supplied.
2530 * Exception is nfs/bootp_subr.c. It is arguable that the VNET context needs
2531 * to be set at all. This function should just boil down to a static inline
2532 * calling the protocol method.
2533 */
2534 int
2535 sosend(struct socket *so, struct sockaddr *addr, struct uio *uio,
2536 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
2537 {
2538 int error;
2539
2540 CURVNET_SET(so->so_vnet);
2541 error = so->so_proto->pr_sosend(so, addr, uio,
2542 top, control, flags, td);
2543 CURVNET_RESTORE();
2544 return (error);
2545 }
2546
2547 /*
2548 * send(2), write(2) or aio_write(2) on a socket.
2549 */
2550 int
2551 sousrsend(struct socket *so, struct sockaddr *addr, struct uio *uio,
2552 struct mbuf *control, int flags, struct proc *userproc)
2553 {
2554 struct thread *td;
2555 ssize_t len;
2556 int error;
2557
2558 td = uio->uio_td;
2559 len = uio->uio_resid;
2560 CURVNET_SET(so->so_vnet);
2561 error = so->so_proto->pr_sosend(so, addr, uio, NULL, control, flags,
2562 td);
2563 CURVNET_RESTORE();
2564 if (error != 0) {
2565 /*
2566 * Clear transient errors for stream protocols if they made
2567 * some progress. Make exclusion for aio(4) that would
2568 * schedule a new write in case of EWOULDBLOCK and clear
2569 * error itself. See soaio_process_job().
2570 */
2571 if (uio->uio_resid != len &&
2572 (so->so_proto->pr_flags & PR_ATOMIC) == 0 &&
2573 userproc == NULL &&
2574 (error == ERESTART || error == EINTR ||
2575 error == EWOULDBLOCK))
2576 error = 0;
2577 /* Generation of SIGPIPE can be controlled per socket. */
2578 if (error == EPIPE && (so->so_options & SO_NOSIGPIPE) == 0 &&
2579 (flags & MSG_NOSIGNAL) == 0) {
2580 if (userproc != NULL) {
2581 /* aio(4) job */
2582 PROC_LOCK(userproc);
2583 kern_psignal(userproc, SIGPIPE);
2584 PROC_UNLOCK(userproc);
2585 } else {
2586 PROC_LOCK(td->td_proc);
2587 tdsignal(td, SIGPIPE);
2588 PROC_UNLOCK(td->td_proc);
2589 }
2590 }
2591 }
2592 return (error);
2593 }
2594
2595 /*
2596 * The part of soreceive() that implements reading non-inline out-of-band
2597 * data from a socket. For more complete comments, see soreceive(), from
2598 * which this code originated.
2599 *
2600 * Note that soreceive_rcvoob(), unlike the remainder of soreceive(), is
2601 * unable to return an mbuf chain to the caller.
2602 */
2603 static int
2604 soreceive_rcvoob(struct socket *so, struct uio *uio, int flags)
2605 {
2606 struct protosw *pr = so->so_proto;
2607 struct mbuf *m;
2608 int error;
2609
2610 KASSERT(flags & MSG_OOB, ("soreceive_rcvoob: (flags & MSG_OOB) == 0"));
2611 VNET_SO_ASSERT(so);
2612
2613 m = m_get(M_WAITOK, MT_DATA);
2614 error = pr->pr_rcvoob(so, m, flags & MSG_PEEK);
2615 if (error)
2616 goto bad;
2617 do {
2618 error = uiomove(mtod(m, void *),
2619 (int) min(uio->uio_resid, m->m_len), uio);
2620 m = m_free(m);
2621 } while (uio->uio_resid && error == 0 && m);
2622 bad:
2623 if (m != NULL)
2624 m_freem(m);
2625 return (error);
2626 }
2627
2628 /*
2629 * Following replacement or removal of the first mbuf on the first mbuf chain
2630 * of a socket buffer, push necessary state changes back into the socket
2631 * buffer so that other consumers see the values consistently. 'nextrecord'
2632 * is the callers locally stored value of the original value of
2633 * sb->sb_mb->m_nextpkt which must be restored when the lead mbuf changes.
2634 * NOTE: 'nextrecord' may be NULL.
2635 */
2636 static __inline void
2637 sockbuf_pushsync(struct sockbuf *sb, struct mbuf *nextrecord)
2638 {
2639
2640 SOCKBUF_LOCK_ASSERT(sb);
2641 /*
2642 * First, update for the new value of nextrecord. If necessary, make
2643 * it the first record.
2644 */
2645 if (sb->sb_mb != NULL)
2646 sb->sb_mb->m_nextpkt = nextrecord;
2647 else
2648 sb->sb_mb = nextrecord;
2649
2650 /*
2651 * Now update any dependent socket buffer fields to reflect the new
2652 * state. This is an expanded inline of SB_EMPTY_FIXUP(), with the
2653 * addition of a second clause that takes care of the case where
2654 * sb_mb has been updated, but remains the last record.
2655 */
2656 if (sb->sb_mb == NULL) {
2657 sb->sb_mbtail = NULL;
2658 sb->sb_lastrecord = NULL;
2659 } else if (sb->sb_mb->m_nextpkt == NULL)
2660 sb->sb_lastrecord = sb->sb_mb;
2661 }
2662
2663 /*
2664 * Implement receive operations on a socket. We depend on the way that
2665 * records are added to the sockbuf by sbappend. In particular, each record
2666 * (mbufs linked through m_next) must begin with an address if the protocol
2667 * so specifies, followed by an optional mbuf or mbufs containing ancillary
2668 * data, and then zero or more mbufs of data. In order to allow parallelism
2669 * between network receive and copying to user space, as well as avoid
2670 * sleeping with a mutex held, we release the socket buffer mutex during the
2671 * user space copy. Although the sockbuf is locked, new data may still be
2672 * appended, and thus we must maintain consistency of the sockbuf during that
2673 * time.
2674 *
2675 * The caller may receive the data as a single mbuf chain by supplying an
2676 * mbuf **mp0 for use in returning the chain. The uio is then used only for
2677 * the count in uio_resid.
2678 */
2679 static int
2680 soreceive_generic_locked(struct socket *so, struct sockaddr **psa,
2681 struct uio *uio, struct mbuf **mp, struct mbuf **controlp, int *flagsp)
2682 {
2683 struct mbuf *m;
2684 int flags, error, offset;
2685 ssize_t len;
2686 struct protosw *pr = so->so_proto;
2687 struct mbuf *nextrecord;
2688 int moff, type = 0;
2689 ssize_t orig_resid = uio->uio_resid;
2690 bool report_real_len = false;
2691
2692 SOCK_IO_RECV_ASSERT_LOCKED(so);
2693
2694 error = 0;
2695 if (flagsp != NULL) {
2696 report_real_len = *flagsp & MSG_TRUNC;
2697 *flagsp &= ~MSG_TRUNC;
2698 flags = *flagsp &~ MSG_EOR;
2699 } else
2700 flags = 0;
2701
2702 restart:
2703 SOCKBUF_LOCK(&so->so_rcv);
2704 m = so->so_rcv.sb_mb;
2705 /*
2706 * If we have less data than requested, block awaiting more (subject
2707 * to any timeout) if:
2708 * 1. the current count is less than the low water mark, or
2709 * 2. MSG_DONTWAIT is not set
2710 */
2711 if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
2712 sbavail(&so->so_rcv) < uio->uio_resid) &&
2713 sbavail(&so->so_rcv) < so->so_rcv.sb_lowat &&
2714 m->m_nextpkt == NULL && (pr->pr_flags & PR_ATOMIC) == 0)) {
2715 KASSERT(m != NULL || !sbavail(&so->so_rcv),
2716 ("receive: m == %p sbavail == %u",
2717 m, sbavail(&so->so_rcv)));
2718 if (so->so_error || so->so_rerror) {
2719 if (m != NULL)
2720 goto dontblock;
2721 if (so->so_error)
2722 error = so->so_error;
2723 else
2724 error = so->so_rerror;
2725 if ((flags & MSG_PEEK) == 0) {
2726 if (so->so_error)
2727 so->so_error = 0;
2728 else
2729 so->so_rerror = 0;
2730 }
2731 SOCKBUF_UNLOCK(&so->so_rcv);
2732 goto release;
2733 }
2734 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2735 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
2736 if (m != NULL)
2737 goto dontblock;
2738 #ifdef KERN_TLS
2739 else if (so->so_rcv.sb_tlsdcc == 0 &&
2740 so->so_rcv.sb_tlscc == 0) {
2741 #else
2742 else {
2743 #endif
2744 SOCKBUF_UNLOCK(&so->so_rcv);
2745 goto release;
2746 }
2747 }
2748 for (; m != NULL; m = m->m_next)
2749 if (m->m_type == MT_OOBDATA || (m->m_flags & M_EOR)) {
2750 m = so->so_rcv.sb_mb;
2751 goto dontblock;
2752 }
2753 if ((so->so_state & (SS_ISCONNECTING | SS_ISCONNECTED |
2754 SS_ISDISCONNECTING | SS_ISDISCONNECTED)) == 0 &&
2755 (so->so_proto->pr_flags & PR_CONNREQUIRED) != 0) {
2756 SOCKBUF_UNLOCK(&so->so_rcv);
2757 error = ENOTCONN;
2758 goto release;
2759 }
2760 if (uio->uio_resid == 0 && !report_real_len) {
2761 SOCKBUF_UNLOCK(&so->so_rcv);
2762 goto release;
2763 }
2764 if ((so->so_state & SS_NBIO) ||
2765 (flags & (MSG_DONTWAIT|MSG_NBIO))) {
2766 SOCKBUF_UNLOCK(&so->so_rcv);
2767 error = EWOULDBLOCK;
2768 goto release;
2769 }
2770 SBLASTRECORDCHK(&so->so_rcv);
2771 SBLASTMBUFCHK(&so->so_rcv);
2772 error = sbwait(so, SO_RCV);
2773 SOCKBUF_UNLOCK(&so->so_rcv);
2774 if (error)
2775 goto release;
2776 goto restart;
2777 }
2778 dontblock:
2779 /*
2780 * From this point onward, we maintain 'nextrecord' as a cache of the
2781 * pointer to the next record in the socket buffer. We must keep the
2782 * various socket buffer pointers and local stack versions of the
2783 * pointers in sync, pushing out modifications before dropping the
2784 * socket buffer mutex, and re-reading them when picking it up.
2785 *
2786 * Otherwise, we will race with the network stack appending new data
2787 * or records onto the socket buffer by using inconsistent/stale
2788 * versions of the field, possibly resulting in socket buffer
2789 * corruption.
2790 *
2791 * By holding the high-level sblock(), we prevent simultaneous
2792 * readers from pulling off the front of the socket buffer.
2793 */
2794 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2795 if (uio->uio_td)
2796 uio->uio_td->td_ru.ru_msgrcv++;
2797 KASSERT(m == so->so_rcv.sb_mb, ("soreceive: m != so->so_rcv.sb_mb"));
2798 SBLASTRECORDCHK(&so->so_rcv);
2799 SBLASTMBUFCHK(&so->so_rcv);
2800 nextrecord = m->m_nextpkt;
2801 if (pr->pr_flags & PR_ADDR) {
2802 KASSERT(m->m_type == MT_SONAME,
2803 ("m->m_type == %d", m->m_type));
2804 orig_resid = 0;
2805 if (psa != NULL)
2806 *psa = sodupsockaddr(mtod(m, struct sockaddr *),
2807 M_NOWAIT);
2808 if (flags & MSG_PEEK) {
2809 m = m->m_next;
2810 } else {
2811 sbfree(&so->so_rcv, m);
2812 so->so_rcv.sb_mb = m_free(m);
2813 m = so->so_rcv.sb_mb;
2814 sockbuf_pushsync(&so->so_rcv, nextrecord);
2815 }
2816 }
2817
2818 /*
2819 * Process one or more MT_CONTROL mbufs present before any data mbufs
2820 * in the first mbuf chain on the socket buffer. If MSG_PEEK, we
2821 * just copy the data; if !MSG_PEEK, we call into the protocol to
2822 * perform externalization (or freeing if controlp == NULL).
2823 */
2824 if (m != NULL && m->m_type == MT_CONTROL) {
2825 struct mbuf *cm = NULL, *cmn;
2826 struct mbuf **cme = &cm;
2827 #ifdef KERN_TLS
2828 struct cmsghdr *cmsg;
2829 struct tls_get_record tgr;
2830
2831 /*
2832 * For MSG_TLSAPPDATA, check for an alert record.
2833 * If found, return ENXIO without removing
2834 * it from the receive queue. This allows a subsequent
2835 * call without MSG_TLSAPPDATA to receive it.
2836 * Note that, for TLS, there should only be a single
2837 * control mbuf with the TLS_GET_RECORD message in it.
2838 */
2839 if (flags & MSG_TLSAPPDATA) {
2840 cmsg = mtod(m, struct cmsghdr *);
2841 if (cmsg->cmsg_type == TLS_GET_RECORD &&
2842 cmsg->cmsg_len == CMSG_LEN(sizeof(tgr))) {
2843 memcpy(&tgr, CMSG_DATA(cmsg), sizeof(tgr));
2844 if (__predict_false(tgr.tls_type ==
2845 TLS_RLTYPE_ALERT)) {
2846 SOCKBUF_UNLOCK(&so->so_rcv);
2847 error = ENXIO;
2848 goto release;
2849 }
2850 }
2851 }
2852 #endif
2853
2854 do {
2855 if (flags & MSG_PEEK) {
2856 if (controlp != NULL) {
2857 *controlp = m_copym(m, 0, m->m_len,
2858 M_NOWAIT);
2859 controlp = &(*controlp)->m_next;
2860 }
2861 m = m->m_next;
2862 } else {
2863 sbfree(&so->so_rcv, m);
2864 so->so_rcv.sb_mb = m->m_next;
2865 m->m_next = NULL;
2866 *cme = m;
2867 cme = &(*cme)->m_next;
2868 m = so->so_rcv.sb_mb;
2869 }
2870 } while (m != NULL && m->m_type == MT_CONTROL);
2871 if ((flags & MSG_PEEK) == 0)
2872 sockbuf_pushsync(&so->so_rcv, nextrecord);
2873 while (cm != NULL) {
2874 cmn = cm->m_next;
2875 cm->m_next = NULL;
2876 if (pr->pr_domain->dom_externalize != NULL) {
2877 SOCKBUF_UNLOCK(&so->so_rcv);
2878 VNET_SO_ASSERT(so);
2879 error = (*pr->pr_domain->dom_externalize)
2880 (cm, controlp, flags);
2881 SOCKBUF_LOCK(&so->so_rcv);
2882 } else if (controlp != NULL)
2883 *controlp = cm;
2884 else
2885 m_freem(cm);
2886 if (controlp != NULL) {
2887 while (*controlp != NULL)
2888 controlp = &(*controlp)->m_next;
2889 }
2890 cm = cmn;
2891 }
2892 if (m != NULL)
2893 nextrecord = so->so_rcv.sb_mb->m_nextpkt;
2894 else
2895 nextrecord = so->so_rcv.sb_mb;
2896 orig_resid = 0;
2897 }
2898 if (m != NULL) {
2899 if ((flags & MSG_PEEK) == 0) {
2900 KASSERT(m->m_nextpkt == nextrecord,
2901 ("soreceive: post-control, nextrecord !sync"));
2902 if (nextrecord == NULL) {
2903 KASSERT(so->so_rcv.sb_mb == m,
2904 ("soreceive: post-control, sb_mb!=m"));
2905 KASSERT(so->so_rcv.sb_lastrecord == m,
2906 ("soreceive: post-control, lastrecord!=m"));
2907 }
2908 }
2909 type = m->m_type;
2910 if (type == MT_OOBDATA)
2911 flags |= MSG_OOB;
2912 } else {
2913 if ((flags & MSG_PEEK) == 0) {
2914 KASSERT(so->so_rcv.sb_mb == nextrecord,
2915 ("soreceive: sb_mb != nextrecord"));
2916 if (so->so_rcv.sb_mb == NULL) {
2917 KASSERT(so->so_rcv.sb_lastrecord == NULL,
2918 ("soreceive: sb_lastercord != NULL"));
2919 }
2920 }
2921 }
2922 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2923 SBLASTRECORDCHK(&so->so_rcv);
2924 SBLASTMBUFCHK(&so->so_rcv);
2925
2926 /*
2927 * Now continue to read any data mbufs off of the head of the socket
2928 * buffer until the read request is satisfied. Note that 'type' is
2929 * used to store the type of any mbuf reads that have happened so far
2930 * such that soreceive() can stop reading if the type changes, which
2931 * causes soreceive() to return only one of regular data and inline
2932 * out-of-band data in a single socket receive operation.
2933 */
2934 moff = 0;
2935 offset = 0;
2936 while (m != NULL && !(m->m_flags & M_NOTAVAIL) && uio->uio_resid > 0
2937 && error == 0) {
2938 /*
2939 * If the type of mbuf has changed since the last mbuf
2940 * examined ('type'), end the receive operation.
2941 */
2942 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2943 if (m->m_type == MT_OOBDATA || m->m_type == MT_CONTROL) {
2944 if (type != m->m_type)
2945 break;
2946 } else if (type == MT_OOBDATA)
2947 break;
2948 else
2949 KASSERT(m->m_type == MT_DATA,
2950 ("m->m_type == %d", m->m_type));
2951 so->so_rcv.sb_state &= ~SBS_RCVATMARK;
2952 len = uio->uio_resid;
2953 if (so->so_oobmark && len > so->so_oobmark - offset)
2954 len = so->so_oobmark - offset;
2955 if (len > m->m_len - moff)
2956 len = m->m_len - moff;
2957 /*
2958 * If mp is set, just pass back the mbufs. Otherwise copy
2959 * them out via the uio, then free. Sockbuf must be
2960 * consistent here (points to current mbuf, it points to next
2961 * record) when we drop priority; we must note any additions
2962 * to the sockbuf when we block interrupts again.
2963 */
2964 if (mp == NULL) {
2965 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2966 SBLASTRECORDCHK(&so->so_rcv);
2967 SBLASTMBUFCHK(&so->so_rcv);
2968 SOCKBUF_UNLOCK(&so->so_rcv);
2969 if ((m->m_flags & M_EXTPG) != 0)
2970 error = m_unmapped_uiomove(m, moff, uio,
2971 (int)len);
2972 else
2973 error = uiomove(mtod(m, char *) + moff,
2974 (int)len, uio);
2975 SOCKBUF_LOCK(&so->so_rcv);
2976 if (error) {
2977 /*
2978 * The MT_SONAME mbuf has already been removed
2979 * from the record, so it is necessary to
2980 * remove the data mbufs, if any, to preserve
2981 * the invariant in the case of PR_ADDR that
2982 * requires MT_SONAME mbufs at the head of
2983 * each record.
2984 */
2985 if (pr->pr_flags & PR_ATOMIC &&
2986 ((flags & MSG_PEEK) == 0))
2987 (void)sbdroprecord_locked(&so->so_rcv);
2988 SOCKBUF_UNLOCK(&so->so_rcv);
2989 goto release;
2990 }
2991 } else
2992 uio->uio_resid -= len;
2993 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2994 if (len == m->m_len - moff) {
2995 if (m->m_flags & M_EOR)
2996 flags |= MSG_EOR;
2997 if (flags & MSG_PEEK) {
2998 m = m->m_next;
2999 moff = 0;
3000 } else {
3001 nextrecord = m->m_nextpkt;
3002 sbfree(&so->so_rcv, m);
3003 if (mp != NULL) {
3004 m->m_nextpkt = NULL;
3005 *mp = m;
3006 mp = &m->m_next;
3007 so->so_rcv.sb_mb = m = m->m_next;
3008 *mp = NULL;
3009 } else {
3010 so->so_rcv.sb_mb = m_free(m);
3011 m = so->so_rcv.sb_mb;
3012 }
3013 sockbuf_pushsync(&so->so_rcv, nextrecord);
3014 SBLASTRECORDCHK(&so->so_rcv);
3015 SBLASTMBUFCHK(&so->so_rcv);
3016 }
3017 } else {
3018 if (flags & MSG_PEEK)
3019 moff += len;
3020 else {
3021 if (mp != NULL) {
3022 if (flags & MSG_DONTWAIT) {
3023 *mp = m_copym(m, 0, len,
3024 M_NOWAIT);
3025 if (*mp == NULL) {
3026 /*
3027 * m_copym() couldn't
3028 * allocate an mbuf.
3029 * Adjust uio_resid back
3030 * (it was adjusted
3031 * down by len bytes,
3032 * which we didn't end
3033 * up "copying" over).
3034 */
3035 uio->uio_resid += len;
3036 break;
3037 }
3038 } else {
3039 SOCKBUF_UNLOCK(&so->so_rcv);
3040 *mp = m_copym(m, 0, len,
3041 M_WAITOK);
3042 SOCKBUF_LOCK(&so->so_rcv);
3043 }
3044 }
3045 sbcut_locked(&so->so_rcv, len);
3046 }
3047 }
3048 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
3049 if (so->so_oobmark) {
3050 if ((flags & MSG_PEEK) == 0) {
3051 so->so_oobmark -= len;
3052 if (so->so_oobmark == 0) {
3053 so->so_rcv.sb_state |= SBS_RCVATMARK;
3054 break;
3055 }
3056 } else {
3057 offset += len;
3058 if (offset == so->so_oobmark)
3059 break;
3060 }
3061 }
3062 if (flags & MSG_EOR)
3063 break;
3064 /*
3065 * If the MSG_WAITALL flag is set (for non-atomic socket), we
3066 * must not quit until "uio->uio_resid == 0" or an error
3067 * termination. If a signal/timeout occurs, return with a
3068 * short count but without error. Keep sockbuf locked
3069 * against other readers.
3070 */
3071 while (flags & MSG_WAITALL && m == NULL && uio->uio_resid > 0 &&
3072 !sosendallatonce(so) && nextrecord == NULL) {
3073 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
3074 if (so->so_error || so->so_rerror ||
3075 so->so_rcv.sb_state & SBS_CANTRCVMORE)
3076 break;
3077 /*
3078 * Notify the protocol that some data has been
3079 * drained before blocking.
3080 */
3081 if (pr->pr_flags & PR_WANTRCVD) {
3082 SOCKBUF_UNLOCK(&so->so_rcv);
3083 VNET_SO_ASSERT(so);
3084 pr->pr_rcvd(so, flags);
3085 SOCKBUF_LOCK(&so->so_rcv);
3086 if (__predict_false(so->so_rcv.sb_mb == NULL &&
3087 (so->so_error || so->so_rerror ||
3088 so->so_rcv.sb_state & SBS_CANTRCVMORE)))
3089 break;
3090 }
3091 SBLASTRECORDCHK(&so->so_rcv);
3092 SBLASTMBUFCHK(&so->so_rcv);
3093 /*
3094 * We could receive some data while was notifying
3095 * the protocol. Skip blocking in this case.
3096 */
3097 if (so->so_rcv.sb_mb == NULL) {
3098 error = sbwait(so, SO_RCV);
3099 if (error) {
3100 SOCKBUF_UNLOCK(&so->so_rcv);
3101 goto release;
3102 }
3103 }
3104 m = so->so_rcv.sb_mb;
3105 if (m != NULL)
3106 nextrecord = m->m_nextpkt;
3107 }
3108 }
3109
3110 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
3111 if (m != NULL && pr->pr_flags & PR_ATOMIC) {
3112 if (report_real_len)
3113 uio->uio_resid -= m_length(m, NULL) - moff;
3114 flags |= MSG_TRUNC;
3115 if ((flags & MSG_PEEK) == 0)
3116 (void) sbdroprecord_locked(&so->so_rcv);
3117 }
3118 if ((flags & MSG_PEEK) == 0) {
3119 if (m == NULL) {
3120 /*
3121 * First part is an inline SB_EMPTY_FIXUP(). Second
3122 * part makes sure sb_lastrecord is up-to-date if
3123 * there is still data in the socket buffer.
3124 */
3125 so->so_rcv.sb_mb = nextrecord;
3126 if (so->so_rcv.sb_mb == NULL) {
3127 so->so_rcv.sb_mbtail = NULL;
3128 so->so_rcv.sb_lastrecord = NULL;
3129 } else if (nextrecord->m_nextpkt == NULL)
3130 so->so_rcv.sb_lastrecord = nextrecord;
3131 }
3132 SBLASTRECORDCHK(&so->so_rcv);
3133 SBLASTMBUFCHK(&so->so_rcv);
3134 /*
3135 * If soreceive() is being done from the socket callback,
3136 * then don't need to generate ACK to peer to update window,
3137 * since ACK will be generated on return to TCP.
3138 */
3139 if (!(flags & MSG_SOCALLBCK) &&
3140 (pr->pr_flags & PR_WANTRCVD)) {
3141 SOCKBUF_UNLOCK(&so->so_rcv);
3142 VNET_SO_ASSERT(so);
3143 pr->pr_rcvd(so, flags);
3144 SOCKBUF_LOCK(&so->so_rcv);
3145 }
3146 }
3147 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
3148 if (orig_resid == uio->uio_resid && orig_resid &&
3149 (flags & MSG_EOR) == 0 && (so->so_rcv.sb_state & SBS_CANTRCVMORE) == 0) {
3150 SOCKBUF_UNLOCK(&so->so_rcv);
3151 goto restart;
3152 }
3153 SOCKBUF_UNLOCK(&so->so_rcv);
3154
3155 if (flagsp != NULL)
3156 *flagsp |= flags;
3157 release:
3158 return (error);
3159 }
3160
3161 int
3162 soreceive_generic(struct socket *so, struct sockaddr **psa, struct uio *uio,
3163 struct mbuf **mp, struct mbuf **controlp, int *flagsp)
3164 {
3165 int error, flags;
3166
3167 if (psa != NULL)
3168 *psa = NULL;
3169 if (controlp != NULL)
3170 *controlp = NULL;
3171 if (flagsp != NULL) {
3172 flags = *flagsp;
3173 if ((flags & MSG_OOB) != 0)
3174 return (soreceive_rcvoob(so, uio, flags));
3175 } else {
3176 flags = 0;
3177 }
3178 if (mp != NULL)
3179 *mp = NULL;
3180 if ((so->so_proto->pr_flags & PR_WANTRCVD) &&
3181 (so->so_state & SS_ISCONFIRMING) && uio->uio_resid) {
3182 VNET_SO_ASSERT(so);
3183 so->so_proto->pr_rcvd(so, 0);
3184 }
3185
3186 error = SOCK_IO_RECV_LOCK(so, SBLOCKWAIT(flags));
3187 if (error)
3188 return (error);
3189 error = soreceive_generic_locked(so, psa, uio, mp, controlp, flagsp);
3190 SOCK_IO_RECV_UNLOCK(so);
3191 return (error);
3192 }
3193
3194 /*
3195 * Optimized version of soreceive() for stream (TCP) sockets.
3196 */
3197 static int
3198 soreceive_stream_locked(struct socket *so, struct sockbuf *sb,
3199 struct sockaddr **psa, struct uio *uio, struct mbuf **mp0,
3200 struct mbuf **controlp, int flags)
3201 {
3202 int len = 0, error = 0, oresid;
3203 struct mbuf *m, *n = NULL;
3204
3205 SOCK_IO_RECV_ASSERT_LOCKED(so);
3206
3207 /* Easy one, no space to copyout anything. */
3208 if (uio->uio_resid == 0)
3209 return (EINVAL);
3210 oresid = uio->uio_resid;
3211
3212 SOCKBUF_LOCK(sb);
3213 /* We will never ever get anything unless we are or were connected. */
3214 if (!(so->so_state & (SS_ISCONNECTED|SS_ISDISCONNECTED))) {
3215 error = ENOTCONN;
3216 goto out;
3217 }
3218
3219 restart:
3220 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
3221
3222 /* Abort if socket has reported problems. */
3223 if (so->so_error) {
3224 if (sbavail(sb) > 0)
3225 goto deliver;
3226 if (oresid > uio->uio_resid)
3227 goto out;
3228 error = so->so_error;
3229 if (!(flags & MSG_PEEK))
3230 so->so_error = 0;
3231 goto out;
3232 }
3233
3234 /* Door is closed. Deliver what is left, if any. */
3235 if (sb->sb_state & SBS_CANTRCVMORE) {
3236 if (sbavail(sb) > 0)
3237 goto deliver;
3238 else
3239 goto out;
3240 }
3241
3242 /* Socket buffer is empty and we shall not block. */
3243 if (sbavail(sb) == 0 &&
3244 ((so->so_state & SS_NBIO) || (flags & (MSG_DONTWAIT|MSG_NBIO)))) {
3245 error = EAGAIN;
3246 goto out;
3247 }
3248
3249 /* Socket buffer got some data that we shall deliver now. */
3250 if (sbavail(sb) > 0 && !(flags & MSG_WAITALL) &&
3251 ((so->so_state & SS_NBIO) ||
3252 (flags & (MSG_DONTWAIT|MSG_NBIO)) ||
3253 sbavail(sb) >= sb->sb_lowat ||
3254 sbavail(sb) >= uio->uio_resid ||
3255 sbavail(sb) >= sb->sb_hiwat) ) {
3256 goto deliver;
3257 }
3258
3259 /* On MSG_WAITALL we must wait until all data or error arrives. */
3260 if ((flags & MSG_WAITALL) &&
3261 (sbavail(sb) >= uio->uio_resid || sbavail(sb) >= sb->sb_hiwat))
3262 goto deliver;
3263
3264 /*
3265 * Wait and block until (more) data comes in.
3266 * NB: Drops the sockbuf lock during wait.
3267 */
3268 error = sbwait(so, SO_RCV);
3269 if (error)
3270 goto out;
3271 goto restart;
3272
3273 deliver:
3274 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
3275 KASSERT(sbavail(sb) > 0, ("%s: sockbuf empty", __func__));
3276 KASSERT(sb->sb_mb != NULL, ("%s: sb_mb == NULL", __func__));
3277
3278 /* Statistics. */
3279 if (uio->uio_td)
3280 uio->uio_td->td_ru.ru_msgrcv++;
3281
3282 /* Fill uio until full or current end of socket buffer is reached. */
3283 len = min(uio->uio_resid, sbavail(sb));
3284 if (mp0 != NULL) {
3285 /* Dequeue as many mbufs as possible. */
3286 if (!(flags & MSG_PEEK) && len >= sb->sb_mb->m_len) {
3287 if (*mp0 == NULL)
3288 *mp0 = sb->sb_mb;
3289 else
3290 m_cat(*mp0, sb->sb_mb);
3291 for (m = sb->sb_mb;
3292 m != NULL && m->m_len <= len;
3293 m = m->m_next) {
3294 KASSERT(!(m->m_flags & M_NOTAVAIL),
3295 ("%s: m %p not available", __func__, m));
3296 len -= m->m_len;
3297 uio->uio_resid -= m->m_len;
3298 sbfree(sb, m);
3299 n = m;
3300 }
3301 n->m_next = NULL;
3302 sb->sb_mb = m;
3303 sb->sb_lastrecord = sb->sb_mb;
3304 if (sb->sb_mb == NULL)
3305 SB_EMPTY_FIXUP(sb);
3306 }
3307 /* Copy the remainder. */
3308 if (len > 0) {
3309 KASSERT(sb->sb_mb != NULL,
3310 ("%s: len > 0 && sb->sb_mb empty", __func__));
3311
3312 m = m_copym(sb->sb_mb, 0, len, M_NOWAIT);
3313 if (m == NULL)
3314 len = 0; /* Don't flush data from sockbuf. */
3315 else
3316 uio->uio_resid -= len;
3317 if (*mp0 != NULL)
3318 m_cat(*mp0, m);
3319 else
3320 *mp0 = m;
3321 if (*mp0 == NULL) {
3322 error = ENOBUFS;
3323 goto out;
3324 }
3325 }
3326 } else {
3327 /* NB: Must unlock socket buffer as uiomove may sleep. */
3328 SOCKBUF_UNLOCK(sb);
3329 error = m_mbuftouio(uio, sb->sb_mb, len);
3330 SOCKBUF_LOCK(sb);
3331 if (error)
3332 goto out;
3333 }
3334 SBLASTRECORDCHK(sb);
3335 SBLASTMBUFCHK(sb);
3336
3337 /*
3338 * Remove the delivered data from the socket buffer unless we
3339 * were only peeking.
3340 */
3341 if (!(flags & MSG_PEEK)) {
3342 if (len > 0)
3343 sbdrop_locked(sb, len);
3344
3345 /* Notify protocol that we drained some data. */
3346 if ((so->so_proto->pr_flags & PR_WANTRCVD) &&
3347 (((flags & MSG_WAITALL) && uio->uio_resid > 0) ||
3348 !(flags & MSG_SOCALLBCK))) {
3349 SOCKBUF_UNLOCK(sb);
3350 VNET_SO_ASSERT(so);
3351 so->so_proto->pr_rcvd(so, flags);
3352 SOCKBUF_LOCK(sb);
3353 }
3354 }
3355
3356 /*
3357 * For MSG_WAITALL we may have to loop again and wait for
3358 * more data to come in.
3359 */
3360 if ((flags & MSG_WAITALL) && uio->uio_resid > 0)
3361 goto restart;
3362 out:
3363 SBLASTRECORDCHK(sb);
3364 SBLASTMBUFCHK(sb);
3365 SOCKBUF_UNLOCK(sb);
3366 return (error);
3367 }
3368
3369 int
3370 soreceive_stream(struct socket *so, struct sockaddr **psa, struct uio *uio,
3371 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
3372 {
3373 struct sockbuf *sb;
3374 int error, flags;
3375
3376 sb = &so->so_rcv;
3377
3378 /* We only do stream sockets. */
3379 if (so->so_type != SOCK_STREAM)
3380 return (EINVAL);
3381 if (psa != NULL)
3382 *psa = NULL;
3383 if (flagsp != NULL)
3384 flags = *flagsp & ~MSG_EOR;
3385 else
3386 flags = 0;
3387 if (controlp != NULL)
3388 *controlp = NULL;
3389 if (flags & MSG_OOB)
3390 return (soreceive_rcvoob(so, uio, flags));
3391 if (mp0 != NULL)
3392 *mp0 = NULL;
3393
3394 #ifdef KERN_TLS
3395 /*
3396 * KTLS store TLS records as records with a control message to
3397 * describe the framing.
3398 *
3399 * We check once here before acquiring locks to optimize the
3400 * common case.
3401 */
3402 if (sb->sb_tls_info != NULL)
3403 return (soreceive_generic(so, psa, uio, mp0, controlp,
3404 flagsp));
3405 #endif
3406
3407 /*
3408 * Prevent other threads from reading from the socket. This lock may be
3409 * dropped in order to sleep waiting for data to arrive.
3410 */
3411 error = SOCK_IO_RECV_LOCK(so, SBLOCKWAIT(flags));
3412 if (error)
3413 return (error);
3414 #ifdef KERN_TLS
3415 if (__predict_false(sb->sb_tls_info != NULL)) {
3416 SOCK_IO_RECV_UNLOCK(so);
3417 return (soreceive_generic(so, psa, uio, mp0, controlp,
3418 flagsp));
3419 }
3420 #endif
3421 error = soreceive_stream_locked(so, sb, psa, uio, mp0, controlp, flags);
3422 SOCK_IO_RECV_UNLOCK(so);
3423 return (error);
3424 }
3425
3426 /*
3427 * Optimized version of soreceive() for simple datagram cases from userspace.
3428 * Unlike in the stream case, we're able to drop a datagram if copyout()
3429 * fails, and because we handle datagrams atomically, we don't need to use a
3430 * sleep lock to prevent I/O interlacing.
3431 */
3432 int
3433 soreceive_dgram(struct socket *so, struct sockaddr **psa, struct uio *uio,
3434 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
3435 {
3436 struct mbuf *m, *m2;
3437 int flags, error;
3438 ssize_t len;
3439 struct protosw *pr = so->so_proto;
3440 struct mbuf *nextrecord;
3441
3442 if (psa != NULL)
3443 *psa = NULL;
3444 if (controlp != NULL)
3445 *controlp = NULL;
3446 if (flagsp != NULL)
3447 flags = *flagsp &~ MSG_EOR;
3448 else
3449 flags = 0;
3450
3451 /*
3452 * For any complicated cases, fall back to the full
3453 * soreceive_generic().
3454 */
3455 if (mp0 != NULL || (flags & (MSG_PEEK | MSG_OOB | MSG_TRUNC)))
3456 return (soreceive_generic(so, psa, uio, mp0, controlp,
3457 flagsp));
3458
3459 /*
3460 * Enforce restrictions on use.
3461 */
3462 KASSERT((pr->pr_flags & PR_WANTRCVD) == 0,
3463 ("soreceive_dgram: wantrcvd"));
3464 KASSERT(pr->pr_flags & PR_ATOMIC, ("soreceive_dgram: !atomic"));
3465 KASSERT((so->so_rcv.sb_state & SBS_RCVATMARK) == 0,
3466 ("soreceive_dgram: SBS_RCVATMARK"));
3467 KASSERT((so->so_proto->pr_flags & PR_CONNREQUIRED) == 0,
3468 ("soreceive_dgram: P_CONNREQUIRED"));
3469
3470 /*
3471 * Loop blocking while waiting for a datagram.
3472 */
3473 SOCKBUF_LOCK(&so->so_rcv);
3474 while ((m = so->so_rcv.sb_mb) == NULL) {
3475 KASSERT(sbavail(&so->so_rcv) == 0,
3476 ("soreceive_dgram: sb_mb NULL but sbavail %u",
3477 sbavail(&so->so_rcv)));
3478 if (so->so_error) {
3479 error = so->so_error;
3480 so->so_error = 0;
3481 SOCKBUF_UNLOCK(&so->so_rcv);
3482 return (error);
3483 }
3484 if (so->so_rcv.sb_state & SBS_CANTRCVMORE ||
3485 uio->uio_resid == 0) {
3486 SOCKBUF_UNLOCK(&so->so_rcv);
3487 return (0);
3488 }
3489 if ((so->so_state & SS_NBIO) ||
3490 (flags & (MSG_DONTWAIT|MSG_NBIO))) {
3491 SOCKBUF_UNLOCK(&so->so_rcv);
3492 return (EWOULDBLOCK);
3493 }
3494 SBLASTRECORDCHK(&so->so_rcv);
3495 SBLASTMBUFCHK(&so->so_rcv);
3496 error = sbwait(so, SO_RCV);
3497 if (error) {
3498 SOCKBUF_UNLOCK(&so->so_rcv);
3499 return (error);
3500 }
3501 }
3502 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
3503
3504 if (uio->uio_td)
3505 uio->uio_td->td_ru.ru_msgrcv++;
3506 SBLASTRECORDCHK(&so->so_rcv);
3507 SBLASTMBUFCHK(&so->so_rcv);
3508 nextrecord = m->m_nextpkt;
3509 if (nextrecord == NULL) {
3510 KASSERT(so->so_rcv.sb_lastrecord == m,
3511 ("soreceive_dgram: lastrecord != m"));
3512 }
3513
3514 KASSERT(so->so_rcv.sb_mb->m_nextpkt == nextrecord,
3515 ("soreceive_dgram: m_nextpkt != nextrecord"));
3516
3517 /*
3518 * Pull 'm' and its chain off the front of the packet queue.
3519 */
3520 so->so_rcv.sb_mb = NULL;
3521 sockbuf_pushsync(&so->so_rcv, nextrecord);
3522
3523 /*
3524 * Walk 'm's chain and free that many bytes from the socket buffer.
3525 */
3526 for (m2 = m; m2 != NULL; m2 = m2->m_next)
3527 sbfree(&so->so_rcv, m2);
3528
3529 /*
3530 * Do a few last checks before we let go of the lock.
3531 */
3532 SBLASTRECORDCHK(&so->so_rcv);
3533 SBLASTMBUFCHK(&so->so_rcv);
3534 SOCKBUF_UNLOCK(&so->so_rcv);
3535
3536 if (pr->pr_flags & PR_ADDR) {
3537 KASSERT(m->m_type == MT_SONAME,
3538 ("m->m_type == %d", m->m_type));
3539 if (psa != NULL)
3540 *psa = sodupsockaddr(mtod(m, struct sockaddr *),
3541 M_NOWAIT);
3542 m = m_free(m);
3543 }
3544 if (m == NULL) {
3545 /* XXXRW: Can this happen? */
3546 return (0);
3547 }
3548
3549 /*
3550 * Packet to copyout() is now in 'm' and it is disconnected from the
3551 * queue.
3552 *
3553 * Process one or more MT_CONTROL mbufs present before any data mbufs
3554 * in the first mbuf chain on the socket buffer. We call into the
3555 * protocol to perform externalization (or freeing if controlp ==
3556 * NULL). In some cases there can be only MT_CONTROL mbufs without
3557 * MT_DATA mbufs.
3558 */
3559 if (m->m_type == MT_CONTROL) {
3560 struct mbuf *cm = NULL, *cmn;
3561 struct mbuf **cme = &cm;
3562
3563 do {
3564 m2 = m->m_next;
3565 m->m_next = NULL;
3566 *cme = m;
3567 cme = &(*cme)->m_next;
3568 m = m2;
3569 } while (m != NULL && m->m_type == MT_CONTROL);
3570 while (cm != NULL) {
3571 cmn = cm->m_next;
3572 cm->m_next = NULL;
3573 if (pr->pr_domain->dom_externalize != NULL) {
3574 error = (*pr->pr_domain->dom_externalize)
3575 (cm, controlp, flags);
3576 } else if (controlp != NULL)
3577 *controlp = cm;
3578 else
3579 m_freem(cm);
3580 if (controlp != NULL) {
3581 while (*controlp != NULL)
3582 controlp = &(*controlp)->m_next;
3583 }
3584 cm = cmn;
3585 }
3586 }
3587 KASSERT(m == NULL || m->m_type == MT_DATA,
3588 ("soreceive_dgram: !data"));
3589 while (m != NULL && uio->uio_resid > 0) {
3590 len = uio->uio_resid;
3591 if (len > m->m_len)
3592 len = m->m_len;
3593 error = uiomove(mtod(m, char *), (int)len, uio);
3594 if (error) {
3595 m_freem(m);
3596 return (error);
3597 }
3598 if (len == m->m_len)
3599 m = m_free(m);
3600 else {
3601 m->m_data += len;
3602 m->m_len -= len;
3603 }
3604 }
3605 if (m != NULL) {
3606 flags |= MSG_TRUNC;
3607 m_freem(m);
3608 }
3609 if (flagsp != NULL)
3610 *flagsp |= flags;
3611 return (0);
3612 }
3613
3614 int
3615 soreceive(struct socket *so, struct sockaddr **psa, struct uio *uio,
3616 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
3617 {
3618 int error;
3619
3620 CURVNET_SET(so->so_vnet);
3621 error = so->so_proto->pr_soreceive(so, psa, uio, mp0, controlp, flagsp);
3622 CURVNET_RESTORE();
3623 return (error);
3624 }
3625
3626 int
3627 soshutdown(struct socket *so, int how)
3628 {
3629 struct protosw *pr;
3630 int error, soerror_enotconn;
3631
3632 if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
3633 return (EINVAL);
3634
3635 soerror_enotconn = 0;
3636 SOCK_LOCK(so);
3637 if ((so->so_state &
3638 (SS_ISCONNECTED | SS_ISCONNECTING | SS_ISDISCONNECTING)) == 0) {
3639 /*
3640 * POSIX mandates us to return ENOTCONN when shutdown(2) is
3641 * invoked on a datagram sockets, however historically we would
3642 * actually tear socket down. This is known to be leveraged by
3643 * some applications to unblock process waiting in recvXXX(2)
3644 * by other process that it shares that socket with. Try to meet
3645 * both backward-compatibility and POSIX requirements by forcing
3646 * ENOTCONN but still asking protocol to perform pru_shutdown().
3647 */
3648 if (so->so_type != SOCK_DGRAM && !SOLISTENING(so)) {
3649 SOCK_UNLOCK(so);
3650 return (ENOTCONN);
3651 }
3652 soerror_enotconn = 1;
3653 }
3654
3655 if (SOLISTENING(so)) {
3656 if (how != SHUT_WR) {
3657 so->so_error = ECONNABORTED;
3658 solisten_wakeup(so); /* unlocks so */
3659 } else {
3660 SOCK_UNLOCK(so);
3661 }
3662 goto done;
3663 }
3664 SOCK_UNLOCK(so);
3665
3666 CURVNET_SET(so->so_vnet);
3667 pr = so->so_proto;
3668 if (pr->pr_flush != NULL)
3669 pr->pr_flush(so, how);
3670 if (how != SHUT_WR)
3671 sorflush(so);
3672 if (how != SHUT_RD) {
3673 error = pr->pr_shutdown(so);
3674 wakeup(&so->so_timeo);
3675 CURVNET_RESTORE();
3676 return ((error == 0 && soerror_enotconn) ? ENOTCONN : error);
3677 }
3678 wakeup(&so->so_timeo);
3679 CURVNET_RESTORE();
3680
3681 done:
3682 return (soerror_enotconn ? ENOTCONN : 0);
3683 }
3684
3685 void
3686 sorflush(struct socket *so)
3687 {
3688 struct protosw *pr;
3689 int error;
3690
3691 VNET_SO_ASSERT(so);
3692
3693 /*
3694 * Dislodge threads currently blocked in receive and wait to acquire
3695 * a lock against other simultaneous readers before clearing the
3696 * socket buffer. Don't let our acquire be interrupted by a signal
3697 * despite any existing socket disposition on interruptable waiting.
3698 */
3699 socantrcvmore(so);
3700
3701 error = SOCK_IO_RECV_LOCK(so, SBL_WAIT | SBL_NOINTR);
3702 if (error != 0) {
3703 KASSERT(SOLISTENING(so),
3704 ("%s: soiolock(%p) failed", __func__, so));
3705 return;
3706 }
3707
3708 pr = so->so_proto;
3709 if (pr->pr_flags & PR_RIGHTS) {
3710 MPASS(pr->pr_domain->dom_dispose != NULL);
3711 (*pr->pr_domain->dom_dispose)(so);
3712 } else {
3713 sbrelease(so, SO_RCV);
3714 SOCK_IO_RECV_UNLOCK(so);
3715 }
3716
3717 }
3718
3719 int
3720 sosetfib(struct socket *so, int fibnum)
3721 {
3722 if (fibnum < 0 || fibnum >= rt_numfibs)
3723 return (EINVAL);
3724
3725 SOCK_LOCK(so);
3726 so->so_fibnum = fibnum;
3727 SOCK_UNLOCK(so);
3728
3729 return (0);
3730 }
3731
3732 /*
3733 * Wrapper for Socket established helper hook.
3734 * Parameters: socket, context of the hook point, hook id.
3735 */
3736 static int inline
3737 hhook_run_socket(struct socket *so, void *hctx, int32_t h_id)
3738 {
3739 struct socket_hhook_data hhook_data = {
3740 .so = so,
3741 .hctx = hctx,
3742 .m = NULL,
3743 .status = 0
3744 };
3745
3746 CURVNET_SET(so->so_vnet);
3747 HHOOKS_RUN_IF(V_socket_hhh[h_id], &hhook_data, &so->osd);
3748 CURVNET_RESTORE();
3749
3750 /* Ugly but needed, since hhooks return void for now */
3751 return (hhook_data.status);
3752 }
3753
3754 /*
3755 * Perhaps this routine, and sooptcopyout(), below, ought to come in an
3756 * additional variant to handle the case where the option value needs to be
3757 * some kind of integer, but not a specific size. In addition to their use
3758 * here, these functions are also called by the protocol-level pr_ctloutput()
3759 * routines.
3760 */
3761 int
3762 sooptcopyin(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
3763 {
3764 size_t valsize;
3765
3766 /*
3767 * If the user gives us more than we wanted, we ignore it, but if we
3768 * don't get the minimum length the caller wants, we return EINVAL.
3769 * On success, sopt->sopt_valsize is set to however much we actually
3770 * retrieved.
3771 */
3772 if ((valsize = sopt->sopt_valsize) < minlen)
3773 return EINVAL;
3774 if (valsize > len)
3775 sopt->sopt_valsize = valsize = len;
3776
3777 if (sopt->sopt_td != NULL)
3778 return (copyin(sopt->sopt_val, buf, valsize));
3779
3780 bcopy(sopt->sopt_val, buf, valsize);
3781 return (0);
3782 }
3783
3784 /*
3785 * Kernel version of setsockopt(2).
3786 *
3787 * XXX: optlen is size_t, not socklen_t
3788 */
3789 int
3790 so_setsockopt(struct socket *so, int level, int optname, void *optval,
3791 size_t optlen)
3792 {
3793 struct sockopt sopt;
3794
3795 sopt.sopt_level = level;
3796 sopt.sopt_name = optname;
3797 sopt.sopt_dir = SOPT_SET;
3798 sopt.sopt_val = optval;
3799 sopt.sopt_valsize = optlen;
3800 sopt.sopt_td = NULL;
3801 return (sosetopt(so, &sopt));
3802 }
3803
3804 int
3805 sosetopt(struct socket *so, struct sockopt *sopt)
3806 {
3807 int error, optval;
3808 struct linger l;
3809 struct timeval tv;
3810 sbintime_t val, *valp;
3811 uint32_t val32;
3812 #ifdef MAC
3813 struct mac extmac;
3814 #endif
3815
3816 CURVNET_SET(so->so_vnet);
3817 error = 0;
3818 if (sopt->sopt_level != SOL_SOCKET) {
3819 error = (*so->so_proto->pr_ctloutput)(so, sopt);
3820 } else {
3821 switch (sopt->sopt_name) {
3822 case SO_ACCEPTFILTER:
3823 error = accept_filt_setopt(so, sopt);
3824 if (error)
3825 goto bad;
3826 break;
3827
3828 case SO_LINGER:
3829 error = sooptcopyin(sopt, &l, sizeof l, sizeof l);
3830 if (error)
3831 goto bad;
3832 if (l.l_linger < 0 ||
3833 l.l_linger > USHRT_MAX ||
3834 l.l_linger > (INT_MAX / hz)) {
3835 error = EDOM;
3836 goto bad;
3837 }
3838 SOCK_LOCK(so);
3839 so->so_linger = l.l_linger;
3840 if (l.l_onoff)
3841 so->so_options |= SO_LINGER;
3842 else
3843 so->so_options &= ~SO_LINGER;
3844 SOCK_UNLOCK(so);
3845 break;
3846
3847 case SO_DEBUG:
3848 case SO_KEEPALIVE:
3849 case SO_DONTROUTE:
3850 case SO_USELOOPBACK:
3851 case SO_BROADCAST:
3852 case SO_REUSEADDR:
3853 case SO_REUSEPORT:
3854 case SO_REUSEPORT_LB:
3855 case SO_OOBINLINE:
3856 case SO_TIMESTAMP:
3857 case SO_BINTIME:
3858 case SO_NOSIGPIPE:
3859 case SO_NO_DDP:
3860 case SO_NO_OFFLOAD:
3861 case SO_RERROR:
3862 error = sooptcopyin(sopt, &optval, sizeof optval,
3863 sizeof optval);
3864 if (error)
3865 goto bad;
3866 SOCK_LOCK(so);
3867 if (optval)
3868 so->so_options |= sopt->sopt_name;
3869 else
3870 so->so_options &= ~sopt->sopt_name;
3871 SOCK_UNLOCK(so);
3872 break;
3873
3874 case SO_SETFIB:
3875 error = so->so_proto->pr_ctloutput(so, sopt);
3876 break;
3877
3878 case SO_USER_COOKIE:
3879 error = sooptcopyin(sopt, &val32, sizeof val32,
3880 sizeof val32);
3881 if (error)
3882 goto bad;
3883 so->so_user_cookie = val32;
3884 break;
3885
3886 case SO_SNDBUF:
3887 case SO_RCVBUF:
3888 case SO_SNDLOWAT:
3889 case SO_RCVLOWAT:
3890 error = so->so_proto->pr_setsbopt(so, sopt);
3891 if (error)
3892 goto bad;
3893 break;
3894
3895 case SO_SNDTIMEO:
3896 case SO_RCVTIMEO:
3897 #ifdef COMPAT_FREEBSD32
3898 if (SV_CURPROC_FLAG(SV_ILP32)) {
3899 struct timeval32 tv32;
3900
3901 error = sooptcopyin(sopt, &tv32, sizeof tv32,
3902 sizeof tv32);
3903 CP(tv32, tv, tv_sec);
3904 CP(tv32, tv, tv_usec);
3905 } else
3906 #endif
3907 error = sooptcopyin(sopt, &tv, sizeof tv,
3908 sizeof tv);
3909 if (error)
3910 goto bad;
3911 if (tv.tv_sec < 0 || tv.tv_usec < 0 ||
3912 tv.tv_usec >= 1000000) {
3913 error = EDOM;
3914 goto bad;
3915 }
3916 if (tv.tv_sec > INT32_MAX)
3917 val = SBT_MAX;
3918 else
3919 val = tvtosbt(tv);
3920 SOCK_LOCK(so);
3921 valp = sopt->sopt_name == SO_SNDTIMEO ?
3922 (SOLISTENING(so) ? &so->sol_sbsnd_timeo :
3923 &so->so_snd.sb_timeo) :
3924 (SOLISTENING(so) ? &so->sol_sbrcv_timeo :
3925 &so->so_rcv.sb_timeo);
3926 *valp = val;
3927 SOCK_UNLOCK(so);
3928 break;
3929
3930 case SO_LABEL:
3931 #ifdef MAC
3932 error = sooptcopyin(sopt, &extmac, sizeof extmac,
3933 sizeof extmac);
3934 if (error)
3935 goto bad;
3936 error = mac_setsockopt_label(sopt->sopt_td->td_ucred,
3937 so, &extmac);
3938 #else
3939 error = EOPNOTSUPP;
3940 #endif
3941 break;
3942
3943 case SO_TS_CLOCK:
3944 error = sooptcopyin(sopt, &optval, sizeof optval,
3945 sizeof optval);
3946 if (error)
3947 goto bad;
3948 if (optval < 0 || optval > SO_TS_CLOCK_MAX) {
3949 error = EINVAL;
3950 goto bad;
3951 }
3952 so->so_ts_clock = optval;
3953 break;
3954
3955 case SO_MAX_PACING_RATE:
3956 error = sooptcopyin(sopt, &val32, sizeof(val32),
3957 sizeof(val32));
3958 if (error)
3959 goto bad;
3960 so->so_max_pacing_rate = val32;
3961 break;
3962
3963 case SO_SPLICE: {
3964 struct splice splice;
3965
3966 #ifdef COMPAT_FREEBSD32
3967 if (SV_CURPROC_FLAG(SV_ILP32)) {
3968 struct splice32 splice32;
3969
3970 error = sooptcopyin(sopt, &splice32,
3971 sizeof(splice32), sizeof(splice32));
3972 if (error == 0) {
3973 splice.sp_fd = splice32.sp_fd;
3974 splice.sp_max = splice32.sp_max;
3975 CP(splice32.sp_idle, splice.sp_idle,
3976 tv_sec);
3977 CP(splice32.sp_idle, splice.sp_idle,
3978 tv_usec);
3979 }
3980 } else
3981 #endif
3982 {
3983 error = sooptcopyin(sopt, &splice,
3984 sizeof(splice), sizeof(splice));
3985 }
3986 if (error)
3987 goto bad;
3988 #ifdef KTRACE
3989 if (KTRPOINT(curthread, KTR_STRUCT))
3990 ktrsplice(&splice);
3991 #endif
3992
3993 error = splice_init();
3994 if (error != 0)
3995 goto bad;
3996
3997 if (splice.sp_fd >= 0) {
3998 struct file *fp;
3999 struct socket *so2;
4000
4001 if (!cap_rights_contains(sopt->sopt_rights,
4002 &cap_recv_rights)) {
4003 error = ENOTCAPABLE;
4004 goto bad;
4005 }
4006 error = getsock(sopt->sopt_td, splice.sp_fd,
4007 &cap_send_rights, &fp);
4008 if (error != 0)
4009 goto bad;
4010 so2 = fp->f_data;
4011
4012 error = so_splice(so, so2, &splice);
4013 fdrop(fp, sopt->sopt_td);
4014 } else {
4015 error = so_unsplice(so, false);
4016 }
4017 break;
4018 }
4019 default:
4020 if (V_socket_hhh[HHOOK_SOCKET_OPT]->hhh_nhooks > 0)
4021 error = hhook_run_socket(so, sopt,
4022 HHOOK_SOCKET_OPT);
4023 else
4024 error = ENOPROTOOPT;
4025 break;
4026 }
4027 if (error == 0)
4028 (void)(*so->so_proto->pr_ctloutput)(so, sopt);
4029 }
4030 bad:
4031 CURVNET_RESTORE();
4032 return (error);
4033 }
4034
4035 /*
4036 * Helper routine for getsockopt.
4037 */
4038 int
4039 sooptcopyout(struct sockopt *sopt, const void *buf, size_t len)
4040 {
4041 int error;
4042 size_t valsize;
4043
4044 error = 0;
4045
4046 /*
4047 * Documented get behavior is that we always return a value, possibly
4048 * truncated to fit in the user's buffer. Traditional behavior is
4049 * that we always tell the user precisely how much we copied, rather
4050 * than something useful like the total amount we had available for
4051 * her. Note that this interface is not idempotent; the entire
4052 * answer must be generated ahead of time.
4053 */
4054 valsize = min(len, sopt->sopt_valsize);
4055 sopt->sopt_valsize = valsize;
4056 if (sopt->sopt_val != NULL) {
4057 if (sopt->sopt_td != NULL)
4058 error = copyout(buf, sopt->sopt_val, valsize);
4059 else
4060 bcopy(buf, sopt->sopt_val, valsize);
4061 }
4062 return (error);
4063 }
4064
4065 int
4066 sogetopt(struct socket *so, struct sockopt *sopt)
4067 {
4068 int error, optval;
4069 struct linger l;
4070 struct timeval tv;
4071 #ifdef MAC
4072 struct mac extmac;
4073 #endif
4074
4075 CURVNET_SET(so->so_vnet);
4076 error = 0;
4077 if (sopt->sopt_level != SOL_SOCKET) {
4078 error = (*so->so_proto->pr_ctloutput)(so, sopt);
4079 CURVNET_RESTORE();
4080 return (error);
4081 } else {
4082 switch (sopt->sopt_name) {
4083 case SO_ACCEPTFILTER:
4084 error = accept_filt_getopt(so, sopt);
4085 break;
4086
4087 case SO_LINGER:
4088 SOCK_LOCK(so);
4089 l.l_onoff = so->so_options & SO_LINGER;
4090 l.l_linger = so->so_linger;
4091 SOCK_UNLOCK(so);
4092 error = sooptcopyout(sopt, &l, sizeof l);
4093 break;
4094
4095 case SO_USELOOPBACK:
4096 case SO_DONTROUTE:
4097 case SO_DEBUG:
4098 case SO_KEEPALIVE:
4099 case SO_REUSEADDR:
4100 case SO_REUSEPORT:
4101 case SO_REUSEPORT_LB:
4102 case SO_BROADCAST:
4103 case SO_OOBINLINE:
4104 case SO_ACCEPTCONN:
4105 case SO_TIMESTAMP:
4106 case SO_BINTIME:
4107 case SO_NOSIGPIPE:
4108 case SO_NO_DDP:
4109 case SO_NO_OFFLOAD:
4110 case SO_RERROR:
4111 optval = so->so_options & sopt->sopt_name;
4112 integer:
4113 error = sooptcopyout(sopt, &optval, sizeof optval);
4114 break;
4115
4116 case SO_FIB:
4117 SOCK_LOCK(so);
4118 optval = so->so_fibnum;
4119 SOCK_UNLOCK(so);
4120 goto integer;
4121
4122 case SO_DOMAIN:
4123 optval = so->so_proto->pr_domain->dom_family;
4124 goto integer;
4125
4126 case SO_TYPE:
4127 optval = so->so_type;
4128 goto integer;
4129
4130 case SO_PROTOCOL:
4131 optval = so->so_proto->pr_protocol;
4132 goto integer;
4133
4134 case SO_ERROR:
4135 SOCK_LOCK(so);
4136 if (so->so_error) {
4137 optval = so->so_error;
4138 so->so_error = 0;
4139 } else {
4140 optval = so->so_rerror;
4141 so->so_rerror = 0;
4142 }
4143 SOCK_UNLOCK(so);
4144 goto integer;
4145
4146 case SO_SNDBUF:
4147 SOCK_LOCK(so);
4148 optval = SOLISTENING(so) ? so->sol_sbsnd_hiwat :
4149 so->so_snd.sb_hiwat;
4150 SOCK_UNLOCK(so);
4151 goto integer;
4152
4153 case SO_RCVBUF:
4154 SOCK_LOCK(so);
4155 optval = SOLISTENING(so) ? so->sol_sbrcv_hiwat :
4156 so->so_rcv.sb_hiwat;
4157 SOCK_UNLOCK(so);
4158 goto integer;
4159
4160 case SO_SNDLOWAT:
4161 SOCK_LOCK(so);
4162 optval = SOLISTENING(so) ? so->sol_sbsnd_lowat :
4163 so->so_snd.sb_lowat;
4164 SOCK_UNLOCK(so);
4165 goto integer;
4166
4167 case SO_RCVLOWAT:
4168 SOCK_LOCK(so);
4169 optval = SOLISTENING(so) ? so->sol_sbrcv_lowat :
4170 so->so_rcv.sb_lowat;
4171 SOCK_UNLOCK(so);
4172 goto integer;
4173
4174 case SO_SNDTIMEO:
4175 case SO_RCVTIMEO:
4176 SOCK_LOCK(so);
4177 tv = sbttotv(sopt->sopt_name == SO_SNDTIMEO ?
4178 (SOLISTENING(so) ? so->sol_sbsnd_timeo :
4179 so->so_snd.sb_timeo) :
4180 (SOLISTENING(so) ? so->sol_sbrcv_timeo :
4181 so->so_rcv.sb_timeo));
4182 SOCK_UNLOCK(so);
4183 #ifdef COMPAT_FREEBSD32
4184 if (SV_CURPROC_FLAG(SV_ILP32)) {
4185 struct timeval32 tv32;
4186
4187 CP(tv, tv32, tv_sec);
4188 CP(tv, tv32, tv_usec);
4189 error = sooptcopyout(sopt, &tv32, sizeof tv32);
4190 } else
4191 #endif
4192 error = sooptcopyout(sopt, &tv, sizeof tv);
4193 break;
4194
4195 case SO_LABEL:
4196 #ifdef MAC
4197 error = sooptcopyin(sopt, &extmac, sizeof(extmac),
4198 sizeof(extmac));
4199 if (error)
4200 goto bad;
4201 error = mac_getsockopt_label(sopt->sopt_td->td_ucred,
4202 so, &extmac);
4203 if (error)
4204 goto bad;
4205 error = sooptcopyout(sopt, &extmac, sizeof extmac);
4206 #else
4207 error = EOPNOTSUPP;
4208 #endif
4209 break;
4210
4211 case SO_PEERLABEL:
4212 #ifdef MAC
4213 error = sooptcopyin(sopt, &extmac, sizeof(extmac),
4214 sizeof(extmac));
4215 if (error)
4216 goto bad;
4217 error = mac_getsockopt_peerlabel(
4218 sopt->sopt_td->td_ucred, so, &extmac);
4219 if (error)
4220 goto bad;
4221 error = sooptcopyout(sopt, &extmac, sizeof extmac);
4222 #else
4223 error = EOPNOTSUPP;
4224 #endif
4225 break;
4226
4227 case SO_LISTENQLIMIT:
4228 SOCK_LOCK(so);
4229 optval = SOLISTENING(so) ? so->sol_qlimit : 0;
4230 SOCK_UNLOCK(so);
4231 goto integer;
4232
4233 case SO_LISTENQLEN:
4234 SOCK_LOCK(so);
4235 optval = SOLISTENING(so) ? so->sol_qlen : 0;
4236 SOCK_UNLOCK(so);
4237 goto integer;
4238
4239 case SO_LISTENINCQLEN:
4240 SOCK_LOCK(so);
4241 optval = SOLISTENING(so) ? so->sol_incqlen : 0;
4242 SOCK_UNLOCK(so);
4243 goto integer;
4244
4245 case SO_TS_CLOCK:
4246 optval = so->so_ts_clock;
4247 goto integer;
4248
4249 case SO_MAX_PACING_RATE:
4250 optval = so->so_max_pacing_rate;
4251 goto integer;
4252
4253 case SO_SPLICE: {
4254 off_t n;
4255
4256 /*
4257 * Acquire the I/O lock to serialize with
4258 * so_splice_xfer(). This is not required for
4259 * correctness, but makes testing simpler: once a byte
4260 * has been transmitted to the sink and observed (e.g.,
4261 * by reading from the socket to which the sink is
4262 * connected), a subsequent getsockopt(SO_SPLICE) will
4263 * return an up-to-date value.
4264 */
4265 error = SOCK_IO_RECV_LOCK(so, SBL_WAIT);
4266 if (error != 0)
4267 goto bad;
4268 SOCK_LOCK(so);
4269 if (SOLISTENING(so)) {
4270 n = 0;
4271 } else {
4272 n = so->so_splice_sent;
4273 }
4274 SOCK_UNLOCK(so);
4275 SOCK_IO_RECV_UNLOCK(so);
4276 error = sooptcopyout(sopt, &n, sizeof(n));
4277 break;
4278 }
4279
4280 default:
4281 if (V_socket_hhh[HHOOK_SOCKET_OPT]->hhh_nhooks > 0)
4282 error = hhook_run_socket(so, sopt,
4283 HHOOK_SOCKET_OPT);
4284 else
4285 error = ENOPROTOOPT;
4286 break;
4287 }
4288 }
4289 bad:
4290 CURVNET_RESTORE();
4291 return (error);
4292 }
4293
4294 int
4295 soopt_getm(struct sockopt *sopt, struct mbuf **mp)
4296 {
4297 struct mbuf *m, *m_prev;
4298 int sopt_size = sopt->sopt_valsize;
4299
4300 MGET(m, sopt->sopt_td ? M_WAITOK : M_NOWAIT, MT_DATA);
4301 if (m == NULL)
4302 return ENOBUFS;
4303 if (sopt_size > MLEN) {
4304 MCLGET(m, sopt->sopt_td ? M_WAITOK : M_NOWAIT);
4305 if ((m->m_flags & M_EXT) == 0) {
4306 m_free(m);
4307 return ENOBUFS;
4308 }
4309 m->m_len = min(MCLBYTES, sopt_size);
4310 } else {
4311 m->m_len = min(MLEN, sopt_size);
4312 }
4313 sopt_size -= m->m_len;
4314 *mp = m;
4315 m_prev = m;
4316
4317 while (sopt_size) {
4318 MGET(m, sopt->sopt_td ? M_WAITOK : M_NOWAIT, MT_DATA);
4319 if (m == NULL) {
4320 m_freem(*mp);
4321 return ENOBUFS;
4322 }
4323 if (sopt_size > MLEN) {
4324 MCLGET(m, sopt->sopt_td != NULL ? M_WAITOK :
4325 M_NOWAIT);
4326 if ((m->m_flags & M_EXT) == 0) {
4327 m_freem(m);
4328 m_freem(*mp);
4329 return ENOBUFS;
4330 }
4331 m->m_len = min(MCLBYTES, sopt_size);
4332 } else {
4333 m->m_len = min(MLEN, sopt_size);
4334 }
4335 sopt_size -= m->m_len;
4336 m_prev->m_next = m;
4337 m_prev = m;
4338 }
4339 return (0);
4340 }
4341
4342 int
4343 soopt_mcopyin(struct sockopt *sopt, struct mbuf *m)
4344 {
4345 struct mbuf *m0 = m;
4346
4347 if (sopt->sopt_val == NULL)
4348 return (0);
4349 while (m != NULL && sopt->sopt_valsize >= m->m_len) {
4350 if (sopt->sopt_td != NULL) {
4351 int error;
4352
4353 error = copyin(sopt->sopt_val, mtod(m, char *),
4354 m->m_len);
4355 if (error != 0) {
4356 m_freem(m0);
4357 return(error);
4358 }
4359 } else
4360 bcopy(sopt->sopt_val, mtod(m, char *), m->m_len);
4361 sopt->sopt_valsize -= m->m_len;
4362 sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
4363 m = m->m_next;
4364 }
4365 if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */
4366 panic("ip6_sooptmcopyin");
4367 return (0);
4368 }
4369
4370 int
4371 soopt_mcopyout(struct sockopt *sopt, struct mbuf *m)
4372 {
4373 struct mbuf *m0 = m;
4374 size_t valsize = 0;
4375
4376 if (sopt->sopt_val == NULL)
4377 return (0);
4378 while (m != NULL && sopt->sopt_valsize >= m->m_len) {
4379 if (sopt->sopt_td != NULL) {
4380 int error;
4381
4382 error = copyout(mtod(m, char *), sopt->sopt_val,
4383 m->m_len);
4384 if (error != 0) {
4385 m_freem(m0);
4386 return(error);
4387 }
4388 } else
4389 bcopy(mtod(m, char *), sopt->sopt_val, m->m_len);
4390 sopt->sopt_valsize -= m->m_len;
4391 sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
4392 valsize += m->m_len;
4393 m = m->m_next;
4394 }
4395 if (m != NULL) {
4396 /* enough soopt buffer should be given from user-land */
4397 m_freem(m0);
4398 return(EINVAL);
4399 }
4400 sopt->sopt_valsize = valsize;
4401 return (0);
4402 }
4403
4404 /*
4405 * sohasoutofband(): protocol notifies socket layer of the arrival of new
4406 * out-of-band data, which will then notify socket consumers.
4407 */
4408 void
4409 sohasoutofband(struct socket *so)
4410 {
4411
4412 if (so->so_sigio != NULL)
4413 pgsigio(&so->so_sigio, SIGURG, 0);
4414 selwakeuppri(&so->so_rdsel, PSOCK);
4415 }
4416
4417 int
4418 sopoll(struct socket *so, int events, struct ucred *active_cred,
4419 struct thread *td)
4420 {
4421
4422 /*
4423 * We do not need to set or assert curvnet as long as everyone uses
4424 * sopoll_generic().
4425 */
4426 return (so->so_proto->pr_sopoll(so, events, active_cred, td));
4427 }
4428
4429 int
4430 sopoll_generic(struct socket *so, int events, struct ucred *active_cred,
4431 struct thread *td)
4432 {
4433 int revents;
4434
4435 SOCK_LOCK(so);
4436 if (SOLISTENING(so)) {
4437 if (!(events & (POLLIN | POLLRDNORM)))
4438 revents = 0;
4439 else if (!TAILQ_EMPTY(&so->sol_comp))
4440 revents = events & (POLLIN | POLLRDNORM);
4441 else if ((events & POLLINIGNEOF) == 0 && so->so_error)
4442 revents = (events & (POLLIN | POLLRDNORM)) | POLLHUP;
4443 else {
4444 selrecord(td, &so->so_rdsel);
4445 revents = 0;
4446 }
4447 } else {
4448 revents = 0;
4449 SOCK_SENDBUF_LOCK(so);
4450 SOCK_RECVBUF_LOCK(so);
4451 if (events & (POLLIN | POLLRDNORM))
4452 if (soreadabledata(so) && !isspliced(so))
4453 revents |= events & (POLLIN | POLLRDNORM);
4454 if (events & (POLLOUT | POLLWRNORM))
4455 if (sowriteable(so) && !issplicedback(so))
4456 revents |= events & (POLLOUT | POLLWRNORM);
4457 if (events & (POLLPRI | POLLRDBAND))
4458 if (so->so_oobmark ||
4459 (so->so_rcv.sb_state & SBS_RCVATMARK))
4460 revents |= events & (POLLPRI | POLLRDBAND);
4461 if ((events & POLLINIGNEOF) == 0) {
4462 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
4463 revents |= events & (POLLIN | POLLRDNORM);
4464 if (so->so_snd.sb_state & SBS_CANTSENDMORE)
4465 revents |= POLLHUP;
4466 }
4467 }
4468 if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
4469 revents |= events & POLLRDHUP;
4470 if (revents == 0) {
4471 if (events &
4472 (POLLIN | POLLPRI | POLLRDNORM | POLLRDBAND | POLLRDHUP)) {
4473 selrecord(td, &so->so_rdsel);
4474 so->so_rcv.sb_flags |= SB_SEL;
4475 }
4476 if (events & (POLLOUT | POLLWRNORM)) {
4477 selrecord(td, &so->so_wrsel);
4478 so->so_snd.sb_flags |= SB_SEL;
4479 }
4480 }
4481 SOCK_RECVBUF_UNLOCK(so);
4482 SOCK_SENDBUF_UNLOCK(so);
4483 }
4484 SOCK_UNLOCK(so);
4485 return (revents);
4486 }
4487
4488 int
4489 soo_kqfilter(struct file *fp, struct knote *kn)
4490 {
4491 struct socket *so = kn->kn_fp->f_data;
4492 struct sockbuf *sb;
4493 sb_which which;
4494 struct knlist *knl;
4495
4496 switch (kn->kn_filter) {
4497 case EVFILT_READ:
4498 kn->kn_fop = &soread_filtops;
4499 knl = &so->so_rdsel.si_note;
4500 sb = &so->so_rcv;
4501 which = SO_RCV;
4502 break;
4503 case EVFILT_WRITE:
4504 kn->kn_fop = &sowrite_filtops;
4505 knl = &so->so_wrsel.si_note;
4506 sb = &so->so_snd;
4507 which = SO_SND;
4508 break;
4509 case EVFILT_EMPTY:
4510 kn->kn_fop = &soempty_filtops;
4511 knl = &so->so_wrsel.si_note;
4512 sb = &so->so_snd;
4513 which = SO_SND;
4514 break;
4515 default:
4516 return (EINVAL);
4517 }
4518
4519 SOCK_LOCK(so);
4520 if (SOLISTENING(so)) {
4521 knlist_add(knl, kn, 1);
4522 } else {
4523 SOCK_BUF_LOCK(so, which);
4524 knlist_add(knl, kn, 1);
4525 sb->sb_flags |= SB_KNOTE;
4526 SOCK_BUF_UNLOCK(so, which);
4527 }
4528 SOCK_UNLOCK(so);
4529 return (0);
4530 }
4531
4532 static void
4533 filt_sordetach(struct knote *kn)
4534 {
4535 struct socket *so = kn->kn_fp->f_data;
4536
4537 so_rdknl_lock(so);
4538 knlist_remove(&so->so_rdsel.si_note, kn, 1);
4539 if (!SOLISTENING(so) && knlist_empty(&so->so_rdsel.si_note))
4540 so->so_rcv.sb_flags &= ~SB_KNOTE;
4541 so_rdknl_unlock(so);
4542 }
4543
4544 /*ARGSUSED*/
4545 static int
4546 filt_soread(struct knote *kn, long hint)
4547 {
4548 struct socket *so;
4549
4550 so = kn->kn_fp->f_data;
4551
4552 if (SOLISTENING(so)) {
4553 SOCK_LOCK_ASSERT(so);
4554 kn->kn_data = so->sol_qlen;
4555 if (so->so_error) {
4556 kn->kn_flags |= EV_EOF;
4557 kn->kn_fflags = so->so_error;
4558 return (1);
4559 }
4560 return (!TAILQ_EMPTY(&so->sol_comp));
4561 }
4562
4563 if ((so->so_rcv.sb_flags & SB_SPLICED) != 0)
4564 return (0);
4565
4566 SOCK_RECVBUF_LOCK_ASSERT(so);
4567
4568 kn->kn_data = sbavail(&so->so_rcv) - so->so_rcv.sb_ctl;
4569 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
4570 kn->kn_flags |= EV_EOF;
4571 kn->kn_fflags = so->so_error;
4572 return (1);
4573 } else if (so->so_error || so->so_rerror)
4574 return (1);
4575
4576 if (kn->kn_sfflags & NOTE_LOWAT) {
4577 if (kn->kn_data >= kn->kn_sdata)
4578 return (1);
4579 } else if (sbavail(&so->so_rcv) >= so->so_rcv.sb_lowat)
4580 return (1);
4581
4582 /* This hook returning non-zero indicates an event, not error */
4583 return (hhook_run_socket(so, NULL, HHOOK_FILT_SOREAD));
4584 }
4585
4586 static void
4587 filt_sowdetach(struct knote *kn)
4588 {
4589 struct socket *so = kn->kn_fp->f_data;
4590
4591 so_wrknl_lock(so);
4592 knlist_remove(&so->so_wrsel.si_note, kn, 1);
4593 if (!SOLISTENING(so) && knlist_empty(&so->so_wrsel.si_note))
4594 so->so_snd.sb_flags &= ~SB_KNOTE;
4595 so_wrknl_unlock(so);
4596 }
4597
4598 /*ARGSUSED*/
4599 static int
4600 filt_sowrite(struct knote *kn, long hint)
4601 {
4602 struct socket *so;
4603
4604 so = kn->kn_fp->f_data;
4605
4606 if (SOLISTENING(so))
4607 return (0);
4608
4609 SOCK_SENDBUF_LOCK_ASSERT(so);
4610 kn->kn_data = sbspace(&so->so_snd);
4611
4612 hhook_run_socket(so, kn, HHOOK_FILT_SOWRITE);
4613
4614 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
4615 kn->kn_flags |= EV_EOF;
4616 kn->kn_fflags = so->so_error;
4617 return (1);
4618 } else if (so->so_error) /* temporary udp error */
4619 return (1);
4620 else if (((so->so_state & SS_ISCONNECTED) == 0) &&
4621 (so->so_proto->pr_flags & PR_CONNREQUIRED))
4622 return (0);
4623 else if (kn->kn_sfflags & NOTE_LOWAT)
4624 return (kn->kn_data >= kn->kn_sdata);
4625 else
4626 return (kn->kn_data >= so->so_snd.sb_lowat);
4627 }
4628
4629 static int
4630 filt_soempty(struct knote *kn, long hint)
4631 {
4632 struct socket *so;
4633
4634 so = kn->kn_fp->f_data;
4635
4636 if (SOLISTENING(so))
4637 return (1);
4638
4639 SOCK_SENDBUF_LOCK_ASSERT(so);
4640 kn->kn_data = sbused(&so->so_snd);
4641
4642 if (kn->kn_data == 0)
4643 return (1);
4644 else
4645 return (0);
4646 }
4647
4648 int
4649 socheckuid(struct socket *so, uid_t uid)
4650 {
4651
4652 if (so == NULL)
4653 return (EPERM);
4654 if (so->so_cred->cr_uid != uid)
4655 return (EPERM);
4656 return (0);
4657 }
4658
4659 /*
4660 * These functions are used by protocols to notify the socket layer (and its
4661 * consumers) of state changes in the sockets driven by protocol-side events.
4662 */
4663
4664 /*
4665 * Procedures to manipulate state flags of socket and do appropriate wakeups.
4666 *
4667 * Normal sequence from the active (originating) side is that
4668 * soisconnecting() is called during processing of connect() call, resulting
4669 * in an eventual call to soisconnected() if/when the connection is
4670 * established. When the connection is torn down soisdisconnecting() is
4671 * called during processing of disconnect() call, and soisdisconnected() is
4672 * called when the connection to the peer is totally severed. The semantics
4673 * of these routines are such that connectionless protocols can call
4674 * soisconnected() and soisdisconnected() only, bypassing the in-progress
4675 * calls when setting up a ``connection'' takes no time.
4676 *
4677 * From the passive side, a socket is created with two queues of sockets:
4678 * so_incomp for connections in progress and so_comp for connections already
4679 * made and awaiting user acceptance. As a protocol is preparing incoming
4680 * connections, it creates a socket structure queued on so_incomp by calling
4681 * sonewconn(). When the connection is established, soisconnected() is
4682 * called, and transfers the socket structure to so_comp, making it available
4683 * to accept().
4684 *
4685 * If a socket is closed with sockets on either so_incomp or so_comp, these
4686 * sockets are dropped.
4687 *
4688 * If higher-level protocols are implemented in the kernel, the wakeups done
4689 * here will sometimes cause software-interrupt process scheduling.
4690 */
4691 void
4692 soisconnecting(struct socket *so)
4693 {
4694
4695 SOCK_LOCK(so);
4696 so->so_state &= ~(SS_ISCONNECTED|SS_ISDISCONNECTING);
4697 so->so_state |= SS_ISCONNECTING;
4698 SOCK_UNLOCK(so);
4699 }
4700
4701 void
4702 soisconnected(struct socket *so)
4703 {
4704 bool last __diagused;
4705
4706 SOCK_LOCK(so);
4707 so->so_state &= ~(SS_ISCONNECTING|SS_ISDISCONNECTING|SS_ISCONFIRMING);
4708 so->so_state |= SS_ISCONNECTED;
4709
4710 if (so->so_qstate == SQ_INCOMP) {
4711 struct socket *head = so->so_listen;
4712 int ret;
4713
4714 KASSERT(head, ("%s: so %p on incomp of NULL", __func__, so));
4715 /*
4716 * Promoting a socket from incomplete queue to complete, we
4717 * need to go through reverse order of locking. We first do
4718 * trylock, and if that doesn't succeed, we go the hard way
4719 * leaving a reference and rechecking consistency after proper
4720 * locking.
4721 */
4722 if (__predict_false(SOLISTEN_TRYLOCK(head) == 0)) {
4723 soref(head);
4724 SOCK_UNLOCK(so);
4725 SOLISTEN_LOCK(head);
4726 SOCK_LOCK(so);
4727 if (__predict_false(head != so->so_listen)) {
4728 /*
4729 * The socket went off the listen queue,
4730 * should be lost race to close(2) of sol.
4731 * The socket is about to soabort().
4732 */
4733 SOCK_UNLOCK(so);
4734 sorele_locked(head);
4735 return;
4736 }
4737 last = refcount_release(&head->so_count);
4738 KASSERT(!last, ("%s: released last reference for %p",
4739 __func__, head));
4740 }
4741 again:
4742 if ((so->so_options & SO_ACCEPTFILTER) == 0) {
4743 TAILQ_REMOVE(&head->sol_incomp, so, so_list);
4744 head->sol_incqlen--;
4745 TAILQ_INSERT_TAIL(&head->sol_comp, so, so_list);
4746 head->sol_qlen++;
4747 so->so_qstate = SQ_COMP;
4748 SOCK_UNLOCK(so);
4749 solisten_wakeup(head); /* unlocks */
4750 } else {
4751 SOCK_RECVBUF_LOCK(so);
4752 soupcall_set(so, SO_RCV,
4753 head->sol_accept_filter->accf_callback,
4754 head->sol_accept_filter_arg);
4755 so->so_options &= ~SO_ACCEPTFILTER;
4756 ret = head->sol_accept_filter->accf_callback(so,
4757 head->sol_accept_filter_arg, M_NOWAIT);
4758 if (ret == SU_ISCONNECTED) {
4759 soupcall_clear(so, SO_RCV);
4760 SOCK_RECVBUF_UNLOCK(so);
4761 goto again;
4762 }
4763 SOCK_RECVBUF_UNLOCK(so);
4764 SOCK_UNLOCK(so);
4765 SOLISTEN_UNLOCK(head);
4766 }
4767 return;
4768 }
4769 SOCK_UNLOCK(so);
4770 wakeup(&so->so_timeo);
4771 sorwakeup(so);
4772 sowwakeup(so);
4773 }
4774
4775 void
4776 soisdisconnecting(struct socket *so)
4777 {
4778
4779 SOCK_LOCK(so);
4780 so->so_state &= ~SS_ISCONNECTING;
4781 so->so_state |= SS_ISDISCONNECTING;
4782
4783 if (!SOLISTENING(so)) {
4784 SOCK_RECVBUF_LOCK(so);
4785 socantrcvmore_locked(so);
4786 SOCK_SENDBUF_LOCK(so);
4787 socantsendmore_locked(so);
4788 }
4789 SOCK_UNLOCK(so);
4790 wakeup(&so->so_timeo);
4791 }
4792
4793 void
4794 soisdisconnected(struct socket *so)
4795 {
4796
4797 SOCK_LOCK(so);
4798
4799 /*
4800 * There is at least one reader of so_state that does not
4801 * acquire socket lock, namely soreceive_generic(). Ensure
4802 * that it never sees all flags that track connection status
4803 * cleared, by ordering the update with a barrier semantic of
4804 * our release thread fence.
4805 */
4806 so->so_state |= SS_ISDISCONNECTED;
4807 atomic_thread_fence_rel();
4808 so->so_state &= ~(SS_ISCONNECTING|SS_ISCONNECTED|SS_ISDISCONNECTING);
4809
4810 if (!SOLISTENING(so)) {
4811 SOCK_UNLOCK(so);
4812 SOCK_RECVBUF_LOCK(so);
4813 socantrcvmore_locked(so);
4814 SOCK_SENDBUF_LOCK(so);
4815 sbdrop_locked(&so->so_snd, sbused(&so->so_snd));
4816 socantsendmore_locked(so);
4817 } else
4818 SOCK_UNLOCK(so);
4819 wakeup(&so->so_timeo);
4820 }
4821
4822 int
4823 soiolock(struct socket *so, struct sx *sx, int flags)
4824 {
4825 int error;
4826
4827 KASSERT((flags & SBL_VALID) == flags,
4828 ("soiolock: invalid flags %#x", flags));
4829
4830 if ((flags & SBL_WAIT) != 0) {
4831 if ((flags & SBL_NOINTR) != 0) {
4832 sx_xlock(sx);
4833 } else {
4834 error = sx_xlock_sig(sx);
4835 if (error != 0)
4836 return (error);
4837 }
4838 } else if (!sx_try_xlock(sx)) {
4839 return (EWOULDBLOCK);
4840 }
4841
4842 if (__predict_false(SOLISTENING(so))) {
4843 sx_xunlock(sx);
4844 return (ENOTCONN);
4845 }
4846 return (0);
4847 }
4848
4849 void
4850 soiounlock(struct sx *sx)
4851 {
4852 sx_xunlock(sx);
4853 }
4854
4855 /*
4856 * Make a copy of a sockaddr in a malloced buffer of type M_SONAME.
4857 */
4858 struct sockaddr *
4859 sodupsockaddr(const struct sockaddr *sa, int mflags)
4860 {
4861 struct sockaddr *sa2;
4862
4863 sa2 = malloc(sa->sa_len, M_SONAME, mflags);
4864 if (sa2)
4865 bcopy(sa, sa2, sa->sa_len);
4866 return sa2;
4867 }
4868
4869 /*
4870 * Register per-socket destructor.
4871 */
4872 void
4873 sodtor_set(struct socket *so, so_dtor_t *func)
4874 {
4875
4876 SOCK_LOCK_ASSERT(so);
4877 so->so_dtor = func;
4878 }
4879
4880 /*
4881 * Register per-socket buffer upcalls.
4882 */
4883 void
4884 soupcall_set(struct socket *so, sb_which which, so_upcall_t func, void *arg)
4885 {
4886 struct sockbuf *sb;
4887
4888 KASSERT(!SOLISTENING(so), ("%s: so %p listening", __func__, so));
4889
4890 switch (which) {
4891 case SO_RCV:
4892 sb = &so->so_rcv;
4893 break;
4894 case SO_SND:
4895 sb = &so->so_snd;
4896 break;
4897 }
4898 SOCK_BUF_LOCK_ASSERT(so, which);
4899 sb->sb_upcall = func;
4900 sb->sb_upcallarg = arg;
4901 sb->sb_flags |= SB_UPCALL;
4902 }
4903
4904 void
4905 soupcall_clear(struct socket *so, sb_which which)
4906 {
4907 struct sockbuf *sb;
4908
4909 KASSERT(!SOLISTENING(so), ("%s: so %p listening", __func__, so));
4910
4911 switch (which) {
4912 case SO_RCV:
4913 sb = &so->so_rcv;
4914 break;
4915 case SO_SND:
4916 sb = &so->so_snd;
4917 break;
4918 }
4919 SOCK_BUF_LOCK_ASSERT(so, which);
4920 KASSERT(sb->sb_upcall != NULL,
4921 ("%s: so %p no upcall to clear", __func__, so));
4922 sb->sb_upcall = NULL;
4923 sb->sb_upcallarg = NULL;
4924 sb->sb_flags &= ~SB_UPCALL;
4925 }
4926
4927 void
4928 solisten_upcall_set(struct socket *so, so_upcall_t func, void *arg)
4929 {
4930
4931 SOLISTEN_LOCK_ASSERT(so);
4932 so->sol_upcall = func;
4933 so->sol_upcallarg = arg;
4934 }
4935
4936 static void
4937 so_rdknl_lock(void *arg)
4938 {
4939 struct socket *so = arg;
4940
4941 retry:
4942 if (SOLISTENING(so)) {
4943 SOLISTEN_LOCK(so);
4944 } else {
4945 SOCK_RECVBUF_LOCK(so);
4946 if (__predict_false(SOLISTENING(so))) {
4947 SOCK_RECVBUF_UNLOCK(so);
4948 goto retry;
4949 }
4950 }
4951 }
4952
4953 static void
4954 so_rdknl_unlock(void *arg)
4955 {
4956 struct socket *so = arg;
4957
4958 if (SOLISTENING(so))
4959 SOLISTEN_UNLOCK(so);
4960 else
4961 SOCK_RECVBUF_UNLOCK(so);
4962 }
4963
4964 static void
4965 so_rdknl_assert_lock(void *arg, int what)
4966 {
4967 struct socket *so = arg;
4968
4969 if (what == LA_LOCKED) {
4970 if (SOLISTENING(so))
4971 SOLISTEN_LOCK_ASSERT(so);
4972 else
4973 SOCK_RECVBUF_LOCK_ASSERT(so);
4974 } else {
4975 if (SOLISTENING(so))
4976 SOLISTEN_UNLOCK_ASSERT(so);
4977 else
4978 SOCK_RECVBUF_UNLOCK_ASSERT(so);
4979 }
4980 }
4981
4982 static void
4983 so_wrknl_lock(void *arg)
4984 {
4985 struct socket *so = arg;
4986
4987 retry:
4988 if (SOLISTENING(so)) {
4989 SOLISTEN_LOCK(so);
4990 } else {
4991 SOCK_SENDBUF_LOCK(so);
4992 if (__predict_false(SOLISTENING(so))) {
4993 SOCK_SENDBUF_UNLOCK(so);
4994 goto retry;
4995 }
4996 }
4997 }
4998
4999 static void
5000 so_wrknl_unlock(void *arg)
5001 {
5002 struct socket *so = arg;
5003
5004 if (SOLISTENING(so))
5005 SOLISTEN_UNLOCK(so);
5006 else
5007 SOCK_SENDBUF_UNLOCK(so);
5008 }
5009
5010 static void
5011 so_wrknl_assert_lock(void *arg, int what)
5012 {
5013 struct socket *so = arg;
5014
5015 if (what == LA_LOCKED) {
5016 if (SOLISTENING(so))
5017 SOLISTEN_LOCK_ASSERT(so);
5018 else
5019 SOCK_SENDBUF_LOCK_ASSERT(so);
5020 } else {
5021 if (SOLISTENING(so))
5022 SOLISTEN_UNLOCK_ASSERT(so);
5023 else
5024 SOCK_SENDBUF_UNLOCK_ASSERT(so);
5025 }
5026 }
5027
5028 /*
5029 * Create an external-format (``xsocket'') structure using the information in
5030 * the kernel-format socket structure pointed to by so. This is done to
5031 * reduce the spew of irrelevant information over this interface, to isolate
5032 * user code from changes in the kernel structure, and potentially to provide
5033 * information-hiding if we decide that some of this information should be
5034 * hidden from users.
5035 */
5036 void
5037 sotoxsocket(struct socket *so, struct xsocket *xso)
5038 {
5039
5040 bzero(xso, sizeof(*xso));
5041 xso->xso_len = sizeof *xso;
5042 xso->xso_so = (uintptr_t)so;
5043 xso->so_type = so->so_type;
5044 xso->so_options = so->so_options;
5045 xso->so_linger = so->so_linger;
5046 xso->so_state = so->so_state;
5047 xso->so_pcb = (uintptr_t)so->so_pcb;
5048 xso->xso_protocol = so->so_proto->pr_protocol;
5049 xso->xso_family = so->so_proto->pr_domain->dom_family;
5050 xso->so_timeo = so->so_timeo;
5051 xso->so_error = so->so_error;
5052 xso->so_uid = so->so_cred->cr_uid;
5053 xso->so_pgid = so->so_sigio ? so->so_sigio->sio_pgid : 0;
5054 SOCK_LOCK(so);
5055 xso->so_fibnum = so->so_fibnum;
5056 if (SOLISTENING(so)) {
5057 xso->so_qlen = so->sol_qlen;
5058 xso->so_incqlen = so->sol_incqlen;
5059 xso->so_qlimit = so->sol_qlimit;
5060 xso->so_oobmark = 0;
5061 } else {
5062 xso->so_state |= so->so_qstate;
5063 xso->so_qlen = xso->so_incqlen = xso->so_qlimit = 0;
5064 xso->so_oobmark = so->so_oobmark;
5065 sbtoxsockbuf(&so->so_snd, &xso->so_snd);
5066 sbtoxsockbuf(&so->so_rcv, &xso->so_rcv);
5067 if ((so->so_rcv.sb_flags & SB_SPLICED) != 0)
5068 xso->so_splice_so = (uintptr_t)so->so_splice->dst;
5069 }
5070 SOCK_UNLOCK(so);
5071 }
5072
5073 struct sockbuf *
5074 so_sockbuf_rcv(struct socket *so)
5075 {
5076
5077 return (&so->so_rcv);
5078 }
5079
5080 struct sockbuf *
5081 so_sockbuf_snd(struct socket *so)
5082 {
5083
5084 return (&so->so_snd);
5085 }
5086
5087 int
5088 so_state_get(const struct socket *so)
5089 {
5090
5091 return (so->so_state);
5092 }
5093
5094 void
5095 so_state_set(struct socket *so, int val)
5096 {
5097
5098 so->so_state = val;
5099 }
5100
5101 int
5102 so_options_get(const struct socket *so)
5103 {
5104
5105 return (so->so_options);
5106 }
5107
5108 void
5109 so_options_set(struct socket *so, int val)
5110 {
5111
5112 so->so_options = val;
5113 }
5114
5115 int
5116 so_error_get(const struct socket *so)
5117 {
5118
5119 return (so->so_error);
5120 }
5121
5122 void
5123 so_error_set(struct socket *so, int val)
5124 {
5125
5126 so->so_error = val;
5127 }
5128
5129 int
5130 so_linger_get(const struct socket *so)
5131 {
5132
5133 return (so->so_linger);
5134 }
5135
5136 void
5137 so_linger_set(struct socket *so, int val)
5138 {
5139
5140 KASSERT(val >= 0 && val <= USHRT_MAX && val <= (INT_MAX / hz),
5141 ("%s: val %d out of range", __func__, val));
5142
5143 so->so_linger = val;
5144 }
5145
5146 struct protosw *
5147 so_protosw_get(const struct socket *so)
5148 {
5149
5150 return (so->so_proto);
5151 }
5152
5153 void
5154 so_protosw_set(struct socket *so, struct protosw *val)
5155 {
5156
5157 so->so_proto = val;
5158 }
5159
5160 void
5161 so_sorwakeup(struct socket *so)
5162 {
5163
5164 sorwakeup(so);
5165 }
5166
5167 void
5168 so_sowwakeup(struct socket *so)
5169 {
5170
5171 sowwakeup(so);
5172 }
5173
5174 void
5175 so_sorwakeup_locked(struct socket *so)
5176 {
5177
5178 sorwakeup_locked(so);
5179 }
5180
5181 void
5182 so_sowwakeup_locked(struct socket *so)
5183 {
5184
5185 sowwakeup_locked(so);
5186 }
5187
5188 void
5189 so_lock(struct socket *so)
5190 {
5191
5192 SOCK_LOCK(so);
5193 }
5194
5195 void
5196 so_unlock(struct socket *so)
5197 {
5198
5199 SOCK_UNLOCK(so);
5200 }
5201