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