PageRenderTime 78ms CodeModel.GetById 32ms RepoModel.GetById 1ms app.codeStats 0ms

/kern/uipc_socket.c

https://bitbucket.org/brucec/sctpdrv
C | 3490 lines | 2503 code | 328 blank | 659 comment | 708 complexity | 837653b306623c240174d108dff4766b MD5 | raw file
  1. /*-
  2. * Copyright (c) 1982, 1986, 1988, 1990, 1993
  3. * The Regents of the University of California.
  4. * Copyright (c) 2004 The FreeBSD Foundation
  5. * Copyright (c) 2004-2008 Robert N. M. Watson
  6. * All rights reserved.
  7. *
  8. * Redistribution and use in source and binary forms, with or without
  9. * modification, are permitted provided that the following conditions
  10. * are met:
  11. * 1. Redistributions of source code must retain the above copyright
  12. * notice, this list of conditions and the following disclaimer.
  13. * 2. Redistributions in binary form must reproduce the above copyright
  14. * notice, this list of conditions and the following disclaimer in the
  15. * documentation and/or other materials provided with the distribution.
  16. * 4. Neither the name of the University nor the names of its contributors
  17. * may be used to endorse or promote products derived from this software
  18. * without specific prior written permission.
  19. *
  20. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  21. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  22. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  23. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  24. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  25. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  26. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  27. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  28. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  29. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  30. * SUCH DAMAGE.
  31. *
  32. * @(#)uipc_socket.c 8.3 (Berkeley) 4/15/94
  33. */
  34. /*
  35. * Comments on the socket life cycle:
  36. *
  37. * soalloc() sets of socket layer state for a socket, called only by
  38. * socreate() and sonewconn(). Socket layer private.
  39. *
  40. * sodealloc() tears down socket layer state for a socket, called only by
  41. * sofree() and sonewconn(). Socket layer private.
  42. *
  43. * pru_attach() associates protocol layer state with an allocated socket;
  44. * called only once, may fail, aborting socket allocation. This is called
  45. * from socreate() and sonewconn(). Socket layer private.
  46. *
  47. * pru_detach() disassociates protocol layer state from an attached socket,
  48. * and will be called exactly once for sockets in which pru_attach() has
  49. * been successfully called. If pru_attach() returned an error,
  50. * pru_detach() will not be called. Socket layer private.
  51. *
  52. * pru_abort() and pru_close() notify the protocol layer that the last
  53. * consumer of a socket is starting to tear down the socket, and that the
  54. * protocol should terminate the connection. Historically, pru_abort() also
  55. * detached protocol state from the socket state, but this is no longer the
  56. * case.
  57. *
  58. * socreate() creates a socket and attaches protocol state. This is a public
  59. * interface that may be used by socket layer consumers to create new
  60. * sockets.
  61. *
  62. * sonewconn() creates a socket and attaches protocol state. This is a
  63. * public interface that may be used by protocols to create new sockets when
  64. * a new connection is received and will be available for accept() on a
  65. * listen socket.
  66. *
  67. * soclose() destroys a socket after possibly waiting for it to disconnect.
  68. * This is a public interface that socket consumers should use to close and
  69. * release a socket when done with it.
  70. *
  71. * soabort() destroys a socket without waiting for it to disconnect (used
  72. * only for incoming connections that are already partially or fully
  73. * connected). This is used internally by the socket layer when clearing
  74. * listen socket queues (due to overflow or close on the listen socket), but
  75. * is also a public interface protocols may use to abort connections in
  76. * their incomplete listen queues should they no longer be required. Sockets
  77. * placed in completed connection listen queues should not be aborted for
  78. * reasons described in the comment above the soclose() implementation. This
  79. * is not a general purpose close routine, and except in the specific
  80. * circumstances described here, should not be used.
  81. *
  82. * sofree() will free a socket and its protocol state if all references on
  83. * the socket have been released, and is the public interface to attempt to
  84. * free a socket when a reference is removed. This is a socket layer private
  85. * interface.
  86. *
  87. * NOTE: In addition to socreate() and soclose(), which provide a single
  88. * socket reference to the consumer to be managed as required, there are two
  89. * calls to explicitly manage socket references, soref(), and sorele().
  90. * Currently, these are generally required only when transitioning a socket
  91. * from a listen queue to a file descriptor, in order to prevent garbage
  92. * collection of the socket at an untimely moment. For a number of reasons,
  93. * these interfaces are not preferred, and should be avoided.
  94. */
  95. #include <sys/cdefs.h>
  96. __FBSDID("$FreeBSD: src/sys/kern/uipc_socket.c,v 1.317 2008/10/01 19:14:05 jhb Exp $");
  97. #include <ntifs.h>
  98. #include <sys/param.h>
  99. #include <sys/systm.h>
  100. #include <sys/malloc.h>
  101. #include <sys/lock.h>
  102. #include <sys/spinlock.h>
  103. #include <sys/mbuf.h>
  104. #include <sys/domain.h>
  105. #include <sys/poll.h>
  106. #include <sys/protosw.h>
  107. #include <sys/socket.h>
  108. #include <sys/socketvar.h>
  109. #include <sys/sysctl.h>
  110. #include <sys/uio.h>
  111. #include <netinet/sctp_os.h>
  112. static int soreceive_rcvoob(struct socket *so, struct uio *uio,
  113. int flags);
  114. #if 0
  115. static void filt_sordetach(struct knote *kn);
  116. static int filt_soread(struct knote *kn, long hint);
  117. static void filt_sowdetach(struct knote *kn);
  118. static int filt_sowrite(struct knote *kn, long hint);
  119. static int filt_solisten(struct knote *kn, long hint);
  120. static struct filterops solisten_filtops =
  121. { 1, NULL, filt_sordetach, filt_solisten };
  122. static struct filterops soread_filtops =
  123. { 1, NULL, filt_sordetach, filt_soread };
  124. static struct filterops sowrite_filtops =
  125. { 1, NULL, filt_sowdetach, filt_sowrite };
  126. #endif
  127. NPAGED_LOOKASIDE_LIST socket_zone;
  128. so_gen_t so_gencnt; /* generation count for sockets */
  129. int maxsockets;
  130. MALLOC_DEFINE(M_SONAME, 'km01', "soname", "socket name");
  131. MALLOC_DEFINE(M_PCB, 'km02', "pcb", "protocol control block");
  132. static int somaxconn = SOMAXCONN;
  133. #if 0
  134. static int sysctl_somaxconn(SYSCTL_HANDLER_ARGS);
  135. /* XXX: we dont have SYSCTL_USHORT */
  136. SYSCTL_PROC(_kern_ipc, KIPC_SOMAXCONN, somaxconn, CTLTYPE_UINT | CTLFLAG_RW,
  137. 0, sizeof(int), sysctl_somaxconn, "I", "Maximum pending socket connection "
  138. "queue size");
  139. #endif
  140. static int numopensockets;
  141. #if 0
  142. SYSCTL_INT(_kern_ipc, OID_AUTO, numopensockets, CTLFLAG_RD,
  143. &numopensockets, 0, "Number of open sockets");
  144. #endif
  145. #ifdef ZERO_COPY_SOCKETS
  146. /* These aren't static because they're used in other files. */
  147. int so_zero_copy_send = 1;
  148. int so_zero_copy_receive = 1;
  149. SYSCTL_NODE(_kern_ipc, OID_AUTO, zero_copy, CTLFLAG_RD, 0,
  150. "Zero copy controls");
  151. SYSCTL_INT(_kern_ipc_zero_copy, OID_AUTO, receive, CTLFLAG_RW,
  152. &so_zero_copy_receive, 0, "Enable zero copy receive");
  153. SYSCTL_INT(_kern_ipc_zero_copy, OID_AUTO, send, CTLFLAG_RW,
  154. &so_zero_copy_send, 0, "Enable zero copy send");
  155. #endif /* ZERO_COPY_SOCKETS */
  156. /*
  157. * accept_mtx locks down per-socket fields relating to accept queues. See
  158. * socketvar.h for an annotation of the protected fields of struct socket.
  159. */
  160. struct spinlock accept_lock;
  161. /*
  162. * so_global_mtx protects so_gencnt, numopensockets, and the per-socket
  163. * so_gencnt field.
  164. */
  165. struct spinlock so_global_lock;
  166. #if 0
  167. /*
  168. * General IPC sysctl name space, used by sockets and a variety of other IPC
  169. * types.
  170. */
  171. SYSCTL_NODE(_kern, KERN_IPC, ipc, CTLFLAG_RW, 0, "IPC");
  172. /*
  173. * Sysctl to get and set the maximum global sockets limit. Notify protocols
  174. * of the change so that they can update their dependent limits as required.
  175. */
  176. static int
  177. sysctl_maxsockets(SYSCTL_HANDLER_ARGS)
  178. {
  179. int error, newmaxsockets;
  180. newmaxsockets = maxsockets;
  181. error = sysctl_handle_int(oidp, &newmaxsockets, 0, req);
  182. if (error == 0 && req->newptr) {
  183. if (newmaxsockets > maxsockets) {
  184. maxsockets = newmaxsockets;
  185. if (maxsockets > ((maxfiles / 4) * 3)) {
  186. maxfiles = (maxsockets * 5) / 4;
  187. maxfilesperproc = (maxfiles * 9) / 10;
  188. }
  189. EVENTHANDLER_INVOKE(maxsockets_change);
  190. } else
  191. error = EINVAL;
  192. }
  193. return (error);
  194. }
  195. SYSCTL_PROC(_kern_ipc, OID_AUTO, maxsockets, CTLTYPE_INT|CTLFLAG_RW,
  196. &maxsockets, 0, sysctl_maxsockets, "IU",
  197. "Maximum number of sockets avaliable");
  198. /*
  199. * Initialise maxsockets.
  200. */
  201. static void init_maxsockets(void *ignored)
  202. {
  203. TUNABLE_INT_FETCH("kern.ipc.maxsockets", &maxsockets);
  204. maxsockets = imax(maxsockets, imax(maxfiles, nmbclusters));
  205. }
  206. SYSINIT(param, SI_SUB_TUNABLES, SI_ORDER_ANY, init_maxsockets, NULL);
  207. #endif
  208. /*
  209. * Socket operation routines. These routines are called by the routines in
  210. * sys_socket.c or from a system process, and implement the semantics of
  211. * socket operations by switching out to the protocol specific routines.
  212. */
  213. /*
  214. * Get a socket structure from our zone, and initialize it. Note that it
  215. * would probably be better to allocate socket and PCB at the same time, but
  216. * I'm not convinced that all the protocols can be easily modified to do
  217. * this.
  218. *
  219. * soalloc() returns a socket with a ref count of 0.
  220. */
  221. static struct socket *
  222. soalloc(void)
  223. {
  224. struct socket *so;
  225. so = (struct socket *)ExAllocateFromNPagedLookasideList(&socket_zone);
  226. if (so == NULL)
  227. return (NULL);
  228. RtlZeroMemory(so, sizeof(*so));
  229. #ifdef MAC
  230. if (mac_socket_init(so, M_NOWAIT) != 0) {
  231. uma_zfree(socket_zone, so);
  232. return (NULL);
  233. }
  234. #endif
  235. SOCKBUF_LOCK_INIT(&so->so_snd, "so_snd");
  236. SOCKBUF_LOCK_INIT(&so->so_rcv, "so_rcv");
  237. SOCKEVENT_LOCK_INIT(&so->so_event, "so_event");
  238. InitializeListHead(&so->so_snd.sb_csq.irpList);
  239. spinlock_init(&so->so_snd.sb_csq.lock, "sb_csq", "sb_csq", 0);
  240. IoCsqInitialize((PIO_CSQ)&so->so_snd.sb_csq,
  241. AioCsqInsertIrp, AioCsqRemoveIrp, AioCsqPeekNextIrp,
  242. AioCsqAcquireLock, AioCsqReleaseLock, AioCsqCompleteCanceledIrp);
  243. InitializeListHead(&so->so_rcv.sb_csq.irpList);
  244. spinlock_init(&so->so_rcv.sb_csq.lock, "sb_csq", "sb_csq", 0);
  245. IoCsqInitialize((PIO_CSQ)&so->so_rcv.sb_csq,
  246. AioCsqInsertIrp, AioCsqRemoveIrp, AioCsqPeekNextIrp,
  247. AioCsqAcquireLock, AioCsqReleaseLock, AioCsqCompleteCanceledIrp);
  248. spinlock_acquire(&so_global_lock);
  249. so->so_gencnt = ++so_gencnt;
  250. ++numopensockets;
  251. spinlock_release(&so_global_lock);
  252. return (so);
  253. }
  254. /*
  255. * Free the storage associated with a socket at the socket layer, tear down
  256. * locks, labels, etc. All protocol state is assumed already to have been
  257. * torn down (and possibly never set up) by the caller.
  258. */
  259. static void
  260. sodealloc(struct socket *so)
  261. {
  262. KASSERT(so->so_count == 0, ("sodealloc(): so_count %d", so->so_count));
  263. KASSERT(so->so_pcb == NULL, ("sodealloc(): so_pcb != NULL"));
  264. spinlock_acquire(&so_global_lock);
  265. so->so_gencnt = ++so_gencnt;
  266. --numopensockets; /* Could be below, but faster here. */
  267. spinlock_release(&so_global_lock);
  268. #if 0
  269. if (so->so_rcv.sb_hiwat)
  270. (void)chgsbsize(so->so_cred->cr_uidinfo,
  271. &so->so_rcv.sb_hiwat, 0, RLIM_INFINITY);
  272. if (so->so_snd.sb_hiwat)
  273. (void)chgsbsize(so->so_cred->cr_uidinfo,
  274. &so->so_snd.sb_hiwat, 0, RLIM_INFINITY);
  275. #ifdef INET
  276. /* remove acccept filter if one is present. */
  277. if (so->so_accf != NULL)
  278. do_setopt_accept_filter(so, NULL);
  279. #endif
  280. #endif
  281. #ifdef MAC
  282. mac_socket_destroy(so);
  283. #endif
  284. //crfree(so->so_cred);
  285. SOCKBUF_LOCK_DESTROY(&so->so_snd);
  286. SOCKBUF_LOCK_DESTROY(&so->so_rcv);
  287. SOCKEVENT_LOCK(&so->so_event);
  288. if (so->so_event.se_Event != NULL) {
  289. ObDereferenceObject(so->so_event.se_Event);
  290. so->so_event.se_Event = NULL;
  291. }
  292. SOCKEVENT_LOCK_DESTROY(&so->so_event);
  293. ExFreeToNPagedLookasideList(&socket_zone, so);
  294. }
  295. /*
  296. * socreate returns a socket with a ref count of 1. The socket should be
  297. * closed with soclose().
  298. */
  299. int
  300. socreate(int dom, struct socket **aso, int type, int proto,
  301. struct ucred *cred, PKTHREAD td)
  302. {
  303. struct protosw *prp;
  304. struct socket *so;
  305. int error;
  306. if (proto)
  307. prp = pffindproto(dom, proto, type);
  308. else
  309. prp = pffindtype(dom, type);
  310. if (prp == NULL || prp->pr_usrreqs->pru_attach == NULL ||
  311. prp->pr_usrreqs->pru_attach == pru_attach_notsupp)
  312. return (EPROTONOSUPPORT);
  313. if (prp->pr_type != type)
  314. return (EPROTOTYPE);
  315. so = soalloc();
  316. if (so == NULL)
  317. return (ENOBUFS);
  318. TAILQ_INIT(&so->so_incomp);
  319. TAILQ_INIT(&so->so_comp);
  320. so->so_type = type;
  321. #if 0
  322. so->so_cred = crhold(cred);
  323. if ((prp->pr_domain->dom_family == PF_INET) ||
  324. (prp->pr_domain->dom_family == PF_ROUTE))
  325. so->so_fibnum = td->td_proc->p_fibnum;
  326. else
  327. #endif
  328. so->so_fibnum = 0;
  329. so->so_proto = prp;
  330. #ifdef MAC
  331. mac_create_socket(cred, so);
  332. #endif
  333. KeInitializeEvent(&so->so_waitEvent, NotificationEvent, FALSE);
  334. KeInitializeEvent(&so->so_waitSyncEvent, SynchronizationEvent, FALSE);
  335. KeInitializeEvent(&so->so_rcv.sb_waitEvent, NotificationEvent, FALSE);
  336. KeInitializeEvent(&so->so_snd.sb_waitEvent, NotificationEvent, FALSE);
  337. KeInitializeEvent(&so->so_rcv.sb_selEvent, SynchronizationEvent, FALSE);
  338. KeInitializeEvent(&so->so_snd.sb_selEvent, SynchronizationEvent, FALSE);
  339. KeInitializeEvent(&so->so_rcv.sb_lockEvent, SynchronizationEvent, FALSE);
  340. KeInitializeEvent(&so->so_snd.sb_lockEvent, SynchronizationEvent, FALSE);
  341. so->so_count = 1;
  342. /*
  343. * Auto-sizing of socket buffers is managed by the protocols and
  344. * the appropriate flags must be set in the pru_attach function.
  345. */
  346. error = (*prp->pr_usrreqs->pru_attach)(so, proto, td);
  347. if (error) {
  348. KASSERT(so->so_count == 1, ("socreate: so_count %d",
  349. so->so_count));
  350. so->so_count = 0;
  351. sodealloc(so);
  352. return (error);
  353. }
  354. *aso = so;
  355. return (0);
  356. }
  357. #ifdef REGRESSION
  358. static int regression_sonewconn_earlytest = 1;
  359. SYSCTL_INT(_regression, OID_AUTO, sonewconn_earlytest, CTLFLAG_RW,
  360. &regression_sonewconn_earlytest, 0, "Perform early sonewconn limit test");
  361. #endif
  362. /*
  363. * When an attempt at a new connection is noted on a socket which accepts
  364. * connections, sonewconn is called. If the connection is possible (subject
  365. * to space constraints, etc.) then we allocate a new structure, propoerly
  366. * linked into the data structure of the original socket, and return this.
  367. * Connstatus may be 0, or SO_ISCONFIRMING, or SO_ISCONNECTED.
  368. *
  369. * Note: the ref count on the socket is 0 on return.
  370. */
  371. struct socket *
  372. sonewconn(struct socket *head, int connstatus)
  373. {
  374. struct socket *so;
  375. int over;
  376. ACCEPT_LOCK();
  377. over = (head->so_qlen > 3 * head->so_qlimit / 2);
  378. ACCEPT_UNLOCK();
  379. #ifdef REGRESSION
  380. if (regression_sonewconn_earlytest && over)
  381. #else
  382. if (over)
  383. #endif
  384. return (NULL);
  385. so = soalloc();
  386. if (so == NULL)
  387. return (NULL);
  388. if ((head->so_options & SO_ACCEPTFILTER) != 0)
  389. connstatus = 0;
  390. so->so_head = head;
  391. so->so_type = head->so_type;
  392. so->so_options = head->so_options &~ SO_ACCEPTCONN;
  393. so->so_linger = head->so_linger;
  394. so->so_state = head->so_state | SS_NOFDREF;
  395. so->so_proto = head->so_proto;
  396. //so->so_cred = crhold(head->so_cred);
  397. #ifdef MAC
  398. SOCK_LOCK(head);
  399. mac_socket_newconn(head, so);
  400. SOCK_UNLOCK(head);
  401. #endif
  402. KeInitializeEvent(&so->so_waitEvent, NotificationEvent, FALSE);
  403. KeInitializeEvent(&so->so_waitSyncEvent, SynchronizationEvent, FALSE);
  404. KeInitializeEvent(&so->so_rcv.sb_waitEvent, NotificationEvent, FALSE);
  405. KeInitializeEvent(&so->so_snd.sb_waitEvent, NotificationEvent, FALSE);
  406. KeInitializeEvent(&so->so_rcv.sb_selEvent, SynchronizationEvent, FALSE);
  407. KeInitializeEvent(&so->so_snd.sb_selEvent, SynchronizationEvent, FALSE);
  408. KeInitializeEvent(&so->so_rcv.sb_lockEvent, SynchronizationEvent, FALSE);
  409. KeInitializeEvent(&so->so_snd.sb_lockEvent, SynchronizationEvent, FALSE);
  410. if (soreserve(so, head->so_snd.sb_hiwat, head->so_rcv.sb_hiwat) ||
  411. (*so->so_proto->pr_usrreqs->pru_attach)(so, 0, NULL)) {
  412. sodealloc(so);
  413. return (NULL);
  414. }
  415. so->so_rcv.sb_lowat = head->so_rcv.sb_lowat;
  416. so->so_snd.sb_lowat = head->so_snd.sb_lowat;
  417. so->so_rcv.sb_timeo = head->so_rcv.sb_timeo;
  418. so->so_snd.sb_timeo = head->so_snd.sb_timeo;
  419. so->so_rcv.sb_flags |= head->so_rcv.sb_flags & SB_AUTOSIZE;
  420. so->so_snd.sb_flags |= head->so_snd.sb_flags & SB_AUTOSIZE;
  421. so->so_state |= connstatus;
  422. SOCKEVENT_LOCK(&head->so_event);
  423. if (head->so_event.se_Event != NULL) {
  424. ObReferenceObject(head->so_event.se_Event);
  425. so->so_event.se_Event = head->so_event.se_Event;
  426. }
  427. SOCKEVENT_UNLOCK(&head->so_event);
  428. ACCEPT_LOCK();
  429. if (connstatus) {
  430. TAILQ_INSERT_TAIL(&head->so_comp, so, so_list);
  431. so->so_qstate |= SQ_COMP;
  432. head->so_qlen++;
  433. } else {
  434. /*
  435. * Keep removing sockets from the head until there's room for
  436. * us to insert on the tail. In pre-locking revisions, this
  437. * was a simple if(), but as we could be racing with other
  438. * threads and soabort() requires dropping locks, we must
  439. * loop waiting for the condition to be true.
  440. */
  441. while (head->so_incqlen > head->so_qlimit) {
  442. struct socket *sp;
  443. sp = TAILQ_FIRST(&head->so_incomp);
  444. TAILQ_REMOVE(&head->so_incomp, sp, so_list);
  445. head->so_incqlen--;
  446. sp->so_qstate &= ~SQ_INCOMP;
  447. sp->so_head = NULL;
  448. ACCEPT_UNLOCK();
  449. soabort(sp);
  450. ACCEPT_LOCK();
  451. }
  452. TAILQ_INSERT_TAIL(&head->so_incomp, so, so_list);
  453. so->so_qstate |= SQ_INCOMP;
  454. head->so_incqlen++;
  455. }
  456. ACCEPT_UNLOCK();
  457. if (connstatus) {
  458. SOCKEVENT_LOCK(&head->so_event);
  459. if (head->so_event.se_Event != NULL && (head->so_event.se_Events & FD_ACCEPT) != 0) {
  460. head->so_event.se_EventsRet.lNetworkEvents |= FD_ACCEPT;
  461. KeSetEvent(head->so_event.se_Event, 0, FALSE);
  462. }
  463. SOCKEVENT_UNLOCK(&head->so_event);
  464. sorwakeup(head);
  465. KeSetEvent(&head->so_waitSyncEvent, 0, FALSE);
  466. }
  467. return (so);
  468. }
  469. int
  470. sobind(struct socket *so, struct sockaddr *nam, PKTHREAD td)
  471. {
  472. return ((*so->so_proto->pr_usrreqs->pru_bind)(so, nam, td));
  473. }
  474. /*
  475. * solisten() transitions a socket from a non-listening state to a listening
  476. * state, but can also be used to update the listen queue depth on an
  477. * existing listen socket. The protocol will call back into the sockets
  478. * layer using solisten_proto_check() and solisten_proto() to check and set
  479. * socket-layer listen state. Call backs are used so that the protocol can
  480. * acquire both protocol and socket layer locks in whatever order is required
  481. * by the protocol.
  482. *
  483. * Protocol implementors are advised to hold the socket lock across the
  484. * socket-layer test and set to avoid races at the socket layer.
  485. */
  486. int
  487. solisten(struct socket *so, int backlog, PKTHREAD td)
  488. {
  489. return ((*so->so_proto->pr_usrreqs->pru_listen)(so, backlog, td));
  490. }
  491. int
  492. solisten_proto_check(struct socket *so)
  493. {
  494. SOCK_LOCK_ASSERT(so);
  495. if (so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING |
  496. SS_ISDISCONNECTING))
  497. return (EINVAL);
  498. return (0);
  499. }
  500. void
  501. solisten_proto(struct socket *so, int backlog)
  502. {
  503. SOCK_LOCK_ASSERT(so);
  504. if (backlog < 0 || backlog > somaxconn)
  505. backlog = somaxconn;
  506. so->so_qlimit = backlog;
  507. so->so_options |= SO_ACCEPTCONN;
  508. }
  509. /*
  510. * Attempt to free a socket. This should really be sotryfree().
  511. *
  512. * sofree() will succeed if:
  513. *
  514. * - There are no outstanding file descriptor references or related consumers
  515. * (so_count == 0).
  516. *
  517. * - The socket has been closed by user space, if ever open (SS_NOFDREF).
  518. *
  519. * - The protocol does not have an outstanding strong reference on the socket
  520. * (SS_PROTOREF).
  521. *
  522. * - The socket is not in a completed connection queue, so a process has been
  523. * notified that it is present. If it is removed, the user process may
  524. * block in accept() despite select() saying the socket was ready.
  525. *
  526. * Otherwise, it will quietly abort so that a future call to sofree(), when
  527. * conditions are right, can succeed.
  528. */
  529. void
  530. sofree(struct socket *so)
  531. {
  532. struct socket *head;
  533. ACCEPT_LOCK_ASSERT();
  534. SOCK_LOCK_ASSERT(so);
  535. if ((so->so_state & SS_NOFDREF) == 0 || so->so_count != 0 ||
  536. (so->so_state & SS_PROTOREF) || (so->so_qstate & SQ_COMP)) {
  537. SOCK_UNLOCK(so);
  538. ACCEPT_UNLOCK();
  539. return;
  540. }
  541. head = so->so_head;
  542. if (head != NULL) {
  543. KASSERT((so->so_qstate & SQ_COMP) != 0 ||
  544. (so->so_qstate & SQ_INCOMP) != 0,
  545. ("sofree: so_head != NULL, but neither SQ_COMP nor "
  546. "SQ_INCOMP"));
  547. KASSERT((so->so_qstate & SQ_COMP) == 0 ||
  548. (so->so_qstate & SQ_INCOMP) == 0,
  549. ("sofree: so->so_qstate is SQ_COMP and also SQ_INCOMP"));
  550. TAILQ_REMOVE(&head->so_incomp, so, so_list);
  551. head->so_incqlen--;
  552. so->so_qstate &= ~SQ_INCOMP;
  553. so->so_head = NULL;
  554. }
  555. KASSERT((so->so_qstate & SQ_COMP) == 0 &&
  556. (so->so_qstate & SQ_INCOMP) == 0,
  557. ("sofree: so_head == NULL, but still SQ_COMP(%d) or SQ_INCOMP(%d)",
  558. so->so_qstate & SQ_COMP, so->so_qstate & SQ_INCOMP));
  559. if (so->so_options & SO_ACCEPTCONN) {
  560. KASSERT((TAILQ_EMPTY(&so->so_comp)), ("sofree: so_comp populated"));
  561. KASSERT((TAILQ_EMPTY(&so->so_incomp)), ("sofree: so_comp populated"));
  562. }
  563. SOCK_UNLOCK(so);
  564. ACCEPT_UNLOCK();
  565. #if 0
  566. if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose != NULL)
  567. (*pr->pr_domain->dom_dispose)(so->so_rcv.sb_mb);
  568. #endif
  569. if (so->so_proto->pr_usrreqs->pru_detach != NULL)
  570. (*so->so_proto->pr_usrreqs->pru_detach)(so);
  571. /*
  572. * From this point on, we assume that no other references to this
  573. * socket exist anywhere else in the stack. Therefore, no locks need
  574. * to be acquired or held.
  575. *
  576. * We used to do a lot of socket buffer and socket locking here, as
  577. * well as invoke sorflush() and perform wakeups. The direct call to
  578. * dom_dispose() and sbrelease_internal() are an inlining of what was
  579. * necessary from sorflush().
  580. *
  581. * Notice that the socket buffer and kqueue state are torn down
  582. * before calling pru_detach. This means that protocols shold not
  583. * assume they can perform socket wakeups, etc, in their detach code.
  584. */
  585. sbdestroy(&so->so_snd, so);
  586. sbdestroy(&so->so_rcv, so);
  587. sodealloc(so);
  588. }
  589. /*
  590. * Close a socket on last file table reference removal. Initiate disconnect
  591. * if connected. Free socket when disconnect complete.
  592. *
  593. * This function will sorele() the socket. Note that soclose() may be called
  594. * prior to the ref count reaching zero. The actual socket structure will
  595. * not be freed until the ref count reaches zero.
  596. */
  597. int
  598. soclose(struct socket *so)
  599. {
  600. int error = 0;
  601. NTSTATUS status = STATUS_SUCCESS;
  602. LARGE_INTEGER timeout;
  603. KIRQL oldIrql;
  604. KASSERT(!(so->so_state & SS_NOFDREF), ("soclose: SS_NOFDREF on enter"));
  605. //funsetown(&so->so_sigio);
  606. if (so->so_state & SS_ISCONNECTED) {
  607. if ((so->so_state & SS_ISDISCONNECTING) == 0) {
  608. error = sodisconnect(so);
  609. if (error)
  610. goto drop;
  611. }
  612. if (so->so_options & SO_LINGER) {
  613. if ((so->so_state & SS_ISDISCONNECTING) &&
  614. (so->so_state & SS_NBIO))
  615. goto drop;
  616. timeout.QuadPart = -10000000 * so->so_linger;
  617. SOCK_LOCK(so);
  618. if (so->so_state & SS_ISCONNECTED) {
  619. SOCK_UNLOCK(so);
  620. KeClearEvent(&so->so_waitEvent);
  621. status = KeWaitForSingleObject(&so->so_waitEvent, UserRequest,
  622. UserMode, FALSE, so->so_linger > 0 ? &timeout : NULL);
  623. } else {
  624. SOCK_UNLOCK(so);
  625. }
  626. }
  627. }
  628. drop:
  629. if (so->so_proto->pr_usrreqs->pru_close != NULL)
  630. (*so->so_proto->pr_usrreqs->pru_close)(so);
  631. if (so->so_options & SO_ACCEPTCONN) {
  632. struct socket *sp;
  633. ACCEPT_LOCK();
  634. while ((sp = TAILQ_FIRST(&so->so_incomp)) != NULL) {
  635. TAILQ_REMOVE(&so->so_incomp, sp, so_list);
  636. so->so_incqlen--;
  637. sp->so_qstate &= ~SQ_INCOMP;
  638. sp->so_head = NULL;
  639. ACCEPT_UNLOCK();
  640. soabort(sp);
  641. ACCEPT_LOCK();
  642. }
  643. while ((sp = TAILQ_FIRST(&so->so_comp)) != NULL) {
  644. TAILQ_REMOVE(&so->so_comp, sp, so_list);
  645. so->so_qlen--;
  646. sp->so_qstate &= ~SQ_COMP;
  647. sp->so_head = NULL;
  648. ACCEPT_UNLOCK();
  649. soabort(sp);
  650. ACCEPT_LOCK();
  651. }
  652. ACCEPT_UNLOCK();
  653. } else {
  654. SOCKEVENT_LOCK(&so->so_event);
  655. if (so->so_event.se_Event != NULL && (so->so_event.se_Events & FD_CLOSE) != 0) {
  656. so->so_event.se_EventsRet.lNetworkEvents |= FD_CLOSE;
  657. KeSetEvent(so->so_event.se_Event, 0, FALSE);
  658. }
  659. SOCKEVENT_UNLOCK(&so->so_event);
  660. }
  661. ACCEPT_LOCK();
  662. SOCK_LOCK(so);
  663. KASSERT((so->so_state & SS_NOFDREF) == 0, ("soclose: NOFDREF"));
  664. so->so_state |= SS_NOFDREF;
  665. sorele(so);
  666. return (error);
  667. }
  668. /*
  669. * soabort() is used to abruptly tear down a connection, such as when a
  670. * resource limit is reached (listen queue depth exceeded), or if a listen
  671. * socket is closed while there are sockets waiting to be accepted.
  672. *
  673. * This interface is tricky, because it is called on an unreferenced socket,
  674. * and must be called only by a thread that has actually removed the socket
  675. * from the listen queue it was on, or races with other threads are risked.
  676. *
  677. * This interface will call into the protocol code, so must not be called
  678. * with any socket locks held. Protocols do call it while holding their own
  679. * recursible protocol mutexes, but this is something that should be subject
  680. * to review in the future.
  681. */
  682. void
  683. soabort(struct socket *so)
  684. {
  685. /*
  686. * In as much as is possible, assert that no references to this
  687. * socket are held. This is not quite the same as asserting that the
  688. * current thread is responsible for arranging for no references, but
  689. * is as close as we can get for now.
  690. */
  691. KASSERT(so->so_count == 0, ("soabort: so_count"));
  692. KASSERT((so->so_state & SS_PROTOREF) == 0, ("soabort: SS_PROTOREF"));
  693. KASSERT(so->so_state & SS_NOFDREF, ("soabort: !SS_NOFDREF"));
  694. KASSERT((so->so_state & SQ_COMP) == 0, ("soabort: SQ_COMP"));
  695. KASSERT((so->so_state & SQ_INCOMP) == 0, ("soabort: SQ_INCOMP"));
  696. if (so->so_proto->pr_usrreqs->pru_abort != NULL)
  697. (*so->so_proto->pr_usrreqs->pru_abort)(so);
  698. ACCEPT_LOCK();
  699. SOCK_LOCK(so);
  700. sofree(so);
  701. }
  702. int
  703. soaccept(struct socket *so, struct sockaddr **nam)
  704. {
  705. int error;
  706. SOCK_LOCK(so);
  707. KASSERT((so->so_state & SS_NOFDREF) != 0, ("soaccept: !NOFDREF"));
  708. so->so_state &= ~SS_NOFDREF;
  709. SOCK_UNLOCK(so);
  710. error = (*so->so_proto->pr_usrreqs->pru_accept)(so, nam);
  711. return (error);
  712. }
  713. int
  714. soconnect(struct socket *so, struct sockaddr *nam, PKTHREAD td)
  715. {
  716. int error;
  717. if (so->so_options & SO_ACCEPTCONN)
  718. return (EOPNOTSUPP);
  719. /*
  720. * If protocol is connection-based, can only connect once.
  721. * Otherwise, if connected, try to disconnect first. This allows
  722. * user to disconnect by connecting to, e.g., a null address.
  723. */
  724. if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
  725. ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
  726. (error = sodisconnect(so)))) {
  727. error = EISCONN;
  728. } else {
  729. /*
  730. * Prevent accumulated error from previous connection from
  731. * biting us.
  732. */
  733. so->so_error = 0;
  734. error = (*so->so_proto->pr_usrreqs->pru_connect)(so, nam, td);
  735. }
  736. return (error);
  737. }
  738. int
  739. soconnect2(struct socket *so1, struct socket *so2)
  740. {
  741. return ((*so1->so_proto->pr_usrreqs->pru_connect2)(so1, so2));
  742. }
  743. int
  744. sodisconnect(struct socket *so)
  745. {
  746. int error;
  747. if ((so->so_state & SS_ISCONNECTED) == 0)
  748. return (ENOTCONN);
  749. if (so->so_state & SS_ISDISCONNECTING)
  750. return (EALREADY);
  751. error = (*so->so_proto->pr_usrreqs->pru_disconnect)(so);
  752. return (error);
  753. }
  754. #ifdef ZERO_COPY_SOCKETS
  755. struct so_zerocopy_stats{
  756. int size_ok;
  757. int align_ok;
  758. int found_ifp;
  759. };
  760. struct so_zerocopy_stats so_zerocp_stats = {0,0,0};
  761. #include <netinet/in.h>
  762. #include <net/route.h>
  763. #include <netinet/in_pcb.h>
  764. #include <vm/vm.h>
  765. #include <vm/vm_page.h>
  766. #include <vm/vm_object.h>
  767. /*
  768. * sosend_copyin() is only used if zero copy sockets are enabled. Otherwise
  769. * sosend_dgram() and sosend_generic() use m_uiotombuf().
  770. *
  771. * sosend_copyin() accepts a uio and prepares an mbuf chain holding part or
  772. * all of the data referenced by the uio. If desired, it uses zero-copy.
  773. * *space will be updated to reflect data copied in.
  774. *
  775. * NB: If atomic I/O is requested, the caller must already have checked that
  776. * space can hold resid bytes.
  777. *
  778. * NB: In the event of an error, the caller may need to free the partial
  779. * chain pointed to by *mpp. The contents of both *uio and *space may be
  780. * modified even in the case of an error.
  781. */
  782. static int
  783. sosend_copyin(struct uio *uio, struct mbuf **retmp, int atomic, long *space,
  784. int flags)
  785. {
  786. struct mbuf *m, **mp, *top;
  787. long len, resid;
  788. int error;
  789. #ifdef ZERO_COPY_SOCKETS
  790. int cow_send;
  791. #endif
  792. *retmp = top = NULL;
  793. mp = &top;
  794. len = 0;
  795. resid = uio->uio_resid;
  796. error = 0;
  797. do {
  798. #ifdef ZERO_COPY_SOCKETS
  799. cow_send = 0;
  800. #endif /* ZERO_COPY_SOCKETS */
  801. if (resid >= MINCLSIZE) {
  802. #ifdef ZERO_COPY_SOCKETS
  803. if (top == NULL) {
  804. m = m_gethdr(M_WAITOK, MT_DATA);
  805. m->m_pkthdr.len = 0;
  806. m->m_pkthdr.rcvif = NULL;
  807. } else
  808. m = m_get(M_WAITOK, MT_DATA);
  809. if (so_zero_copy_send &&
  810. resid>=PAGE_SIZE &&
  811. *space>=PAGE_SIZE &&
  812. uio->uio_iov->iov_len>=PAGE_SIZE) {
  813. so_zerocp_stats.size_ok++;
  814. so_zerocp_stats.align_ok++;
  815. cow_send = socow_setup(m, uio);
  816. len = cow_send;
  817. }
  818. if (!cow_send) {
  819. m_clget(m, M_WAITOK);
  820. len = min(min(MCLBYTES, resid), *space);
  821. }
  822. #else /* ZERO_COPY_SOCKETS */
  823. if (top == NULL) {
  824. m = m_getcl(M_WAIT, MT_DATA, M_PKTHDR);
  825. m->m_pkthdr.len = 0;
  826. m->m_pkthdr.rcvif = NULL;
  827. } else
  828. m = m_getcl(M_WAIT, MT_DATA, 0);
  829. len = min(min(MCLBYTES, resid), *space);
  830. #endif /* ZERO_COPY_SOCKETS */
  831. } else {
  832. if (top == NULL) {
  833. m = m_gethdr(M_WAIT, MT_DATA);
  834. m->m_pkthdr.len = 0;
  835. m->m_pkthdr.rcvif = NULL;
  836. len = min(min(MHLEN, resid), *space);
  837. /*
  838. * For datagram protocols, leave room
  839. * for protocol headers in first mbuf.
  840. */
  841. if (atomic && m && len < MHLEN)
  842. MH_ALIGN(m, len);
  843. } else {
  844. m = m_get(M_WAIT, MT_DATA);
  845. len = min(min(MLEN, resid), *space);
  846. }
  847. }
  848. if (m == NULL) {
  849. error = ENOBUFS;
  850. goto out;
  851. }
  852. *space -= len;
  853. #ifdef ZERO_COPY_SOCKETS
  854. if (cow_send)
  855. error = 0;
  856. else
  857. #endif /* ZERO_COPY_SOCKETS */
  858. error = uiomove(mtod(m, void *), (int)len, uio);
  859. resid = uio->uio_resid;
  860. m->m_len = len;
  861. *mp = m;
  862. top->m_pkthdr.len += len;
  863. if (error)
  864. goto out;
  865. mp = &m->m_next;
  866. if (resid <= 0) {
  867. if (flags & MSG_EOR)
  868. top->m_flags |= M_EOR;
  869. break;
  870. }
  871. } while (*space > 0 && atomic);
  872. out:
  873. *retmp = top;
  874. return (error);
  875. }
  876. #endif /*ZERO_COPY_SOCKETS*/
  877. #define SBLOCKWAIT(f) (((f) & MSG_DONTWAIT) ? 0 : SBL_WAIT)
  878. #if 0
  879. int
  880. sosend_dgram(struct socket *so, struct sockaddr *addr, struct uio *uio,
  881. struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
  882. {
  883. long space, resid;
  884. int clen = 0, error, dontroute;
  885. #ifdef ZERO_COPY_SOCKETS
  886. int atomic = sosendallatonce(so) || top;
  887. #endif
  888. KASSERT(so->so_type == SOCK_DGRAM, ("sodgram_send: !SOCK_DGRAM"));
  889. KASSERT(so->so_proto->pr_flags & PR_ATOMIC,
  890. ("sodgram_send: !PR_ATOMIC"));
  891. if (uio != NULL)
  892. resid = uio->uio_resid;
  893. else
  894. resid = top->m_pkthdr.len;
  895. /*
  896. * In theory resid should be unsigned. However, space must be
  897. * signed, as it might be less than 0 if we over-committed, and we
  898. * must use a signed comparison of space and resid. On the other
  899. * hand, a negative resid causes us to loop sending 0-length
  900. * segments to the protocol.
  901. *
  902. * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
  903. * type sockets since that's an error.
  904. */
  905. if (resid < 0) {
  906. error = EINVAL;
  907. goto out;
  908. }
  909. dontroute =
  910. (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0;
  911. if (td != NULL)
  912. td->td_ru.ru_msgsnd++;
  913. if (control != NULL)
  914. clen = control->m_len;
  915. SOCKBUF_LOCK(&so->so_snd);
  916. if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
  917. SOCKBUF_UNLOCK(&so->so_snd);
  918. error = EPIPE;
  919. goto out;
  920. }
  921. if (so->so_error) {
  922. error = so->so_error;
  923. so->so_error = 0;
  924. SOCKBUF_UNLOCK(&so->so_snd);
  925. goto out;
  926. }
  927. if ((so->so_state & SS_ISCONNECTED) == 0) {
  928. /*
  929. * `sendto' and `sendmsg' is allowed on a connection-based
  930. * socket if it supports implied connect. Return ENOTCONN if
  931. * not connected and no address is supplied.
  932. */
  933. if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
  934. (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
  935. if ((so->so_state & SS_ISCONFIRMING) == 0 &&
  936. !(resid == 0 && clen != 0)) {
  937. SOCKBUF_UNLOCK(&so->so_snd);
  938. error = ENOTCONN;
  939. goto out;
  940. }
  941. } else if (addr == NULL) {
  942. if (so->so_proto->pr_flags & PR_CONNREQUIRED)
  943. error = ENOTCONN;
  944. else
  945. error = EDESTADDRREQ;
  946. SOCKBUF_UNLOCK(&so->so_snd);
  947. goto out;
  948. }
  949. }
  950. /*
  951. * Do we need MSG_OOB support in SOCK_DGRAM? Signs here may be a
  952. * problem and need fixing.
  953. */
  954. space = sbspace(&so->so_snd);
  955. if (flags & MSG_OOB)
  956. space += 1024;
  957. space -= clen;
  958. SOCKBUF_UNLOCK(&so->so_snd);
  959. if (resid > space) {
  960. error = EMSGSIZE;
  961. goto out;
  962. }
  963. if (uio == NULL) {
  964. resid = 0;
  965. if (flags & MSG_EOR)
  966. top->m_flags |= M_EOR;
  967. } else {
  968. #ifdef ZERO_COPY_SOCKETS
  969. error = sosend_copyin(uio, &top, atomic, &space, flags);
  970. if (error)
  971. goto out;
  972. #else
  973. /*
  974. * Copy the data from userland into a mbuf chain.
  975. * If no data is to be copied in, a single empty mbuf
  976. * is returned.
  977. */
  978. top = m_uiotombuf(uio, M_WAITOK, space, max_hdr,
  979. (M_PKTHDR | ((flags & MSG_EOR) ? M_EOR : 0)));
  980. if (top == NULL) {
  981. error = EFAULT; /* only possible error */
  982. goto out;
  983. }
  984. space -= resid - uio->uio_resid;
  985. #endif
  986. resid = uio->uio_resid;
  987. }
  988. KASSERT(resid == 0, ("sosend_dgram: resid != 0"));
  989. /*
  990. * XXXRW: Frobbing SO_DONTROUTE here is even worse without sblock
  991. * than with.
  992. */
  993. if (dontroute) {
  994. SOCK_LOCK(so);
  995. so->so_options |= SO_DONTROUTE;
  996. SOCK_UNLOCK(so);
  997. }
  998. /*
  999. * XXX all the SBS_CANTSENDMORE checks previously done could be out
  1000. * of date. We could have recieved a reset packet in an interrupt or
  1001. * maybe we slept while doing page faults in uiomove() etc. We could
  1002. * probably recheck again inside the locking protection here, but
  1003. * there are probably other places that this also happens. We must
  1004. * rethink this.
  1005. */
  1006. error = (*so->so_proto->pr_usrreqs->pru_send)(so,
  1007. (flags & MSG_OOB) ? PRUS_OOB :
  1008. /*
  1009. * If the user set MSG_EOF, the protocol understands this flag and
  1010. * nothing left to send then use PRU_SEND_EOF instead of PRU_SEND.
  1011. */
  1012. ((flags & MSG_EOF) &&
  1013. (so->so_proto->pr_flags & PR_IMPLOPCL) &&
  1014. (resid <= 0)) ?
  1015. PRUS_EOF :
  1016. /* If there is more to send set PRUS_MORETOCOME */
  1017. (resid > 0 && space > 0) ? PRUS_MORETOCOME : 0,
  1018. top, addr, control, td);
  1019. if (dontroute) {
  1020. SOCK_LOCK(so);
  1021. so->so_options &= ~SO_DONTROUTE;
  1022. SOCK_UNLOCK(so);
  1023. }
  1024. clen = 0;
  1025. control = NULL;
  1026. top = NULL;
  1027. out:
  1028. if (top != NULL)
  1029. m_freem(top);
  1030. if (control != NULL)
  1031. m_freem(control);
  1032. return (error);
  1033. }
  1034. /*
  1035. * Send on a socket. If send must go all at once and message is larger than
  1036. * send buffering, then hard error. Lock against other senders. If must go
  1037. * all at once and not enough room now, then inform user that this would
  1038. * block and do nothing. Otherwise, if nonblocking, send as much as
  1039. * possible. The data to be sent is described by "uio" if nonzero, otherwise
  1040. * by the mbuf chain "top" (which must be null if uio is not). Data provided
  1041. * in mbuf chain must be small enough to send all at once.
  1042. *
  1043. * Returns nonzero on error, timeout or signal; callers must check for short
  1044. * counts if EINTR/ERESTART are returned. Data and control buffers are freed
  1045. * on return.
  1046. */
  1047. int
  1048. sosend_generic(struct socket *so, struct sockaddr *addr, struct uio *uio,
  1049. struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
  1050. {
  1051. long space, resid;
  1052. int clen = 0, error, dontroute;
  1053. int atomic = sosendallatonce(so) || top;
  1054. if (uio != NULL)
  1055. resid = uio->uio_resid;
  1056. else
  1057. resid = top->m_pkthdr.len;
  1058. /*
  1059. * In theory resid should be unsigned. However, space must be
  1060. * signed, as it might be less than 0 if we over-committed, and we
  1061. * must use a signed comparison of space and resid. On the other
  1062. * hand, a negative resid causes us to loop sending 0-length
  1063. * segments to the protocol.
  1064. *
  1065. * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
  1066. * type sockets since that's an error.
  1067. */
  1068. if (resid < 0 || (so->so_type == SOCK_STREAM && (flags & MSG_EOR))) {
  1069. error = EINVAL;
  1070. goto out;
  1071. }
  1072. dontroute =
  1073. (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
  1074. (so->so_proto->pr_flags & PR_ATOMIC);
  1075. if (td != NULL)
  1076. td->td_ru.ru_msgsnd++;
  1077. if (control != NULL)
  1078. clen = control->m_len;
  1079. error = sblock(&so->so_snd, SBLOCKWAIT(flags));
  1080. if (error)
  1081. goto out;
  1082. restart:
  1083. do {
  1084. SOCKBUF_LOCK(&so->so_snd);
  1085. if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
  1086. SOCKBUF_UNLOCK(&so->so_snd);
  1087. error = EPIPE;
  1088. goto release;
  1089. }
  1090. if (so->so_error) {
  1091. error = so->so_error;
  1092. so->so_error = 0;
  1093. SOCKBUF_UNLOCK(&so->so_snd);
  1094. goto release;
  1095. }
  1096. if ((so->so_state & SS_ISCONNECTED) == 0) {
  1097. /*
  1098. * `sendto' and `sendmsg' is allowed on a connection-
  1099. * based socket if it supports implied connect.
  1100. * Return ENOTCONN if not connected and no address is
  1101. * supplied.
  1102. */
  1103. if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
  1104. (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
  1105. if ((so->so_state & SS_ISCONFIRMING) == 0 &&
  1106. !(resid == 0 && clen != 0)) {
  1107. SOCKBUF_UNLOCK(&so->so_snd);
  1108. error = ENOTCONN;
  1109. goto release;
  1110. }
  1111. } else if (addr == NULL) {
  1112. SOCKBUF_UNLOCK(&so->so_snd);
  1113. if (so->so_proto->pr_flags & PR_CONNREQUIRED)
  1114. error = ENOTCONN;
  1115. else
  1116. error = EDESTADDRREQ;
  1117. goto release;
  1118. }
  1119. }
  1120. space = sbspace(&so->so_snd);
  1121. if (flags & MSG_OOB)
  1122. space += 1024;
  1123. if ((atomic && resid > so->so_snd.sb_hiwat) ||
  1124. clen > so->so_snd.sb_hiwat) {
  1125. SOCKBUF_UNLOCK(&so->so_snd);
  1126. error = EMSGSIZE;
  1127. goto release;
  1128. }
  1129. if (space < resid + clen &&
  1130. (atomic || space < so->so_snd.sb_lowat || space < clen)) {
  1131. if ((so->so_state & SS_NBIO) || (flags & MSG_NBIO)) {
  1132. SOCKBUF_UNLOCK(&so->so_snd);
  1133. error = EWOULDBLOCK;
  1134. goto release;
  1135. }
  1136. error = sbwait(&so->so_snd);
  1137. SOCKBUF_UNLOCK(&so->so_snd);
  1138. if (error)
  1139. goto release;
  1140. goto restart;
  1141. }
  1142. SOCKBUF_UNLOCK(&so->so_snd);
  1143. space -= clen;
  1144. do {
  1145. if (uio == NULL) {
  1146. resid = 0;
  1147. if (flags & MSG_EOR)
  1148. top->m_flags |= M_EOR;
  1149. } else {
  1150. #ifdef ZERO_COPY_SOCKETS
  1151. error = sosend_copyin(uio, &top, atomic,
  1152. &space, flags);
  1153. if (error != 0)
  1154. goto release;
  1155. #else
  1156. /*
  1157. * Copy the data from userland into a mbuf
  1158. * chain. If no data is to be copied in,
  1159. * a single empty mbuf is returned.
  1160. */
  1161. top = m_uiotombuf(uio, M_WAITOK, space,
  1162. (atomic ? max_hdr : 0),
  1163. (atomic ? M_PKTHDR : 0) |
  1164. ((flags & MSG_EOR) ? M_EOR : 0));
  1165. if (top == NULL) {
  1166. error = EFAULT; /* only possible error */
  1167. goto release;
  1168. }
  1169. space -= resid - uio->uio_resid;
  1170. #endif
  1171. resid = uio->uio_resid;
  1172. }
  1173. if (dontroute) {
  1174. SOCK_LOCK(so);
  1175. so->so_options |= SO_DONTROUTE;
  1176. SOCK_UNLOCK(so);
  1177. }
  1178. /*
  1179. * XXX all the SBS_CANTSENDMORE checks previously
  1180. * done could be out of date. We could have recieved
  1181. * a reset packet in an interrupt or maybe we slept
  1182. * while doing page faults in uiomove() etc. We
  1183. * could probably recheck again inside the locking
  1184. * protection here, but there are probably other
  1185. * places that this also happens. We must rethink
  1186. * this.
  1187. */
  1188. error = (*so->so_proto->pr_usrreqs->pru_send)(so,
  1189. (flags & MSG_OOB) ? PRUS_OOB :
  1190. /*
  1191. * If the user set MSG_EOF, the protocol understands
  1192. * this flag and nothing left to send then use
  1193. * PRU_SEND_EOF instead of PRU_SEND.
  1194. */
  1195. ((flags & MSG_EOF) &&
  1196. (so->so_proto->pr_flags & PR_IMPLOPCL) &&
  1197. (resid <= 0)) ?
  1198. PRUS_EOF :
  1199. /* If there is more to send set PRUS_MORETOCOME. */
  1200. (resid > 0 && space > 0) ? PRUS_MORETOCOME : 0,
  1201. top, addr, control, td);
  1202. if (dontroute) {
  1203. SOCK_LOCK(so);
  1204. so->so_options &= ~SO_DONTROUTE;
  1205. SOCK_UNLOCK(so);
  1206. }
  1207. clen = 0;
  1208. control = NULL;
  1209. top = NULL;
  1210. if (error)
  1211. goto release;
  1212. } while (resid && space > 0);
  1213. } while (resid);
  1214. release:
  1215. sbunlock(&so->so_snd);
  1216. out:
  1217. if (top != NULL)
  1218. m_freem(top);
  1219. if (control != NULL)
  1220. m_freem(control);
  1221. return (error);
  1222. }
  1223. #endif
  1224. int
  1225. sosend(struct socket *so, struct sockaddr *addr, struct uio *uio,
  1226. struct mbuf *top, struct mbuf *control, int flags, PKTHREAD td)
  1227. {
  1228. /* XXXRW: Temporary debugging. */
  1229. KASSERT(so->so_proto->pr_usrreqs->pru_sosend != sosend,
  1230. ("sosend: protocol calls sosend"));
  1231. return (so->so_proto->pr_usrreqs->pru_sosend(so, addr, uio, top,
  1232. control, flags, td));
  1233. }
  1234. /*
  1235. * The part of soreceive() that implements reading non-inline out-of-band
  1236. * data from a socket. For more complete comments, see soreceive(), from
  1237. * which this code originated.
  1238. *
  1239. * Note that soreceive_rcvoob(), unlike the remainder of soreceive(), is
  1240. * unable to return an mbuf chain to the caller.
  1241. */
  1242. static int
  1243. soreceive_rcvoob(struct socket *so, struct uio *uio, int flags)
  1244. {
  1245. struct protosw *pr = so->so_proto;
  1246. struct mbuf *m;
  1247. int error;
  1248. KASSERT(flags & MSG_OOB, ("soreceive_rcvoob: (flags & MSG_OOB) == 0"));
  1249. m = m_get(M_WAIT, MT_DATA);
  1250. error = (*pr->pr_usrreqs->pru_rcvoob)(so, m, flags & MSG_PEEK);
  1251. if (error)
  1252. goto bad;
  1253. do {
  1254. #ifdef ZERO_COPY_SOCKETS
  1255. if (so_zero_copy_receive) {
  1256. int disposable;
  1257. if ((m->m_flags & M_EXT)
  1258. && (m->m_ext.ext_type == EXT_DISPOSABLE))
  1259. disposable = 1;
  1260. else
  1261. disposable = 0;
  1262. error = uiomoveco(mtod(m, void *),
  1263. min(uio->uio_resid, m->m_len),
  1264. uio, disposable);
  1265. } else
  1266. #endif /* ZERO_COPY_SOCKETS */
  1267. error = uiomove(mtod(m, void *),
  1268. (int) min(uio->uio_resid, m->m_len), uio);
  1269. m = m_free(m);
  1270. } while (uio->uio_resid && error == 0 && m);
  1271. bad:
  1272. if (m != NULL)
  1273. m_freem(m);
  1274. return (error);
  1275. }
  1276. /*
  1277. * Following replacement or removal of the first mbuf on the first mbuf chain
  1278. * of a socket buffer, push necessary state changes back into the socket
  1279. * buffer so that other consumers see the values consistently. 'nextrecord'
  1280. * is the callers locally stored value of the original value of
  1281. * sb->sb_mb->m_nextpkt which must be restored when the lead mbuf changes.
  1282. * NOTE: 'nextrecord' may be NULL.
  1283. */
  1284. static __inline void
  1285. sockbuf_pushsync(struct sockbuf *sb, struct mbuf *nextrecord)
  1286. {
  1287. SOCKBUF_LOCK_ASSERT(sb);
  1288. /*
  1289. * First, update for the new value of nextrecord. If necessary, make
  1290. * it the first record.
  1291. */
  1292. if (sb->sb_mb != NULL)
  1293. sb->sb_mb->m_nextpkt = nextrecord;
  1294. else
  1295. sb->sb_mb = nextrecord;
  1296. /*
  1297. * Now update any dependent socket buffer fields to reflect the new
  1298. * state. This is an expanded inline of SB_EMPTY_FIXUP(), with the
  1299. * addition of a second clause that takes care of the case where
  1300. * sb_mb has been updated, but remains the last record.
  1301. */
  1302. if (sb->sb_mb == NULL) {
  1303. sb->sb_mbtail = NULL;
  1304. sb->sb_lastrecord = NULL;
  1305. } else if (sb->sb_mb->m_nextpkt == NULL)
  1306. sb->sb_lastrecord = sb->sb_mb;
  1307. }
  1308. /*
  1309. * Implement receive operations on a socket. We depend on the way that
  1310. * records are added to the sockbuf by sbappend. In particular, each record
  1311. * (mbufs linked through m_next) must begin with an address if the protocol
  1312. * so specifies, followed by an optional mbuf or mbufs containing ancillary
  1313. * data, and then zero or more mbufs of data. In order to allow parallelism
  1314. * between network receive and copying to user space, as well as avoid
  1315. * sleeping with a mutex held, we release the socket buffer mutex during the
  1316. * user space copy. Although the sockbuf is locked, new data may still be
  1317. * appended, and thus we must maintain consistency of the sockbuf during that
  1318. * time.
  1319. *
  1320. * The caller may receive the data as a single mbuf chain by supplying an
  1321. * mbuf **mp0 for use in returning the chain. The uio is then used only for
  1322. * the count in uio_resid.
  1323. */
  1324. int
  1325. soreceive_generic(struct socket *so, struct sockaddr **psa, struct uio *uio,
  1326. struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
  1327. {
  1328. struct mbuf *m, **mp;
  1329. int flags, len, error, offset;
  1330. struct protosw *pr = so->so_proto;
  1331. struct mbuf *nextrecord;
  1332. int moff, type = 0;
  1333. int orig_resid = uio->uio_resid;
  1334. mp = mp0;
  1335. if (psa != NULL)
  1336. *psa = NULL;
  1337. if (controlp != NULL)
  1338. *controlp = NULL;
  1339. if (flagsp != NULL)
  1340. flags = *flagsp &~ MSG_EOR;
  1341. else
  1342. flags = 0;
  1343. if (flags & MSG_OOB)
  1344. return (soreceive_rcvoob(so, uio, flags));
  1345. if (mp != NULL)
  1346. *mp = NULL;
  1347. if ((pr->pr_flags & PR_WANTRCVD) && (so->so_state & SS_ISCONFIRMING)
  1348. && uio->uio_resid)
  1349. (*pr->pr_usrreqs->pru_rcvd)(so, 0);
  1350. error = sblock(&so->so_rcv, SBLOCKWAIT(flags));
  1351. if (error)
  1352. return (error);
  1353. restart:
  1354. SOCKBUF_LOCK(&so->so_rcv);
  1355. m = so->so_rcv.sb_mb;
  1356. /*
  1357. * If we have less data than requested, block awaiting more (subject
  1358. * to any timeout) if:
  1359. * 1. the current count is less than the low water mark, or
  1360. * 2. MSG_WAITALL is set, and it is possible to do the entire
  1361. * receive operation at once if we block (resid <= hiwat).
  1362. * 3. MSG_DONTWAIT is not set
  1363. * If MSG_WAITALL is set but resid is larger than the receive buffer,
  1364. * we have to do the receive in sections, and thus risk returning a
  1365. * short count if a timeout or signal occurs after we start.
  1366. */
  1367. if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
  1368. so->so_rcv.sb_cc < uio->uio_resid) &&
  1369. (so->so_rcv.sb_cc < so->so_rcv.sb_lowat ||
  1370. ((flags & MSG_WAITALL) && uio->uio_resid <= so->so_rcv.sb_hiwat)) &&
  1371. m->m_nextpkt == NULL && (pr->pr_flags & PR_ATOMIC) == 0)) {
  1372. KASSERT(m != NULL || !so->so_rcv.sb_cc,
  1373. ("receive: m == %p so->so_rcv.sb_cc == %u",
  1374. m, so->so_rcv.sb_cc));
  1375. if (so->so_error) {
  1376. if (m != NULL)
  1377. goto dontblock;
  1378. error = so->so_error;
  1379. if ((flags & MSG_PEEK) == 0)
  1380. so->so_error = 0;
  1381. SOCKBUF_UNLOCK(&so->so_rcv);
  1382. goto release;
  1383. }
  1384. SOCKBUF_LOCK_ASSERT(&so->so_rcv);
  1385. if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
  1386. if (m == NULL) {
  1387. SOCKBUF_UNLOCK(&so->so_rcv);
  1388. goto release;
  1389. } else
  1390. goto dontblock;
  1391. }
  1392. for (; m != NULL; m = m->m_next)
  1393. if (m->m_type == MT_OOBDATA || (m->m_flags & M_EOR)) {
  1394. m = so->so_rcv.sb_mb;
  1395. goto dontblock;
  1396. }
  1397. if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
  1398. (so->so_proto->pr_flags & PR_CONNREQUIRED)) {
  1399. SOCKBUF_UNLOCK(&so->so_rcv);
  1400. error = ENOTCONN;
  1401. goto release;
  1402. }
  1403. if (uio->uio_resid == 0) {
  1404. SOCKBUF_UNLOCK(&so->so_rcv);
  1405. goto release;
  1406. }
  1407. if ((so->so_state & SS_NBIO) ||
  1408. (flags & (MSG_DONTWAIT|MSG_NBIO))) {
  1409. SOCKBUF_UNLOCK(&so->so_rcv);
  1410. error = EWOULDBLOCK;
  1411. goto release;
  1412. }
  1413. SBLASTRECORDCHK(&so->so_rcv);
  1414. SBLASTMBUFCHK(&so->so_rcv);
  1415. error = sbwait(&so->so_rcv);
  1416. SOCKBUF_UNLOCK(&so->so_rcv);
  1417. if (error)
  1418. goto release;
  1419. goto restart;
  1420. }
  1421. dontblock:
  1422. /*
  1423. * From this point onward, we maintain 'nextrecord' as a cache of the
  1424. * pointer to the next record in the socket buffer. We must keep the
  1425. * various socket buffer pointers and local stack versions of the
  1426. * pointers in sync, pushing out modifications before dropping the
  1427. * socket buffer mutex, and re-reading them when picking it up.
  1428. *
  1429. * Otherwise, we will race with the network stack appending new data
  1430. * or records onto the socket buffer by using inconsistent/stale
  1431. * versions of the field, possibly resulting in socket buffer
  1432. * corruption.
  1433. *
  1434. * By holding the high-level sblock(), we prevent simultaneous
  1435. * readers from pulling off the front of the socket buffer.
  1436. */
  1437. SOCKBUF_LOCK_ASSERT(&so->so_rcv);
  1438. #if 0
  1439. if (uio->uio_td)
  1440. uio->uio_td->td_ru.ru_msgrcv++;
  1441. #endif
  1442. KASSERT(m == so->so_rcv.sb_mb, ("soreceive: m != so->so_rcv.sb_mb"));
  1443. SBLASTRECORDCHK(&so->so_rcv);
  1444. SBLASTMBUFCHK(&so->so_rcv);
  1445. nextrecord = m->m_nextpkt;
  1446. if (pr->pr_flags & PR_ADDR) {
  1447. KASSERT(m->m_type == MT_SONAME,
  1448. ("m->m_type == %d", m->m_type));
  1449. orig_resid = 0;
  1450. if (psa != NULL)
  1451. *psa = sodupsockaddr(mtod(m, struct sockaddr *),
  1452. M_NOWAIT);
  1453. if (flags & MSG_PEEK) {
  1454. m = m->m_next;
  1455. } else {
  1456. sbfree(&so->so_rcv, m);
  1457. so->so_rcv.sb_mb = m_free(m);
  1458. m = so->so_rcv.sb_mb;
  1459. sockbuf_pushsync(&so->so_rcv, nextrecord);
  1460. }
  1461. }
  1462. /*
  1463. * Process one or more MT_CONTROL mbufs present before any data mbufs
  1464. * in the first mbuf chain on the socket buffer. If MSG_PEEK, we
  1465. * just copy the data; if !MSG_PEEK, we call into the protocol to
  1466. * perform externalization (or freeing if controlp == NULL).
  1467. */
  1468. if (m != NULL && m->m_type == MT_CONTROL) {
  1469. struct mbuf *cm = NULL, *cmn;
  1470. struct mbuf **cme = &cm;
  1471. do {
  1472. if (flags & MSG_PEEK) {
  1473. if (controlp != NULL) {
  1474. *controlp = m_copy(m, 0, m->m_len);
  1475. controlp = &(*controlp)->m_next;
  1476. }
  1477. m = m->m_next;
  1478. } else {
  1479. sbfree(&so->so_rcv, m);
  1480. so->so_rcv.sb_mb = m->m_next;
  1481. m->m_next = NULL;
  1482. *cme = m;
  1483. cme = &(*cme)->m_next;
  1484. m = so->so_rcv.sb_mb;
  1485. }
  1486. } while (m != NULL && m->m_type == MT_CONTROL);
  1487. if ((flags & MSG_PEEK) == 0)
  1488. sockbuf_pushsync(&so->so_rcv, nextrecord);
  1489. while (cm != NULL) {
  1490. cmn = cm->m_next;
  1491. cm->m_next = NULL;
  1492. if (pr->pr_domain->dom_externalize != NULL) {
  1493. SOCKBUF_UNLOCK(&so->so_rcv);
  1494. error = (*pr->pr_domain->dom_externalize)
  1495. (cm, controlp);
  1496. SOCKBUF_LOCK(&so->so_rcv);
  1497. } else if (controlp != NULL)
  1498. *controlp = cm;
  1499. else
  1500. m_freem(cm);
  1501. if (controlp != NULL) {
  1502. orig_resid = 0;
  1503. while (*controlp != NULL)
  1504. controlp = &(*controlp)->m_next;
  1505. }
  1506. cm = cmn;
  1507. }
  1508. if (m != NULL)
  1509. nextrecord = so->so_rcv.sb_mb->m_nextpkt;
  1510. else
  1511. nextrecord = so->so_rcv.sb_mb;
  1512. orig_resid = 0;
  1513. }
  1514. if (m != NULL) {
  1515. if ((flags & MSG_PEEK) == 0) {
  1516. KASSERT(m->m_nextpkt == nextrecord,
  1517. ("soreceive: post-control, nextrecord !sync"));
  1518. if (nextrecord == NULL) {
  1519. KASSERT(so->so_rcv.sb_mb == m,
  1520. ("soreceive: post-control, sb_mb!=m"));
  1521. KASSERT(so->so_rcv.sb_lastrecord == m,
  1522. ("soreceive: post-control, lastrecord!=m"));
  1523. }
  1524. }
  1525. type = m->m_type;
  1526. if (type == MT_OOBDATA)
  1527. flags |= MSG_OOB;
  1528. } else {
  1529. if ((flags & MSG_PEEK) == 0) {
  1530. KASSERT(so->so_rcv.sb_mb == nextrecord,
  1531. ("soreceive: sb_mb != nextrecord"));
  1532. if (so->so_rcv.sb_mb == NULL) {
  1533. KASSERT(so->so_rcv.sb_lastrecord == NULL,
  1534. ("soreceive: sb_lastercord != NULL"));
  1535. }
  1536. }
  1537. }
  1538. SOCKBUF_LOCK_ASSERT(&so->so_rcv);
  1539. SBLASTRECORDCHK(&so->so_rcv);
  1540. SBLASTMBUFCHK(&so->so_rcv);
  1541. /*
  1542. * Now continue to read any data mbufs off of the head of the socket
  1543. * buffer until the read request is satisfied. Note that 'type' is
  1544. * used to store the type of any mbuf reads that have happened so far
  1545. * such that soreceive() can stop reading if the type changes, which
  1546. * causes soreceive() to return only one of regular data and inline
  1547. * out-of-band data in a single socket receive operation.
  1548. */
  1549. moff = 0;
  1550. offset = 0;
  1551. while (m != NULL && uio->uio_resid > 0 && error == 0) {
  1552. /*
  1553. * If the type of mbuf has changed since the last mbuf
  1554. * examined ('type'), end the receive operation.
  1555. */
  1556. SOCKBUF_LOCK_ASSERT(&so->so_rcv);
  1557. if (m->m_type == MT_OOBDATA) {
  1558. if (type != MT_OOBDATA)
  1559. break;
  1560. } else if (type == MT_OOBDATA)
  1561. break;
  1562. else
  1563. KASSERT(m->m_type == MT_DATA,
  1564. ("m->m_type == %d", m->m_type));
  1565. so->so_rcv.sb_state &= ~SBS_RCVATMARK;
  1566. len = uio->uio_resid;
  1567. if (so->so_oobmark && len > so->so_oobmark - offset)
  1568. len = so->so_oobmark - offset;
  1569. if (len > m->m_len - moff)
  1570. len = m->m_len - moff;
  1571. /*
  1572. * If mp is set, just pass back the mbufs. Otherwise copy
  1573. * them out via the uio, then free. Sockbuf must be
  1574. * consistent here (points to current mbuf, it points to next
  1575. * record) when we drop priority; we must note any additions
  1576. * to the sockbuf when we block interrupts again.
  1577. */
  1578. if (mp == NULL) {
  1579. SOCKBUF_LOCK_ASSERT(&so->so_rcv);
  1580. SBLASTRECORDCHK(&so->so_rcv);
  1581. SBLASTMBUFCHK(&so->so_rcv);
  1582. SOCKBUF_UNLOCK(&so->so_rcv);
  1583. #ifdef ZERO_COPY_SOCKETS
  1584. if (so_zero_copy_receive) {
  1585. int disposable;
  1586. if ((m->m_flags & M_EXT)
  1587. && (m->m_ext.ext_type == EXT_DISPOSABLE))
  1588. disposable = 1;
  1589. else
  1590. disposable = 0;
  1591. error = uiomoveco(mtod(m, char *) + moff,
  1592. (int)len, uio,
  1593. disposable);
  1594. } else
  1595. #endif /* ZERO_COPY_SOCKETS */
  1596. error = uiomove(mtod(m, char *) + moff, (int)len, uio);
  1597. SOCKBUF_LOCK(&so->so_rcv);
  1598. if (error) {
  1599. /*
  1600. * The MT_SONAME mbuf has already been removed
  1601. * from the record, so it is necessary to
  1602. * remove the data mbufs, if any, to preserve
  1603. * the invariant in the case of PR_ADDR that
  1604. * requires MT_SONAME mbufs at the head of
  1605. * each record.
  1606. */
  1607. if (m && pr->pr_flags & PR_ATOMIC &&
  1608. ((flags & MSG_PEEK) == 0))
  1609. (void)sbdroprecord_locked(&so->so_rcv);
  1610. SOCKBUF_UNLOCK(&so->so_rcv);
  1611. goto release;
  1612. }
  1613. } else
  1614. uio->uio_resid -= len;
  1615. SOCKBUF_LOCK_ASSERT(&so->so_rcv);
  1616. if (len == m->m_len - moff) {
  1617. if (m->m_flags & M_EOR)
  1618. flags |= MSG_EOR;
  1619. if (flags & MSG_PEEK) {
  1620. m = m->m_next;
  1621. moff = 0;
  1622. } else {
  1623. nextrecord = m->m_nextpkt;
  1624. sbfree(&so->so_rcv, m);
  1625. if (mp != NULL) {
  1626. *mp = m;
  1627. mp = &m->m_next;
  1628. so->so_rcv.sb_mb = m = m->m_next;
  1629. *mp = NULL;
  1630. } else {
  1631. so->so_rcv.sb_mb = m_free(m);
  1632. m = so->so_rcv.sb_mb;
  1633. }
  1634. sockbuf_pushsync(&so->so_rcv, nextrecord);
  1635. SBLASTRECORDCHK(&so->so_rcv);
  1636. SBLASTMBUFCHK(&so->so_rcv);
  1637. }
  1638. } else {
  1639. if (flags & MSG_PEEK)
  1640. moff += len;
  1641. else {
  1642. if (mp != NULL) {
  1643. int copy_flag;
  1644. if (flags & MSG_DONTWAIT)
  1645. copy_flag = M_DONTWAIT;
  1646. else
  1647. copy_flag = M_WAIT;
  1648. if (copy_flag == M_WAIT)
  1649. SOCKBUF_UNLOCK(&so->so_rcv);
  1650. *mp = m_copym(m, 0, len, copy_flag);
  1651. if (copy_flag == M_WAIT)
  1652. SOCKBUF_LOCK(&so->so_rcv);
  1653. if (*mp == NULL) {
  1654. /*
  1655. * m_copym() couldn't
  1656. * allocate an mbuf. Adjust
  1657. * uio_resid back (it was
  1658. * adjusted down by len
  1659. * bytes, which we didn't end
  1660. * up "copying" over).
  1661. */
  1662. uio->uio_resid += len;
  1663. break;
  1664. }
  1665. }
  1666. m->m_data += len;
  1667. m->m_len -= len;
  1668. so->so_rcv.sb_cc -= len;
  1669. }
  1670. }
  1671. SOCKBUF_LOCK_ASSERT(&so->so_rcv);
  1672. if (so->so_oobmark) {
  1673. if ((flags & MSG_PEEK) == 0) {
  1674. so->so_oobmark -= len;
  1675. if (so->so_oobmark == 0) {
  1676. so->so_rcv.sb_state |= SBS_RCVATMARK;
  1677. break;
  1678. }
  1679. } else {
  1680. offset += len;
  1681. if (offset == so->so_oobmark)
  1682. break;
  1683. }
  1684. }
  1685. if (flags & MSG_EOR)
  1686. break;
  1687. /*
  1688. * If the MSG_WAITALL flag is set (for non-atomic socket), we
  1689. * must not quit until "uio->uio_resid == 0" or an error
  1690. * termination. If a signal/timeout occurs, return with a
  1691. * short count but without error. Keep sockbuf locked
  1692. * against other readers.
  1693. */
  1694. while (flags & MSG_WAITALL && m == NULL && uio->uio_resid > 0 &&
  1695. !sosendallatonce(so) && nextrecord == NULL) {
  1696. SOCKBUF_LOCK_ASSERT(&so->so_rcv);
  1697. if (so->so_error || so->so_rcv.sb_state & SBS_CANTRCVMORE)
  1698. break;
  1699. /*
  1700. * Notify the protocol that some data has been
  1701. * drained before blocking.
  1702. */
  1703. if (pr->pr_flags & PR_WANTRCVD) {
  1704. SOCKBUF_UNLOCK(&so->so_rcv);
  1705. (*pr->pr_usrreqs->pru_rcvd)(so, flags);
  1706. SOCKBUF_LOCK(&so->so_rcv);
  1707. }
  1708. SBLASTRECORDCHK(&so->so_rcv);
  1709. SBLASTMBUFCHK(&so->so_rcv);
  1710. error = sbwait(&so->so_rcv);
  1711. if (error) {
  1712. SOCKBUF_UNLOCK(&so->so_rcv);
  1713. goto release;
  1714. }
  1715. m = so->so_rcv.sb_mb;
  1716. if (m != NULL)
  1717. nextrecord = m->m_nextpkt;
  1718. }
  1719. }
  1720. SOCKBUF_LOCK_ASSERT(&so->so_rcv);
  1721. if (m != NULL && pr->pr_flags & PR_ATOMIC) {
  1722. flags |= MSG_TRUNC;
  1723. if ((flags & MSG_PEEK) == 0)
  1724. (void) sbdroprecord_locked(&so->so_rcv);
  1725. }
  1726. if ((flags & MSG_PEEK) == 0) {
  1727. if (m == NULL) {
  1728. /*
  1729. * First part is an inline SB_EMPTY_FIXUP(). Second
  1730. * part makes sure sb_lastrecord is up-to-date if
  1731. * there is still data in the socket buffer.
  1732. */
  1733. so->so_rcv.sb_mb = nextrecord;
  1734. if (so->so_rcv.sb_mb == NULL) {
  1735. so->so_rcv.sb_mbtail = NULL;
  1736. so->so_rcv.sb_lastrecord = NULL;
  1737. } else if (nextrecord->m_nextpkt == NULL)
  1738. so->so_rcv.sb_lastrecord = nextrecord;
  1739. }
  1740. SBLASTRECORDCHK(&so->so_rcv);
  1741. SBLASTMBUFCHK(&so->so_rcv);
  1742. /*
  1743. * If soreceive() is being done from the socket callback,
  1744. * then don't need to generate ACK to peer to update window,
  1745. * since ACK will be generated on return to TCP.
  1746. */
  1747. if (!(flags & MSG_SOCALLBCK) &&
  1748. (pr->pr_flags & PR_WANTRCVD)) {
  1749. SOCKBUF_UNLOCK(&so->so_rcv);
  1750. (*pr->pr_usrreqs->pru_rcvd)(so, flags);
  1751. SOCKBUF_LOCK(&so->so_rcv);
  1752. }
  1753. }
  1754. SOCKBUF_LOCK_ASSERT(&so->so_rcv);
  1755. if (orig_resid == uio->uio_resid && orig_resid &&
  1756. (flags & MSG_EOR) == 0 && (so->so_rcv.sb_state & SBS_CANTRCVMORE) == 0) {
  1757. SOCKBUF_UNLOCK(&so->so_rcv);
  1758. goto restart;
  1759. }
  1760. SOCKBUF_UNLOCK(&so->so_rcv);
  1761. if (flagsp != NULL)
  1762. *flagsp |= flags;
  1763. release:
  1764. sbunlock(&so->so_rcv);
  1765. return (error);
  1766. }
  1767. /*
  1768. * Optimized version of soreceive() for simple datagram cases from userspace.
  1769. * Unlike in the stream case, we're able to drop a datagram if copyout()
  1770. * fails, and because we handle datagrams atomically, we don't need to use a
  1771. * sleep lock to prevent I/O interlacing.
  1772. */
  1773. int
  1774. soreceive_dgram(struct socket *so, struct sockaddr **psa, struct uio *uio,
  1775. struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
  1776. {
  1777. struct mbuf *m, *m2;
  1778. int flags, len, error, offset;
  1779. struct protosw *pr = so->so_proto;
  1780. struct mbuf *nextrecord;
  1781. if (psa != NULL)
  1782. *psa = NULL;
  1783. if (controlp != NULL)
  1784. *controlp = NULL;
  1785. if (flagsp != NULL)
  1786. flags = *flagsp &~ MSG_EOR;
  1787. else
  1788. flags = 0;
  1789. /*
  1790. * For any complicated cases, fall back to the full
  1791. * soreceive_generic().
  1792. */
  1793. if (mp0 != NULL || (flags & MSG_PEEK) || (flags & MSG_OOB))
  1794. return (soreceive_generic(so, psa, uio, mp0, controlp,
  1795. flagsp));
  1796. /*
  1797. * Enforce restrictions on use.
  1798. */
  1799. KASSERT((pr->pr_flags & PR_WANTRCVD) == 0,
  1800. ("soreceive_dgram: wantrcvd"));
  1801. KASSERT(pr->pr_flags & PR_ATOMIC, ("soreceive_dgram: !atomic"));
  1802. KASSERT((so->so_rcv.sb_state & SBS_RCVATMARK) == 0,
  1803. ("soreceive_dgram: SBS_RCVATMARK"));
  1804. KASSERT((so->so_proto->pr_flags & PR_CONNREQUIRED) == 0,
  1805. ("soreceive_dgram: P_CONNREQUIRED"));
  1806. /*
  1807. * Loop blocking while waiting for a datagram.
  1808. */
  1809. SOCKBUF_LOCK(&so->so_rcv);
  1810. while ((m = so->so_rcv.sb_mb) == NULL) {
  1811. KASSERT(so->so_rcv.sb_cc == 0,
  1812. ("soreceive_dgram: sb_mb NULL but sb_cc %u",
  1813. so->so_rcv.sb_cc));
  1814. if (so->so_error) {
  1815. error = so->so_error;
  1816. so->so_error = 0;
  1817. SOCKBUF_UNLOCK(&so->so_rcv);
  1818. return (error);
  1819. }
  1820. if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
  1821. SOCKBUF_UNLOCK(&so->so_rcv);
  1822. return (0);
  1823. }
  1824. if ((so->so_state & SS_NBIO) ||
  1825. (flags & (MSG_DONTWAIT|MSG_NBIO))) {
  1826. SOCKBUF_UNLOCK(&so->so_rcv);
  1827. return (EWOULDBLOCK);
  1828. }
  1829. SBLASTRECORDCHK(&so->so_rcv);
  1830. SBLASTMBUFCHK(&so->so_rcv);
  1831. error = sbwait(&so->so_rcv);
  1832. if (error) {
  1833. SOCKBUF_UNLOCK(&so->so_rcv);
  1834. return (error);
  1835. }
  1836. }
  1837. SOCKBUF_LOCK_ASSERT(&so->so_rcv);
  1838. #if 0
  1839. if (uio->uio_td)
  1840. uio->uio_td->td_ru.ru_msgrcv++;
  1841. #endif
  1842. SBLASTRECORDCHK(&so->so_rcv);
  1843. SBLASTMBUFCHK(&so->so_rcv);
  1844. nextrecord = m->m_nextpkt;
  1845. if (nextrecord == NULL) {
  1846. KASSERT(so->so_rcv.sb_lastrecord == m,
  1847. ("soreceive_dgram: lastrecord != m"));
  1848. }
  1849. KASSERT(so->so_rcv.sb_mb->m_nextpkt == nextrecord,
  1850. ("soreceive_dgram: m_nextpkt != nextrecord"));
  1851. /*
  1852. * Pull 'm' and its chain off the front of the packet queue.
  1853. */
  1854. so->so_rcv.sb_mb = NULL;
  1855. sockbuf_pushsync(&so->so_rcv, nextrecord);
  1856. /*
  1857. * Walk 'm's chain and free that many bytes from the socket buffer.
  1858. */
  1859. for (m2 = m; m2 != NULL; m2 = m2->m_next)
  1860. sbfree(&so->so_rcv, m2);
  1861. /*
  1862. * Do a few last checks before we let go of the lock.
  1863. */
  1864. SBLASTRECORDCHK(&so->so_rcv);
  1865. SBLASTMBUFCHK(&so->so_rcv);
  1866. SOCKBUF_UNLOCK(&so->so_rcv);
  1867. if (pr->pr_flags & PR_ADDR) {
  1868. KASSERT(m->m_type == MT_SONAME,
  1869. ("m->m_type == %d", m->m_type));
  1870. if (psa != NULL)
  1871. *psa = sodupsockaddr(mtod(m, struct sockaddr *),
  1872. M_NOWAIT);
  1873. m = m_free(m);
  1874. }
  1875. if (m == NULL) {
  1876. /* XXXRW: Can this happen? */
  1877. return (0);
  1878. }
  1879. /*
  1880. * Packet to copyout() is now in 'm' and it is disconnected from the
  1881. * queue.
  1882. *
  1883. * Process one or more MT_CONTROL mbufs present before any data mbufs
  1884. * in the first mbuf chain on the socket buffer. We call into the
  1885. * protocol to perform externalization (or freeing if controlp ==
  1886. * NULL).
  1887. */
  1888. if (m->m_type == MT_CONTROL) {
  1889. struct mbuf *cm = NULL, *cmn;
  1890. struct mbuf **cme = &cm;
  1891. do {
  1892. m2 = m->m_next;
  1893. m->m_next = NULL;
  1894. *cme = m;
  1895. cme = &(*cme)->m_next;
  1896. m = m2;
  1897. } while (m != NULL && m->m_type == MT_CONTROL);
  1898. while (cm != NULL) {
  1899. cmn = cm->m_next;
  1900. cm->m_next = NULL;
  1901. if (pr->pr_domain->dom_externalize != NULL) {
  1902. error = (*pr->pr_domain->dom_externalize)
  1903. (cm, controlp);
  1904. } else if (controlp != NULL)
  1905. *controlp = cm;
  1906. else
  1907. m_freem(cm);
  1908. if (controlp != NULL) {
  1909. while (*controlp != NULL)
  1910. controlp = &(*controlp)->m_next;
  1911. }
  1912. cm = cmn;
  1913. }
  1914. }
  1915. KASSERT(m->m_type == MT_DATA, ("soreceive_dgram: !data"));
  1916. offset = 0;
  1917. while (m != NULL && uio->uio_resid > 0) {
  1918. len = uio->uio_resid;
  1919. if (len > m->m_len)
  1920. len = m->m_len;
  1921. error = uiomove(mtod(m, char *), (int)len, uio);
  1922. if (error) {
  1923. m_freem(m);
  1924. return (error);
  1925. }
  1926. m = m_free(m);
  1927. }
  1928. if (m != NULL)
  1929. flags |= MSG_TRUNC;
  1930. m_freem(m);
  1931. if (flagsp != NULL)
  1932. *flagsp |= flags;
  1933. return (0);
  1934. }
  1935. int
  1936. soreceive(struct socket *so, struct sockaddr **psa, struct uio *uio,
  1937. struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
  1938. {
  1939. /* XXXRW: Temporary debugging. */
  1940. KASSERT(so->so_proto->pr_usrreqs->pru_soreceive != soreceive,
  1941. ("soreceive: protocol calls soreceive"));
  1942. return (so->so_proto->pr_usrreqs->pru_soreceive(so, psa, uio, mp0,
  1943. controlp, flagsp));
  1944. }
  1945. int
  1946. soshutdown(struct socket *so, int how)
  1947. {
  1948. struct protosw *pr = so->so_proto;
  1949. if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
  1950. return (EINVAL);
  1951. if (pr->pr_usrreqs->pru_flush != NULL) {
  1952. (*pr->pr_usrreqs->pru_flush)(so, how);
  1953. }
  1954. if (how != SHUT_WR)
  1955. sorflush(so);
  1956. if (how != SHUT_RD)
  1957. return ((*pr->pr_usrreqs->pru_shutdown)(so));
  1958. return (0);
  1959. }
  1960. void
  1961. sorflush(struct socket *so)
  1962. {
  1963. struct sockbuf *sb = &so->so_rcv;
  1964. struct protosw *pr = so->so_proto;
  1965. struct sockbuf asb;
  1966. /*
  1967. * In order to avoid calling dom_dispose with the socket buffer mutex
  1968. * held, and in order to generally avoid holding the lock for a long
  1969. * time, we make a copy of the socket buffer and clear the original
  1970. * (except locks, state). The new socket buffer copy won't have
  1971. * initialized locks so we can only call routines that won't use or
  1972. * assert those locks.
  1973. *
  1974. * Dislodge threads currently blocked in receive and wait to acquire
  1975. * a lock against other simultaneous readers before clearing the
  1976. * socket buffer. Don't let our acquire be interrupted by a signal
  1977. * despite any existing socket disposition on interruptable waiting.
  1978. */
  1979. socantrcvmore(so);
  1980. (void) sblock(sb, SBL_WAIT | SBL_NOINTR);
  1981. /*
  1982. * Invalidate/clear most of the sockbuf structure, but leave selinfo
  1983. * and mutex data unchanged.
  1984. */
  1985. SOCKBUF_LOCK(sb);
  1986. bzero(&asb, offsetof(struct sockbuf, sb_startzero));
  1987. bcopy(&sb->sb_startzero, &asb.sb_startzero,
  1988. sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
  1989. bzero(&sb->sb_startzero,
  1990. sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
  1991. SOCKBUF_UNLOCK(sb);
  1992. sbunlock(sb);
  1993. /*
  1994. * Dispose of special rights and flush the socket buffer. Don't call
  1995. * any unsafe routines (that rely on locks being initialized) on asb.
  1996. */
  1997. if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose != NULL)
  1998. (*pr->pr_domain->dom_dispose)(asb.sb_mb);
  1999. sbrelease_internal(&asb, so);
  2000. }
  2001. /*
  2002. * Perhaps this routine, and sooptcopyout(), below, ought to come in an
  2003. * additional variant to handle the case where the option value needs to be
  2004. * some kind of integer, but not a specific size. In addition to their use
  2005. * here, these functions are also called by the protocol-level pr_ctloutput()
  2006. * routines.
  2007. */
  2008. int
  2009. sooptcopyin(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
  2010. {
  2011. size_t valsize;
  2012. /*
  2013. * If the user gives us more than we wanted, we ignore it, but if we
  2014. * don't get the minimum length the caller wants, we return EINVAL.
  2015. * On success, sopt->sopt_valsize is set to however much we actually
  2016. * retrieved.
  2017. */
  2018. if ((valsize = sopt->sopt_valsize) < minlen)
  2019. return EINVAL;
  2020. if (valsize > len)
  2021. sopt->sopt_valsize = valsize = len;
  2022. bcopy(sopt->sopt_val, buf, valsize);
  2023. return (0);
  2024. }
  2025. /*
  2026. * Kernel version of setsockopt(2).
  2027. *
  2028. * XXX: optlen is size_t, not socklen_t
  2029. */
  2030. int
  2031. so_setsockopt(struct socket *so, int level, int optname, void *optval,
  2032. size_t optlen)
  2033. {
  2034. struct sockopt sopt;
  2035. sopt.sopt_level = level;
  2036. sopt.sopt_name = optname;
  2037. sopt.sopt_dir = SOPT_SET;
  2038. sopt.sopt_val = optval;
  2039. sopt.sopt_valsize = optlen;
  2040. sopt.sopt_td = NULL;
  2041. return (sosetopt(so, &sopt));
  2042. }
  2043. int
  2044. sosetopt(struct socket *so, struct sockopt *sopt)
  2045. {
  2046. int error, optval;
  2047. struct linger l;
  2048. struct timeval tv;
  2049. u_long val;
  2050. #ifdef MAC
  2051. struct mac extmac;
  2052. #endif
  2053. error = 0;
  2054. if (sopt->sopt_level != SOL_SOCKET) {
  2055. if (so->so_proto && so->so_proto->pr_ctloutput)
  2056. return ((*so->so_proto->pr_ctloutput)
  2057. (so, sopt));
  2058. error = ENOPROTOOPT;
  2059. } else {
  2060. switch (sopt->sopt_name) {
  2061. case SO_LINGER:
  2062. error = sooptcopyin(sopt, &l, sizeof l, sizeof l);
  2063. if (error)
  2064. goto bad;
  2065. SOCK_LOCK(so);
  2066. so->so_linger = l.l_linger;
  2067. if (l.l_onoff)
  2068. so->so_options |= SO_LINGER;
  2069. else
  2070. so->so_options &= ~SO_LINGER;
  2071. SOCK_UNLOCK(so);
  2072. break;
  2073. case SO_DEBUG:
  2074. case SO_KEEPALIVE:
  2075. case SO_DONTROUTE:
  2076. case SO_USELOOPBACK:
  2077. case SO_BROADCAST:
  2078. case SO_REUSEADDR:
  2079. case SO_OOBINLINE:
  2080. case SO_DONTLINGER:
  2081. case SO_EXCLUSIVEADDRUSE:
  2082. error = sooptcopyin(sopt, &optval, sizeof optval,
  2083. sizeof optval);
  2084. if (error)
  2085. goto bad;
  2086. SOCK_LOCK(so);
  2087. switch (sopt->sopt_name) {
  2088. case SO_DONTLINGER:
  2089. if (optval)
  2090. so->so_options &= ~SO_LINGER;
  2091. else
  2092. so->so_options |= SO_LINGER;
  2093. break;
  2094. case SO_EXCLUSIVEADDRUSE:
  2095. if (optval)
  2096. so->so_options &= ~SO_REUSEADDR;
  2097. else
  2098. so->so_options |= SO_REUSEADDR;
  2099. break;
  2100. default:
  2101. if (optval)
  2102. so->so_options |= sopt->sopt_name;
  2103. else
  2104. so->so_options &= ~sopt->sopt_name;
  2105. }
  2106. SOCK_UNLOCK(so);
  2107. break;
  2108. #if 0
  2109. case SO_SETFIB:
  2110. error = sooptcopyin(sopt, &optval, sizeof optval,
  2111. sizeof optval);
  2112. if (optval < 1 || optval > rt_numfibs) {
  2113. error = EINVAL;
  2114. goto bad;
  2115. }
  2116. if ((so->so_proto->pr_domain->dom_family == PF_INET) ||
  2117. (so->so_proto->pr_domain->dom_family == PF_ROUTE)) {
  2118. so->so_fibnum = optval;
  2119. } else {
  2120. so->so_fibnum = 0;
  2121. }
  2122. break;
  2123. #endif
  2124. case SO_SNDBUF:
  2125. case SO_RCVBUF:
  2126. case SO_SNDLOWAT:
  2127. case SO_RCVLOWAT:
  2128. error = sooptcopyin(sopt, &optval, sizeof optval,
  2129. sizeof optval);
  2130. if (error)
  2131. goto bad;
  2132. /*
  2133. * Values < 1 make no sense for any of these options,
  2134. * so disallow them.
  2135. */
  2136. if (optval < 1) {
  2137. error = EINVAL;
  2138. goto bad;
  2139. }
  2140. switch (sopt->sopt_name) {
  2141. case SO_SNDBUF:
  2142. case SO_RCVBUF:
  2143. if (sbreserve(sopt->sopt_name == SO_SNDBUF ?
  2144. &so->so_snd : &so->so_rcv, (u_long)optval,
  2145. so, sopt->sopt_td) == 0) {
  2146. error = ENOBUFS;
  2147. goto bad;
  2148. }
  2149. (sopt->sopt_name == SO_SNDBUF ? &so->so_snd :
  2150. &so->so_rcv)->sb_flags &= ~SB_AUTOSIZE;
  2151. break;
  2152. /*
  2153. * Make sure the low-water is never greater than the
  2154. * high-water.
  2155. */
  2156. case SO_SNDLOWAT:
  2157. SOCKBUF_LOCK(&so->so_snd);
  2158. so->so_snd.sb_lowat =
  2159. (optval > so->so_snd.sb_hiwat) ?
  2160. so->so_snd.sb_hiwat : optval;
  2161. SOCKBUF_UNLOCK(&so->so_snd);
  2162. break;
  2163. case SO_RCVLOWAT:
  2164. SOCKBUF_LOCK(&so->so_rcv);
  2165. so->so_rcv.sb_lowat =
  2166. (optval > so->so_rcv.sb_hiwat) ?
  2167. so->so_rcv.sb_hiwat : optval;
  2168. SOCKBUF_UNLOCK(&so->so_rcv);
  2169. break;
  2170. }
  2171. break;
  2172. case SO_SNDTIMEO:
  2173. case SO_RCVTIMEO:
  2174. #ifdef COMPAT_IA32
  2175. if (curthread->td_proc->p_sysent == &ia32_freebsd_sysvec) {
  2176. struct timeval32 tv32;
  2177. error = sooptcopyin(sopt, &tv32, sizeof tv32,
  2178. sizeof tv32);
  2179. CP(tv32, tv, tv_sec);
  2180. CP(tv32, tv, tv_usec);
  2181. } else
  2182. #endif
  2183. error = sooptcopyin(sopt, &tv, sizeof tv,
  2184. sizeof tv);
  2185. if (error)
  2186. goto bad;
  2187. /* assert(hz > 0); */
  2188. if (tv.tv_sec < 0 || tv.tv_sec > INT_MAX / hz ||
  2189. tv.tv_usec < 0 || tv.tv_usec >= 1000000) {
  2190. error = EDOM;
  2191. goto bad;
  2192. }
  2193. /* assert(tick > 0); */
  2194. /* assert(ULONG_MAX - INT_MAX >= 1000000); */
  2195. val = (u_long)(tv.tv_sec * hz) + tv.tv_usec / tick;
  2196. if (val > INT_MAX) {
  2197. error = EDOM;
  2198. goto bad;
  2199. }
  2200. if (val == 0 && tv.tv_usec != 0)
  2201. val = 1;
  2202. switch (sopt->sopt_name) {
  2203. case SO_SNDTIMEO:
  2204. so->so_snd.sb_timeo = val;
  2205. break;
  2206. case SO_RCVTIMEO:
  2207. so->so_rcv.sb_timeo = val;
  2208. break;
  2209. }
  2210. break;
  2211. default:
  2212. error = ENOPROTOOPT;
  2213. break;
  2214. }
  2215. if (error == 0 && so->so_proto != NULL &&
  2216. so->so_proto->pr_ctloutput != NULL) {
  2217. (void) ((*so->so_proto->pr_ctloutput)
  2218. (so, sopt));
  2219. }
  2220. }
  2221. bad:
  2222. return (error);
  2223. }
  2224. /*
  2225. * Helper routine for getsockopt.
  2226. */
  2227. int
  2228. sooptcopyout(struct sockopt *sopt, void *buf, size_t len)
  2229. {
  2230. int error;
  2231. size_t valsize;
  2232. error = 0;
  2233. /*
  2234. * Documented get behavior is that we always return a value, possibly
  2235. * truncated to fit in the user's buffer. Traditional behavior is
  2236. * that we always tell the user precisely how much we copied, rather
  2237. * than something useful like the total amount we had available for
  2238. * her. Note that this interface is not idempotent; the entire
  2239. * answer must generated ahead of time.
  2240. */
  2241. valsize = min(len, sopt->sopt_valsize);
  2242. sopt->sopt_valsize = valsize;
  2243. if (sopt->sopt_val != NULL) {
  2244. bcopy(buf, sopt->sopt_val, valsize);
  2245. }
  2246. return (error);
  2247. }
  2248. int
  2249. sogetopt(struct socket *so, struct sockopt *sopt)
  2250. {
  2251. int error, optval;
  2252. struct linger l;
  2253. struct timeval tv;
  2254. #ifdef MAC
  2255. struct mac extmac;
  2256. #endif
  2257. error = 0;
  2258. if (sopt->sopt_level != SOL_SOCKET) {
  2259. if (so->so_proto && so->so_proto->pr_ctloutput) {
  2260. return ((*so->so_proto->pr_ctloutput)
  2261. (so, sopt));
  2262. } else
  2263. return (ENOPROTOOPT);
  2264. } else {
  2265. switch (sopt->sopt_name) {
  2266. case SO_LINGER:
  2267. SOCK_LOCK(so);
  2268. l.l_onoff = so->so_options & SO_LINGER;
  2269. l.l_linger = so->so_linger;
  2270. SOCK_UNLOCK(so);
  2271. error = sooptcopyout(sopt, &l, sizeof l);
  2272. break;
  2273. case SO_USELOOPBACK:
  2274. case SO_DONTROUTE:
  2275. case SO_DEBUG:
  2276. case SO_KEEPALIVE:
  2277. case SO_REUSEADDR:
  2278. case SO_BROADCAST:
  2279. case SO_OOBINLINE:
  2280. case SO_ACCEPTCONN:
  2281. optval = so->so_options & sopt->sopt_name;
  2282. integer:
  2283. error = sooptcopyout(sopt, &optval, sizeof optval);
  2284. break;
  2285. case SO_DONTLINGER:
  2286. optval = (so->so_options & SO_LINGER) == 0;
  2287. goto integer;
  2288. case SO_EXCLUSIVEADDRUSE:
  2289. optval = (so->so_options & SO_REUSEADDR) == 0;
  2290. goto integer;
  2291. case SO_TYPE:
  2292. optval = so->so_type;
  2293. goto integer;
  2294. case SO_ERROR:
  2295. SOCK_LOCK(so);
  2296. optval = so->so_error;
  2297. so->so_error = 0;
  2298. SOCK_UNLOCK(so);
  2299. goto integer;
  2300. case SO_SNDBUF:
  2301. optval = so->so_snd.sb_hiwat;
  2302. goto integer;
  2303. case SO_RCVBUF:
  2304. optval = so->so_rcv.sb_hiwat;
  2305. goto integer;
  2306. case SO_SNDLOWAT:
  2307. optval = so->so_snd.sb_lowat;
  2308. goto integer;
  2309. case SO_RCVLOWAT:
  2310. optval = so->so_rcv.sb_lowat;
  2311. goto integer;
  2312. case SO_SNDTIMEO:
  2313. case SO_RCVTIMEO:
  2314. optval = (sopt->sopt_name == SO_SNDTIMEO ?
  2315. so->so_snd.sb_timeo : so->so_rcv.sb_timeo);
  2316. tv.tv_sec = optval / hz;
  2317. tv.tv_usec = (optval % hz) * tick;
  2318. #ifdef COMPAT_IA32
  2319. if (curthread->td_proc->p_sysent == &ia32_freebsd_sysvec) {
  2320. struct timeval32 tv32;
  2321. CP(tv, tv32, tv_sec);
  2322. CP(tv, tv32, tv_usec);
  2323. error = sooptcopyout(sopt, &tv32, sizeof tv32);
  2324. } else
  2325. #endif
  2326. error = sooptcopyout(sopt, &tv, sizeof tv);
  2327. break;
  2328. default:
  2329. error = ENOPROTOOPT;
  2330. break;
  2331. }
  2332. return (error);
  2333. }
  2334. }
  2335. /* XXX; prepare mbuf for (__FreeBSD__ < 3) routines. */
  2336. int
  2337. soopt_getm(struct sockopt *sopt, struct mbuf **mp)
  2338. {
  2339. struct mbuf *m, *m_prev;
  2340. int sopt_size = sopt->sopt_valsize;
  2341. MGET(m, sopt->sopt_td ? M_WAIT : M_DONTWAIT, MT_DATA);
  2342. if (m == NULL)
  2343. return ENOBUFS;
  2344. if (sopt_size > MLEN) {
  2345. MCLGET(m, sopt->sopt_td ? M_WAIT : M_DONTWAIT);
  2346. if ((m->m_flags & M_EXT) == 0) {
  2347. m_free(m);
  2348. return ENOBUFS;
  2349. }
  2350. m->m_len = min(MCLBYTES, sopt_size);
  2351. } else {
  2352. m->m_len = min(MLEN, sopt_size);
  2353. }
  2354. sopt_size -= m->m_len;
  2355. *mp = m;
  2356. m_prev = m;
  2357. while (sopt_size) {
  2358. MGET(m, sopt->sopt_td ? M_WAIT : M_DONTWAIT, MT_DATA);
  2359. if (m == NULL) {
  2360. m_freem(*mp);
  2361. return ENOBUFS;
  2362. }
  2363. if (sopt_size > MLEN) {
  2364. MCLGET(m, sopt->sopt_td != NULL ? M_WAIT :
  2365. M_DONTWAIT);
  2366. if ((m->m_flags & M_EXT) == 0) {
  2367. m_freem(m);
  2368. m_freem(*mp);
  2369. return ENOBUFS;
  2370. }
  2371. m->m_len = min(MCLBYTES, sopt_size);
  2372. } else {
  2373. m->m_len = min(MLEN, sopt_size);
  2374. }
  2375. sopt_size -= m->m_len;
  2376. m_prev->m_next = m;
  2377. m_prev = m;
  2378. }
  2379. return (0);
  2380. }
  2381. /* XXX; copyin sopt data into mbuf chain for (__FreeBSD__ < 3) routines. */
  2382. int
  2383. soopt_mcopyin(struct sockopt *sopt, struct mbuf *m)
  2384. {
  2385. struct mbuf *m0 = m;
  2386. if (sopt->sopt_val == NULL)
  2387. return (0);
  2388. while (m != NULL && sopt->sopt_valsize >= m->m_len) {
  2389. bcopy(sopt->sopt_val, mtod(m, char *), m->m_len);
  2390. sopt->sopt_valsize -= m->m_len;
  2391. sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
  2392. m = m->m_next;
  2393. }
  2394. if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */
  2395. panic("ip6_sooptmcopyin");
  2396. return (0);
  2397. }
  2398. /* XXX; copyout mbuf chain data into soopt for (__FreeBSD__ < 3) routines. */
  2399. int
  2400. soopt_mcopyout(struct sockopt *sopt, struct mbuf *m)
  2401. {
  2402. struct mbuf *m0 = m;
  2403. size_t valsize = 0;
  2404. if (sopt->sopt_val == NULL)
  2405. return (0);
  2406. while (m != NULL && sopt->sopt_valsize >= m->m_len) {
  2407. bcopy(mtod(m, char *), sopt->sopt_val, m->m_len);
  2408. sopt->sopt_valsize -= m->m_len;
  2409. sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
  2410. valsize += m->m_len;
  2411. m = m->m_next;
  2412. }
  2413. if (m != NULL) {
  2414. /* enough soopt buffer should be given from user-land */
  2415. m_freem(m0);
  2416. return(EINVAL);
  2417. }
  2418. sopt->sopt_valsize = valsize;
  2419. return (0);
  2420. }
  2421. /*
  2422. * sohasoutofband(): protocol notifies socket layer of the arrival of new
  2423. * out-of-band data, which will then notify socket consumers.
  2424. */
  2425. void
  2426. sohasoutofband(struct socket *so)
  2427. {
  2428. #if 0
  2429. if (so->so_sigio != NULL)
  2430. pgsigio(&so->so_sigio, SIGURG, 0);
  2431. selwakeuppri(&so->so_rcv.sb_sel, PSOCK);
  2432. #endif
  2433. }
  2434. int
  2435. sopoll(struct socket *so, int events, struct ucred *active_cred,
  2436. PKTHREAD td)
  2437. {
  2438. /* XXXRW: Temporary debugging. */
  2439. KASSERT(so->so_proto->pr_usrreqs->pru_sopoll != sopoll,
  2440. ("sopoll: protocol calls sopoll"));
  2441. return (so->so_proto->pr_usrreqs->pru_sopoll(so, events, active_cred,
  2442. td));
  2443. }
  2444. int
  2445. sopoll_generic(struct socket *so, int events, struct ucred *active_cred,
  2446. PKTHREAD td)
  2447. {
  2448. int revents = 0;
  2449. SOCKBUF_LOCK(&so->so_snd);
  2450. SOCKBUF_LOCK(&so->so_rcv);
  2451. if (events & (POLLIN | POLLRDNORM))
  2452. if (soreadable(so))
  2453. revents |= events & (POLLIN | POLLRDNORM);
  2454. if (events & POLLINIGNEOF)
  2455. if (so->so_rcv.sb_cc >= so->so_rcv.sb_lowat ||
  2456. !TAILQ_EMPTY(&so->so_comp) || so->so_error)
  2457. revents |= POLLINIGNEOF;
  2458. if (events & (POLLOUT | POLLWRNORM))
  2459. if (sowriteable(so))
  2460. revents |= events & (POLLOUT | POLLWRNORM);
  2461. if (events & (POLLPRI | POLLRDBAND))
  2462. if (so->so_oobmark || (so->so_rcv.sb_state & SBS_RCVATMARK))
  2463. revents |= events & (POLLPRI | POLLRDBAND);
  2464. if (revents == 0) {
  2465. if (events &
  2466. (POLLIN | POLLINIGNEOF | POLLPRI | POLLRDNORM |
  2467. POLLRDBAND)) {
  2468. //selrecord(td, &so->so_rcv.sb_sel);
  2469. so->so_rcv.sb_flags |= SB_SEL;
  2470. }
  2471. if (events & (POLLOUT | POLLWRNORM)) {
  2472. //selrecord(td, &so->so_snd.sb_sel);
  2473. so->so_snd.sb_flags |= SB_SEL;
  2474. }
  2475. }
  2476. SOCKBUF_UNLOCK(&so->so_rcv);
  2477. SOCKBUF_UNLOCK(&so->so_snd);
  2478. return (revents);
  2479. }
  2480. #if 0
  2481. int
  2482. soo_kqfilter(struct file *fp, struct knote *kn)
  2483. {
  2484. struct socket *so = kn->kn_fp->f_data;
  2485. struct sockbuf *sb;
  2486. switch (kn->kn_filter) {
  2487. case EVFILT_READ:
  2488. if (so->so_options & SO_ACCEPTCONN)
  2489. kn->kn_fop = &solisten_filtops;
  2490. else
  2491. kn->kn_fop = &soread_filtops;
  2492. sb = &so->so_rcv;
  2493. break;
  2494. case EVFILT_WRITE:
  2495. kn->kn_fop = &sowrite_filtops;
  2496. sb = &so->so_snd;
  2497. break;
  2498. default:
  2499. return (EINVAL);
  2500. }
  2501. SOCKBUF_LOCK(sb);
  2502. knlist_add(&sb->sb_sel.si_note, kn, 1);
  2503. sb->sb_flags |= SB_KNOTE;
  2504. SOCKBUF_UNLOCK(sb);
  2505. return (0);
  2506. }
  2507. #endif
  2508. /*
  2509. * Some routines that return EOPNOTSUPP for entry points that are not
  2510. * supported by a protocol. Fill in as needed.
  2511. */
  2512. int
  2513. pru_accept_notsupp(struct socket *so, struct sockaddr **nam)
  2514. {
  2515. return EOPNOTSUPP;
  2516. }
  2517. int
  2518. pru_attach_notsupp(struct socket *so, int proto, PKTHREAD td)
  2519. {
  2520. return EOPNOTSUPP;
  2521. }
  2522. int
  2523. pru_bind_notsupp(struct socket *so, struct sockaddr *nam, PKTHREAD td)
  2524. {
  2525. return EOPNOTSUPP;
  2526. }
  2527. int
  2528. pru_connect_notsupp(struct socket *so, struct sockaddr *nam, PKTHREAD td)
  2529. {
  2530. return EOPNOTSUPP;
  2531. }
  2532. int
  2533. pru_connect2_notsupp(struct socket *so1, struct socket *so2)
  2534. {
  2535. return EOPNOTSUPP;
  2536. }
  2537. int
  2538. pru_control_notsupp(struct socket *so, u_long cmd, caddr_t data,
  2539. struct ifnet *ifp, PKTHREAD td)
  2540. {
  2541. return EOPNOTSUPP;
  2542. }
  2543. int
  2544. pru_disconnect_notsupp(struct socket *so)
  2545. {
  2546. return EOPNOTSUPP;
  2547. }
  2548. int
  2549. pru_listen_notsupp(struct socket *so, int backlog, PKTHREAD td)
  2550. {
  2551. return EOPNOTSUPP;
  2552. }
  2553. int
  2554. pru_peeraddr_notsupp(struct socket *so, struct sockaddr **nam)
  2555. {
  2556. return EOPNOTSUPP;
  2557. }
  2558. int
  2559. pru_rcvd_notsupp(struct socket *so, int flags)
  2560. {
  2561. return EOPNOTSUPP;
  2562. }
  2563. int
  2564. pru_rcvoob_notsupp(struct socket *so, struct mbuf *m, int flags)
  2565. {
  2566. return EOPNOTSUPP;
  2567. }
  2568. int
  2569. pru_send_notsupp(struct socket *so, int flags, struct mbuf *m,
  2570. struct sockaddr *addr, struct mbuf *control, PKTHREAD td)
  2571. {
  2572. return EOPNOTSUPP;
  2573. }
  2574. /*
  2575. * This isn't really a ``null'' operation, but it's the default one and
  2576. * doesn't do anything destructive.
  2577. */
  2578. int
  2579. pru_sense_null(struct socket *so, void *sb)
  2580. {
  2581. return 0;
  2582. }
  2583. int
  2584. pru_shutdown_notsupp(struct socket *so)
  2585. {
  2586. return EOPNOTSUPP;
  2587. }
  2588. int
  2589. pru_sockaddr_notsupp(struct socket *so, struct sockaddr **nam)
  2590. {
  2591. return EOPNOTSUPP;
  2592. }
  2593. int
  2594. pru_sosend_notsupp(struct socket *so, struct sockaddr *addr, struct uio *uio,
  2595. struct mbuf *top, struct mbuf *control, int flags, PKTHREAD td)
  2596. {
  2597. return EOPNOTSUPP;
  2598. }
  2599. int
  2600. pru_soreceive_notsupp(struct socket *so, struct sockaddr **paddr,
  2601. struct uio *uio, struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
  2602. {
  2603. return EOPNOTSUPP;
  2604. }
  2605. int
  2606. pru_sopoll_notsupp(struct socket *so, int events, struct ucred *cred,
  2607. PKTHREAD td)
  2608. {
  2609. return EOPNOTSUPP;
  2610. }
  2611. #if 0
  2612. static void
  2613. filt_sordetach(struct knote *kn)
  2614. {
  2615. struct socket *so = kn->kn_fp->f_data;
  2616. SOCKBUF_LOCK(&so->so_rcv);
  2617. knlist_remove(&so->so_rcv.sb_sel.si_note, kn, 1);
  2618. if (knlist_empty(&so->so_rcv.sb_sel.si_note))
  2619. so->so_rcv.sb_flags &= ~SB_KNOTE;
  2620. SOCKBUF_UNLOCK(&so->so_rcv);
  2621. }
  2622. /*ARGSUSED*/
  2623. static int
  2624. filt_soread(struct knote *kn, long hint)
  2625. {
  2626. struct socket *so;
  2627. so = kn->kn_fp->f_data;
  2628. SOCKBUF_LOCK_ASSERT(&so->so_rcv);
  2629. kn->kn_data = so->so_rcv.sb_cc - so->so_rcv.sb_ctl;
  2630. if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
  2631. kn->kn_flags |= EV_EOF;
  2632. kn->kn_fflags = so->so_error;
  2633. return (1);
  2634. } else if (so->so_error) /* temporary udp error */
  2635. return (1);
  2636. else if (kn->kn_sfflags & NOTE_LOWAT)
  2637. return (kn->kn_data >= kn->kn_sdata);
  2638. else
  2639. return (so->so_rcv.sb_cc >= so->so_rcv.sb_lowat);
  2640. }
  2641. static void
  2642. filt_sowdetach(struct knote *kn)
  2643. {
  2644. struct socket *so = kn->kn_fp->f_data;
  2645. SOCKBUF_LOCK(&so->so_snd);
  2646. knlist_remove(&so->so_snd.sb_sel.si_note, kn, 1);
  2647. if (knlist_empty(&so->so_snd.sb_sel.si_note))
  2648. so->so_snd.sb_flags &= ~SB_KNOTE;
  2649. SOCKBUF_UNLOCK(&so->so_snd);
  2650. }
  2651. /*ARGSUSED*/
  2652. static int
  2653. filt_sowrite(struct knote *kn, long hint)
  2654. {
  2655. struct socket *so;
  2656. so = kn->kn_fp->f_data;
  2657. SOCKBUF_LOCK_ASSERT(&so->so_snd);
  2658. kn->kn_data = sbspace(&so->so_snd);
  2659. if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
  2660. kn->kn_flags |= EV_EOF;
  2661. kn->kn_fflags = so->so_error;
  2662. return (1);
  2663. } else if (so->so_error) /* temporary udp error */
  2664. return (1);
  2665. else if (((so->so_state & SS_ISCONNECTED) == 0) &&
  2666. (so->so_proto->pr_flags & PR_CONNREQUIRED))
  2667. return (0);
  2668. else if (kn->kn_sfflags & NOTE_LOWAT)
  2669. return (kn->kn_data >= kn->kn_sdata);
  2670. else
  2671. return (kn->kn_data >= so->so_snd.sb_lowat);
  2672. }
  2673. /*ARGSUSED*/
  2674. static int
  2675. filt_solisten(struct knote *kn, long hint)
  2676. {
  2677. struct socket *so = kn->kn_fp->f_data;
  2678. kn->kn_data = so->so_qlen;
  2679. return (! TAILQ_EMPTY(&so->so_comp));
  2680. }
  2681. int
  2682. socheckuid(struct socket *so, uid_t uid)
  2683. {
  2684. if (so == NULL)
  2685. return (EPERM);
  2686. if (so->so_cred->cr_uid != uid)
  2687. return (EPERM);
  2688. return (0);
  2689. }
  2690. static int
  2691. sysctl_somaxconn(SYSCTL_HANDLER_ARGS)
  2692. {
  2693. int error;
  2694. int val;
  2695. val = somaxconn;
  2696. error = sysctl_handle_int(oidp, &val, 0, req);
  2697. if (error || !req->newptr )
  2698. return (error);
  2699. if (val < 1 || val > USHRT_MAX)
  2700. return (EINVAL);
  2701. somaxconn = val;
  2702. return (0);
  2703. }
  2704. #endif
  2705. /*
  2706. * These functions are used by protocols to notify the socket layer (and its
  2707. * consumers) of state changes in the sockets driven by protocol-side events.
  2708. */
  2709. /*
  2710. * Procedures to manipulate state flags of socket and do appropriate wakeups.
  2711. *
  2712. * Normal sequence from the active (originating) side is that
  2713. * soisconnecting() is called during processing of connect() call, resulting
  2714. * in an eventual call to soisconnected() if/when the connection is
  2715. * established. When the connection is torn down soisdisconnecting() is
  2716. * called during processing of disconnect() call, and soisdisconnected() is
  2717. * called when the connection to the peer is totally severed. The semantics
  2718. * of these routines are such that connectionless protocols can call
  2719. * soisconnected() and soisdisconnected() only, bypassing the in-progress
  2720. * calls when setting up a ``connection'' takes no time.
  2721. *
  2722. * From the passive side, a socket is created with two queues of sockets:
  2723. * so_incomp for connections in progress and so_comp for connections already
  2724. * made and awaiting user acceptance. As a protocol is preparing incoming
  2725. * connections, it creates a socket structure queued on so_incomp by calling
  2726. * sonewconn(). When the connection is established, soisconnected() is
  2727. * called, and transfers the socket structure to so_comp, making it available
  2728. * to accept().
  2729. *
  2730. * If a socket is closed with sockets on either so_incomp or so_comp, these
  2731. * sockets are dropped.
  2732. *
  2733. * If higher-level protocols are implemented in the kernel, the wakeups done
  2734. * here will sometimes cause software-interrupt process scheduling.
  2735. */
  2736. void
  2737. soisconnecting(struct socket *so)
  2738. {
  2739. SOCK_LOCK(so);
  2740. so->so_state &= ~(SS_ISCONNECTED|SS_ISDISCONNECTING);
  2741. so->so_state |= SS_ISCONNECTING;
  2742. SOCK_UNLOCK(so);
  2743. }
  2744. void
  2745. soisconnected(struct socket *so)
  2746. {
  2747. struct socket *head;
  2748. ACCEPT_LOCK();
  2749. SOCK_LOCK(so);
  2750. so->so_state &= ~(SS_ISCONNECTING|SS_ISDISCONNECTING|SS_ISCONFIRMING);
  2751. so->so_state |= SS_ISCONNECTED;
  2752. head = so->so_head;
  2753. if (head != NULL && (so->so_qstate & SQ_INCOMP)) {
  2754. if (head->so_tdi_event.so_tdi_conn != NULL) {
  2755. int error = 0;
  2756. struct sockaddr *addr = NULL;
  2757. PTRANSPORT_ADDRESS tAddr = NULL;
  2758. union {
  2759. TA_IP_ADDRESS tIpAddr;
  2760. TA_IP6_ADDRESS tIp6Addr;
  2761. } tAddrStorage;
  2762. ULONG tAddrLength = 0;
  2763. NTSTATUS status = STATUS_SUCCESS;
  2764. CONNECTION_CONTEXT connContext = NULL;
  2765. PIRP irp = NULL;
  2766. SOCK_UNLOCK(so);
  2767. TAILQ_REMOVE(&head->so_incomp, so, so_list);
  2768. head->so_incqlen--;
  2769. so->so_qstate &= ~SQ_INCOMP;
  2770. ACCEPT_UNLOCK();
  2771. error = soaccept(so, &addr);
  2772. if (error != 0 || addr == NULL) {
  2773. soabort(so);
  2774. goto done0;
  2775. }
  2776. tAddr = (PTRANSPORT_ADDRESS)&tAddrStorage;
  2777. tAddrLength = sizeof(tAddrStorage);
  2778. if (sa2ta(addr, tAddr, &tAddrLength) < 0) {
  2779. soabort(so);
  2780. goto done0;
  2781. }
  2782. status = (*(head->so_tdi_event.so_tdi_conn))(head->so_tdi_event.so_tdi_conn_arg,
  2783. tAddrLength,
  2784. tAddr,
  2785. 0,
  2786. NULL,
  2787. 0,
  2788. NULL,
  2789. &connContext,
  2790. &irp
  2791. );
  2792. if (status == STATUS_MORE_PROCESSING_REQUIRED) {
  2793. PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation(irp);
  2794. PTDI_CONTEXT tdiContext = (PTDI_CONTEXT)irpSp->FileObject->FsContext;
  2795. PTDI_REQUEST_KERNEL_ACCEPT acceptRequest = (PTDI_REQUEST_KERNEL_ACCEPT)&(irpSp->Parameters);
  2796. PTDI_CONNECTION_INFORMATION returnInformation = acceptRequest->ReturnConnectionInformation;
  2797. PTDI_CONTEXT tdiContext2 = NULL;
  2798. if (tdiContext == NULL || tdiContext->fileObject == NULL) {
  2799. status = STATUS_INVALID_PARAMETER;
  2800. soabort(so);
  2801. goto done0;
  2802. }
  2803. tdiContext2 = (PTDI_CONTEXT)tdiContext->fileObject->FsContext;
  2804. if (tdiContext2 == NULL || tdiContext2->socket != so->so_head) {
  2805. status = STATUS_INVALID_PARAMETER;
  2806. soabort(so);
  2807. goto done0;
  2808. }
  2809. atomic_add_int(&tdiContext2->backlog, -1);
  2810. error = solisten(so->so_head, tdiContext2->backlog, NULL);
  2811. if (error != 0) {
  2812. DbgPrint("solisten=%d\n", error);
  2813. }
  2814. ObDereferenceObject(tdiContext->fileObject);
  2815. tdiContext->fileObject = NULL;
  2816. RtlCopyMemory(&so->so_tdi_event, &head->so_tdi_event, sizeof(struct so_tdi_event));
  2817. so->so_tdi_event.so_tdi_conn_ctx= connContext;
  2818. tdiContext->socket = so;
  2819. if (returnInformation != NULL) {
  2820. if (returnInformation->RemoteAddressLength >= tAddrLength) {
  2821. RtlCopyMemory(returnInformation->RemoteAddress, tAddr, tAddrLength);
  2822. returnInformation->RemoteAddressLength = tAddrLength;
  2823. } else {
  2824. returnInformation->RemoteAddress = NULL;
  2825. returnInformation->RemoteAddressLength = 0;
  2826. }
  2827. }
  2828. SOCK_LOCK(so);
  2829. soref(so);
  2830. SOCK_UNLOCK(so);
  2831. done0:
  2832. irp->IoStatus.Information = 0;
  2833. irp->IoStatus.Status = status;
  2834. IoCompleteRequest(irp, 2);
  2835. } else {
  2836. soabort(so);
  2837. }
  2838. done1:
  2839. if (addr != NULL) {
  2840. ExFreePool(addr);
  2841. }
  2842. } else if ((so->so_options & SO_ACCEPTFILTER) == 0) {
  2843. SOCK_UNLOCK(so);
  2844. TAILQ_REMOVE(&head->so_incomp, so, so_list);
  2845. head->so_incqlen--;
  2846. so->so_qstate &= ~SQ_INCOMP;
  2847. TAILQ_INSERT_TAIL(&head->so_comp, so, so_list);
  2848. head->so_qlen++;
  2849. so->so_qstate |= SQ_COMP;
  2850. ACCEPT_UNLOCK();
  2851. SOCKEVENT_LOCK(&head->so_event);
  2852. if (head->so_event.se_Event != NULL && (head->so_event.se_Events & FD_ACCEPT) != 0) {
  2853. head->so_event.se_EventsRet.lNetworkEvents |= FD_ACCEPT;
  2854. KeSetEvent(head->so_event.se_Event, 0, FALSE);
  2855. }
  2856. SOCKEVENT_UNLOCK(&head->so_event);
  2857. sorwakeup(head);
  2858. KeSetEvent(&head->so_waitSyncEvent, 0, FALSE);
  2859. } else {
  2860. ACCEPT_UNLOCK();
  2861. so->so_upcall =
  2862. head->so_accf->so_accept_filter->accf_callback;
  2863. so->so_upcallarg = head->so_accf->so_accept_filter_arg;
  2864. so->so_rcv.sb_flags |= SB_UPCALL;
  2865. so->so_options &= ~SO_ACCEPTFILTER;
  2866. SOCK_UNLOCK(so);
  2867. so->so_upcall(so, so->so_upcallarg, M_DONTWAIT);
  2868. }
  2869. return;
  2870. } else if (
  2871. head == NULL) {
  2872. SOCKEVENT_LOCK(&so->so_event);
  2873. if (so->so_event.se_Event != NULL && (so->so_event.se_Events & FD_CONNECT) != 0) {
  2874. so->so_event.se_EventsRet.lNetworkEvents |= FD_CONNECT;
  2875. KeSetEvent(so->so_event.se_Event, 0, FALSE);
  2876. }
  2877. SOCKEVENT_UNLOCK(&so->so_event);
  2878. }
  2879. SOCK_UNLOCK(so);
  2880. ACCEPT_UNLOCK();
  2881. KeSetEvent(&so->so_waitEvent, 0, FALSE);
  2882. sorwakeup(so);
  2883. sowwakeup(so);
  2884. }
  2885. void
  2886. soisdisconnecting(struct socket *so)
  2887. {
  2888. /*
  2889. * Note: This code assumes that SOCK_LOCK(so) and
  2890. * SOCKBUF_LOCK(&so->so_rcv) are the same.
  2891. */
  2892. SOCKBUF_LOCK(&so->so_rcv);
  2893. so->so_state &= ~SS_ISCONNECTING;
  2894. so->so_state |= SS_ISDISCONNECTING;
  2895. so->so_rcv.sb_state |= SBS_CANTRCVMORE;
  2896. sorwakeup_locked(so);
  2897. SOCKBUF_LOCK(&so->so_snd);
  2898. so->so_snd.sb_state |= SBS_CANTSENDMORE;
  2899. KeSetEvent(&so->so_waitEvent, 0, FALSE);
  2900. sowwakeup_locked(so);
  2901. }
  2902. void
  2903. soisdisconnected(struct socket *so)
  2904. {
  2905. /*
  2906. * Note: This code assumes that SOCK_LOCK(so) and
  2907. * SOCKBUF_LOCK(&so->so_rcv) are the same.
  2908. */
  2909. SOCKBUF_LOCK(&so->so_rcv);
  2910. so->so_state &= ~(SS_ISCONNECTING|SS_ISCONNECTED|SS_ISDISCONNECTING);
  2911. so->so_state |= SS_ISDISCONNECTED;
  2912. so->so_rcv.sb_state |= SBS_CANTRCVMORE;
  2913. sorwakeup_locked(so);
  2914. SOCKBUF_LOCK(&so->so_snd);
  2915. so->so_snd.sb_state |= SBS_CANTSENDMORE;
  2916. sbdrop_locked(&so->so_snd, so->so_snd.sb_cc);
  2917. KeSetEvent(&so->so_waitEvent, 0, FALSE);
  2918. sowwakeup_locked(so);
  2919. }
  2920. /*
  2921. * Make a copy of a sockaddr in a malloced buffer of type M_SONAME.
  2922. */
  2923. struct sockaddr *
  2924. sodupsockaddr(const struct sockaddr *sa, int mflags)
  2925. {
  2926. struct sockaddr *sa2;
  2927. socklen_t sa_len;
  2928. switch (sa->sa_family) {
  2929. case AF_INET:
  2930. sa_len = sizeof(struct sockaddr_in);
  2931. break;
  2932. case AF_INET6:
  2933. sa_len = sizeof(struct sockaddr_in6);
  2934. break;
  2935. default:
  2936. return NULL;
  2937. }
  2938. sa2 = malloc(sa_len, M_SONAME, mflags);
  2939. if (sa2)
  2940. bcopy(sa, sa2, sa_len);
  2941. return sa2;
  2942. }
  2943. int
  2944. sa2ta(
  2945. IN struct sockaddr *sa,
  2946. OUT PTRANSPORT_ADDRESS tAddr,
  2947. IN OUT ULONG *len0)
  2948. {
  2949. ULONG len = 0;
  2950. if (sa == NULL || tAddr == NULL || len0 == NULL) {
  2951. return -1;
  2952. }
  2953. len = *len0;
  2954. if (sa->sa_family == AF_INET &&
  2955. len >= sizeof(TA_IP_ADDRESS)
  2956. ) {
  2957. struct sockaddr_in *sin = (struct sockaddr_in *)sa;
  2958. PTA_IP_ADDRESS taIpAddr = (PTA_IP_ADDRESS)tAddr;
  2959. RtlZeroMemory(taIpAddr, sizeof(TA_IP_ADDRESS));
  2960. taIpAddr->TAAddressCount = 1;
  2961. taIpAddr->Address[0].AddressLength = 14;
  2962. taIpAddr->Address[0].AddressType = TDI_ADDRESS_TYPE_IP;
  2963. taIpAddr->Address[0].Address[0].sin_port = sin->sin_port;
  2964. taIpAddr->Address[0].Address[0].in_addr = sin->sin_addr.s_addr;
  2965. *len0 = sizeof(TA_IP_ADDRESS);
  2966. } else if (
  2967. sa->sa_family == AF_INET6 &&
  2968. len >= sizeof(TA_IP6_ADDRESS)
  2969. ) {
  2970. struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sa;
  2971. PTA_IP6_ADDRESS taIp6Addr = (PTA_IP6_ADDRESS)tAddr;
  2972. RtlZeroMemory(taIp6Addr, sizeof(TA_IP6_ADDRESS));
  2973. taIp6Addr->TAAddressCount = 1;
  2974. taIp6Addr->Address[0].AddressLength = TDI_ADDRESS_LENGTH_IP6;
  2975. taIp6Addr->Address[0].AddressType = TDI_ADDRESS_TYPE_IP6;
  2976. taIp6Addr->Address[0].Address[0].sin6_port = sin6->sin6_port;
  2977. RtlCopyMemory(&taIp6Addr->Address[0].Address[0].sin6_addr,
  2978. &sin6->sin6_addr, sizeof(struct in6_addr));
  2979. taIp6Addr->Address[0].Address[0].sin6_scope_id = sin6->sin6_scope_id;
  2980. *len0 = sizeof(TA_IP6_ADDRESS);
  2981. } else {
  2982. return -1;
  2983. }
  2984. return *len0;
  2985. }
  2986. int
  2987. ta2sa(
  2988. IN PTRANSPORT_ADDRESS tAddr,
  2989. OUT struct sockaddr *sa,
  2990. IN OUT ULONG *len0)
  2991. {
  2992. ULONG len = 0;
  2993. if (tAddr == NULL || sa == NULL || len0 == NULL) {
  2994. return -1;
  2995. }
  2996. len = *len0;
  2997. if (tAddr->Address[0].AddressType == TDI_ADDRESS_TYPE_IP &&
  2998. tAddr->Address[0].AddressLength == sizeof(TDI_ADDRESS_IP) &&
  2999. len >= sizeof(struct sockaddr_in)
  3000. ) {
  3001. PTA_IP_ADDRESS taIpAddr = (PTA_IP_ADDRESS)tAddr;
  3002. struct sockaddr_in *sin = (struct sockaddr_in *)sa;
  3003. sin->sin_family = AF_INET;
  3004. sin->sin_port = taIpAddr->Address[0].Address[0].sin_port;
  3005. RtlCopyMemory(&sin->sin_addr, &taIpAddr->Address[0].Address[0].in_addr,
  3006. sizeof(struct in_addr));
  3007. *len0 = sizeof(struct sockaddr_in);
  3008. } else if (
  3009. tAddr->Address[0].AddressType == TDI_ADDRESS_TYPE_IP6 &&
  3010. tAddr->Address[0].AddressLength == sizeof(TDI_ADDRESS_IP6) &&
  3011. len >= sizeof(struct sockaddr_in6)
  3012. ) {
  3013. PTA_IP6_ADDRESS taIp6Addr = (PTA_IP6_ADDRESS)tAddr;
  3014. struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sa;
  3015. sin6->sin6_family = AF_INET6;
  3016. sin6->sin6_port = taIp6Addr->Address[0].Address[0].sin6_port;
  3017. RtlCopyMemory(&sin6->sin6_addr, taIp6Addr->Address[0].Address[0].sin6_addr,
  3018. sizeof(struct in6_addr));
  3019. sin6->sin6_flowinfo = taIp6Addr->Address[0].Address[0].sin6_flowinfo;
  3020. sin6->sin6_scope_id = taIp6Addr->Address[0].Address[0].sin6_scope_id;
  3021. *len0 = sizeof(struct sockaddr_in6);
  3022. } else {
  3023. return -1;
  3024. }
  3025. return *len0;
  3026. }
  3027. /*
  3028. * Create an external-format (``xsocket'') structure using the information in
  3029. * the kernel-format socket structure pointed to by so. This is done to
  3030. * reduce the spew of irrelevant information over this interface, to isolate
  3031. * user code from changes in the kernel structure, and potentially to provide
  3032. * information-hiding if we decide that some of this information should be
  3033. * hidden from users.
  3034. */
  3035. void
  3036. sotoxsocket(struct socket *so, struct xsocket *xso)
  3037. {
  3038. xso->xso_len = sizeof *xso;
  3039. xso->xso_so = so;
  3040. xso->so_type = so->so_type;
  3041. xso->so_options = so->so_options;
  3042. xso->so_linger = so->so_linger;
  3043. xso->so_state = so->so_state;
  3044. xso->so_pcb = so->so_pcb;
  3045. xso->xso_protocol = so->so_proto->pr_protocol;
  3046. xso->xso_family = so->so_proto->pr_domain->dom_family;
  3047. xso->so_qlen = so->so_qlen;
  3048. xso->so_incqlen = so->so_incqlen;
  3049. xso->so_qlimit = so->so_qlimit;
  3050. xso->so_timeo = so->so_timeo;
  3051. xso->so_error = so->so_error;
  3052. #if 0
  3053. xso->so_pgid = so->so_sigio ? so->so_sigio->sio_pgid : 0;
  3054. #endif
  3055. xso->so_oobmark = so->so_oobmark;
  3056. sbtoxsockbuf(&so->so_snd, &xso->so_snd);
  3057. sbtoxsockbuf(&so->so_rcv, &xso->so_rcv);
  3058. #if 0
  3059. xso->so_uid = so->so_cred->cr_uid;
  3060. #endif
  3061. }
  3062. /*
  3063. * Socket accessor functions to provide external consumers with
  3064. * a safe interface to socket state
  3065. *
  3066. */
  3067. void
  3068. so_listeners_apply_all(struct socket *so, void (*func)(struct socket *, void *), void *arg)
  3069. {
  3070. TAILQ_FOREACH(so, &so->so_comp, so_list)
  3071. func(so, arg);
  3072. }
  3073. struct sockbuf *
  3074. so_sockbuf_rcv(struct socket *so)
  3075. {
  3076. return (&so->so_rcv);
  3077. }
  3078. struct sockbuf *
  3079. so_sockbuf_snd(struct socket *so)
  3080. {
  3081. return (&so->so_snd);
  3082. }
  3083. int
  3084. so_state_get(const struct socket *so)
  3085. {
  3086. return (so->so_state);
  3087. }
  3088. void
  3089. so_state_set(struct socket *so, int val)
  3090. {
  3091. so->so_state = val;
  3092. }
  3093. int
  3094. so_options_get(const struct socket *so)
  3095. {
  3096. return (so->so_options);
  3097. }
  3098. void
  3099. so_options_set(struct socket *so, int val)
  3100. {
  3101. so->so_options = val;
  3102. }
  3103. int
  3104. so_error_get(const struct socket *so)
  3105. {
  3106. return (so->so_error);
  3107. }
  3108. void
  3109. so_error_set(struct socket *so, int val)
  3110. {
  3111. so->so_error = val;
  3112. }
  3113. int
  3114. so_linger_get(const struct socket *so)
  3115. {
  3116. return (so->so_linger);
  3117. }
  3118. void
  3119. so_linger_set(struct socket *so, int val)
  3120. {
  3121. so->so_linger = val;
  3122. }
  3123. struct protosw *
  3124. so_protosw_get(const struct socket *so)
  3125. {
  3126. return (so->so_proto);
  3127. }
  3128. void
  3129. so_protosw_set(struct socket *so, struct protosw *val)
  3130. {
  3131. so->so_proto = val;
  3132. }
  3133. void
  3134. so_sorwakeup(struct socket *so)
  3135. {
  3136. sorwakeup(so);
  3137. }
  3138. void
  3139. so_sowwakeup(struct socket *so)
  3140. {
  3141. sowwakeup(so);
  3142. }
  3143. void
  3144. so_sorwakeup_locked(struct socket *so)
  3145. {
  3146. sorwakeup_locked(so);
  3147. }
  3148. void
  3149. so_sowwakeup_locked(struct socket *so)
  3150. {
  3151. sowwakeup_locked(so);
  3152. }
  3153. void
  3154. so_lock(struct socket *so)
  3155. {
  3156. SOCK_LOCK(so);
  3157. }
  3158. void
  3159. so_unlock(struct socket *so)
  3160. {
  3161. SOCK_UNLOCK(so);
  3162. }