• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* SCTP kernel implementation
2  * (C) Copyright IBM Corp. 2001, 2004
3  * Copyright (c) 1999-2000 Cisco, Inc.
4  * Copyright (c) 1999-2001 Motorola, Inc.
5  * Copyright (c) 2001-2003 Intel Corp.
6  * Copyright (c) 2001-2002 Nokia, Inc.
7  * Copyright (c) 2001 La Monte H.P. Yarroll
8  *
9  * This file is part of the SCTP kernel implementation
10  *
11  * These functions interface with the sockets layer to implement the
12  * SCTP Extensions for the Sockets API.
13  *
14  * Note that the descriptions from the specification are USER level
15  * functions--this file is the functions which populate the struct proto
16  * for SCTP which is the BOTTOM of the sockets interface.
17  *
18  * This SCTP implementation is free software;
19  * you can redistribute it and/or modify it under the terms of
20  * the GNU General Public License as published by
21  * the Free Software Foundation; either version 2, or (at your option)
22  * any later version.
23  *
24  * This SCTP implementation is distributed in the hope that it
25  * will be useful, but WITHOUT ANY WARRANTY; without even the implied
26  *                 ************************
27  * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
28  * See the GNU General Public License for more details.
29  *
30  * You should have received a copy of the GNU General Public License
31  * along with GNU CC; see the file COPYING.  If not, see
32  * <http://www.gnu.org/licenses/>.
33  *
34  * Please send any bug reports or fixes you make to the
35  * email address(es):
36  *    lksctp developers <linux-sctp@vger.kernel.org>
37  *
38  * Written or modified by:
39  *    La Monte H.P. Yarroll <piggy@acm.org>
40  *    Narasimha Budihal     <narsi@refcode.org>
41  *    Karl Knutson          <karl@athena.chicago.il.us>
42  *    Jon Grimm             <jgrimm@us.ibm.com>
43  *    Xingang Guo           <xingang.guo@intel.com>
44  *    Daisy Chang           <daisyc@us.ibm.com>
45  *    Sridhar Samudrala     <samudrala@us.ibm.com>
46  *    Inaky Perez-Gonzalez  <inaky.gonzalez@intel.com>
47  *    Ardelle Fan	    <ardelle.fan@intel.com>
48  *    Ryan Layer	    <rmlayer@us.ibm.com>
49  *    Anup Pemmaiah         <pemmaiah@cc.usu.edu>
50  *    Kevin Gao             <kevin.gao@intel.com>
51  */
52 
53 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
54 
55 #include <linux/types.h>
56 #include <linux/kernel.h>
57 #include <linux/wait.h>
58 #include <linux/time.h>
59 #include <linux/ip.h>
60 #include <linux/capability.h>
61 #include <linux/fcntl.h>
62 #include <linux/poll.h>
63 #include <linux/init.h>
64 #include <linux/crypto.h>
65 #include <linux/slab.h>
66 #include <linux/file.h>
67 #include <linux/compat.h>
68 
69 #include <net/ip.h>
70 #include <net/icmp.h>
71 #include <net/route.h>
72 #include <net/ipv6.h>
73 #include <net/inet_common.h>
74 #include <net/busy_poll.h>
75 
76 #include <linux/socket.h> /* for sa_family_t */
77 #include <linux/export.h>
78 #include <net/sock.h>
79 #include <net/sctp/sctp.h>
80 #include <net/sctp/sm.h>
81 
82 /* Forward declarations for internal helper functions. */
83 static int sctp_writeable(struct sock *sk);
84 static void sctp_wfree(struct sk_buff *skb);
85 static int sctp_wait_for_sndbuf(struct sctp_association *asoc, long *timeo_p,
86 				size_t msg_len);
87 static int sctp_wait_for_packet(struct sock *sk, int *err, long *timeo_p);
88 static int sctp_wait_for_connect(struct sctp_association *, long *timeo_p);
89 static int sctp_wait_for_accept(struct sock *sk, long timeo);
90 static void sctp_wait_for_close(struct sock *sk, long timeo);
91 static void sctp_destruct_sock(struct sock *sk);
92 static struct sctp_af *sctp_sockaddr_af(struct sctp_sock *opt,
93 					union sctp_addr *addr, int len);
94 static int sctp_bindx_add(struct sock *, struct sockaddr *, int);
95 static int sctp_bindx_rem(struct sock *, struct sockaddr *, int);
96 static int sctp_send_asconf_add_ip(struct sock *, struct sockaddr *, int);
97 static int sctp_send_asconf_del_ip(struct sock *, struct sockaddr *, int);
98 static int sctp_send_asconf(struct sctp_association *asoc,
99 			    struct sctp_chunk *chunk);
100 static int sctp_do_bind(struct sock *, union sctp_addr *, int);
101 static int sctp_autobind(struct sock *sk);
102 static void sctp_sock_migrate(struct sock *, struct sock *,
103 			      struct sctp_association *, sctp_socket_type_t);
104 
105 extern struct kmem_cache *sctp_bucket_cachep;
106 extern long sysctl_sctp_mem[3];
107 extern int sysctl_sctp_rmem[3];
108 extern int sysctl_sctp_wmem[3];
109 
110 static int sctp_memory_pressure;
111 static atomic_long_t sctp_memory_allocated;
112 struct percpu_counter sctp_sockets_allocated;
113 
sctp_enter_memory_pressure(struct sock * sk)114 static void sctp_enter_memory_pressure(struct sock *sk)
115 {
116 	sctp_memory_pressure = 1;
117 }
118 
119 
120 /* Get the sndbuf space available at the time on the association.  */
sctp_wspace(struct sctp_association * asoc)121 static inline int sctp_wspace(struct sctp_association *asoc)
122 {
123 	int amt;
124 
125 	if (asoc->ep->sndbuf_policy)
126 		amt = asoc->sndbuf_used;
127 	else
128 		amt = sk_wmem_alloc_get(asoc->base.sk);
129 
130 	if (amt >= asoc->base.sk->sk_sndbuf) {
131 		if (asoc->base.sk->sk_userlocks & SOCK_SNDBUF_LOCK)
132 			amt = 0;
133 		else {
134 			amt = sk_stream_wspace(asoc->base.sk);
135 			if (amt < 0)
136 				amt = 0;
137 		}
138 	} else {
139 		amt = asoc->base.sk->sk_sndbuf - amt;
140 	}
141 	return amt;
142 }
143 
144 /* Increment the used sndbuf space count of the corresponding association by
145  * the size of the outgoing data chunk.
146  * Also, set the skb destructor for sndbuf accounting later.
147  *
148  * Since it is always 1-1 between chunk and skb, and also a new skb is always
149  * allocated for chunk bundling in sctp_packet_transmit(), we can use the
150  * destructor in the data chunk skb for the purpose of the sndbuf space
151  * tracking.
152  */
sctp_set_owner_w(struct sctp_chunk * chunk)153 static inline void sctp_set_owner_w(struct sctp_chunk *chunk)
154 {
155 	struct sctp_association *asoc = chunk->asoc;
156 	struct sock *sk = asoc->base.sk;
157 
158 	/* The sndbuf space is tracked per association.  */
159 	sctp_association_hold(asoc);
160 
161 	skb_set_owner_w(chunk->skb, sk);
162 
163 	chunk->skb->destructor = sctp_wfree;
164 	/* Save the chunk pointer in skb for sctp_wfree to use later.  */
165 	*((struct sctp_chunk **)(chunk->skb->cb)) = chunk;
166 
167 	asoc->sndbuf_used += SCTP_DATA_SNDSIZE(chunk) +
168 				sizeof(struct sk_buff) +
169 				sizeof(struct sctp_chunk);
170 
171 	atomic_add(sizeof(struct sctp_chunk), &sk->sk_wmem_alloc);
172 	sk->sk_wmem_queued += chunk->skb->truesize;
173 	sk_mem_charge(sk, chunk->skb->truesize);
174 }
175 
sctp_clear_owner_w(struct sctp_chunk * chunk)176 static void sctp_clear_owner_w(struct sctp_chunk *chunk)
177 {
178 	skb_orphan(chunk->skb);
179 }
180 
sctp_for_each_tx_datachunk(struct sctp_association * asoc,void (* cb)(struct sctp_chunk *))181 static void sctp_for_each_tx_datachunk(struct sctp_association *asoc,
182 				       void (*cb)(struct sctp_chunk *))
183 
184 {
185 	struct sctp_outq *q = &asoc->outqueue;
186 	struct sctp_transport *t;
187 	struct sctp_chunk *chunk;
188 
189 	list_for_each_entry(t, &asoc->peer.transport_addr_list, transports)
190 		list_for_each_entry(chunk, &t->transmitted, transmitted_list)
191 			cb(chunk);
192 
193 	list_for_each_entry(chunk, &q->retransmit, list)
194 		cb(chunk);
195 
196 	list_for_each_entry(chunk, &q->sacked, list)
197 		cb(chunk);
198 
199 	list_for_each_entry(chunk, &q->abandoned, list)
200 		cb(chunk);
201 
202 	list_for_each_entry(chunk, &q->out_chunk_list, list)
203 		cb(chunk);
204 }
205 
206 /* Verify that this is a valid address. */
sctp_verify_addr(struct sock * sk,union sctp_addr * addr,int len)207 static inline int sctp_verify_addr(struct sock *sk, union sctp_addr *addr,
208 				   int len)
209 {
210 	struct sctp_af *af;
211 
212 	/* Verify basic sockaddr. */
213 	af = sctp_sockaddr_af(sctp_sk(sk), addr, len);
214 	if (!af)
215 		return -EINVAL;
216 
217 	/* Is this a valid SCTP address?  */
218 	if (!af->addr_valid(addr, sctp_sk(sk), NULL))
219 		return -EINVAL;
220 
221 	if (!sctp_sk(sk)->pf->send_verify(sctp_sk(sk), (addr)))
222 		return -EINVAL;
223 
224 	return 0;
225 }
226 
227 /* Look up the association by its id.  If this is not a UDP-style
228  * socket, the ID field is always ignored.
229  */
sctp_id2assoc(struct sock * sk,sctp_assoc_t id)230 struct sctp_association *sctp_id2assoc(struct sock *sk, sctp_assoc_t id)
231 {
232 	struct sctp_association *asoc = NULL;
233 
234 	/* If this is not a UDP-style socket, assoc id should be ignored. */
235 	if (!sctp_style(sk, UDP)) {
236 		/* Return NULL if the socket state is not ESTABLISHED. It
237 		 * could be a TCP-style listening socket or a socket which
238 		 * hasn't yet called connect() to establish an association.
239 		 */
240 		if (!sctp_sstate(sk, ESTABLISHED))
241 			return NULL;
242 
243 		/* Get the first and the only association from the list. */
244 		if (!list_empty(&sctp_sk(sk)->ep->asocs))
245 			asoc = list_entry(sctp_sk(sk)->ep->asocs.next,
246 					  struct sctp_association, asocs);
247 		return asoc;
248 	}
249 
250 	/* Otherwise this is a UDP-style socket. */
251 	if (!id || (id == (sctp_assoc_t)-1))
252 		return NULL;
253 
254 	spin_lock_bh(&sctp_assocs_id_lock);
255 	asoc = (struct sctp_association *)idr_find(&sctp_assocs_id, (int)id);
256 	spin_unlock_bh(&sctp_assocs_id_lock);
257 
258 	if (!asoc || (asoc->base.sk != sk) || asoc->base.dead)
259 		return NULL;
260 
261 	return asoc;
262 }
263 
264 /* Look up the transport from an address and an assoc id. If both address and
265  * id are specified, the associations matching the address and the id should be
266  * the same.
267  */
sctp_addr_id2transport(struct sock * sk,struct sockaddr_storage * addr,sctp_assoc_t id)268 static struct sctp_transport *sctp_addr_id2transport(struct sock *sk,
269 					      struct sockaddr_storage *addr,
270 					      sctp_assoc_t id)
271 {
272 	struct sctp_association *addr_asoc = NULL, *id_asoc = NULL;
273 	struct sctp_transport *transport;
274 	union sctp_addr *laddr = (union sctp_addr *)addr;
275 
276 	addr_asoc = sctp_endpoint_lookup_assoc(sctp_sk(sk)->ep,
277 					       laddr,
278 					       &transport);
279 
280 	if (!addr_asoc)
281 		return NULL;
282 
283 	id_asoc = sctp_id2assoc(sk, id);
284 	if (id_asoc && (id_asoc != addr_asoc))
285 		return NULL;
286 
287 	sctp_get_pf_specific(sk->sk_family)->addr_to_user(sctp_sk(sk),
288 						(union sctp_addr *)addr);
289 
290 	return transport;
291 }
292 
293 /* API 3.1.2 bind() - UDP Style Syntax
294  * The syntax of bind() is,
295  *
296  *   ret = bind(int sd, struct sockaddr *addr, int addrlen);
297  *
298  *   sd      - the socket descriptor returned by socket().
299  *   addr    - the address structure (struct sockaddr_in or struct
300  *             sockaddr_in6 [RFC 2553]),
301  *   addr_len - the size of the address structure.
302  */
sctp_bind(struct sock * sk,struct sockaddr * addr,int addr_len)303 static int sctp_bind(struct sock *sk, struct sockaddr *addr, int addr_len)
304 {
305 	int retval = 0;
306 
307 	lock_sock(sk);
308 
309 	pr_debug("%s: sk:%p, addr:%p, addr_len:%d\n", __func__, sk,
310 		 addr, addr_len);
311 
312 	/* Disallow binding twice. */
313 	if (!sctp_sk(sk)->ep->base.bind_addr.port)
314 		retval = sctp_do_bind(sk, (union sctp_addr *)addr,
315 				      addr_len);
316 	else
317 		retval = -EINVAL;
318 
319 	release_sock(sk);
320 
321 	return retval;
322 }
323 
324 static long sctp_get_port_local(struct sock *, union sctp_addr *);
325 
326 /* Verify this is a valid sockaddr. */
sctp_sockaddr_af(struct sctp_sock * opt,union sctp_addr * addr,int len)327 static struct sctp_af *sctp_sockaddr_af(struct sctp_sock *opt,
328 					union sctp_addr *addr, int len)
329 {
330 	struct sctp_af *af;
331 
332 	/* Check minimum size.  */
333 	if (len < sizeof (struct sockaddr))
334 		return NULL;
335 
336 	if (!opt->pf->af_supported(addr->sa.sa_family, opt))
337 		return NULL;
338 
339 	/* V4 mapped address are really of AF_INET family */
340 	if (addr->sa.sa_family == AF_INET6 &&
341 	    ipv6_addr_v4mapped(&addr->v6.sin6_addr) &&
342 	    !opt->pf->af_supported(AF_INET, opt))
343 		return NULL;
344 
345 	/* If we get this far, af is valid. */
346 	af = sctp_get_af_specific(addr->sa.sa_family);
347 
348 	if (len < af->sockaddr_len)
349 		return NULL;
350 
351 	return af;
352 }
353 
354 /* Bind a local address either to an endpoint or to an association.  */
sctp_do_bind(struct sock * sk,union sctp_addr * addr,int len)355 static int sctp_do_bind(struct sock *sk, union sctp_addr *addr, int len)
356 {
357 	struct net *net = sock_net(sk);
358 	struct sctp_sock *sp = sctp_sk(sk);
359 	struct sctp_endpoint *ep = sp->ep;
360 	struct sctp_bind_addr *bp = &ep->base.bind_addr;
361 	struct sctp_af *af;
362 	unsigned short snum;
363 	int ret = 0;
364 
365 	/* Common sockaddr verification. */
366 	af = sctp_sockaddr_af(sp, addr, len);
367 	if (!af) {
368 		pr_debug("%s: sk:%p, newaddr:%p, len:%d EINVAL\n",
369 			 __func__, sk, addr, len);
370 		return -EINVAL;
371 	}
372 
373 	snum = ntohs(addr->v4.sin_port);
374 
375 	pr_debug("%s: sk:%p, new addr:%pISc, port:%d, new port:%d, len:%d\n",
376 		 __func__, sk, &addr->sa, bp->port, snum, len);
377 
378 	/* PF specific bind() address verification. */
379 	if (!sp->pf->bind_verify(sp, addr))
380 		return -EADDRNOTAVAIL;
381 
382 	/* We must either be unbound, or bind to the same port.
383 	 * It's OK to allow 0 ports if we are already bound.
384 	 * We'll just inhert an already bound port in this case
385 	 */
386 	if (bp->port) {
387 		if (!snum)
388 			snum = bp->port;
389 		else if (snum != bp->port) {
390 			pr_debug("%s: new port %d doesn't match existing port "
391 				 "%d\n", __func__, snum, bp->port);
392 			return -EINVAL;
393 		}
394 	}
395 
396 	if (snum && snum < PROT_SOCK &&
397 	    !ns_capable(net->user_ns, CAP_NET_BIND_SERVICE))
398 		return -EACCES;
399 
400 	/* See if the address matches any of the addresses we may have
401 	 * already bound before checking against other endpoints.
402 	 */
403 	if (sctp_bind_addr_match(bp, addr, sp))
404 		return -EINVAL;
405 
406 	/* Make sure we are allowed to bind here.
407 	 * The function sctp_get_port_local() does duplicate address
408 	 * detection.
409 	 */
410 	addr->v4.sin_port = htons(snum);
411 	if ((ret = sctp_get_port_local(sk, addr))) {
412 		return -EADDRINUSE;
413 	}
414 
415 	/* Refresh ephemeral port.  */
416 	if (!bp->port)
417 		bp->port = inet_sk(sk)->inet_num;
418 
419 	/* Add the address to the bind address list.
420 	 * Use GFP_ATOMIC since BHs will be disabled.
421 	 */
422 	ret = sctp_add_bind_addr(bp, addr, SCTP_ADDR_SRC, GFP_ATOMIC);
423 
424 	/* Copy back into socket for getsockname() use. */
425 	if (!ret) {
426 		inet_sk(sk)->inet_sport = htons(inet_sk(sk)->inet_num);
427 		sp->pf->to_sk_saddr(addr, sk);
428 	}
429 
430 	return ret;
431 }
432 
433  /* ADDIP Section 4.1.1 Congestion Control of ASCONF Chunks
434  *
435  * R1) One and only one ASCONF Chunk MAY be in transit and unacknowledged
436  * at any one time.  If a sender, after sending an ASCONF chunk, decides
437  * it needs to transfer another ASCONF Chunk, it MUST wait until the
438  * ASCONF-ACK Chunk returns from the previous ASCONF Chunk before sending a
439  * subsequent ASCONF. Note this restriction binds each side, so at any
440  * time two ASCONF may be in-transit on any given association (one sent
441  * from each endpoint).
442  */
sctp_send_asconf(struct sctp_association * asoc,struct sctp_chunk * chunk)443 static int sctp_send_asconf(struct sctp_association *asoc,
444 			    struct sctp_chunk *chunk)
445 {
446 	struct net 	*net = sock_net(asoc->base.sk);
447 	int		retval = 0;
448 
449 	/* If there is an outstanding ASCONF chunk, queue it for later
450 	 * transmission.
451 	 */
452 	if (asoc->addip_last_asconf) {
453 		list_add_tail(&chunk->list, &asoc->addip_chunk_list);
454 		goto out;
455 	}
456 
457 	/* Hold the chunk until an ASCONF_ACK is received. */
458 	sctp_chunk_hold(chunk);
459 	retval = sctp_primitive_ASCONF(net, asoc, chunk);
460 	if (retval)
461 		sctp_chunk_free(chunk);
462 	else
463 		asoc->addip_last_asconf = chunk;
464 
465 out:
466 	return retval;
467 }
468 
469 /* Add a list of addresses as bind addresses to local endpoint or
470  * association.
471  *
472  * Basically run through each address specified in the addrs/addrcnt
473  * array/length pair, determine if it is IPv6 or IPv4 and call
474  * sctp_do_bind() on it.
475  *
476  * If any of them fails, then the operation will be reversed and the
477  * ones that were added will be removed.
478  *
479  * Only sctp_setsockopt_bindx() is supposed to call this function.
480  */
sctp_bindx_add(struct sock * sk,struct sockaddr * addrs,int addrcnt)481 static int sctp_bindx_add(struct sock *sk, struct sockaddr *addrs, int addrcnt)
482 {
483 	int cnt;
484 	int retval = 0;
485 	void *addr_buf;
486 	struct sockaddr *sa_addr;
487 	struct sctp_af *af;
488 
489 	pr_debug("%s: sk:%p, addrs:%p, addrcnt:%d\n", __func__, sk,
490 		 addrs, addrcnt);
491 
492 	addr_buf = addrs;
493 	for (cnt = 0; cnt < addrcnt; cnt++) {
494 		/* The list may contain either IPv4 or IPv6 address;
495 		 * determine the address length for walking thru the list.
496 		 */
497 		sa_addr = addr_buf;
498 		af = sctp_get_af_specific(sa_addr->sa_family);
499 		if (!af) {
500 			retval = -EINVAL;
501 			goto err_bindx_add;
502 		}
503 
504 		retval = sctp_do_bind(sk, (union sctp_addr *)sa_addr,
505 				      af->sockaddr_len);
506 
507 		addr_buf += af->sockaddr_len;
508 
509 err_bindx_add:
510 		if (retval < 0) {
511 			/* Failed. Cleanup the ones that have been added */
512 			if (cnt > 0)
513 				sctp_bindx_rem(sk, addrs, cnt);
514 			return retval;
515 		}
516 	}
517 
518 	return retval;
519 }
520 
521 /* Send an ASCONF chunk with Add IP address parameters to all the peers of the
522  * associations that are part of the endpoint indicating that a list of local
523  * addresses are added to the endpoint.
524  *
525  * If any of the addresses is already in the bind address list of the
526  * association, we do not send the chunk for that association.  But it will not
527  * affect other associations.
528  *
529  * Only sctp_setsockopt_bindx() is supposed to call this function.
530  */
sctp_send_asconf_add_ip(struct sock * sk,struct sockaddr * addrs,int addrcnt)531 static int sctp_send_asconf_add_ip(struct sock		*sk,
532 				   struct sockaddr	*addrs,
533 				   int 			addrcnt)
534 {
535 	struct net *net = sock_net(sk);
536 	struct sctp_sock		*sp;
537 	struct sctp_endpoint		*ep;
538 	struct sctp_association		*asoc;
539 	struct sctp_bind_addr		*bp;
540 	struct sctp_chunk		*chunk;
541 	struct sctp_sockaddr_entry	*laddr;
542 	union sctp_addr			*addr;
543 	union sctp_addr			saveaddr;
544 	void				*addr_buf;
545 	struct sctp_af			*af;
546 	struct list_head		*p;
547 	int 				i;
548 	int 				retval = 0;
549 
550 	if (!net->sctp.addip_enable)
551 		return retval;
552 
553 	sp = sctp_sk(sk);
554 	ep = sp->ep;
555 
556 	pr_debug("%s: sk:%p, addrs:%p, addrcnt:%d\n",
557 		 __func__, sk, addrs, addrcnt);
558 
559 	list_for_each_entry(asoc, &ep->asocs, asocs) {
560 		if (!asoc->peer.asconf_capable)
561 			continue;
562 
563 		if (asoc->peer.addip_disabled_mask & SCTP_PARAM_ADD_IP)
564 			continue;
565 
566 		if (!sctp_state(asoc, ESTABLISHED))
567 			continue;
568 
569 		/* Check if any address in the packed array of addresses is
570 		 * in the bind address list of the association. If so,
571 		 * do not send the asconf chunk to its peer, but continue with
572 		 * other associations.
573 		 */
574 		addr_buf = addrs;
575 		for (i = 0; i < addrcnt; i++) {
576 			addr = addr_buf;
577 			af = sctp_get_af_specific(addr->v4.sin_family);
578 			if (!af) {
579 				retval = -EINVAL;
580 				goto out;
581 			}
582 
583 			if (sctp_assoc_lookup_laddr(asoc, addr))
584 				break;
585 
586 			addr_buf += af->sockaddr_len;
587 		}
588 		if (i < addrcnt)
589 			continue;
590 
591 		/* Use the first valid address in bind addr list of
592 		 * association as Address Parameter of ASCONF CHUNK.
593 		 */
594 		bp = &asoc->base.bind_addr;
595 		p = bp->address_list.next;
596 		laddr = list_entry(p, struct sctp_sockaddr_entry, list);
597 		chunk = sctp_make_asconf_update_ip(asoc, &laddr->a, addrs,
598 						   addrcnt, SCTP_PARAM_ADD_IP);
599 		if (!chunk) {
600 			retval = -ENOMEM;
601 			goto out;
602 		}
603 
604 		/* Add the new addresses to the bind address list with
605 		 * use_as_src set to 0.
606 		 */
607 		addr_buf = addrs;
608 		for (i = 0; i < addrcnt; i++) {
609 			addr = addr_buf;
610 			af = sctp_get_af_specific(addr->v4.sin_family);
611 			memcpy(&saveaddr, addr, af->sockaddr_len);
612 			retval = sctp_add_bind_addr(bp, &saveaddr,
613 						    SCTP_ADDR_NEW, GFP_ATOMIC);
614 			addr_buf += af->sockaddr_len;
615 		}
616 		if (asoc->src_out_of_asoc_ok) {
617 			struct sctp_transport *trans;
618 
619 			list_for_each_entry(trans,
620 			    &asoc->peer.transport_addr_list, transports) {
621 				/* Clear the source and route cache */
622 				dst_release(trans->dst);
623 				trans->cwnd = min(4*asoc->pathmtu, max_t(__u32,
624 				    2*asoc->pathmtu, 4380));
625 				trans->ssthresh = asoc->peer.i.a_rwnd;
626 				trans->rto = asoc->rto_initial;
627 				sctp_max_rto(asoc, trans);
628 				trans->rtt = trans->srtt = trans->rttvar = 0;
629 				sctp_transport_route(trans, NULL,
630 				    sctp_sk(asoc->base.sk));
631 			}
632 		}
633 		retval = sctp_send_asconf(asoc, chunk);
634 	}
635 
636 out:
637 	return retval;
638 }
639 
640 /* Remove a list of addresses from bind addresses list.  Do not remove the
641  * last address.
642  *
643  * Basically run through each address specified in the addrs/addrcnt
644  * array/length pair, determine if it is IPv6 or IPv4 and call
645  * sctp_del_bind() on it.
646  *
647  * If any of them fails, then the operation will be reversed and the
648  * ones that were removed will be added back.
649  *
650  * At least one address has to be left; if only one address is
651  * available, the operation will return -EBUSY.
652  *
653  * Only sctp_setsockopt_bindx() is supposed to call this function.
654  */
sctp_bindx_rem(struct sock * sk,struct sockaddr * addrs,int addrcnt)655 static int sctp_bindx_rem(struct sock *sk, struct sockaddr *addrs, int addrcnt)
656 {
657 	struct sctp_sock *sp = sctp_sk(sk);
658 	struct sctp_endpoint *ep = sp->ep;
659 	int cnt;
660 	struct sctp_bind_addr *bp = &ep->base.bind_addr;
661 	int retval = 0;
662 	void *addr_buf;
663 	union sctp_addr *sa_addr;
664 	struct sctp_af *af;
665 
666 	pr_debug("%s: sk:%p, addrs:%p, addrcnt:%d\n",
667 		 __func__, sk, addrs, addrcnt);
668 
669 	addr_buf = addrs;
670 	for (cnt = 0; cnt < addrcnt; cnt++) {
671 		/* If the bind address list is empty or if there is only one
672 		 * bind address, there is nothing more to be removed (we need
673 		 * at least one address here).
674 		 */
675 		if (list_empty(&bp->address_list) ||
676 		    (sctp_list_single_entry(&bp->address_list))) {
677 			retval = -EBUSY;
678 			goto err_bindx_rem;
679 		}
680 
681 		sa_addr = addr_buf;
682 		af = sctp_get_af_specific(sa_addr->sa.sa_family);
683 		if (!af) {
684 			retval = -EINVAL;
685 			goto err_bindx_rem;
686 		}
687 
688 		if (!af->addr_valid(sa_addr, sp, NULL)) {
689 			retval = -EADDRNOTAVAIL;
690 			goto err_bindx_rem;
691 		}
692 
693 		if (sa_addr->v4.sin_port &&
694 		    sa_addr->v4.sin_port != htons(bp->port)) {
695 			retval = -EINVAL;
696 			goto err_bindx_rem;
697 		}
698 
699 		if (!sa_addr->v4.sin_port)
700 			sa_addr->v4.sin_port = htons(bp->port);
701 
702 		/* FIXME - There is probably a need to check if sk->sk_saddr and
703 		 * sk->sk_rcv_addr are currently set to one of the addresses to
704 		 * be removed. This is something which needs to be looked into
705 		 * when we are fixing the outstanding issues with multi-homing
706 		 * socket routing and failover schemes. Refer to comments in
707 		 * sctp_do_bind(). -daisy
708 		 */
709 		retval = sctp_del_bind_addr(bp, sa_addr);
710 
711 		addr_buf += af->sockaddr_len;
712 err_bindx_rem:
713 		if (retval < 0) {
714 			/* Failed. Add the ones that has been removed back */
715 			if (cnt > 0)
716 				sctp_bindx_add(sk, addrs, cnt);
717 			return retval;
718 		}
719 	}
720 
721 	return retval;
722 }
723 
724 /* Send an ASCONF chunk with Delete IP address parameters to all the peers of
725  * the associations that are part of the endpoint indicating that a list of
726  * local addresses are removed from the endpoint.
727  *
728  * If any of the addresses is already in the bind address list of the
729  * association, we do not send the chunk for that association.  But it will not
730  * affect other associations.
731  *
732  * Only sctp_setsockopt_bindx() is supposed to call this function.
733  */
sctp_send_asconf_del_ip(struct sock * sk,struct sockaddr * addrs,int addrcnt)734 static int sctp_send_asconf_del_ip(struct sock		*sk,
735 				   struct sockaddr	*addrs,
736 				   int			addrcnt)
737 {
738 	struct net *net = sock_net(sk);
739 	struct sctp_sock	*sp;
740 	struct sctp_endpoint	*ep;
741 	struct sctp_association	*asoc;
742 	struct sctp_transport	*transport;
743 	struct sctp_bind_addr	*bp;
744 	struct sctp_chunk	*chunk;
745 	union sctp_addr		*laddr;
746 	void			*addr_buf;
747 	struct sctp_af		*af;
748 	struct sctp_sockaddr_entry *saddr;
749 	int 			i;
750 	int 			retval = 0;
751 	int			stored = 0;
752 
753 	chunk = NULL;
754 	if (!net->sctp.addip_enable)
755 		return retval;
756 
757 	sp = sctp_sk(sk);
758 	ep = sp->ep;
759 
760 	pr_debug("%s: sk:%p, addrs:%p, addrcnt:%d\n",
761 		 __func__, sk, addrs, addrcnt);
762 
763 	list_for_each_entry(asoc, &ep->asocs, asocs) {
764 
765 		if (!asoc->peer.asconf_capable)
766 			continue;
767 
768 		if (asoc->peer.addip_disabled_mask & SCTP_PARAM_DEL_IP)
769 			continue;
770 
771 		if (!sctp_state(asoc, ESTABLISHED))
772 			continue;
773 
774 		/* Check if any address in the packed array of addresses is
775 		 * not present in the bind address list of the association.
776 		 * If so, do not send the asconf chunk to its peer, but
777 		 * continue with other associations.
778 		 */
779 		addr_buf = addrs;
780 		for (i = 0; i < addrcnt; i++) {
781 			laddr = addr_buf;
782 			af = sctp_get_af_specific(laddr->v4.sin_family);
783 			if (!af) {
784 				retval = -EINVAL;
785 				goto out;
786 			}
787 
788 			if (!sctp_assoc_lookup_laddr(asoc, laddr))
789 				break;
790 
791 			addr_buf += af->sockaddr_len;
792 		}
793 		if (i < addrcnt)
794 			continue;
795 
796 		/* Find one address in the association's bind address list
797 		 * that is not in the packed array of addresses. This is to
798 		 * make sure that we do not delete all the addresses in the
799 		 * association.
800 		 */
801 		bp = &asoc->base.bind_addr;
802 		laddr = sctp_find_unmatch_addr(bp, (union sctp_addr *)addrs,
803 					       addrcnt, sp);
804 		if ((laddr == NULL) && (addrcnt == 1)) {
805 			if (asoc->asconf_addr_del_pending)
806 				continue;
807 			asoc->asconf_addr_del_pending =
808 			    kzalloc(sizeof(union sctp_addr), GFP_ATOMIC);
809 			if (asoc->asconf_addr_del_pending == NULL) {
810 				retval = -ENOMEM;
811 				goto out;
812 			}
813 			asoc->asconf_addr_del_pending->sa.sa_family =
814 				    addrs->sa_family;
815 			asoc->asconf_addr_del_pending->v4.sin_port =
816 				    htons(bp->port);
817 			if (addrs->sa_family == AF_INET) {
818 				struct sockaddr_in *sin;
819 
820 				sin = (struct sockaddr_in *)addrs;
821 				asoc->asconf_addr_del_pending->v4.sin_addr.s_addr = sin->sin_addr.s_addr;
822 			} else if (addrs->sa_family == AF_INET6) {
823 				struct sockaddr_in6 *sin6;
824 
825 				sin6 = (struct sockaddr_in6 *)addrs;
826 				asoc->asconf_addr_del_pending->v6.sin6_addr = sin6->sin6_addr;
827 			}
828 
829 			pr_debug("%s: keep the last address asoc:%p %pISc at %p\n",
830 				 __func__, asoc, &asoc->asconf_addr_del_pending->sa,
831 				 asoc->asconf_addr_del_pending);
832 
833 			asoc->src_out_of_asoc_ok = 1;
834 			stored = 1;
835 			goto skip_mkasconf;
836 		}
837 
838 		if (laddr == NULL)
839 			return -EINVAL;
840 
841 		/* We do not need RCU protection throughout this loop
842 		 * because this is done under a socket lock from the
843 		 * setsockopt call.
844 		 */
845 		chunk = sctp_make_asconf_update_ip(asoc, laddr, addrs, addrcnt,
846 						   SCTP_PARAM_DEL_IP);
847 		if (!chunk) {
848 			retval = -ENOMEM;
849 			goto out;
850 		}
851 
852 skip_mkasconf:
853 		/* Reset use_as_src flag for the addresses in the bind address
854 		 * list that are to be deleted.
855 		 */
856 		addr_buf = addrs;
857 		for (i = 0; i < addrcnt; i++) {
858 			laddr = addr_buf;
859 			af = sctp_get_af_specific(laddr->v4.sin_family);
860 			list_for_each_entry(saddr, &bp->address_list, list) {
861 				if (sctp_cmp_addr_exact(&saddr->a, laddr))
862 					saddr->state = SCTP_ADDR_DEL;
863 			}
864 			addr_buf += af->sockaddr_len;
865 		}
866 
867 		/* Update the route and saddr entries for all the transports
868 		 * as some of the addresses in the bind address list are
869 		 * about to be deleted and cannot be used as source addresses.
870 		 */
871 		list_for_each_entry(transport, &asoc->peer.transport_addr_list,
872 					transports) {
873 			dst_release(transport->dst);
874 			sctp_transport_route(transport, NULL,
875 					     sctp_sk(asoc->base.sk));
876 		}
877 
878 		if (stored)
879 			/* We don't need to transmit ASCONF */
880 			continue;
881 		retval = sctp_send_asconf(asoc, chunk);
882 	}
883 out:
884 	return retval;
885 }
886 
887 /* set addr events to assocs in the endpoint.  ep and addr_wq must be locked */
sctp_asconf_mgmt(struct sctp_sock * sp,struct sctp_sockaddr_entry * addrw)888 int sctp_asconf_mgmt(struct sctp_sock *sp, struct sctp_sockaddr_entry *addrw)
889 {
890 	struct sock *sk = sctp_opt2sk(sp);
891 	union sctp_addr *addr;
892 	struct sctp_af *af;
893 
894 	/* It is safe to write port space in caller. */
895 	addr = &addrw->a;
896 	addr->v4.sin_port = htons(sp->ep->base.bind_addr.port);
897 	af = sctp_get_af_specific(addr->sa.sa_family);
898 	if (!af)
899 		return -EINVAL;
900 	if (sctp_verify_addr(sk, addr, af->sockaddr_len))
901 		return -EINVAL;
902 
903 	if (addrw->state == SCTP_ADDR_NEW)
904 		return sctp_send_asconf_add_ip(sk, (struct sockaddr *)addr, 1);
905 	else
906 		return sctp_send_asconf_del_ip(sk, (struct sockaddr *)addr, 1);
907 }
908 
909 /* Helper for tunneling sctp_bindx() requests through sctp_setsockopt()
910  *
911  * API 8.1
912  * int sctp_bindx(int sd, struct sockaddr *addrs, int addrcnt,
913  *                int flags);
914  *
915  * If sd is an IPv4 socket, the addresses passed must be IPv4 addresses.
916  * If the sd is an IPv6 socket, the addresses passed can either be IPv4
917  * or IPv6 addresses.
918  *
919  * A single address may be specified as INADDR_ANY or IN6ADDR_ANY, see
920  * Section 3.1.2 for this usage.
921  *
922  * addrs is a pointer to an array of one or more socket addresses. Each
923  * address is contained in its appropriate structure (i.e. struct
924  * sockaddr_in or struct sockaddr_in6) the family of the address type
925  * must be used to distinguish the address length (note that this
926  * representation is termed a "packed array" of addresses). The caller
927  * specifies the number of addresses in the array with addrcnt.
928  *
929  * On success, sctp_bindx() returns 0. On failure, sctp_bindx() returns
930  * -1, and sets errno to the appropriate error code.
931  *
932  * For SCTP, the port given in each socket address must be the same, or
933  * sctp_bindx() will fail, setting errno to EINVAL.
934  *
935  * The flags parameter is formed from the bitwise OR of zero or more of
936  * the following currently defined flags:
937  *
938  * SCTP_BINDX_ADD_ADDR
939  *
940  * SCTP_BINDX_REM_ADDR
941  *
942  * SCTP_BINDX_ADD_ADDR directs SCTP to add the given addresses to the
943  * association, and SCTP_BINDX_REM_ADDR directs SCTP to remove the given
944  * addresses from the association. The two flags are mutually exclusive;
945  * if both are given, sctp_bindx() will fail with EINVAL. A caller may
946  * not remove all addresses from an association; sctp_bindx() will
947  * reject such an attempt with EINVAL.
948  *
949  * An application can use sctp_bindx(SCTP_BINDX_ADD_ADDR) to associate
950  * additional addresses with an endpoint after calling bind().  Or use
951  * sctp_bindx(SCTP_BINDX_REM_ADDR) to remove some addresses a listening
952  * socket is associated with so that no new association accepted will be
953  * associated with those addresses. If the endpoint supports dynamic
954  * address a SCTP_BINDX_REM_ADDR or SCTP_BINDX_ADD_ADDR may cause a
955  * endpoint to send the appropriate message to the peer to change the
956  * peers address lists.
957  *
958  * Adding and removing addresses from a connected association is
959  * optional functionality. Implementations that do not support this
960  * functionality should return EOPNOTSUPP.
961  *
962  * Basically do nothing but copying the addresses from user to kernel
963  * land and invoking either sctp_bindx_add() or sctp_bindx_rem() on the sk.
964  * This is used for tunneling the sctp_bindx() request through sctp_setsockopt()
965  * from userspace.
966  *
967  * We don't use copy_from_user() for optimization: we first do the
968  * sanity checks (buffer size -fast- and access check-healthy
969  * pointer); if all of those succeed, then we can alloc the memory
970  * (expensive operation) needed to copy the data to kernel. Then we do
971  * the copying without checking the user space area
972  * (__copy_from_user()).
973  *
974  * On exit there is no need to do sockfd_put(), sys_setsockopt() does
975  * it.
976  *
977  * sk        The sk of the socket
978  * addrs     The pointer to the addresses in user land
979  * addrssize Size of the addrs buffer
980  * op        Operation to perform (add or remove, see the flags of
981  *           sctp_bindx)
982  *
983  * Returns 0 if ok, <0 errno code on error.
984  */
sctp_setsockopt_bindx(struct sock * sk,struct sockaddr __user * addrs,int addrs_size,int op)985 static int sctp_setsockopt_bindx(struct sock *sk,
986 				 struct sockaddr __user *addrs,
987 				 int addrs_size, int op)
988 {
989 	struct sockaddr *kaddrs;
990 	int err;
991 	int addrcnt = 0;
992 	int walk_size = 0;
993 	struct sockaddr *sa_addr;
994 	void *addr_buf;
995 	struct sctp_af *af;
996 
997 	pr_debug("%s: sk:%p addrs:%p addrs_size:%d opt:%d\n",
998 		 __func__, sk, addrs, addrs_size, op);
999 
1000 	if (unlikely(addrs_size <= 0))
1001 		return -EINVAL;
1002 
1003 	/* Check the user passed a healthy pointer.  */
1004 	if (unlikely(!access_ok(VERIFY_READ, addrs, addrs_size)))
1005 		return -EFAULT;
1006 
1007 	/* Alloc space for the address array in kernel memory.  */
1008 	kaddrs = kmalloc(addrs_size, GFP_KERNEL);
1009 	if (unlikely(!kaddrs))
1010 		return -ENOMEM;
1011 
1012 	if (__copy_from_user(kaddrs, addrs, addrs_size)) {
1013 		kfree(kaddrs);
1014 		return -EFAULT;
1015 	}
1016 
1017 	/* Walk through the addrs buffer and count the number of addresses. */
1018 	addr_buf = kaddrs;
1019 	while (walk_size < addrs_size) {
1020 		if (walk_size + sizeof(sa_family_t) > addrs_size) {
1021 			kfree(kaddrs);
1022 			return -EINVAL;
1023 		}
1024 
1025 		sa_addr = addr_buf;
1026 		af = sctp_get_af_specific(sa_addr->sa_family);
1027 
1028 		/* If the address family is not supported or if this address
1029 		 * causes the address buffer to overflow return EINVAL.
1030 		 */
1031 		if (!af || (walk_size + af->sockaddr_len) > addrs_size) {
1032 			kfree(kaddrs);
1033 			return -EINVAL;
1034 		}
1035 		addrcnt++;
1036 		addr_buf += af->sockaddr_len;
1037 		walk_size += af->sockaddr_len;
1038 	}
1039 
1040 	/* Do the work. */
1041 	switch (op) {
1042 	case SCTP_BINDX_ADD_ADDR:
1043 		err = sctp_bindx_add(sk, kaddrs, addrcnt);
1044 		if (err)
1045 			goto out;
1046 		err = sctp_send_asconf_add_ip(sk, kaddrs, addrcnt);
1047 		break;
1048 
1049 	case SCTP_BINDX_REM_ADDR:
1050 		err = sctp_bindx_rem(sk, kaddrs, addrcnt);
1051 		if (err)
1052 			goto out;
1053 		err = sctp_send_asconf_del_ip(sk, kaddrs, addrcnt);
1054 		break;
1055 
1056 	default:
1057 		err = -EINVAL;
1058 		break;
1059 	}
1060 
1061 out:
1062 	kfree(kaddrs);
1063 
1064 	return err;
1065 }
1066 
1067 /* __sctp_connect(struct sock* sk, struct sockaddr *kaddrs, int addrs_size)
1068  *
1069  * Common routine for handling connect() and sctp_connectx().
1070  * Connect will come in with just a single address.
1071  */
__sctp_connect(struct sock * sk,struct sockaddr * kaddrs,int addrs_size,sctp_assoc_t * assoc_id)1072 static int __sctp_connect(struct sock *sk,
1073 			  struct sockaddr *kaddrs,
1074 			  int addrs_size,
1075 			  sctp_assoc_t *assoc_id)
1076 {
1077 	struct net *net = sock_net(sk);
1078 	struct sctp_sock *sp;
1079 	struct sctp_endpoint *ep;
1080 	struct sctp_association *asoc = NULL;
1081 	struct sctp_association *asoc2;
1082 	struct sctp_transport *transport;
1083 	union sctp_addr to;
1084 	sctp_scope_t scope;
1085 	long timeo;
1086 	int err = 0;
1087 	int addrcnt = 0;
1088 	int walk_size = 0;
1089 	union sctp_addr *sa_addr = NULL;
1090 	void *addr_buf;
1091 	unsigned short port;
1092 	unsigned int f_flags = 0;
1093 
1094 	sp = sctp_sk(sk);
1095 	ep = sp->ep;
1096 
1097 	/* connect() cannot be done on a socket that is already in ESTABLISHED
1098 	 * state - UDP-style peeled off socket or a TCP-style socket that
1099 	 * is already connected.
1100 	 * It cannot be done even on a TCP-style listening socket.
1101 	 */
1102 	if (sctp_sstate(sk, ESTABLISHED) ||
1103 	    (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING))) {
1104 		err = -EISCONN;
1105 		goto out_free;
1106 	}
1107 
1108 	/* Walk through the addrs buffer and count the number of addresses. */
1109 	addr_buf = kaddrs;
1110 	while (walk_size < addrs_size) {
1111 		struct sctp_af *af;
1112 
1113 		if (walk_size + sizeof(sa_family_t) > addrs_size) {
1114 			err = -EINVAL;
1115 			goto out_free;
1116 		}
1117 
1118 		sa_addr = addr_buf;
1119 		af = sctp_get_af_specific(sa_addr->sa.sa_family);
1120 
1121 		/* If the address family is not supported or if this address
1122 		 * causes the address buffer to overflow return EINVAL.
1123 		 */
1124 		if (!af || (walk_size + af->sockaddr_len) > addrs_size) {
1125 			err = -EINVAL;
1126 			goto out_free;
1127 		}
1128 
1129 		port = ntohs(sa_addr->v4.sin_port);
1130 
1131 		/* Save current address so we can work with it */
1132 		memcpy(&to, sa_addr, af->sockaddr_len);
1133 
1134 		err = sctp_verify_addr(sk, &to, af->sockaddr_len);
1135 		if (err)
1136 			goto out_free;
1137 
1138 		/* Make sure the destination port is correctly set
1139 		 * in all addresses.
1140 		 */
1141 		if (asoc && asoc->peer.port && asoc->peer.port != port) {
1142 			err = -EINVAL;
1143 			goto out_free;
1144 		}
1145 
1146 		/* Check if there already is a matching association on the
1147 		 * endpoint (other than the one created here).
1148 		 */
1149 		asoc2 = sctp_endpoint_lookup_assoc(ep, &to, &transport);
1150 		if (asoc2 && asoc2 != asoc) {
1151 			if (asoc2->state >= SCTP_STATE_ESTABLISHED)
1152 				err = -EISCONN;
1153 			else
1154 				err = -EALREADY;
1155 			goto out_free;
1156 		}
1157 
1158 		/* If we could not find a matching association on the endpoint,
1159 		 * make sure that there is no peeled-off association matching
1160 		 * the peer address even on another socket.
1161 		 */
1162 		if (sctp_endpoint_is_peeled_off(ep, &to)) {
1163 			err = -EADDRNOTAVAIL;
1164 			goto out_free;
1165 		}
1166 
1167 		if (!asoc) {
1168 			/* If a bind() or sctp_bindx() is not called prior to
1169 			 * an sctp_connectx() call, the system picks an
1170 			 * ephemeral port and will choose an address set
1171 			 * equivalent to binding with a wildcard address.
1172 			 */
1173 			if (!ep->base.bind_addr.port) {
1174 				if (sctp_autobind(sk)) {
1175 					err = -EAGAIN;
1176 					goto out_free;
1177 				}
1178 			} else {
1179 				/*
1180 				 * If an unprivileged user inherits a 1-many
1181 				 * style socket with open associations on a
1182 				 * privileged port, it MAY be permitted to
1183 				 * accept new associations, but it SHOULD NOT
1184 				 * be permitted to open new associations.
1185 				 */
1186 				if (ep->base.bind_addr.port < PROT_SOCK &&
1187 				    !ns_capable(net->user_ns, CAP_NET_BIND_SERVICE)) {
1188 					err = -EACCES;
1189 					goto out_free;
1190 				}
1191 			}
1192 
1193 			scope = sctp_scope(&to);
1194 			asoc = sctp_association_new(ep, sk, scope, GFP_KERNEL);
1195 			if (!asoc) {
1196 				err = -ENOMEM;
1197 				goto out_free;
1198 			}
1199 
1200 			err = sctp_assoc_set_bind_addr_from_ep(asoc, scope,
1201 							      GFP_KERNEL);
1202 			if (err < 0) {
1203 				goto out_free;
1204 			}
1205 
1206 		}
1207 
1208 		/* Prime the peer's transport structures.  */
1209 		transport = sctp_assoc_add_peer(asoc, &to, GFP_KERNEL,
1210 						SCTP_UNKNOWN);
1211 		if (!transport) {
1212 			err = -ENOMEM;
1213 			goto out_free;
1214 		}
1215 
1216 		addrcnt++;
1217 		addr_buf += af->sockaddr_len;
1218 		walk_size += af->sockaddr_len;
1219 	}
1220 
1221 	/* In case the user of sctp_connectx() wants an association
1222 	 * id back, assign one now.
1223 	 */
1224 	if (assoc_id) {
1225 		err = sctp_assoc_set_id(asoc, GFP_KERNEL);
1226 		if (err < 0)
1227 			goto out_free;
1228 	}
1229 
1230 	err = sctp_primitive_ASSOCIATE(net, asoc, NULL);
1231 	if (err < 0) {
1232 		goto out_free;
1233 	}
1234 
1235 	/* Initialize sk's dport and daddr for getpeername() */
1236 	inet_sk(sk)->inet_dport = htons(asoc->peer.port);
1237 	sp->pf->to_sk_daddr(sa_addr, sk);
1238 	sk->sk_err = 0;
1239 
1240 	/* in-kernel sockets don't generally have a file allocated to them
1241 	 * if all they do is call sock_create_kern().
1242 	 */
1243 	if (sk->sk_socket->file)
1244 		f_flags = sk->sk_socket->file->f_flags;
1245 
1246 	timeo = sock_sndtimeo(sk, f_flags & O_NONBLOCK);
1247 
1248 	err = sctp_wait_for_connect(asoc, &timeo);
1249 	if ((err == 0 || err == -EINPROGRESS) && assoc_id)
1250 		*assoc_id = asoc->assoc_id;
1251 
1252 	/* Don't free association on exit. */
1253 	asoc = NULL;
1254 
1255 out_free:
1256 	pr_debug("%s: took out_free path with asoc:%p kaddrs:%p err:%d\n",
1257 		 __func__, asoc, kaddrs, err);
1258 
1259 	if (asoc) {
1260 		/* sctp_primitive_ASSOCIATE may have added this association
1261 		 * To the hash table, try to unhash it, just in case, its a noop
1262 		 * if it wasn't hashed so we're safe
1263 		 */
1264 		sctp_unhash_established(asoc);
1265 		sctp_association_free(asoc);
1266 	}
1267 	return err;
1268 }
1269 
1270 /* Helper for tunneling sctp_connectx() requests through sctp_setsockopt()
1271  *
1272  * API 8.9
1273  * int sctp_connectx(int sd, struct sockaddr *addrs, int addrcnt,
1274  * 			sctp_assoc_t *asoc);
1275  *
1276  * If sd is an IPv4 socket, the addresses passed must be IPv4 addresses.
1277  * If the sd is an IPv6 socket, the addresses passed can either be IPv4
1278  * or IPv6 addresses.
1279  *
1280  * A single address may be specified as INADDR_ANY or IN6ADDR_ANY, see
1281  * Section 3.1.2 for this usage.
1282  *
1283  * addrs is a pointer to an array of one or more socket addresses. Each
1284  * address is contained in its appropriate structure (i.e. struct
1285  * sockaddr_in or struct sockaddr_in6) the family of the address type
1286  * must be used to distengish the address length (note that this
1287  * representation is termed a "packed array" of addresses). The caller
1288  * specifies the number of addresses in the array with addrcnt.
1289  *
1290  * On success, sctp_connectx() returns 0. It also sets the assoc_id to
1291  * the association id of the new association.  On failure, sctp_connectx()
1292  * returns -1, and sets errno to the appropriate error code.  The assoc_id
1293  * is not touched by the kernel.
1294  *
1295  * For SCTP, the port given in each socket address must be the same, or
1296  * sctp_connectx() will fail, setting errno to EINVAL.
1297  *
1298  * An application can use sctp_connectx to initiate an association with
1299  * an endpoint that is multi-homed.  Much like sctp_bindx() this call
1300  * allows a caller to specify multiple addresses at which a peer can be
1301  * reached.  The way the SCTP stack uses the list of addresses to set up
1302  * the association is implementation dependent.  This function only
1303  * specifies that the stack will try to make use of all the addresses in
1304  * the list when needed.
1305  *
1306  * Note that the list of addresses passed in is only used for setting up
1307  * the association.  It does not necessarily equal the set of addresses
1308  * the peer uses for the resulting association.  If the caller wants to
1309  * find out the set of peer addresses, it must use sctp_getpaddrs() to
1310  * retrieve them after the association has been set up.
1311  *
1312  * Basically do nothing but copying the addresses from user to kernel
1313  * land and invoking either sctp_connectx(). This is used for tunneling
1314  * the sctp_connectx() request through sctp_setsockopt() from userspace.
1315  *
1316  * We don't use copy_from_user() for optimization: we first do the
1317  * sanity checks (buffer size -fast- and access check-healthy
1318  * pointer); if all of those succeed, then we can alloc the memory
1319  * (expensive operation) needed to copy the data to kernel. Then we do
1320  * the copying without checking the user space area
1321  * (__copy_from_user()).
1322  *
1323  * On exit there is no need to do sockfd_put(), sys_setsockopt() does
1324  * it.
1325  *
1326  * sk        The sk of the socket
1327  * addrs     The pointer to the addresses in user land
1328  * addrssize Size of the addrs buffer
1329  *
1330  * Returns >=0 if ok, <0 errno code on error.
1331  */
__sctp_setsockopt_connectx(struct sock * sk,struct sockaddr __user * addrs,int addrs_size,sctp_assoc_t * assoc_id)1332 static int __sctp_setsockopt_connectx(struct sock *sk,
1333 				      struct sockaddr __user *addrs,
1334 				      int addrs_size,
1335 				      sctp_assoc_t *assoc_id)
1336 {
1337 	int err = 0;
1338 	struct sockaddr *kaddrs;
1339 
1340 	pr_debug("%s: sk:%p addrs:%p addrs_size:%d\n",
1341 		 __func__, sk, addrs, addrs_size);
1342 
1343 	if (unlikely(addrs_size <= 0))
1344 		return -EINVAL;
1345 
1346 	/* Check the user passed a healthy pointer.  */
1347 	if (unlikely(!access_ok(VERIFY_READ, addrs, addrs_size)))
1348 		return -EFAULT;
1349 
1350 	/* Alloc space for the address array in kernel memory.  */
1351 	kaddrs = kmalloc(addrs_size, GFP_KERNEL);
1352 	if (unlikely(!kaddrs))
1353 		return -ENOMEM;
1354 
1355 	if (__copy_from_user(kaddrs, addrs, addrs_size)) {
1356 		err = -EFAULT;
1357 	} else {
1358 		err = __sctp_connect(sk, kaddrs, addrs_size, assoc_id);
1359 	}
1360 
1361 	kfree(kaddrs);
1362 
1363 	return err;
1364 }
1365 
1366 /*
1367  * This is an older interface.  It's kept for backward compatibility
1368  * to the option that doesn't provide association id.
1369  */
sctp_setsockopt_connectx_old(struct sock * sk,struct sockaddr __user * addrs,int addrs_size)1370 static int sctp_setsockopt_connectx_old(struct sock *sk,
1371 					struct sockaddr __user *addrs,
1372 					int addrs_size)
1373 {
1374 	return __sctp_setsockopt_connectx(sk, addrs, addrs_size, NULL);
1375 }
1376 
1377 /*
1378  * New interface for the API.  The since the API is done with a socket
1379  * option, to make it simple we feed back the association id is as a return
1380  * indication to the call.  Error is always negative and association id is
1381  * always positive.
1382  */
sctp_setsockopt_connectx(struct sock * sk,struct sockaddr __user * addrs,int addrs_size)1383 static int sctp_setsockopt_connectx(struct sock *sk,
1384 				    struct sockaddr __user *addrs,
1385 				    int addrs_size)
1386 {
1387 	sctp_assoc_t assoc_id = 0;
1388 	int err = 0;
1389 
1390 	err = __sctp_setsockopt_connectx(sk, addrs, addrs_size, &assoc_id);
1391 
1392 	if (err)
1393 		return err;
1394 	else
1395 		return assoc_id;
1396 }
1397 
1398 /*
1399  * New (hopefully final) interface for the API.
1400  * We use the sctp_getaddrs_old structure so that use-space library
1401  * can avoid any unnecessary allocations. The only different part
1402  * is that we store the actual length of the address buffer into the
1403  * addrs_num structure member. That way we can re-use the existing
1404  * code.
1405  */
1406 #ifdef CONFIG_COMPAT
1407 struct compat_sctp_getaddrs_old {
1408 	sctp_assoc_t	assoc_id;
1409 	s32		addr_num;
1410 	compat_uptr_t	addrs;		/* struct sockaddr * */
1411 };
1412 #endif
1413 
sctp_getsockopt_connectx3(struct sock * sk,int len,char __user * optval,int __user * optlen)1414 static int sctp_getsockopt_connectx3(struct sock *sk, int len,
1415 				     char __user *optval,
1416 				     int __user *optlen)
1417 {
1418 	struct sctp_getaddrs_old param;
1419 	sctp_assoc_t assoc_id = 0;
1420 	int err = 0;
1421 
1422 #ifdef CONFIG_COMPAT
1423 	if (is_compat_task()) {
1424 		struct compat_sctp_getaddrs_old param32;
1425 
1426 		if (len < sizeof(param32))
1427 			return -EINVAL;
1428 		if (copy_from_user(&param32, optval, sizeof(param32)))
1429 			return -EFAULT;
1430 
1431 		param.assoc_id = param32.assoc_id;
1432 		param.addr_num = param32.addr_num;
1433 		param.addrs = compat_ptr(param32.addrs);
1434 	} else
1435 #endif
1436 	{
1437 		if (len < sizeof(param))
1438 			return -EINVAL;
1439 		if (copy_from_user(&param, optval, sizeof(param)))
1440 			return -EFAULT;
1441 	}
1442 
1443 	err = __sctp_setsockopt_connectx(sk, (struct sockaddr __user *)
1444 					 param.addrs, param.addr_num,
1445 					 &assoc_id);
1446 	if (err == 0 || err == -EINPROGRESS) {
1447 		if (copy_to_user(optval, &assoc_id, sizeof(assoc_id)))
1448 			return -EFAULT;
1449 		if (put_user(sizeof(assoc_id), optlen))
1450 			return -EFAULT;
1451 	}
1452 
1453 	return err;
1454 }
1455 
1456 /* API 3.1.4 close() - UDP Style Syntax
1457  * Applications use close() to perform graceful shutdown (as described in
1458  * Section 10.1 of [SCTP]) on ALL the associations currently represented
1459  * by a UDP-style socket.
1460  *
1461  * The syntax is
1462  *
1463  *   ret = close(int sd);
1464  *
1465  *   sd      - the socket descriptor of the associations to be closed.
1466  *
1467  * To gracefully shutdown a specific association represented by the
1468  * UDP-style socket, an application should use the sendmsg() call,
1469  * passing no user data, but including the appropriate flag in the
1470  * ancillary data (see Section xxxx).
1471  *
1472  * If sd in the close() call is a branched-off socket representing only
1473  * one association, the shutdown is performed on that association only.
1474  *
1475  * 4.1.6 close() - TCP Style Syntax
1476  *
1477  * Applications use close() to gracefully close down an association.
1478  *
1479  * The syntax is:
1480  *
1481  *    int close(int sd);
1482  *
1483  *      sd      - the socket descriptor of the association to be closed.
1484  *
1485  * After an application calls close() on a socket descriptor, no further
1486  * socket operations will succeed on that descriptor.
1487  *
1488  * API 7.1.4 SO_LINGER
1489  *
1490  * An application using the TCP-style socket can use this option to
1491  * perform the SCTP ABORT primitive.  The linger option structure is:
1492  *
1493  *  struct  linger {
1494  *     int     l_onoff;                // option on/off
1495  *     int     l_linger;               // linger time
1496  * };
1497  *
1498  * To enable the option, set l_onoff to 1.  If the l_linger value is set
1499  * to 0, calling close() is the same as the ABORT primitive.  If the
1500  * value is set to a negative value, the setsockopt() call will return
1501  * an error.  If the value is set to a positive value linger_time, the
1502  * close() can be blocked for at most linger_time ms.  If the graceful
1503  * shutdown phase does not finish during this period, close() will
1504  * return but the graceful shutdown phase continues in the system.
1505  */
sctp_close(struct sock * sk,long timeout)1506 static void sctp_close(struct sock *sk, long timeout)
1507 {
1508 	struct net *net = sock_net(sk);
1509 	struct sctp_endpoint *ep;
1510 	struct sctp_association *asoc;
1511 	struct list_head *pos, *temp;
1512 	unsigned int data_was_unread;
1513 
1514 	pr_debug("%s: sk:%p, timeout:%ld\n", __func__, sk, timeout);
1515 
1516 	lock_sock(sk);
1517 	sk->sk_shutdown = SHUTDOWN_MASK;
1518 	sk->sk_state = SCTP_SS_CLOSING;
1519 
1520 	ep = sctp_sk(sk)->ep;
1521 
1522 	/* Clean up any skbs sitting on the receive queue.  */
1523 	data_was_unread = sctp_queue_purge_ulpevents(&sk->sk_receive_queue);
1524 	data_was_unread += sctp_queue_purge_ulpevents(&sctp_sk(sk)->pd_lobby);
1525 
1526 	/* Walk all associations on an endpoint.  */
1527 	list_for_each_safe(pos, temp, &ep->asocs) {
1528 		asoc = list_entry(pos, struct sctp_association, asocs);
1529 
1530 		if (sctp_style(sk, TCP)) {
1531 			/* A closed association can still be in the list if
1532 			 * it belongs to a TCP-style listening socket that is
1533 			 * not yet accepted. If so, free it. If not, send an
1534 			 * ABORT or SHUTDOWN based on the linger options.
1535 			 */
1536 			if (sctp_state(asoc, CLOSED)) {
1537 				sctp_unhash_established(asoc);
1538 				sctp_association_free(asoc);
1539 				continue;
1540 			}
1541 		}
1542 
1543 		if (data_was_unread || !skb_queue_empty(&asoc->ulpq.lobby) ||
1544 		    !skb_queue_empty(&asoc->ulpq.reasm) ||
1545 		    (sock_flag(sk, SOCK_LINGER) && !sk->sk_lingertime)) {
1546 			struct sctp_chunk *chunk;
1547 
1548 			chunk = sctp_make_abort_user(asoc, NULL, 0);
1549 			sctp_primitive_ABORT(net, asoc, chunk);
1550 		} else
1551 			sctp_primitive_SHUTDOWN(net, asoc, NULL);
1552 	}
1553 
1554 	/* On a TCP-style socket, block for at most linger_time if set. */
1555 	if (sctp_style(sk, TCP) && timeout)
1556 		sctp_wait_for_close(sk, timeout);
1557 
1558 	/* This will run the backlog queue.  */
1559 	release_sock(sk);
1560 
1561 	/* Supposedly, no process has access to the socket, but
1562 	 * the net layers still may.
1563 	 * Also, sctp_destroy_sock() needs to be called with addr_wq_lock
1564 	 * held and that should be grabbed before socket lock.
1565 	 */
1566 	spin_lock_bh(&net->sctp.addr_wq_lock);
1567 	bh_lock_sock(sk);
1568 
1569 	/* Hold the sock, since sk_common_release() will put sock_put()
1570 	 * and we have just a little more cleanup.
1571 	 */
1572 	sock_hold(sk);
1573 	sk_common_release(sk);
1574 
1575 	bh_unlock_sock(sk);
1576 	spin_unlock_bh(&net->sctp.addr_wq_lock);
1577 
1578 	sock_put(sk);
1579 
1580 	SCTP_DBG_OBJCNT_DEC(sock);
1581 }
1582 
1583 /* Handle EPIPE error. */
sctp_error(struct sock * sk,int flags,int err)1584 static int sctp_error(struct sock *sk, int flags, int err)
1585 {
1586 	if (err == -EPIPE)
1587 		err = sock_error(sk) ? : -EPIPE;
1588 	if (err == -EPIPE && !(flags & MSG_NOSIGNAL))
1589 		send_sig(SIGPIPE, current, 0);
1590 	return err;
1591 }
1592 
1593 /* API 3.1.3 sendmsg() - UDP Style Syntax
1594  *
1595  * An application uses sendmsg() and recvmsg() calls to transmit data to
1596  * and receive data from its peer.
1597  *
1598  *  ssize_t sendmsg(int socket, const struct msghdr *message,
1599  *                  int flags);
1600  *
1601  *  socket  - the socket descriptor of the endpoint.
1602  *  message - pointer to the msghdr structure which contains a single
1603  *            user message and possibly some ancillary data.
1604  *
1605  *            See Section 5 for complete description of the data
1606  *            structures.
1607  *
1608  *  flags   - flags sent or received with the user message, see Section
1609  *            5 for complete description of the flags.
1610  *
1611  * Note:  This function could use a rewrite especially when explicit
1612  * connect support comes in.
1613  */
1614 /* BUG:  We do not implement the equivalent of sk_stream_wait_memory(). */
1615 
1616 static int sctp_msghdr_parse(const struct msghdr *, sctp_cmsgs_t *);
1617 
sctp_sendmsg(struct kiocb * iocb,struct sock * sk,struct msghdr * msg,size_t msg_len)1618 static int sctp_sendmsg(struct kiocb *iocb, struct sock *sk,
1619 			struct msghdr *msg, size_t msg_len)
1620 {
1621 	struct net *net = sock_net(sk);
1622 	struct sctp_sock *sp;
1623 	struct sctp_endpoint *ep;
1624 	struct sctp_association *new_asoc = NULL, *asoc = NULL;
1625 	struct sctp_transport *transport, *chunk_tp;
1626 	struct sctp_chunk *chunk;
1627 	union sctp_addr to;
1628 	struct sockaddr *msg_name = NULL;
1629 	struct sctp_sndrcvinfo default_sinfo;
1630 	struct sctp_sndrcvinfo *sinfo;
1631 	struct sctp_initmsg *sinit;
1632 	sctp_assoc_t associd = 0;
1633 	sctp_cmsgs_t cmsgs = { NULL };
1634 	sctp_scope_t scope;
1635 	bool fill_sinfo_ttl = false, wait_connect = false;
1636 	struct sctp_datamsg *datamsg;
1637 	int msg_flags = msg->msg_flags;
1638 	__u16 sinfo_flags = 0;
1639 	long timeo;
1640 	int err;
1641 
1642 	err = 0;
1643 	sp = sctp_sk(sk);
1644 	ep = sp->ep;
1645 
1646 	pr_debug("%s: sk:%p, msg:%p, msg_len:%zu ep:%p\n", __func__, sk,
1647 		 msg, msg_len, ep);
1648 
1649 	/* We cannot send a message over a TCP-style listening socket. */
1650 	if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING)) {
1651 		err = -EPIPE;
1652 		goto out_nounlock;
1653 	}
1654 
1655 	/* Parse out the SCTP CMSGs.  */
1656 	err = sctp_msghdr_parse(msg, &cmsgs);
1657 	if (err) {
1658 		pr_debug("%s: msghdr parse err:%x\n", __func__, err);
1659 		goto out_nounlock;
1660 	}
1661 
1662 	/* Fetch the destination address for this packet.  This
1663 	 * address only selects the association--it is not necessarily
1664 	 * the address we will send to.
1665 	 * For a peeled-off socket, msg_name is ignored.
1666 	 */
1667 	if (!sctp_style(sk, UDP_HIGH_BANDWIDTH) && msg->msg_name) {
1668 		int msg_namelen = msg->msg_namelen;
1669 
1670 		err = sctp_verify_addr(sk, (union sctp_addr *)msg->msg_name,
1671 				       msg_namelen);
1672 		if (err)
1673 			return err;
1674 
1675 		if (msg_namelen > sizeof(to))
1676 			msg_namelen = sizeof(to);
1677 		memcpy(&to, msg->msg_name, msg_namelen);
1678 		msg_name = msg->msg_name;
1679 	}
1680 
1681 	sinit = cmsgs.init;
1682 	if (cmsgs.sinfo != NULL) {
1683 		memset(&default_sinfo, 0, sizeof(default_sinfo));
1684 		default_sinfo.sinfo_stream = cmsgs.sinfo->snd_sid;
1685 		default_sinfo.sinfo_flags = cmsgs.sinfo->snd_flags;
1686 		default_sinfo.sinfo_ppid = cmsgs.sinfo->snd_ppid;
1687 		default_sinfo.sinfo_context = cmsgs.sinfo->snd_context;
1688 		default_sinfo.sinfo_assoc_id = cmsgs.sinfo->snd_assoc_id;
1689 
1690 		sinfo = &default_sinfo;
1691 		fill_sinfo_ttl = true;
1692 	} else {
1693 		sinfo = cmsgs.srinfo;
1694 	}
1695 	/* Did the user specify SNDINFO/SNDRCVINFO? */
1696 	if (sinfo) {
1697 		sinfo_flags = sinfo->sinfo_flags;
1698 		associd = sinfo->sinfo_assoc_id;
1699 	}
1700 
1701 	pr_debug("%s: msg_len:%zu, sinfo_flags:0x%x\n", __func__,
1702 		 msg_len, sinfo_flags);
1703 
1704 	/* SCTP_EOF or SCTP_ABORT cannot be set on a TCP-style socket. */
1705 	if (sctp_style(sk, TCP) && (sinfo_flags & (SCTP_EOF | SCTP_ABORT))) {
1706 		err = -EINVAL;
1707 		goto out_nounlock;
1708 	}
1709 
1710 	/* If SCTP_EOF is set, no data can be sent. Disallow sending zero
1711 	 * length messages when SCTP_EOF|SCTP_ABORT is not set.
1712 	 * If SCTP_ABORT is set, the message length could be non zero with
1713 	 * the msg_iov set to the user abort reason.
1714 	 */
1715 	if (((sinfo_flags & SCTP_EOF) && (msg_len > 0)) ||
1716 	    (!(sinfo_flags & (SCTP_EOF|SCTP_ABORT)) && (msg_len == 0))) {
1717 		err = -EINVAL;
1718 		goto out_nounlock;
1719 	}
1720 
1721 	/* If SCTP_ADDR_OVER is set, there must be an address
1722 	 * specified in msg_name.
1723 	 */
1724 	if ((sinfo_flags & SCTP_ADDR_OVER) && (!msg->msg_name)) {
1725 		err = -EINVAL;
1726 		goto out_nounlock;
1727 	}
1728 
1729 	transport = NULL;
1730 
1731 	pr_debug("%s: about to look up association\n", __func__);
1732 
1733 	lock_sock(sk);
1734 
1735 	/* If a msg_name has been specified, assume this is to be used.  */
1736 	if (msg_name) {
1737 		/* Look for a matching association on the endpoint. */
1738 		asoc = sctp_endpoint_lookup_assoc(ep, &to, &transport);
1739 		if (!asoc) {
1740 			/* If we could not find a matching association on the
1741 			 * endpoint, make sure that it is not a TCP-style
1742 			 * socket that already has an association or there is
1743 			 * no peeled-off association on another socket.
1744 			 */
1745 			if ((sctp_style(sk, TCP) &&
1746 			     sctp_sstate(sk, ESTABLISHED)) ||
1747 			    sctp_endpoint_is_peeled_off(ep, &to)) {
1748 				err = -EADDRNOTAVAIL;
1749 				goto out_unlock;
1750 			}
1751 		}
1752 	} else {
1753 		asoc = sctp_id2assoc(sk, associd);
1754 		if (!asoc) {
1755 			err = -EPIPE;
1756 			goto out_unlock;
1757 		}
1758 	}
1759 
1760 	if (asoc) {
1761 		pr_debug("%s: just looked up association:%p\n", __func__, asoc);
1762 
1763 		/* We cannot send a message on a TCP-style SCTP_SS_ESTABLISHED
1764 		 * socket that has an association in CLOSED state. This can
1765 		 * happen when an accepted socket has an association that is
1766 		 * already CLOSED.
1767 		 */
1768 		if (sctp_state(asoc, CLOSED) && sctp_style(sk, TCP)) {
1769 			err = -EPIPE;
1770 			goto out_unlock;
1771 		}
1772 
1773 		if (sinfo_flags & SCTP_EOF) {
1774 			pr_debug("%s: shutting down association:%p\n",
1775 				 __func__, asoc);
1776 
1777 			sctp_primitive_SHUTDOWN(net, asoc, NULL);
1778 			err = 0;
1779 			goto out_unlock;
1780 		}
1781 		if (sinfo_flags & SCTP_ABORT) {
1782 
1783 			chunk = sctp_make_abort_user(asoc, msg, msg_len);
1784 			if (!chunk) {
1785 				err = -ENOMEM;
1786 				goto out_unlock;
1787 			}
1788 
1789 			pr_debug("%s: aborting association:%p\n",
1790 				 __func__, asoc);
1791 
1792 			sctp_primitive_ABORT(net, asoc, chunk);
1793 			err = 0;
1794 			goto out_unlock;
1795 		}
1796 	}
1797 
1798 	/* Do we need to create the association?  */
1799 	if (!asoc) {
1800 		pr_debug("%s: there is no association yet\n", __func__);
1801 
1802 		if (sinfo_flags & (SCTP_EOF | SCTP_ABORT)) {
1803 			err = -EINVAL;
1804 			goto out_unlock;
1805 		}
1806 
1807 		/* Check for invalid stream against the stream counts,
1808 		 * either the default or the user specified stream counts.
1809 		 */
1810 		if (sinfo) {
1811 			if (!sinit || !sinit->sinit_num_ostreams) {
1812 				/* Check against the defaults. */
1813 				if (sinfo->sinfo_stream >=
1814 				    sp->initmsg.sinit_num_ostreams) {
1815 					err = -EINVAL;
1816 					goto out_unlock;
1817 				}
1818 			} else {
1819 				/* Check against the requested.  */
1820 				if (sinfo->sinfo_stream >=
1821 				    sinit->sinit_num_ostreams) {
1822 					err = -EINVAL;
1823 					goto out_unlock;
1824 				}
1825 			}
1826 		}
1827 
1828 		/*
1829 		 * API 3.1.2 bind() - UDP Style Syntax
1830 		 * If a bind() or sctp_bindx() is not called prior to a
1831 		 * sendmsg() call that initiates a new association, the
1832 		 * system picks an ephemeral port and will choose an address
1833 		 * set equivalent to binding with a wildcard address.
1834 		 */
1835 		if (!ep->base.bind_addr.port) {
1836 			if (sctp_autobind(sk)) {
1837 				err = -EAGAIN;
1838 				goto out_unlock;
1839 			}
1840 		} else {
1841 			/*
1842 			 * If an unprivileged user inherits a one-to-many
1843 			 * style socket with open associations on a privileged
1844 			 * port, it MAY be permitted to accept new associations,
1845 			 * but it SHOULD NOT be permitted to open new
1846 			 * associations.
1847 			 */
1848 			if (ep->base.bind_addr.port < PROT_SOCK &&
1849 			    !ns_capable(net->user_ns, CAP_NET_BIND_SERVICE)) {
1850 				err = -EACCES;
1851 				goto out_unlock;
1852 			}
1853 		}
1854 
1855 		scope = sctp_scope(&to);
1856 		new_asoc = sctp_association_new(ep, sk, scope, GFP_KERNEL);
1857 		if (!new_asoc) {
1858 			err = -ENOMEM;
1859 			goto out_unlock;
1860 		}
1861 		asoc = new_asoc;
1862 		err = sctp_assoc_set_bind_addr_from_ep(asoc, scope, GFP_KERNEL);
1863 		if (err < 0) {
1864 			err = -ENOMEM;
1865 			goto out_free;
1866 		}
1867 
1868 		/* If the SCTP_INIT ancillary data is specified, set all
1869 		 * the association init values accordingly.
1870 		 */
1871 		if (sinit) {
1872 			if (sinit->sinit_num_ostreams) {
1873 				asoc->c.sinit_num_ostreams =
1874 					sinit->sinit_num_ostreams;
1875 			}
1876 			if (sinit->sinit_max_instreams) {
1877 				asoc->c.sinit_max_instreams =
1878 					sinit->sinit_max_instreams;
1879 			}
1880 			if (sinit->sinit_max_attempts) {
1881 				asoc->max_init_attempts
1882 					= sinit->sinit_max_attempts;
1883 			}
1884 			if (sinit->sinit_max_init_timeo) {
1885 				asoc->max_init_timeo =
1886 				 msecs_to_jiffies(sinit->sinit_max_init_timeo);
1887 			}
1888 		}
1889 
1890 		/* Prime the peer's transport structures.  */
1891 		transport = sctp_assoc_add_peer(asoc, &to, GFP_KERNEL, SCTP_UNKNOWN);
1892 		if (!transport) {
1893 			err = -ENOMEM;
1894 			goto out_free;
1895 		}
1896 	}
1897 
1898 	/* ASSERT: we have a valid association at this point.  */
1899 	pr_debug("%s: we have a valid association\n", __func__);
1900 
1901 	if (!sinfo) {
1902 		/* If the user didn't specify SNDINFO/SNDRCVINFO, make up
1903 		 * one with some defaults.
1904 		 */
1905 		memset(&default_sinfo, 0, sizeof(default_sinfo));
1906 		default_sinfo.sinfo_stream = asoc->default_stream;
1907 		default_sinfo.sinfo_flags = asoc->default_flags;
1908 		default_sinfo.sinfo_ppid = asoc->default_ppid;
1909 		default_sinfo.sinfo_context = asoc->default_context;
1910 		default_sinfo.sinfo_timetolive = asoc->default_timetolive;
1911 		default_sinfo.sinfo_assoc_id = sctp_assoc2id(asoc);
1912 
1913 		sinfo = &default_sinfo;
1914 	} else if (fill_sinfo_ttl) {
1915 		/* In case SNDINFO was specified, we still need to fill
1916 		 * it with a default ttl from the assoc here.
1917 		 */
1918 		sinfo->sinfo_timetolive = asoc->default_timetolive;
1919 	}
1920 
1921 	/* API 7.1.7, the sndbuf size per association bounds the
1922 	 * maximum size of data that can be sent in a single send call.
1923 	 */
1924 	if (msg_len > sk->sk_sndbuf) {
1925 		err = -EMSGSIZE;
1926 		goto out_free;
1927 	}
1928 
1929 	if (asoc->pmtu_pending)
1930 		sctp_assoc_pending_pmtu(sk, asoc);
1931 
1932 	/* If fragmentation is disabled and the message length exceeds the
1933 	 * association fragmentation point, return EMSGSIZE.  The I-D
1934 	 * does not specify what this error is, but this looks like
1935 	 * a great fit.
1936 	 */
1937 	if (sctp_sk(sk)->disable_fragments && (msg_len > asoc->frag_point)) {
1938 		err = -EMSGSIZE;
1939 		goto out_free;
1940 	}
1941 
1942 	/* Check for invalid stream. */
1943 	if (sinfo->sinfo_stream >= asoc->c.sinit_num_ostreams) {
1944 		err = -EINVAL;
1945 		goto out_free;
1946 	}
1947 
1948 	timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
1949 	if (!sctp_wspace(asoc)) {
1950 		/* sk can be changed by peel off when waiting for buf. */
1951 		err = sctp_wait_for_sndbuf(asoc, &timeo, msg_len);
1952 		if (err) {
1953 			if (err == -ESRCH) {
1954 				/* asoc is already dead. */
1955 				new_asoc = NULL;
1956 				err = -EPIPE;
1957 			}
1958 			goto out_free;
1959 		}
1960 	}
1961 
1962 	/* If an address is passed with the sendto/sendmsg call, it is used
1963 	 * to override the primary destination address in the TCP model, or
1964 	 * when SCTP_ADDR_OVER flag is set in the UDP model.
1965 	 */
1966 	if ((sctp_style(sk, TCP) && msg_name) ||
1967 	    (sinfo_flags & SCTP_ADDR_OVER)) {
1968 		chunk_tp = sctp_assoc_lookup_paddr(asoc, &to);
1969 		if (!chunk_tp) {
1970 			err = -EINVAL;
1971 			goto out_free;
1972 		}
1973 	} else
1974 		chunk_tp = NULL;
1975 
1976 	/* Auto-connect, if we aren't connected already. */
1977 	if (sctp_state(asoc, CLOSED)) {
1978 		err = sctp_primitive_ASSOCIATE(net, asoc, NULL);
1979 		if (err < 0)
1980 			goto out_free;
1981 
1982 		wait_connect = true;
1983 		pr_debug("%s: we associated primitively\n", __func__);
1984 	}
1985 
1986 	/* Break the message into multiple chunks of maximum size. */
1987 	datamsg = sctp_datamsg_from_user(asoc, sinfo, msg, msg_len);
1988 	if (IS_ERR(datamsg)) {
1989 		err = PTR_ERR(datamsg);
1990 		goto out_free;
1991 	}
1992 
1993 	/* Now send the (possibly) fragmented message. */
1994 	list_for_each_entry(chunk, &datamsg->chunks, frag_list) {
1995 		sctp_chunk_hold(chunk);
1996 
1997 		/* Do accounting for the write space.  */
1998 		sctp_set_owner_w(chunk);
1999 
2000 		chunk->transport = chunk_tp;
2001 	}
2002 
2003 	/* Send it to the lower layers.  Note:  all chunks
2004 	 * must either fail or succeed.   The lower layer
2005 	 * works that way today.  Keep it that way or this
2006 	 * breaks.
2007 	 */
2008 	err = sctp_primitive_SEND(net, asoc, datamsg);
2009 	/* Did the lower layer accept the chunk? */
2010 	if (err) {
2011 		sctp_datamsg_free(datamsg);
2012 		goto out_free;
2013 	}
2014 
2015 	pr_debug("%s: we sent primitively\n", __func__);
2016 
2017 	sctp_datamsg_put(datamsg);
2018 	err = msg_len;
2019 
2020 	if (unlikely(wait_connect)) {
2021 		timeo = sock_sndtimeo(sk, msg_flags & MSG_DONTWAIT);
2022 		sctp_wait_for_connect(asoc, &timeo);
2023 	}
2024 
2025 	/* If we are already past ASSOCIATE, the lower
2026 	 * layers are responsible for association cleanup.
2027 	 */
2028 	goto out_unlock;
2029 
2030 out_free:
2031 	if (new_asoc) {
2032 		sctp_unhash_established(asoc);
2033 		sctp_association_free(asoc);
2034 	}
2035 out_unlock:
2036 	release_sock(sk);
2037 
2038 out_nounlock:
2039 	return sctp_error(sk, msg_flags, err);
2040 
2041 #if 0
2042 do_sock_err:
2043 	if (msg_len)
2044 		err = msg_len;
2045 	else
2046 		err = sock_error(sk);
2047 	goto out;
2048 
2049 do_interrupted:
2050 	if (msg_len)
2051 		err = msg_len;
2052 	goto out;
2053 #endif /* 0 */
2054 }
2055 
2056 /* This is an extended version of skb_pull() that removes the data from the
2057  * start of a skb even when data is spread across the list of skb's in the
2058  * frag_list. len specifies the total amount of data that needs to be removed.
2059  * when 'len' bytes could be removed from the skb, it returns 0.
2060  * If 'len' exceeds the total skb length,  it returns the no. of bytes that
2061  * could not be removed.
2062  */
sctp_skb_pull(struct sk_buff * skb,int len)2063 static int sctp_skb_pull(struct sk_buff *skb, int len)
2064 {
2065 	struct sk_buff *list;
2066 	int skb_len = skb_headlen(skb);
2067 	int rlen;
2068 
2069 	if (len <= skb_len) {
2070 		__skb_pull(skb, len);
2071 		return 0;
2072 	}
2073 	len -= skb_len;
2074 	__skb_pull(skb, skb_len);
2075 
2076 	skb_walk_frags(skb, list) {
2077 		rlen = sctp_skb_pull(list, len);
2078 		skb->len -= (len-rlen);
2079 		skb->data_len -= (len-rlen);
2080 
2081 		if (!rlen)
2082 			return 0;
2083 
2084 		len = rlen;
2085 	}
2086 
2087 	return len;
2088 }
2089 
2090 /* API 3.1.3  recvmsg() - UDP Style Syntax
2091  *
2092  *  ssize_t recvmsg(int socket, struct msghdr *message,
2093  *                    int flags);
2094  *
2095  *  socket  - the socket descriptor of the endpoint.
2096  *  message - pointer to the msghdr structure which contains a single
2097  *            user message and possibly some ancillary data.
2098  *
2099  *            See Section 5 for complete description of the data
2100  *            structures.
2101  *
2102  *  flags   - flags sent or received with the user message, see Section
2103  *            5 for complete description of the flags.
2104  */
sctp_recvmsg(struct kiocb * iocb,struct sock * sk,struct msghdr * msg,size_t len,int noblock,int flags,int * addr_len)2105 static int sctp_recvmsg(struct kiocb *iocb, struct sock *sk,
2106 			struct msghdr *msg, size_t len, int noblock,
2107 			int flags, int *addr_len)
2108 {
2109 	struct sctp_ulpevent *event = NULL;
2110 	struct sctp_sock *sp = sctp_sk(sk);
2111 	struct sk_buff *skb;
2112 	int copied;
2113 	int err = 0;
2114 	int skb_len;
2115 
2116 	pr_debug("%s: sk:%p, msghdr:%p, len:%zd, noblock:%d, flags:0x%x, "
2117 		 "addr_len:%p)\n", __func__, sk, msg, len, noblock, flags,
2118 		 addr_len);
2119 
2120 	lock_sock(sk);
2121 
2122 	if (sctp_style(sk, TCP) && !sctp_sstate(sk, ESTABLISHED)) {
2123 		err = -ENOTCONN;
2124 		goto out;
2125 	}
2126 
2127 	skb = sctp_skb_recv_datagram(sk, flags, noblock, &err);
2128 	if (!skb)
2129 		goto out;
2130 
2131 	/* Get the total length of the skb including any skb's in the
2132 	 * frag_list.
2133 	 */
2134 	skb_len = skb->len;
2135 
2136 	copied = skb_len;
2137 	if (copied > len)
2138 		copied = len;
2139 
2140 	err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
2141 
2142 	event = sctp_skb2event(skb);
2143 
2144 	if (err)
2145 		goto out_free;
2146 
2147 	sock_recv_ts_and_drops(msg, sk, skb);
2148 	if (sctp_ulpevent_is_notification(event)) {
2149 		msg->msg_flags |= MSG_NOTIFICATION;
2150 		sp->pf->event_msgname(event, msg->msg_name, addr_len);
2151 	} else {
2152 		sp->pf->skb_msgname(skb, msg->msg_name, addr_len);
2153 	}
2154 
2155 	/* Check if we allow SCTP_NXTINFO. */
2156 	if (sp->recvnxtinfo)
2157 		sctp_ulpevent_read_nxtinfo(event, msg, sk);
2158 	/* Check if we allow SCTP_RCVINFO. */
2159 	if (sp->recvrcvinfo)
2160 		sctp_ulpevent_read_rcvinfo(event, msg);
2161 	/* Check if we allow SCTP_SNDRCVINFO. */
2162 	if (sp->subscribe.sctp_data_io_event)
2163 		sctp_ulpevent_read_sndrcvinfo(event, msg);
2164 
2165 #if 0
2166 	/* FIXME: we should be calling IP/IPv6 layers.  */
2167 	if (sk->sk_protinfo.af_inet.cmsg_flags)
2168 		ip_cmsg_recv(msg, skb);
2169 #endif
2170 
2171 	err = copied;
2172 
2173 	/* If skb's length exceeds the user's buffer, update the skb and
2174 	 * push it back to the receive_queue so that the next call to
2175 	 * recvmsg() will return the remaining data. Don't set MSG_EOR.
2176 	 */
2177 	if (skb_len > copied) {
2178 		msg->msg_flags &= ~MSG_EOR;
2179 		if (flags & MSG_PEEK)
2180 			goto out_free;
2181 		sctp_skb_pull(skb, copied);
2182 		skb_queue_head(&sk->sk_receive_queue, skb);
2183 
2184 		/* When only partial message is copied to the user, increase
2185 		 * rwnd by that amount. If all the data in the skb is read,
2186 		 * rwnd is updated when the event is freed.
2187 		 */
2188 		if (!sctp_ulpevent_is_notification(event))
2189 			sctp_assoc_rwnd_increase(event->asoc, copied);
2190 		goto out;
2191 	} else if ((event->msg_flags & MSG_NOTIFICATION) ||
2192 		   (event->msg_flags & MSG_EOR))
2193 		msg->msg_flags |= MSG_EOR;
2194 	else
2195 		msg->msg_flags &= ~MSG_EOR;
2196 
2197 out_free:
2198 	if (flags & MSG_PEEK) {
2199 		/* Release the skb reference acquired after peeking the skb in
2200 		 * sctp_skb_recv_datagram().
2201 		 */
2202 		kfree_skb(skb);
2203 	} else {
2204 		/* Free the event which includes releasing the reference to
2205 		 * the owner of the skb, freeing the skb and updating the
2206 		 * rwnd.
2207 		 */
2208 		sctp_ulpevent_free(event);
2209 	}
2210 out:
2211 	release_sock(sk);
2212 	return err;
2213 }
2214 
2215 /* 7.1.12 Enable/Disable message fragmentation (SCTP_DISABLE_FRAGMENTS)
2216  *
2217  * This option is a on/off flag.  If enabled no SCTP message
2218  * fragmentation will be performed.  Instead if a message being sent
2219  * exceeds the current PMTU size, the message will NOT be sent and
2220  * instead a error will be indicated to the user.
2221  */
sctp_setsockopt_disable_fragments(struct sock * sk,char __user * optval,unsigned int optlen)2222 static int sctp_setsockopt_disable_fragments(struct sock *sk,
2223 					     char __user *optval,
2224 					     unsigned int optlen)
2225 {
2226 	int val;
2227 
2228 	if (optlen < sizeof(int))
2229 		return -EINVAL;
2230 
2231 	if (get_user(val, (int __user *)optval))
2232 		return -EFAULT;
2233 
2234 	sctp_sk(sk)->disable_fragments = (val == 0) ? 0 : 1;
2235 
2236 	return 0;
2237 }
2238 
sctp_setsockopt_events(struct sock * sk,char __user * optval,unsigned int optlen)2239 static int sctp_setsockopt_events(struct sock *sk, char __user *optval,
2240 				  unsigned int optlen)
2241 {
2242 	struct sctp_association *asoc;
2243 	struct sctp_ulpevent *event;
2244 
2245 	if (optlen > sizeof(struct sctp_event_subscribe))
2246 		return -EINVAL;
2247 	if (copy_from_user(&sctp_sk(sk)->subscribe, optval, optlen))
2248 		return -EFAULT;
2249 
2250 	if (sctp_sk(sk)->subscribe.sctp_data_io_event)
2251 		pr_warn_ratelimited(DEPRECATED "%s (pid %d) "
2252 				    "Requested SCTP_SNDRCVINFO event.\n"
2253 				    "Use SCTP_RCVINFO through SCTP_RECVRCVINFO option instead.\n",
2254 				    current->comm, task_pid_nr(current));
2255 
2256 	/* At the time when a user app subscribes to SCTP_SENDER_DRY_EVENT,
2257 	 * if there is no data to be sent or retransmit, the stack will
2258 	 * immediately send up this notification.
2259 	 */
2260 	if (sctp_ulpevent_type_enabled(SCTP_SENDER_DRY_EVENT,
2261 				       &sctp_sk(sk)->subscribe)) {
2262 		asoc = sctp_id2assoc(sk, 0);
2263 
2264 		if (asoc && sctp_outq_is_empty(&asoc->outqueue)) {
2265 			event = sctp_ulpevent_make_sender_dry_event(asoc,
2266 					GFP_ATOMIC);
2267 			if (!event)
2268 				return -ENOMEM;
2269 
2270 			sctp_ulpq_tail_event(&asoc->ulpq, event);
2271 		}
2272 	}
2273 
2274 	return 0;
2275 }
2276 
2277 /* 7.1.8 Automatic Close of associations (SCTP_AUTOCLOSE)
2278  *
2279  * This socket option is applicable to the UDP-style socket only.  When
2280  * set it will cause associations that are idle for more than the
2281  * specified number of seconds to automatically close.  An association
2282  * being idle is defined an association that has NOT sent or received
2283  * user data.  The special value of '0' indicates that no automatic
2284  * close of any associations should be performed.  The option expects an
2285  * integer defining the number of seconds of idle time before an
2286  * association is closed.
2287  */
sctp_setsockopt_autoclose(struct sock * sk,char __user * optval,unsigned int optlen)2288 static int sctp_setsockopt_autoclose(struct sock *sk, char __user *optval,
2289 				     unsigned int optlen)
2290 {
2291 	struct sctp_sock *sp = sctp_sk(sk);
2292 	struct net *net = sock_net(sk);
2293 
2294 	/* Applicable to UDP-style socket only */
2295 	if (sctp_style(sk, TCP))
2296 		return -EOPNOTSUPP;
2297 	if (optlen != sizeof(int))
2298 		return -EINVAL;
2299 	if (copy_from_user(&sp->autoclose, optval, optlen))
2300 		return -EFAULT;
2301 
2302 	if (sp->autoclose > net->sctp.max_autoclose)
2303 		sp->autoclose = net->sctp.max_autoclose;
2304 
2305 	return 0;
2306 }
2307 
2308 /* 7.1.13 Peer Address Parameters (SCTP_PEER_ADDR_PARAMS)
2309  *
2310  * Applications can enable or disable heartbeats for any peer address of
2311  * an association, modify an address's heartbeat interval, force a
2312  * heartbeat to be sent immediately, and adjust the address's maximum
2313  * number of retransmissions sent before an address is considered
2314  * unreachable.  The following structure is used to access and modify an
2315  * address's parameters:
2316  *
2317  *  struct sctp_paddrparams {
2318  *     sctp_assoc_t            spp_assoc_id;
2319  *     struct sockaddr_storage spp_address;
2320  *     uint32_t                spp_hbinterval;
2321  *     uint16_t                spp_pathmaxrxt;
2322  *     uint32_t                spp_pathmtu;
2323  *     uint32_t                spp_sackdelay;
2324  *     uint32_t                spp_flags;
2325  * };
2326  *
2327  *   spp_assoc_id    - (one-to-many style socket) This is filled in the
2328  *                     application, and identifies the association for
2329  *                     this query.
2330  *   spp_address     - This specifies which address is of interest.
2331  *   spp_hbinterval  - This contains the value of the heartbeat interval,
2332  *                     in milliseconds.  If a  value of zero
2333  *                     is present in this field then no changes are to
2334  *                     be made to this parameter.
2335  *   spp_pathmaxrxt  - This contains the maximum number of
2336  *                     retransmissions before this address shall be
2337  *                     considered unreachable. If a  value of zero
2338  *                     is present in this field then no changes are to
2339  *                     be made to this parameter.
2340  *   spp_pathmtu     - When Path MTU discovery is disabled the value
2341  *                     specified here will be the "fixed" path mtu.
2342  *                     Note that if the spp_address field is empty
2343  *                     then all associations on this address will
2344  *                     have this fixed path mtu set upon them.
2345  *
2346  *   spp_sackdelay   - When delayed sack is enabled, this value specifies
2347  *                     the number of milliseconds that sacks will be delayed
2348  *                     for. This value will apply to all addresses of an
2349  *                     association if the spp_address field is empty. Note
2350  *                     also, that if delayed sack is enabled and this
2351  *                     value is set to 0, no change is made to the last
2352  *                     recorded delayed sack timer value.
2353  *
2354  *   spp_flags       - These flags are used to control various features
2355  *                     on an association. The flag field may contain
2356  *                     zero or more of the following options.
2357  *
2358  *                     SPP_HB_ENABLE  - Enable heartbeats on the
2359  *                     specified address. Note that if the address
2360  *                     field is empty all addresses for the association
2361  *                     have heartbeats enabled upon them.
2362  *
2363  *                     SPP_HB_DISABLE - Disable heartbeats on the
2364  *                     speicifed address. Note that if the address
2365  *                     field is empty all addresses for the association
2366  *                     will have their heartbeats disabled. Note also
2367  *                     that SPP_HB_ENABLE and SPP_HB_DISABLE are
2368  *                     mutually exclusive, only one of these two should
2369  *                     be specified. Enabling both fields will have
2370  *                     undetermined results.
2371  *
2372  *                     SPP_HB_DEMAND - Request a user initiated heartbeat
2373  *                     to be made immediately.
2374  *
2375  *                     SPP_HB_TIME_IS_ZERO - Specify's that the time for
2376  *                     heartbeat delayis to be set to the value of 0
2377  *                     milliseconds.
2378  *
2379  *                     SPP_PMTUD_ENABLE - This field will enable PMTU
2380  *                     discovery upon the specified address. Note that
2381  *                     if the address feild is empty then all addresses
2382  *                     on the association are effected.
2383  *
2384  *                     SPP_PMTUD_DISABLE - This field will disable PMTU
2385  *                     discovery upon the specified address. Note that
2386  *                     if the address feild is empty then all addresses
2387  *                     on the association are effected. Not also that
2388  *                     SPP_PMTUD_ENABLE and SPP_PMTUD_DISABLE are mutually
2389  *                     exclusive. Enabling both will have undetermined
2390  *                     results.
2391  *
2392  *                     SPP_SACKDELAY_ENABLE - Setting this flag turns
2393  *                     on delayed sack. The time specified in spp_sackdelay
2394  *                     is used to specify the sack delay for this address. Note
2395  *                     that if spp_address is empty then all addresses will
2396  *                     enable delayed sack and take on the sack delay
2397  *                     value specified in spp_sackdelay.
2398  *                     SPP_SACKDELAY_DISABLE - Setting this flag turns
2399  *                     off delayed sack. If the spp_address field is blank then
2400  *                     delayed sack is disabled for the entire association. Note
2401  *                     also that this field is mutually exclusive to
2402  *                     SPP_SACKDELAY_ENABLE, setting both will have undefined
2403  *                     results.
2404  */
sctp_apply_peer_addr_params(struct sctp_paddrparams * params,struct sctp_transport * trans,struct sctp_association * asoc,struct sctp_sock * sp,int hb_change,int pmtud_change,int sackdelay_change)2405 static int sctp_apply_peer_addr_params(struct sctp_paddrparams *params,
2406 				       struct sctp_transport   *trans,
2407 				       struct sctp_association *asoc,
2408 				       struct sctp_sock        *sp,
2409 				       int                      hb_change,
2410 				       int                      pmtud_change,
2411 				       int                      sackdelay_change)
2412 {
2413 	int error;
2414 
2415 	if (params->spp_flags & SPP_HB_DEMAND && trans) {
2416 		struct net *net = sock_net(trans->asoc->base.sk);
2417 
2418 		error = sctp_primitive_REQUESTHEARTBEAT(net, trans->asoc, trans);
2419 		if (error)
2420 			return error;
2421 	}
2422 
2423 	/* Note that unless the spp_flag is set to SPP_HB_ENABLE the value of
2424 	 * this field is ignored.  Note also that a value of zero indicates
2425 	 * the current setting should be left unchanged.
2426 	 */
2427 	if (params->spp_flags & SPP_HB_ENABLE) {
2428 
2429 		/* Re-zero the interval if the SPP_HB_TIME_IS_ZERO is
2430 		 * set.  This lets us use 0 value when this flag
2431 		 * is set.
2432 		 */
2433 		if (params->spp_flags & SPP_HB_TIME_IS_ZERO)
2434 			params->spp_hbinterval = 0;
2435 
2436 		if (params->spp_hbinterval ||
2437 		    (params->spp_flags & SPP_HB_TIME_IS_ZERO)) {
2438 			if (trans) {
2439 				trans->hbinterval =
2440 				    msecs_to_jiffies(params->spp_hbinterval);
2441 			} else if (asoc) {
2442 				asoc->hbinterval =
2443 				    msecs_to_jiffies(params->spp_hbinterval);
2444 			} else {
2445 				sp->hbinterval = params->spp_hbinterval;
2446 			}
2447 		}
2448 	}
2449 
2450 	if (hb_change) {
2451 		if (trans) {
2452 			trans->param_flags =
2453 				(trans->param_flags & ~SPP_HB) | hb_change;
2454 		} else if (asoc) {
2455 			asoc->param_flags =
2456 				(asoc->param_flags & ~SPP_HB) | hb_change;
2457 		} else {
2458 			sp->param_flags =
2459 				(sp->param_flags & ~SPP_HB) | hb_change;
2460 		}
2461 	}
2462 
2463 	/* When Path MTU discovery is disabled the value specified here will
2464 	 * be the "fixed" path mtu (i.e. the value of the spp_flags field must
2465 	 * include the flag SPP_PMTUD_DISABLE for this field to have any
2466 	 * effect).
2467 	 */
2468 	if ((params->spp_flags & SPP_PMTUD_DISABLE) && params->spp_pathmtu) {
2469 		if (trans) {
2470 			trans->pathmtu = params->spp_pathmtu;
2471 			sctp_assoc_sync_pmtu(sctp_opt2sk(sp), asoc);
2472 		} else if (asoc) {
2473 			asoc->pathmtu = params->spp_pathmtu;
2474 			sctp_frag_point(asoc, params->spp_pathmtu);
2475 		} else {
2476 			sp->pathmtu = params->spp_pathmtu;
2477 		}
2478 	}
2479 
2480 	if (pmtud_change) {
2481 		if (trans) {
2482 			int update = (trans->param_flags & SPP_PMTUD_DISABLE) &&
2483 				(params->spp_flags & SPP_PMTUD_ENABLE);
2484 			trans->param_flags =
2485 				(trans->param_flags & ~SPP_PMTUD) | pmtud_change;
2486 			if (update) {
2487 				sctp_transport_pmtu(trans, sctp_opt2sk(sp));
2488 				sctp_assoc_sync_pmtu(sctp_opt2sk(sp), asoc);
2489 			}
2490 		} else if (asoc) {
2491 			asoc->param_flags =
2492 				(asoc->param_flags & ~SPP_PMTUD) | pmtud_change;
2493 		} else {
2494 			sp->param_flags =
2495 				(sp->param_flags & ~SPP_PMTUD) | pmtud_change;
2496 		}
2497 	}
2498 
2499 	/* Note that unless the spp_flag is set to SPP_SACKDELAY_ENABLE the
2500 	 * value of this field is ignored.  Note also that a value of zero
2501 	 * indicates the current setting should be left unchanged.
2502 	 */
2503 	if ((params->spp_flags & SPP_SACKDELAY_ENABLE) && params->spp_sackdelay) {
2504 		if (trans) {
2505 			trans->sackdelay =
2506 				msecs_to_jiffies(params->spp_sackdelay);
2507 		} else if (asoc) {
2508 			asoc->sackdelay =
2509 				msecs_to_jiffies(params->spp_sackdelay);
2510 		} else {
2511 			sp->sackdelay = params->spp_sackdelay;
2512 		}
2513 	}
2514 
2515 	if (sackdelay_change) {
2516 		if (trans) {
2517 			trans->param_flags =
2518 				(trans->param_flags & ~SPP_SACKDELAY) |
2519 				sackdelay_change;
2520 		} else if (asoc) {
2521 			asoc->param_flags =
2522 				(asoc->param_flags & ~SPP_SACKDELAY) |
2523 				sackdelay_change;
2524 		} else {
2525 			sp->param_flags =
2526 				(sp->param_flags & ~SPP_SACKDELAY) |
2527 				sackdelay_change;
2528 		}
2529 	}
2530 
2531 	/* Note that a value of zero indicates the current setting should be
2532 	   left unchanged.
2533 	 */
2534 	if (params->spp_pathmaxrxt) {
2535 		if (trans) {
2536 			trans->pathmaxrxt = params->spp_pathmaxrxt;
2537 		} else if (asoc) {
2538 			asoc->pathmaxrxt = params->spp_pathmaxrxt;
2539 		} else {
2540 			sp->pathmaxrxt = params->spp_pathmaxrxt;
2541 		}
2542 	}
2543 
2544 	return 0;
2545 }
2546 
sctp_setsockopt_peer_addr_params(struct sock * sk,char __user * optval,unsigned int optlen)2547 static int sctp_setsockopt_peer_addr_params(struct sock *sk,
2548 					    char __user *optval,
2549 					    unsigned int optlen)
2550 {
2551 	struct sctp_paddrparams  params;
2552 	struct sctp_transport   *trans = NULL;
2553 	struct sctp_association *asoc = NULL;
2554 	struct sctp_sock        *sp = sctp_sk(sk);
2555 	int error;
2556 	int hb_change, pmtud_change, sackdelay_change;
2557 
2558 	if (optlen != sizeof(struct sctp_paddrparams))
2559 		return -EINVAL;
2560 
2561 	if (copy_from_user(&params, optval, optlen))
2562 		return -EFAULT;
2563 
2564 	/* Validate flags and value parameters. */
2565 	hb_change        = params.spp_flags & SPP_HB;
2566 	pmtud_change     = params.spp_flags & SPP_PMTUD;
2567 	sackdelay_change = params.spp_flags & SPP_SACKDELAY;
2568 
2569 	if (hb_change        == SPP_HB ||
2570 	    pmtud_change     == SPP_PMTUD ||
2571 	    sackdelay_change == SPP_SACKDELAY ||
2572 	    params.spp_sackdelay > 500 ||
2573 	    (params.spp_pathmtu &&
2574 	     params.spp_pathmtu < SCTP_DEFAULT_MINSEGMENT))
2575 		return -EINVAL;
2576 
2577 	/* If an address other than INADDR_ANY is specified, and
2578 	 * no transport is found, then the request is invalid.
2579 	 */
2580 	if (!sctp_is_any(sk, (union sctp_addr *)&params.spp_address)) {
2581 		trans = sctp_addr_id2transport(sk, &params.spp_address,
2582 					       params.spp_assoc_id);
2583 		if (!trans)
2584 			return -EINVAL;
2585 	}
2586 
2587 	/* Get association, if assoc_id != 0 and the socket is a one
2588 	 * to many style socket, and an association was not found, then
2589 	 * the id was invalid.
2590 	 */
2591 	asoc = sctp_id2assoc(sk, params.spp_assoc_id);
2592 	if (!asoc && params.spp_assoc_id && sctp_style(sk, UDP))
2593 		return -EINVAL;
2594 
2595 	/* Heartbeat demand can only be sent on a transport or
2596 	 * association, but not a socket.
2597 	 */
2598 	if (params.spp_flags & SPP_HB_DEMAND && !trans && !asoc)
2599 		return -EINVAL;
2600 
2601 	/* Process parameters. */
2602 	error = sctp_apply_peer_addr_params(&params, trans, asoc, sp,
2603 					    hb_change, pmtud_change,
2604 					    sackdelay_change);
2605 
2606 	if (error)
2607 		return error;
2608 
2609 	/* If changes are for association, also apply parameters to each
2610 	 * transport.
2611 	 */
2612 	if (!trans && asoc) {
2613 		list_for_each_entry(trans, &asoc->peer.transport_addr_list,
2614 				transports) {
2615 			sctp_apply_peer_addr_params(&params, trans, asoc, sp,
2616 						    hb_change, pmtud_change,
2617 						    sackdelay_change);
2618 		}
2619 	}
2620 
2621 	return 0;
2622 }
2623 
sctp_spp_sackdelay_enable(__u32 param_flags)2624 static inline __u32 sctp_spp_sackdelay_enable(__u32 param_flags)
2625 {
2626 	return (param_flags & ~SPP_SACKDELAY) | SPP_SACKDELAY_ENABLE;
2627 }
2628 
sctp_spp_sackdelay_disable(__u32 param_flags)2629 static inline __u32 sctp_spp_sackdelay_disable(__u32 param_flags)
2630 {
2631 	return (param_flags & ~SPP_SACKDELAY) | SPP_SACKDELAY_DISABLE;
2632 }
2633 
2634 /*
2635  * 7.1.23.  Get or set delayed ack timer (SCTP_DELAYED_SACK)
2636  *
2637  * This option will effect the way delayed acks are performed.  This
2638  * option allows you to get or set the delayed ack time, in
2639  * milliseconds.  It also allows changing the delayed ack frequency.
2640  * Changing the frequency to 1 disables the delayed sack algorithm.  If
2641  * the assoc_id is 0, then this sets or gets the endpoints default
2642  * values.  If the assoc_id field is non-zero, then the set or get
2643  * effects the specified association for the one to many model (the
2644  * assoc_id field is ignored by the one to one model).  Note that if
2645  * sack_delay or sack_freq are 0 when setting this option, then the
2646  * current values will remain unchanged.
2647  *
2648  * struct sctp_sack_info {
2649  *     sctp_assoc_t            sack_assoc_id;
2650  *     uint32_t                sack_delay;
2651  *     uint32_t                sack_freq;
2652  * };
2653  *
2654  * sack_assoc_id -  This parameter, indicates which association the user
2655  *    is performing an action upon.  Note that if this field's value is
2656  *    zero then the endpoints default value is changed (effecting future
2657  *    associations only).
2658  *
2659  * sack_delay -  This parameter contains the number of milliseconds that
2660  *    the user is requesting the delayed ACK timer be set to.  Note that
2661  *    this value is defined in the standard to be between 200 and 500
2662  *    milliseconds.
2663  *
2664  * sack_freq -  This parameter contains the number of packets that must
2665  *    be received before a sack is sent without waiting for the delay
2666  *    timer to expire.  The default value for this is 2, setting this
2667  *    value to 1 will disable the delayed sack algorithm.
2668  */
2669 
sctp_setsockopt_delayed_ack(struct sock * sk,char __user * optval,unsigned int optlen)2670 static int sctp_setsockopt_delayed_ack(struct sock *sk,
2671 				       char __user *optval, unsigned int optlen)
2672 {
2673 	struct sctp_sack_info    params;
2674 	struct sctp_transport   *trans = NULL;
2675 	struct sctp_association *asoc = NULL;
2676 	struct sctp_sock        *sp = sctp_sk(sk);
2677 
2678 	if (optlen == sizeof(struct sctp_sack_info)) {
2679 		if (copy_from_user(&params, optval, optlen))
2680 			return -EFAULT;
2681 
2682 		if (params.sack_delay == 0 && params.sack_freq == 0)
2683 			return 0;
2684 	} else if (optlen == sizeof(struct sctp_assoc_value)) {
2685 		pr_warn_ratelimited(DEPRECATED
2686 				    "%s (pid %d) "
2687 				    "Use of struct sctp_assoc_value in delayed_ack socket option.\n"
2688 				    "Use struct sctp_sack_info instead\n",
2689 				    current->comm, task_pid_nr(current));
2690 		if (copy_from_user(&params, optval, optlen))
2691 			return -EFAULT;
2692 
2693 		if (params.sack_delay == 0)
2694 			params.sack_freq = 1;
2695 		else
2696 			params.sack_freq = 0;
2697 	} else
2698 		return -EINVAL;
2699 
2700 	/* Validate value parameter. */
2701 	if (params.sack_delay > 500)
2702 		return -EINVAL;
2703 
2704 	/* Get association, if sack_assoc_id != 0 and the socket is a one
2705 	 * to many style socket, and an association was not found, then
2706 	 * the id was invalid.
2707 	 */
2708 	asoc = sctp_id2assoc(sk, params.sack_assoc_id);
2709 	if (!asoc && params.sack_assoc_id && sctp_style(sk, UDP))
2710 		return -EINVAL;
2711 
2712 	if (params.sack_delay) {
2713 		if (asoc) {
2714 			asoc->sackdelay =
2715 				msecs_to_jiffies(params.sack_delay);
2716 			asoc->param_flags =
2717 				sctp_spp_sackdelay_enable(asoc->param_flags);
2718 		} else {
2719 			sp->sackdelay = params.sack_delay;
2720 			sp->param_flags =
2721 				sctp_spp_sackdelay_enable(sp->param_flags);
2722 		}
2723 	}
2724 
2725 	if (params.sack_freq == 1) {
2726 		if (asoc) {
2727 			asoc->param_flags =
2728 				sctp_spp_sackdelay_disable(asoc->param_flags);
2729 		} else {
2730 			sp->param_flags =
2731 				sctp_spp_sackdelay_disable(sp->param_flags);
2732 		}
2733 	} else if (params.sack_freq > 1) {
2734 		if (asoc) {
2735 			asoc->sackfreq = params.sack_freq;
2736 			asoc->param_flags =
2737 				sctp_spp_sackdelay_enable(asoc->param_flags);
2738 		} else {
2739 			sp->sackfreq = params.sack_freq;
2740 			sp->param_flags =
2741 				sctp_spp_sackdelay_enable(sp->param_flags);
2742 		}
2743 	}
2744 
2745 	/* If change is for association, also apply to each transport. */
2746 	if (asoc) {
2747 		list_for_each_entry(trans, &asoc->peer.transport_addr_list,
2748 				transports) {
2749 			if (params.sack_delay) {
2750 				trans->sackdelay =
2751 					msecs_to_jiffies(params.sack_delay);
2752 				trans->param_flags =
2753 					sctp_spp_sackdelay_enable(trans->param_flags);
2754 			}
2755 			if (params.sack_freq == 1) {
2756 				trans->param_flags =
2757 					sctp_spp_sackdelay_disable(trans->param_flags);
2758 			} else if (params.sack_freq > 1) {
2759 				trans->sackfreq = params.sack_freq;
2760 				trans->param_flags =
2761 					sctp_spp_sackdelay_enable(trans->param_flags);
2762 			}
2763 		}
2764 	}
2765 
2766 	return 0;
2767 }
2768 
2769 /* 7.1.3 Initialization Parameters (SCTP_INITMSG)
2770  *
2771  * Applications can specify protocol parameters for the default association
2772  * initialization.  The option name argument to setsockopt() and getsockopt()
2773  * is SCTP_INITMSG.
2774  *
2775  * Setting initialization parameters is effective only on an unconnected
2776  * socket (for UDP-style sockets only future associations are effected
2777  * by the change).  With TCP-style sockets, this option is inherited by
2778  * sockets derived from a listener socket.
2779  */
sctp_setsockopt_initmsg(struct sock * sk,char __user * optval,unsigned int optlen)2780 static int sctp_setsockopt_initmsg(struct sock *sk, char __user *optval, unsigned int optlen)
2781 {
2782 	struct sctp_initmsg sinit;
2783 	struct sctp_sock *sp = sctp_sk(sk);
2784 
2785 	if (optlen != sizeof(struct sctp_initmsg))
2786 		return -EINVAL;
2787 	if (copy_from_user(&sinit, optval, optlen))
2788 		return -EFAULT;
2789 
2790 	if (sinit.sinit_num_ostreams)
2791 		sp->initmsg.sinit_num_ostreams = sinit.sinit_num_ostreams;
2792 	if (sinit.sinit_max_instreams)
2793 		sp->initmsg.sinit_max_instreams = sinit.sinit_max_instreams;
2794 	if (sinit.sinit_max_attempts)
2795 		sp->initmsg.sinit_max_attempts = sinit.sinit_max_attempts;
2796 	if (sinit.sinit_max_init_timeo)
2797 		sp->initmsg.sinit_max_init_timeo = sinit.sinit_max_init_timeo;
2798 
2799 	return 0;
2800 }
2801 
2802 /*
2803  * 7.1.14 Set default send parameters (SCTP_DEFAULT_SEND_PARAM)
2804  *
2805  *   Applications that wish to use the sendto() system call may wish to
2806  *   specify a default set of parameters that would normally be supplied
2807  *   through the inclusion of ancillary data.  This socket option allows
2808  *   such an application to set the default sctp_sndrcvinfo structure.
2809  *   The application that wishes to use this socket option simply passes
2810  *   in to this call the sctp_sndrcvinfo structure defined in Section
2811  *   5.2.2) The input parameters accepted by this call include
2812  *   sinfo_stream, sinfo_flags, sinfo_ppid, sinfo_context,
2813  *   sinfo_timetolive.  The user must provide the sinfo_assoc_id field in
2814  *   to this call if the caller is using the UDP model.
2815  */
sctp_setsockopt_default_send_param(struct sock * sk,char __user * optval,unsigned int optlen)2816 static int sctp_setsockopt_default_send_param(struct sock *sk,
2817 					      char __user *optval,
2818 					      unsigned int optlen)
2819 {
2820 	struct sctp_sock *sp = sctp_sk(sk);
2821 	struct sctp_association *asoc;
2822 	struct sctp_sndrcvinfo info;
2823 
2824 	if (optlen != sizeof(info))
2825 		return -EINVAL;
2826 	if (copy_from_user(&info, optval, optlen))
2827 		return -EFAULT;
2828 	if (info.sinfo_flags &
2829 	    ~(SCTP_UNORDERED | SCTP_ADDR_OVER |
2830 	      SCTP_ABORT | SCTP_EOF))
2831 		return -EINVAL;
2832 
2833 	asoc = sctp_id2assoc(sk, info.sinfo_assoc_id);
2834 	if (!asoc && info.sinfo_assoc_id && sctp_style(sk, UDP))
2835 		return -EINVAL;
2836 	if (asoc) {
2837 		asoc->default_stream = info.sinfo_stream;
2838 		asoc->default_flags = info.sinfo_flags;
2839 		asoc->default_ppid = info.sinfo_ppid;
2840 		asoc->default_context = info.sinfo_context;
2841 		asoc->default_timetolive = info.sinfo_timetolive;
2842 	} else {
2843 		sp->default_stream = info.sinfo_stream;
2844 		sp->default_flags = info.sinfo_flags;
2845 		sp->default_ppid = info.sinfo_ppid;
2846 		sp->default_context = info.sinfo_context;
2847 		sp->default_timetolive = info.sinfo_timetolive;
2848 	}
2849 
2850 	return 0;
2851 }
2852 
2853 /* RFC6458, Section 8.1.31. Set/get Default Send Parameters
2854  * (SCTP_DEFAULT_SNDINFO)
2855  */
sctp_setsockopt_default_sndinfo(struct sock * sk,char __user * optval,unsigned int optlen)2856 static int sctp_setsockopt_default_sndinfo(struct sock *sk,
2857 					   char __user *optval,
2858 					   unsigned int optlen)
2859 {
2860 	struct sctp_sock *sp = sctp_sk(sk);
2861 	struct sctp_association *asoc;
2862 	struct sctp_sndinfo info;
2863 
2864 	if (optlen != sizeof(info))
2865 		return -EINVAL;
2866 	if (copy_from_user(&info, optval, optlen))
2867 		return -EFAULT;
2868 	if (info.snd_flags &
2869 	    ~(SCTP_UNORDERED | SCTP_ADDR_OVER |
2870 	      SCTP_ABORT | SCTP_EOF))
2871 		return -EINVAL;
2872 
2873 	asoc = sctp_id2assoc(sk, info.snd_assoc_id);
2874 	if (!asoc && info.snd_assoc_id && sctp_style(sk, UDP))
2875 		return -EINVAL;
2876 	if (asoc) {
2877 		asoc->default_stream = info.snd_sid;
2878 		asoc->default_flags = info.snd_flags;
2879 		asoc->default_ppid = info.snd_ppid;
2880 		asoc->default_context = info.snd_context;
2881 	} else {
2882 		sp->default_stream = info.snd_sid;
2883 		sp->default_flags = info.snd_flags;
2884 		sp->default_ppid = info.snd_ppid;
2885 		sp->default_context = info.snd_context;
2886 	}
2887 
2888 	return 0;
2889 }
2890 
2891 /* 7.1.10 Set Primary Address (SCTP_PRIMARY_ADDR)
2892  *
2893  * Requests that the local SCTP stack use the enclosed peer address as
2894  * the association primary.  The enclosed address must be one of the
2895  * association peer's addresses.
2896  */
sctp_setsockopt_primary_addr(struct sock * sk,char __user * optval,unsigned int optlen)2897 static int sctp_setsockopt_primary_addr(struct sock *sk, char __user *optval,
2898 					unsigned int optlen)
2899 {
2900 	struct sctp_prim prim;
2901 	struct sctp_transport *trans;
2902 
2903 	if (optlen != sizeof(struct sctp_prim))
2904 		return -EINVAL;
2905 
2906 	if (copy_from_user(&prim, optval, sizeof(struct sctp_prim)))
2907 		return -EFAULT;
2908 
2909 	trans = sctp_addr_id2transport(sk, &prim.ssp_addr, prim.ssp_assoc_id);
2910 	if (!trans)
2911 		return -EINVAL;
2912 
2913 	sctp_assoc_set_primary(trans->asoc, trans);
2914 
2915 	return 0;
2916 }
2917 
2918 /*
2919  * 7.1.5 SCTP_NODELAY
2920  *
2921  * Turn on/off any Nagle-like algorithm.  This means that packets are
2922  * generally sent as soon as possible and no unnecessary delays are
2923  * introduced, at the cost of more packets in the network.  Expects an
2924  *  integer boolean flag.
2925  */
sctp_setsockopt_nodelay(struct sock * sk,char __user * optval,unsigned int optlen)2926 static int sctp_setsockopt_nodelay(struct sock *sk, char __user *optval,
2927 				   unsigned int optlen)
2928 {
2929 	int val;
2930 
2931 	if (optlen < sizeof(int))
2932 		return -EINVAL;
2933 	if (get_user(val, (int __user *)optval))
2934 		return -EFAULT;
2935 
2936 	sctp_sk(sk)->nodelay = (val == 0) ? 0 : 1;
2937 	return 0;
2938 }
2939 
2940 /*
2941  *
2942  * 7.1.1 SCTP_RTOINFO
2943  *
2944  * The protocol parameters used to initialize and bound retransmission
2945  * timeout (RTO) are tunable. sctp_rtoinfo structure is used to access
2946  * and modify these parameters.
2947  * All parameters are time values, in milliseconds.  A value of 0, when
2948  * modifying the parameters, indicates that the current value should not
2949  * be changed.
2950  *
2951  */
sctp_setsockopt_rtoinfo(struct sock * sk,char __user * optval,unsigned int optlen)2952 static int sctp_setsockopt_rtoinfo(struct sock *sk, char __user *optval, unsigned int optlen)
2953 {
2954 	struct sctp_rtoinfo rtoinfo;
2955 	struct sctp_association *asoc;
2956 	unsigned long rto_min, rto_max;
2957 	struct sctp_sock *sp = sctp_sk(sk);
2958 
2959 	if (optlen != sizeof (struct sctp_rtoinfo))
2960 		return -EINVAL;
2961 
2962 	if (copy_from_user(&rtoinfo, optval, optlen))
2963 		return -EFAULT;
2964 
2965 	asoc = sctp_id2assoc(sk, rtoinfo.srto_assoc_id);
2966 
2967 	/* Set the values to the specific association */
2968 	if (!asoc && rtoinfo.srto_assoc_id && sctp_style(sk, UDP))
2969 		return -EINVAL;
2970 
2971 	rto_max = rtoinfo.srto_max;
2972 	rto_min = rtoinfo.srto_min;
2973 
2974 	if (rto_max)
2975 		rto_max = asoc ? msecs_to_jiffies(rto_max) : rto_max;
2976 	else
2977 		rto_max = asoc ? asoc->rto_max : sp->rtoinfo.srto_max;
2978 
2979 	if (rto_min)
2980 		rto_min = asoc ? msecs_to_jiffies(rto_min) : rto_min;
2981 	else
2982 		rto_min = asoc ? asoc->rto_min : sp->rtoinfo.srto_min;
2983 
2984 	if (rto_min > rto_max)
2985 		return -EINVAL;
2986 
2987 	if (asoc) {
2988 		if (rtoinfo.srto_initial != 0)
2989 			asoc->rto_initial =
2990 				msecs_to_jiffies(rtoinfo.srto_initial);
2991 		asoc->rto_max = rto_max;
2992 		asoc->rto_min = rto_min;
2993 	} else {
2994 		/* If there is no association or the association-id = 0
2995 		 * set the values to the endpoint.
2996 		 */
2997 		if (rtoinfo.srto_initial != 0)
2998 			sp->rtoinfo.srto_initial = rtoinfo.srto_initial;
2999 		sp->rtoinfo.srto_max = rto_max;
3000 		sp->rtoinfo.srto_min = rto_min;
3001 	}
3002 
3003 	return 0;
3004 }
3005 
3006 /*
3007  *
3008  * 7.1.2 SCTP_ASSOCINFO
3009  *
3010  * This option is used to tune the maximum retransmission attempts
3011  * of the association.
3012  * Returns an error if the new association retransmission value is
3013  * greater than the sum of the retransmission value  of the peer.
3014  * See [SCTP] for more information.
3015  *
3016  */
sctp_setsockopt_associnfo(struct sock * sk,char __user * optval,unsigned int optlen)3017 static int sctp_setsockopt_associnfo(struct sock *sk, char __user *optval, unsigned int optlen)
3018 {
3019 
3020 	struct sctp_assocparams assocparams;
3021 	struct sctp_association *asoc;
3022 
3023 	if (optlen != sizeof(struct sctp_assocparams))
3024 		return -EINVAL;
3025 	if (copy_from_user(&assocparams, optval, optlen))
3026 		return -EFAULT;
3027 
3028 	asoc = sctp_id2assoc(sk, assocparams.sasoc_assoc_id);
3029 
3030 	if (!asoc && assocparams.sasoc_assoc_id && sctp_style(sk, UDP))
3031 		return -EINVAL;
3032 
3033 	/* Set the values to the specific association */
3034 	if (asoc) {
3035 		if (assocparams.sasoc_asocmaxrxt != 0) {
3036 			__u32 path_sum = 0;
3037 			int   paths = 0;
3038 			struct sctp_transport *peer_addr;
3039 
3040 			list_for_each_entry(peer_addr, &asoc->peer.transport_addr_list,
3041 					transports) {
3042 				path_sum += peer_addr->pathmaxrxt;
3043 				paths++;
3044 			}
3045 
3046 			/* Only validate asocmaxrxt if we have more than
3047 			 * one path/transport.  We do this because path
3048 			 * retransmissions are only counted when we have more
3049 			 * then one path.
3050 			 */
3051 			if (paths > 1 &&
3052 			    assocparams.sasoc_asocmaxrxt > path_sum)
3053 				return -EINVAL;
3054 
3055 			asoc->max_retrans = assocparams.sasoc_asocmaxrxt;
3056 		}
3057 
3058 		if (assocparams.sasoc_cookie_life != 0)
3059 			asoc->cookie_life = ms_to_ktime(assocparams.sasoc_cookie_life);
3060 	} else {
3061 		/* Set the values to the endpoint */
3062 		struct sctp_sock *sp = sctp_sk(sk);
3063 
3064 		if (assocparams.sasoc_asocmaxrxt != 0)
3065 			sp->assocparams.sasoc_asocmaxrxt =
3066 						assocparams.sasoc_asocmaxrxt;
3067 		if (assocparams.sasoc_cookie_life != 0)
3068 			sp->assocparams.sasoc_cookie_life =
3069 						assocparams.sasoc_cookie_life;
3070 	}
3071 	return 0;
3072 }
3073 
3074 /*
3075  * 7.1.16 Set/clear IPv4 mapped addresses (SCTP_I_WANT_MAPPED_V4_ADDR)
3076  *
3077  * This socket option is a boolean flag which turns on or off mapped V4
3078  * addresses.  If this option is turned on and the socket is type
3079  * PF_INET6, then IPv4 addresses will be mapped to V6 representation.
3080  * If this option is turned off, then no mapping will be done of V4
3081  * addresses and a user will receive both PF_INET6 and PF_INET type
3082  * addresses on the socket.
3083  */
sctp_setsockopt_mappedv4(struct sock * sk,char __user * optval,unsigned int optlen)3084 static int sctp_setsockopt_mappedv4(struct sock *sk, char __user *optval, unsigned int optlen)
3085 {
3086 	int val;
3087 	struct sctp_sock *sp = sctp_sk(sk);
3088 
3089 	if (optlen < sizeof(int))
3090 		return -EINVAL;
3091 	if (get_user(val, (int __user *)optval))
3092 		return -EFAULT;
3093 	if (val)
3094 		sp->v4mapped = 1;
3095 	else
3096 		sp->v4mapped = 0;
3097 
3098 	return 0;
3099 }
3100 
3101 /*
3102  * 8.1.16.  Get or Set the Maximum Fragmentation Size (SCTP_MAXSEG)
3103  * This option will get or set the maximum size to put in any outgoing
3104  * SCTP DATA chunk.  If a message is larger than this size it will be
3105  * fragmented by SCTP into the specified size.  Note that the underlying
3106  * SCTP implementation may fragment into smaller sized chunks when the
3107  * PMTU of the underlying association is smaller than the value set by
3108  * the user.  The default value for this option is '0' which indicates
3109  * the user is NOT limiting fragmentation and only the PMTU will effect
3110  * SCTP's choice of DATA chunk size.  Note also that values set larger
3111  * than the maximum size of an IP datagram will effectively let SCTP
3112  * control fragmentation (i.e. the same as setting this option to 0).
3113  *
3114  * The following structure is used to access and modify this parameter:
3115  *
3116  * struct sctp_assoc_value {
3117  *   sctp_assoc_t assoc_id;
3118  *   uint32_t assoc_value;
3119  * };
3120  *
3121  * assoc_id:  This parameter is ignored for one-to-one style sockets.
3122  *    For one-to-many style sockets this parameter indicates which
3123  *    association the user is performing an action upon.  Note that if
3124  *    this field's value is zero then the endpoints default value is
3125  *    changed (effecting future associations only).
3126  * assoc_value:  This parameter specifies the maximum size in bytes.
3127  */
sctp_setsockopt_maxseg(struct sock * sk,char __user * optval,unsigned int optlen)3128 static int sctp_setsockopt_maxseg(struct sock *sk, char __user *optval, unsigned int optlen)
3129 {
3130 	struct sctp_assoc_value params;
3131 	struct sctp_association *asoc;
3132 	struct sctp_sock *sp = sctp_sk(sk);
3133 	int val;
3134 
3135 	if (optlen == sizeof(int)) {
3136 		pr_warn_ratelimited(DEPRECATED
3137 				    "%s (pid %d) "
3138 				    "Use of int in maxseg socket option.\n"
3139 				    "Use struct sctp_assoc_value instead\n",
3140 				    current->comm, task_pid_nr(current));
3141 		if (copy_from_user(&val, optval, optlen))
3142 			return -EFAULT;
3143 		params.assoc_id = 0;
3144 	} else if (optlen == sizeof(struct sctp_assoc_value)) {
3145 		if (copy_from_user(&params, optval, optlen))
3146 			return -EFAULT;
3147 		val = params.assoc_value;
3148 	} else
3149 		return -EINVAL;
3150 
3151 	if ((val != 0) && ((val < 8) || (val > SCTP_MAX_CHUNK_LEN)))
3152 		return -EINVAL;
3153 
3154 	asoc = sctp_id2assoc(sk, params.assoc_id);
3155 	if (!asoc && params.assoc_id && sctp_style(sk, UDP))
3156 		return -EINVAL;
3157 
3158 	if (asoc) {
3159 		if (val == 0) {
3160 			val = asoc->pathmtu;
3161 			val -= sp->pf->af->net_header_len;
3162 			val -= sizeof(struct sctphdr) +
3163 					sizeof(struct sctp_data_chunk);
3164 		}
3165 		asoc->user_frag = val;
3166 		asoc->frag_point = sctp_frag_point(asoc, asoc->pathmtu);
3167 	} else {
3168 		sp->user_frag = val;
3169 	}
3170 
3171 	return 0;
3172 }
3173 
3174 
3175 /*
3176  *  7.1.9 Set Peer Primary Address (SCTP_SET_PEER_PRIMARY_ADDR)
3177  *
3178  *   Requests that the peer mark the enclosed address as the association
3179  *   primary. The enclosed address must be one of the association's
3180  *   locally bound addresses. The following structure is used to make a
3181  *   set primary request:
3182  */
sctp_setsockopt_peer_primary_addr(struct sock * sk,char __user * optval,unsigned int optlen)3183 static int sctp_setsockopt_peer_primary_addr(struct sock *sk, char __user *optval,
3184 					     unsigned int optlen)
3185 {
3186 	struct net *net = sock_net(sk);
3187 	struct sctp_sock	*sp;
3188 	struct sctp_association	*asoc = NULL;
3189 	struct sctp_setpeerprim	prim;
3190 	struct sctp_chunk	*chunk;
3191 	struct sctp_af		*af;
3192 	int 			err;
3193 
3194 	sp = sctp_sk(sk);
3195 
3196 	if (!net->sctp.addip_enable)
3197 		return -EPERM;
3198 
3199 	if (optlen != sizeof(struct sctp_setpeerprim))
3200 		return -EINVAL;
3201 
3202 	if (copy_from_user(&prim, optval, optlen))
3203 		return -EFAULT;
3204 
3205 	asoc = sctp_id2assoc(sk, prim.sspp_assoc_id);
3206 	if (!asoc)
3207 		return -EINVAL;
3208 
3209 	if (!asoc->peer.asconf_capable)
3210 		return -EPERM;
3211 
3212 	if (asoc->peer.addip_disabled_mask & SCTP_PARAM_SET_PRIMARY)
3213 		return -EPERM;
3214 
3215 	if (!sctp_state(asoc, ESTABLISHED))
3216 		return -ENOTCONN;
3217 
3218 	af = sctp_get_af_specific(prim.sspp_addr.ss_family);
3219 	if (!af)
3220 		return -EINVAL;
3221 
3222 	if (!af->addr_valid((union sctp_addr *)&prim.sspp_addr, sp, NULL))
3223 		return -EADDRNOTAVAIL;
3224 
3225 	if (!sctp_assoc_lookup_laddr(asoc, (union sctp_addr *)&prim.sspp_addr))
3226 		return -EADDRNOTAVAIL;
3227 
3228 	/* Create an ASCONF chunk with SET_PRIMARY parameter	*/
3229 	chunk = sctp_make_asconf_set_prim(asoc,
3230 					  (union sctp_addr *)&prim.sspp_addr);
3231 	if (!chunk)
3232 		return -ENOMEM;
3233 
3234 	err = sctp_send_asconf(asoc, chunk);
3235 
3236 	pr_debug("%s: we set peer primary addr primitively\n", __func__);
3237 
3238 	return err;
3239 }
3240 
sctp_setsockopt_adaptation_layer(struct sock * sk,char __user * optval,unsigned int optlen)3241 static int sctp_setsockopt_adaptation_layer(struct sock *sk, char __user *optval,
3242 					    unsigned int optlen)
3243 {
3244 	struct sctp_setadaptation adaptation;
3245 
3246 	if (optlen != sizeof(struct sctp_setadaptation))
3247 		return -EINVAL;
3248 	if (copy_from_user(&adaptation, optval, optlen))
3249 		return -EFAULT;
3250 
3251 	sctp_sk(sk)->adaptation_ind = adaptation.ssb_adaptation_ind;
3252 
3253 	return 0;
3254 }
3255 
3256 /*
3257  * 7.1.29.  Set or Get the default context (SCTP_CONTEXT)
3258  *
3259  * The context field in the sctp_sndrcvinfo structure is normally only
3260  * used when a failed message is retrieved holding the value that was
3261  * sent down on the actual send call.  This option allows the setting of
3262  * a default context on an association basis that will be received on
3263  * reading messages from the peer.  This is especially helpful in the
3264  * one-2-many model for an application to keep some reference to an
3265  * internal state machine that is processing messages on the
3266  * association.  Note that the setting of this value only effects
3267  * received messages from the peer and does not effect the value that is
3268  * saved with outbound messages.
3269  */
sctp_setsockopt_context(struct sock * sk,char __user * optval,unsigned int optlen)3270 static int sctp_setsockopt_context(struct sock *sk, char __user *optval,
3271 				   unsigned int optlen)
3272 {
3273 	struct sctp_assoc_value params;
3274 	struct sctp_sock *sp;
3275 	struct sctp_association *asoc;
3276 
3277 	if (optlen != sizeof(struct sctp_assoc_value))
3278 		return -EINVAL;
3279 	if (copy_from_user(&params, optval, optlen))
3280 		return -EFAULT;
3281 
3282 	sp = sctp_sk(sk);
3283 
3284 	if (params.assoc_id != 0) {
3285 		asoc = sctp_id2assoc(sk, params.assoc_id);
3286 		if (!asoc)
3287 			return -EINVAL;
3288 		asoc->default_rcv_context = params.assoc_value;
3289 	} else {
3290 		sp->default_rcv_context = params.assoc_value;
3291 	}
3292 
3293 	return 0;
3294 }
3295 
3296 /*
3297  * 7.1.24.  Get or set fragmented interleave (SCTP_FRAGMENT_INTERLEAVE)
3298  *
3299  * This options will at a minimum specify if the implementation is doing
3300  * fragmented interleave.  Fragmented interleave, for a one to many
3301  * socket, is when subsequent calls to receive a message may return
3302  * parts of messages from different associations.  Some implementations
3303  * may allow you to turn this value on or off.  If so, when turned off,
3304  * no fragment interleave will occur (which will cause a head of line
3305  * blocking amongst multiple associations sharing the same one to many
3306  * socket).  When this option is turned on, then each receive call may
3307  * come from a different association (thus the user must receive data
3308  * with the extended calls (e.g. sctp_recvmsg) to keep track of which
3309  * association each receive belongs to.
3310  *
3311  * This option takes a boolean value.  A non-zero value indicates that
3312  * fragmented interleave is on.  A value of zero indicates that
3313  * fragmented interleave is off.
3314  *
3315  * Note that it is important that an implementation that allows this
3316  * option to be turned on, have it off by default.  Otherwise an unaware
3317  * application using the one to many model may become confused and act
3318  * incorrectly.
3319  */
sctp_setsockopt_fragment_interleave(struct sock * sk,char __user * optval,unsigned int optlen)3320 static int sctp_setsockopt_fragment_interleave(struct sock *sk,
3321 					       char __user *optval,
3322 					       unsigned int optlen)
3323 {
3324 	int val;
3325 
3326 	if (optlen != sizeof(int))
3327 		return -EINVAL;
3328 	if (get_user(val, (int __user *)optval))
3329 		return -EFAULT;
3330 
3331 	sctp_sk(sk)->frag_interleave = (val == 0) ? 0 : 1;
3332 
3333 	return 0;
3334 }
3335 
3336 /*
3337  * 8.1.21.  Set or Get the SCTP Partial Delivery Point
3338  *       (SCTP_PARTIAL_DELIVERY_POINT)
3339  *
3340  * This option will set or get the SCTP partial delivery point.  This
3341  * point is the size of a message where the partial delivery API will be
3342  * invoked to help free up rwnd space for the peer.  Setting this to a
3343  * lower value will cause partial deliveries to happen more often.  The
3344  * calls argument is an integer that sets or gets the partial delivery
3345  * point.  Note also that the call will fail if the user attempts to set
3346  * this value larger than the socket receive buffer size.
3347  *
3348  * Note that any single message having a length smaller than or equal to
3349  * the SCTP partial delivery point will be delivered in one single read
3350  * call as long as the user provided buffer is large enough to hold the
3351  * message.
3352  */
sctp_setsockopt_partial_delivery_point(struct sock * sk,char __user * optval,unsigned int optlen)3353 static int sctp_setsockopt_partial_delivery_point(struct sock *sk,
3354 						  char __user *optval,
3355 						  unsigned int optlen)
3356 {
3357 	u32 val;
3358 
3359 	if (optlen != sizeof(u32))
3360 		return -EINVAL;
3361 	if (get_user(val, (int __user *)optval))
3362 		return -EFAULT;
3363 
3364 	/* Note: We double the receive buffer from what the user sets
3365 	 * it to be, also initial rwnd is based on rcvbuf/2.
3366 	 */
3367 	if (val > (sk->sk_rcvbuf >> 1))
3368 		return -EINVAL;
3369 
3370 	sctp_sk(sk)->pd_point = val;
3371 
3372 	return 0; /* is this the right error code? */
3373 }
3374 
3375 /*
3376  * 7.1.28.  Set or Get the maximum burst (SCTP_MAX_BURST)
3377  *
3378  * This option will allow a user to change the maximum burst of packets
3379  * that can be emitted by this association.  Note that the default value
3380  * is 4, and some implementations may restrict this setting so that it
3381  * can only be lowered.
3382  *
3383  * NOTE: This text doesn't seem right.  Do this on a socket basis with
3384  * future associations inheriting the socket value.
3385  */
sctp_setsockopt_maxburst(struct sock * sk,char __user * optval,unsigned int optlen)3386 static int sctp_setsockopt_maxburst(struct sock *sk,
3387 				    char __user *optval,
3388 				    unsigned int optlen)
3389 {
3390 	struct sctp_assoc_value params;
3391 	struct sctp_sock *sp;
3392 	struct sctp_association *asoc;
3393 	int val;
3394 	int assoc_id = 0;
3395 
3396 	if (optlen == sizeof(int)) {
3397 		pr_warn_ratelimited(DEPRECATED
3398 				    "%s (pid %d) "
3399 				    "Use of int in max_burst socket option deprecated.\n"
3400 				    "Use struct sctp_assoc_value instead\n",
3401 				    current->comm, task_pid_nr(current));
3402 		if (copy_from_user(&val, optval, optlen))
3403 			return -EFAULT;
3404 	} else if (optlen == sizeof(struct sctp_assoc_value)) {
3405 		if (copy_from_user(&params, optval, optlen))
3406 			return -EFAULT;
3407 		val = params.assoc_value;
3408 		assoc_id = params.assoc_id;
3409 	} else
3410 		return -EINVAL;
3411 
3412 	sp = sctp_sk(sk);
3413 
3414 	if (assoc_id != 0) {
3415 		asoc = sctp_id2assoc(sk, assoc_id);
3416 		if (!asoc)
3417 			return -EINVAL;
3418 		asoc->max_burst = val;
3419 	} else
3420 		sp->max_burst = val;
3421 
3422 	return 0;
3423 }
3424 
3425 /*
3426  * 7.1.18.  Add a chunk that must be authenticated (SCTP_AUTH_CHUNK)
3427  *
3428  * This set option adds a chunk type that the user is requesting to be
3429  * received only in an authenticated way.  Changes to the list of chunks
3430  * will only effect future associations on the socket.
3431  */
sctp_setsockopt_auth_chunk(struct sock * sk,char __user * optval,unsigned int optlen)3432 static int sctp_setsockopt_auth_chunk(struct sock *sk,
3433 				      char __user *optval,
3434 				      unsigned int optlen)
3435 {
3436 	struct sctp_endpoint *ep = sctp_sk(sk)->ep;
3437 	struct sctp_authchunk val;
3438 
3439 	if (!ep->auth_enable)
3440 		return -EACCES;
3441 
3442 	if (optlen != sizeof(struct sctp_authchunk))
3443 		return -EINVAL;
3444 	if (copy_from_user(&val, optval, optlen))
3445 		return -EFAULT;
3446 
3447 	switch (val.sauth_chunk) {
3448 	case SCTP_CID_INIT:
3449 	case SCTP_CID_INIT_ACK:
3450 	case SCTP_CID_SHUTDOWN_COMPLETE:
3451 	case SCTP_CID_AUTH:
3452 		return -EINVAL;
3453 	}
3454 
3455 	/* add this chunk id to the endpoint */
3456 	return sctp_auth_ep_add_chunkid(ep, val.sauth_chunk);
3457 }
3458 
3459 /*
3460  * 7.1.19.  Get or set the list of supported HMAC Identifiers (SCTP_HMAC_IDENT)
3461  *
3462  * This option gets or sets the list of HMAC algorithms that the local
3463  * endpoint requires the peer to use.
3464  */
sctp_setsockopt_hmac_ident(struct sock * sk,char __user * optval,unsigned int optlen)3465 static int sctp_setsockopt_hmac_ident(struct sock *sk,
3466 				      char __user *optval,
3467 				      unsigned int optlen)
3468 {
3469 	struct sctp_endpoint *ep = sctp_sk(sk)->ep;
3470 	struct sctp_hmacalgo *hmacs;
3471 	u32 idents;
3472 	int err;
3473 
3474 	if (!ep->auth_enable)
3475 		return -EACCES;
3476 
3477 	if (optlen < sizeof(struct sctp_hmacalgo))
3478 		return -EINVAL;
3479 
3480 	hmacs = memdup_user(optval, optlen);
3481 	if (IS_ERR(hmacs))
3482 		return PTR_ERR(hmacs);
3483 
3484 	idents = hmacs->shmac_num_idents;
3485 	if (idents == 0 || idents > SCTP_AUTH_NUM_HMACS ||
3486 	    (idents * sizeof(u16)) > (optlen - sizeof(struct sctp_hmacalgo))) {
3487 		err = -EINVAL;
3488 		goto out;
3489 	}
3490 
3491 	err = sctp_auth_ep_set_hmacs(ep, hmacs);
3492 out:
3493 	kfree(hmacs);
3494 	return err;
3495 }
3496 
3497 /*
3498  * 7.1.20.  Set a shared key (SCTP_AUTH_KEY)
3499  *
3500  * This option will set a shared secret key which is used to build an
3501  * association shared key.
3502  */
sctp_setsockopt_auth_key(struct sock * sk,char __user * optval,unsigned int optlen)3503 static int sctp_setsockopt_auth_key(struct sock *sk,
3504 				    char __user *optval,
3505 				    unsigned int optlen)
3506 {
3507 	struct sctp_endpoint *ep = sctp_sk(sk)->ep;
3508 	struct sctp_authkey *authkey;
3509 	struct sctp_association *asoc;
3510 	int ret;
3511 
3512 	if (!ep->auth_enable)
3513 		return -EACCES;
3514 
3515 	if (optlen <= sizeof(struct sctp_authkey))
3516 		return -EINVAL;
3517 
3518 	authkey = memdup_user(optval, optlen);
3519 	if (IS_ERR(authkey))
3520 		return PTR_ERR(authkey);
3521 
3522 	if (authkey->sca_keylength > optlen - sizeof(struct sctp_authkey)) {
3523 		ret = -EINVAL;
3524 		goto out;
3525 	}
3526 
3527 	asoc = sctp_id2assoc(sk, authkey->sca_assoc_id);
3528 	if (!asoc && authkey->sca_assoc_id && sctp_style(sk, UDP)) {
3529 		ret = -EINVAL;
3530 		goto out;
3531 	}
3532 
3533 	ret = sctp_auth_set_key(ep, asoc, authkey);
3534 out:
3535 	kzfree(authkey);
3536 	return ret;
3537 }
3538 
3539 /*
3540  * 7.1.21.  Get or set the active shared key (SCTP_AUTH_ACTIVE_KEY)
3541  *
3542  * This option will get or set the active shared key to be used to build
3543  * the association shared key.
3544  */
sctp_setsockopt_active_key(struct sock * sk,char __user * optval,unsigned int optlen)3545 static int sctp_setsockopt_active_key(struct sock *sk,
3546 				      char __user *optval,
3547 				      unsigned int optlen)
3548 {
3549 	struct sctp_endpoint *ep = sctp_sk(sk)->ep;
3550 	struct sctp_authkeyid val;
3551 	struct sctp_association *asoc;
3552 
3553 	if (!ep->auth_enable)
3554 		return -EACCES;
3555 
3556 	if (optlen != sizeof(struct sctp_authkeyid))
3557 		return -EINVAL;
3558 	if (copy_from_user(&val, optval, optlen))
3559 		return -EFAULT;
3560 
3561 	asoc = sctp_id2assoc(sk, val.scact_assoc_id);
3562 	if (!asoc && val.scact_assoc_id && sctp_style(sk, UDP))
3563 		return -EINVAL;
3564 
3565 	return sctp_auth_set_active_key(ep, asoc, val.scact_keynumber);
3566 }
3567 
3568 /*
3569  * 7.1.22.  Delete a shared key (SCTP_AUTH_DELETE_KEY)
3570  *
3571  * This set option will delete a shared secret key from use.
3572  */
sctp_setsockopt_del_key(struct sock * sk,char __user * optval,unsigned int optlen)3573 static int sctp_setsockopt_del_key(struct sock *sk,
3574 				   char __user *optval,
3575 				   unsigned int optlen)
3576 {
3577 	struct sctp_endpoint *ep = sctp_sk(sk)->ep;
3578 	struct sctp_authkeyid val;
3579 	struct sctp_association *asoc;
3580 
3581 	if (!ep->auth_enable)
3582 		return -EACCES;
3583 
3584 	if (optlen != sizeof(struct sctp_authkeyid))
3585 		return -EINVAL;
3586 	if (copy_from_user(&val, optval, optlen))
3587 		return -EFAULT;
3588 
3589 	asoc = sctp_id2assoc(sk, val.scact_assoc_id);
3590 	if (!asoc && val.scact_assoc_id && sctp_style(sk, UDP))
3591 		return -EINVAL;
3592 
3593 	return sctp_auth_del_key_id(ep, asoc, val.scact_keynumber);
3594 
3595 }
3596 
3597 /*
3598  * 8.1.23 SCTP_AUTO_ASCONF
3599  *
3600  * This option will enable or disable the use of the automatic generation of
3601  * ASCONF chunks to add and delete addresses to an existing association.  Note
3602  * that this option has two caveats namely: a) it only affects sockets that
3603  * are bound to all addresses available to the SCTP stack, and b) the system
3604  * administrator may have an overriding control that turns the ASCONF feature
3605  * off no matter what setting the socket option may have.
3606  * This option expects an integer boolean flag, where a non-zero value turns on
3607  * the option, and a zero value turns off the option.
3608  * Note. In this implementation, socket operation overrides default parameter
3609  * being set by sysctl as well as FreeBSD implementation
3610  */
sctp_setsockopt_auto_asconf(struct sock * sk,char __user * optval,unsigned int optlen)3611 static int sctp_setsockopt_auto_asconf(struct sock *sk, char __user *optval,
3612 					unsigned int optlen)
3613 {
3614 	int val;
3615 	struct sctp_sock *sp = sctp_sk(sk);
3616 
3617 	if (optlen < sizeof(int))
3618 		return -EINVAL;
3619 	if (get_user(val, (int __user *)optval))
3620 		return -EFAULT;
3621 	if (!sctp_is_ep_boundall(sk) && val)
3622 		return -EINVAL;
3623 	if ((val && sp->do_auto_asconf) || (!val && !sp->do_auto_asconf))
3624 		return 0;
3625 
3626 	spin_lock_bh(&sock_net(sk)->sctp.addr_wq_lock);
3627 	if (val == 0 && sp->do_auto_asconf) {
3628 		list_del(&sp->auto_asconf_list);
3629 		sp->do_auto_asconf = 0;
3630 	} else if (val && !sp->do_auto_asconf) {
3631 		list_add_tail(&sp->auto_asconf_list,
3632 		    &sock_net(sk)->sctp.auto_asconf_splist);
3633 		sp->do_auto_asconf = 1;
3634 	}
3635 	spin_unlock_bh(&sock_net(sk)->sctp.addr_wq_lock);
3636 	return 0;
3637 }
3638 
3639 /*
3640  * SCTP_PEER_ADDR_THLDS
3641  *
3642  * This option allows us to alter the partially failed threshold for one or all
3643  * transports in an association.  See Section 6.1 of:
3644  * http://www.ietf.org/id/draft-nishida-tsvwg-sctp-failover-05.txt
3645  */
sctp_setsockopt_paddr_thresholds(struct sock * sk,char __user * optval,unsigned int optlen)3646 static int sctp_setsockopt_paddr_thresholds(struct sock *sk,
3647 					    char __user *optval,
3648 					    unsigned int optlen)
3649 {
3650 	struct sctp_paddrthlds val;
3651 	struct sctp_transport *trans;
3652 	struct sctp_association *asoc;
3653 
3654 	if (optlen < sizeof(struct sctp_paddrthlds))
3655 		return -EINVAL;
3656 	if (copy_from_user(&val, (struct sctp_paddrthlds __user *)optval,
3657 			   sizeof(struct sctp_paddrthlds)))
3658 		return -EFAULT;
3659 
3660 
3661 	if (sctp_is_any(sk, (const union sctp_addr *)&val.spt_address)) {
3662 		asoc = sctp_id2assoc(sk, val.spt_assoc_id);
3663 		if (!asoc)
3664 			return -ENOENT;
3665 		list_for_each_entry(trans, &asoc->peer.transport_addr_list,
3666 				    transports) {
3667 			if (val.spt_pathmaxrxt)
3668 				trans->pathmaxrxt = val.spt_pathmaxrxt;
3669 			trans->pf_retrans = val.spt_pathpfthld;
3670 		}
3671 
3672 		if (val.spt_pathmaxrxt)
3673 			asoc->pathmaxrxt = val.spt_pathmaxrxt;
3674 		asoc->pf_retrans = val.spt_pathpfthld;
3675 	} else {
3676 		trans = sctp_addr_id2transport(sk, &val.spt_address,
3677 					       val.spt_assoc_id);
3678 		if (!trans)
3679 			return -ENOENT;
3680 
3681 		if (val.spt_pathmaxrxt)
3682 			trans->pathmaxrxt = val.spt_pathmaxrxt;
3683 		trans->pf_retrans = val.spt_pathpfthld;
3684 	}
3685 
3686 	return 0;
3687 }
3688 
sctp_setsockopt_recvrcvinfo(struct sock * sk,char __user * optval,unsigned int optlen)3689 static int sctp_setsockopt_recvrcvinfo(struct sock *sk,
3690 				       char __user *optval,
3691 				       unsigned int optlen)
3692 {
3693 	int val;
3694 
3695 	if (optlen < sizeof(int))
3696 		return -EINVAL;
3697 	if (get_user(val, (int __user *) optval))
3698 		return -EFAULT;
3699 
3700 	sctp_sk(sk)->recvrcvinfo = (val == 0) ? 0 : 1;
3701 
3702 	return 0;
3703 }
3704 
sctp_setsockopt_recvnxtinfo(struct sock * sk,char __user * optval,unsigned int optlen)3705 static int sctp_setsockopt_recvnxtinfo(struct sock *sk,
3706 				       char __user *optval,
3707 				       unsigned int optlen)
3708 {
3709 	int val;
3710 
3711 	if (optlen < sizeof(int))
3712 		return -EINVAL;
3713 	if (get_user(val, (int __user *) optval))
3714 		return -EFAULT;
3715 
3716 	sctp_sk(sk)->recvnxtinfo = (val == 0) ? 0 : 1;
3717 
3718 	return 0;
3719 }
3720 
3721 /* API 6.2 setsockopt(), getsockopt()
3722  *
3723  * Applications use setsockopt() and getsockopt() to set or retrieve
3724  * socket options.  Socket options are used to change the default
3725  * behavior of sockets calls.  They are described in Section 7.
3726  *
3727  * The syntax is:
3728  *
3729  *   ret = getsockopt(int sd, int level, int optname, void __user *optval,
3730  *                    int __user *optlen);
3731  *   ret = setsockopt(int sd, int level, int optname, const void __user *optval,
3732  *                    int optlen);
3733  *
3734  *   sd      - the socket descript.
3735  *   level   - set to IPPROTO_SCTP for all SCTP options.
3736  *   optname - the option name.
3737  *   optval  - the buffer to store the value of the option.
3738  *   optlen  - the size of the buffer.
3739  */
sctp_setsockopt(struct sock * sk,int level,int optname,char __user * optval,unsigned int optlen)3740 static int sctp_setsockopt(struct sock *sk, int level, int optname,
3741 			   char __user *optval, unsigned int optlen)
3742 {
3743 	int retval = 0;
3744 
3745 	pr_debug("%s: sk:%p, optname:%d\n", __func__, sk, optname);
3746 
3747 	/* I can hardly begin to describe how wrong this is.  This is
3748 	 * so broken as to be worse than useless.  The API draft
3749 	 * REALLY is NOT helpful here...  I am not convinced that the
3750 	 * semantics of setsockopt() with a level OTHER THAN SOL_SCTP
3751 	 * are at all well-founded.
3752 	 */
3753 	if (level != SOL_SCTP) {
3754 		struct sctp_af *af = sctp_sk(sk)->pf->af;
3755 		retval = af->setsockopt(sk, level, optname, optval, optlen);
3756 		goto out_nounlock;
3757 	}
3758 
3759 	lock_sock(sk);
3760 
3761 	switch (optname) {
3762 	case SCTP_SOCKOPT_BINDX_ADD:
3763 		/* 'optlen' is the size of the addresses buffer. */
3764 		retval = sctp_setsockopt_bindx(sk, (struct sockaddr __user *)optval,
3765 					       optlen, SCTP_BINDX_ADD_ADDR);
3766 		break;
3767 
3768 	case SCTP_SOCKOPT_BINDX_REM:
3769 		/* 'optlen' is the size of the addresses buffer. */
3770 		retval = sctp_setsockopt_bindx(sk, (struct sockaddr __user *)optval,
3771 					       optlen, SCTP_BINDX_REM_ADDR);
3772 		break;
3773 
3774 	case SCTP_SOCKOPT_CONNECTX_OLD:
3775 		/* 'optlen' is the size of the addresses buffer. */
3776 		retval = sctp_setsockopt_connectx_old(sk,
3777 					    (struct sockaddr __user *)optval,
3778 					    optlen);
3779 		break;
3780 
3781 	case SCTP_SOCKOPT_CONNECTX:
3782 		/* 'optlen' is the size of the addresses buffer. */
3783 		retval = sctp_setsockopt_connectx(sk,
3784 					    (struct sockaddr __user *)optval,
3785 					    optlen);
3786 		break;
3787 
3788 	case SCTP_DISABLE_FRAGMENTS:
3789 		retval = sctp_setsockopt_disable_fragments(sk, optval, optlen);
3790 		break;
3791 
3792 	case SCTP_EVENTS:
3793 		retval = sctp_setsockopt_events(sk, optval, optlen);
3794 		break;
3795 
3796 	case SCTP_AUTOCLOSE:
3797 		retval = sctp_setsockopt_autoclose(sk, optval, optlen);
3798 		break;
3799 
3800 	case SCTP_PEER_ADDR_PARAMS:
3801 		retval = sctp_setsockopt_peer_addr_params(sk, optval, optlen);
3802 		break;
3803 
3804 	case SCTP_DELAYED_SACK:
3805 		retval = sctp_setsockopt_delayed_ack(sk, optval, optlen);
3806 		break;
3807 	case SCTP_PARTIAL_DELIVERY_POINT:
3808 		retval = sctp_setsockopt_partial_delivery_point(sk, optval, optlen);
3809 		break;
3810 
3811 	case SCTP_INITMSG:
3812 		retval = sctp_setsockopt_initmsg(sk, optval, optlen);
3813 		break;
3814 	case SCTP_DEFAULT_SEND_PARAM:
3815 		retval = sctp_setsockopt_default_send_param(sk, optval,
3816 							    optlen);
3817 		break;
3818 	case SCTP_DEFAULT_SNDINFO:
3819 		retval = sctp_setsockopt_default_sndinfo(sk, optval, optlen);
3820 		break;
3821 	case SCTP_PRIMARY_ADDR:
3822 		retval = sctp_setsockopt_primary_addr(sk, optval, optlen);
3823 		break;
3824 	case SCTP_SET_PEER_PRIMARY_ADDR:
3825 		retval = sctp_setsockopt_peer_primary_addr(sk, optval, optlen);
3826 		break;
3827 	case SCTP_NODELAY:
3828 		retval = sctp_setsockopt_nodelay(sk, optval, optlen);
3829 		break;
3830 	case SCTP_RTOINFO:
3831 		retval = sctp_setsockopt_rtoinfo(sk, optval, optlen);
3832 		break;
3833 	case SCTP_ASSOCINFO:
3834 		retval = sctp_setsockopt_associnfo(sk, optval, optlen);
3835 		break;
3836 	case SCTP_I_WANT_MAPPED_V4_ADDR:
3837 		retval = sctp_setsockopt_mappedv4(sk, optval, optlen);
3838 		break;
3839 	case SCTP_MAXSEG:
3840 		retval = sctp_setsockopt_maxseg(sk, optval, optlen);
3841 		break;
3842 	case SCTP_ADAPTATION_LAYER:
3843 		retval = sctp_setsockopt_adaptation_layer(sk, optval, optlen);
3844 		break;
3845 	case SCTP_CONTEXT:
3846 		retval = sctp_setsockopt_context(sk, optval, optlen);
3847 		break;
3848 	case SCTP_FRAGMENT_INTERLEAVE:
3849 		retval = sctp_setsockopt_fragment_interleave(sk, optval, optlen);
3850 		break;
3851 	case SCTP_MAX_BURST:
3852 		retval = sctp_setsockopt_maxburst(sk, optval, optlen);
3853 		break;
3854 	case SCTP_AUTH_CHUNK:
3855 		retval = sctp_setsockopt_auth_chunk(sk, optval, optlen);
3856 		break;
3857 	case SCTP_HMAC_IDENT:
3858 		retval = sctp_setsockopt_hmac_ident(sk, optval, optlen);
3859 		break;
3860 	case SCTP_AUTH_KEY:
3861 		retval = sctp_setsockopt_auth_key(sk, optval, optlen);
3862 		break;
3863 	case SCTP_AUTH_ACTIVE_KEY:
3864 		retval = sctp_setsockopt_active_key(sk, optval, optlen);
3865 		break;
3866 	case SCTP_AUTH_DELETE_KEY:
3867 		retval = sctp_setsockopt_del_key(sk, optval, optlen);
3868 		break;
3869 	case SCTP_AUTO_ASCONF:
3870 		retval = sctp_setsockopt_auto_asconf(sk, optval, optlen);
3871 		break;
3872 	case SCTP_PEER_ADDR_THLDS:
3873 		retval = sctp_setsockopt_paddr_thresholds(sk, optval, optlen);
3874 		break;
3875 	case SCTP_RECVRCVINFO:
3876 		retval = sctp_setsockopt_recvrcvinfo(sk, optval, optlen);
3877 		break;
3878 	case SCTP_RECVNXTINFO:
3879 		retval = sctp_setsockopt_recvnxtinfo(sk, optval, optlen);
3880 		break;
3881 	default:
3882 		retval = -ENOPROTOOPT;
3883 		break;
3884 	}
3885 
3886 	release_sock(sk);
3887 
3888 out_nounlock:
3889 	return retval;
3890 }
3891 
3892 /* API 3.1.6 connect() - UDP Style Syntax
3893  *
3894  * An application may use the connect() call in the UDP model to initiate an
3895  * association without sending data.
3896  *
3897  * The syntax is:
3898  *
3899  * ret = connect(int sd, const struct sockaddr *nam, socklen_t len);
3900  *
3901  * sd: the socket descriptor to have a new association added to.
3902  *
3903  * nam: the address structure (either struct sockaddr_in or struct
3904  *    sockaddr_in6 defined in RFC2553 [7]).
3905  *
3906  * len: the size of the address.
3907  */
sctp_connect(struct sock * sk,struct sockaddr * addr,int addr_len)3908 static int sctp_connect(struct sock *sk, struct sockaddr *addr,
3909 			int addr_len)
3910 {
3911 	int err = 0;
3912 	struct sctp_af *af;
3913 
3914 	lock_sock(sk);
3915 
3916 	pr_debug("%s: sk:%p, sockaddr:%p, addr_len:%d\n", __func__, sk,
3917 		 addr, addr_len);
3918 
3919 	/* Validate addr_len before calling common connect/connectx routine. */
3920 	af = sctp_get_af_specific(addr->sa_family);
3921 	if (!af || addr_len < af->sockaddr_len) {
3922 		err = -EINVAL;
3923 	} else {
3924 		/* Pass correct addr len to common routine (so it knows there
3925 		 * is only one address being passed.
3926 		 */
3927 		err = __sctp_connect(sk, addr, af->sockaddr_len, NULL);
3928 	}
3929 
3930 	release_sock(sk);
3931 	return err;
3932 }
3933 
3934 /* FIXME: Write comments. */
sctp_disconnect(struct sock * sk,int flags)3935 static int sctp_disconnect(struct sock *sk, int flags)
3936 {
3937 	return -EOPNOTSUPP; /* STUB */
3938 }
3939 
3940 /* 4.1.4 accept() - TCP Style Syntax
3941  *
3942  * Applications use accept() call to remove an established SCTP
3943  * association from the accept queue of the endpoint.  A new socket
3944  * descriptor will be returned from accept() to represent the newly
3945  * formed association.
3946  */
sctp_accept(struct sock * sk,int flags,int * err)3947 static struct sock *sctp_accept(struct sock *sk, int flags, int *err)
3948 {
3949 	struct sctp_sock *sp;
3950 	struct sctp_endpoint *ep;
3951 	struct sock *newsk = NULL;
3952 	struct sctp_association *asoc;
3953 	long timeo;
3954 	int error = 0;
3955 
3956 	lock_sock(sk);
3957 
3958 	sp = sctp_sk(sk);
3959 	ep = sp->ep;
3960 
3961 	if (!sctp_style(sk, TCP)) {
3962 		error = -EOPNOTSUPP;
3963 		goto out;
3964 	}
3965 
3966 	if (!sctp_sstate(sk, LISTENING)) {
3967 		error = -EINVAL;
3968 		goto out;
3969 	}
3970 
3971 	timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK);
3972 
3973 	error = sctp_wait_for_accept(sk, timeo);
3974 	if (error)
3975 		goto out;
3976 
3977 	/* We treat the list of associations on the endpoint as the accept
3978 	 * queue and pick the first association on the list.
3979 	 */
3980 	asoc = list_entry(ep->asocs.next, struct sctp_association, asocs);
3981 
3982 	newsk = sp->pf->create_accept_sk(sk, asoc);
3983 	if (!newsk) {
3984 		error = -ENOMEM;
3985 		goto out;
3986 	}
3987 
3988 	/* Populate the fields of the newsk from the oldsk and migrate the
3989 	 * asoc to the newsk.
3990 	 */
3991 	sctp_sock_migrate(sk, newsk, asoc, SCTP_SOCKET_TCP);
3992 
3993 out:
3994 	release_sock(sk);
3995 	*err = error;
3996 	return newsk;
3997 }
3998 
3999 /* The SCTP ioctl handler. */
sctp_ioctl(struct sock * sk,int cmd,unsigned long arg)4000 static int sctp_ioctl(struct sock *sk, int cmd, unsigned long arg)
4001 {
4002 	int rc = -ENOTCONN;
4003 
4004 	lock_sock(sk);
4005 
4006 	/*
4007 	 * SEQPACKET-style sockets in LISTENING state are valid, for
4008 	 * SCTP, so only discard TCP-style sockets in LISTENING state.
4009 	 */
4010 	if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING))
4011 		goto out;
4012 
4013 	switch (cmd) {
4014 	case SIOCINQ: {
4015 		struct sk_buff *skb;
4016 		unsigned int amount = 0;
4017 
4018 		skb = skb_peek(&sk->sk_receive_queue);
4019 		if (skb != NULL) {
4020 			/*
4021 			 * We will only return the amount of this packet since
4022 			 * that is all that will be read.
4023 			 */
4024 			amount = skb->len;
4025 		}
4026 		rc = put_user(amount, (int __user *)arg);
4027 		break;
4028 	}
4029 	default:
4030 		rc = -ENOIOCTLCMD;
4031 		break;
4032 	}
4033 out:
4034 	release_sock(sk);
4035 	return rc;
4036 }
4037 
4038 /* This is the function which gets called during socket creation to
4039  * initialized the SCTP-specific portion of the sock.
4040  * The sock structure should already be zero-filled memory.
4041  */
sctp_init_sock(struct sock * sk)4042 static int sctp_init_sock(struct sock *sk)
4043 {
4044 	struct net *net = sock_net(sk);
4045 	struct sctp_sock *sp;
4046 
4047 	pr_debug("%s: sk:%p\n", __func__, sk);
4048 
4049 	sp = sctp_sk(sk);
4050 
4051 	/* Initialize the SCTP per socket area.  */
4052 	switch (sk->sk_type) {
4053 	case SOCK_SEQPACKET:
4054 		sp->type = SCTP_SOCKET_UDP;
4055 		break;
4056 	case SOCK_STREAM:
4057 		sp->type = SCTP_SOCKET_TCP;
4058 		break;
4059 	default:
4060 		return -ESOCKTNOSUPPORT;
4061 	}
4062 
4063 	/* Initialize default send parameters. These parameters can be
4064 	 * modified with the SCTP_DEFAULT_SEND_PARAM socket option.
4065 	 */
4066 	sp->default_stream = 0;
4067 	sp->default_ppid = 0;
4068 	sp->default_flags = 0;
4069 	sp->default_context = 0;
4070 	sp->default_timetolive = 0;
4071 
4072 	sp->default_rcv_context = 0;
4073 	sp->max_burst = net->sctp.max_burst;
4074 
4075 	sp->sctp_hmac_alg = net->sctp.sctp_hmac_alg;
4076 
4077 	/* Initialize default setup parameters. These parameters
4078 	 * can be modified with the SCTP_INITMSG socket option or
4079 	 * overridden by the SCTP_INIT CMSG.
4080 	 */
4081 	sp->initmsg.sinit_num_ostreams   = sctp_max_outstreams;
4082 	sp->initmsg.sinit_max_instreams  = sctp_max_instreams;
4083 	sp->initmsg.sinit_max_attempts   = net->sctp.max_retrans_init;
4084 	sp->initmsg.sinit_max_init_timeo = net->sctp.rto_max;
4085 
4086 	/* Initialize default RTO related parameters.  These parameters can
4087 	 * be modified for with the SCTP_RTOINFO socket option.
4088 	 */
4089 	sp->rtoinfo.srto_initial = net->sctp.rto_initial;
4090 	sp->rtoinfo.srto_max     = net->sctp.rto_max;
4091 	sp->rtoinfo.srto_min     = net->sctp.rto_min;
4092 
4093 	/* Initialize default association related parameters. These parameters
4094 	 * can be modified with the SCTP_ASSOCINFO socket option.
4095 	 */
4096 	sp->assocparams.sasoc_asocmaxrxt = net->sctp.max_retrans_association;
4097 	sp->assocparams.sasoc_number_peer_destinations = 0;
4098 	sp->assocparams.sasoc_peer_rwnd = 0;
4099 	sp->assocparams.sasoc_local_rwnd = 0;
4100 	sp->assocparams.sasoc_cookie_life = net->sctp.valid_cookie_life;
4101 
4102 	/* Initialize default event subscriptions. By default, all the
4103 	 * options are off.
4104 	 */
4105 	memset(&sp->subscribe, 0, sizeof(struct sctp_event_subscribe));
4106 
4107 	/* Default Peer Address Parameters.  These defaults can
4108 	 * be modified via SCTP_PEER_ADDR_PARAMS
4109 	 */
4110 	sp->hbinterval  = net->sctp.hb_interval;
4111 	sp->pathmaxrxt  = net->sctp.max_retrans_path;
4112 	sp->pathmtu     = 0; /* allow default discovery */
4113 	sp->sackdelay   = net->sctp.sack_timeout;
4114 	sp->sackfreq	= 2;
4115 	sp->param_flags = SPP_HB_ENABLE |
4116 			  SPP_PMTUD_ENABLE |
4117 			  SPP_SACKDELAY_ENABLE;
4118 
4119 	/* If enabled no SCTP message fragmentation will be performed.
4120 	 * Configure through SCTP_DISABLE_FRAGMENTS socket option.
4121 	 */
4122 	sp->disable_fragments = 0;
4123 
4124 	/* Enable Nagle algorithm by default.  */
4125 	sp->nodelay           = 0;
4126 
4127 	sp->recvrcvinfo = 0;
4128 	sp->recvnxtinfo = 0;
4129 
4130 	/* Enable by default. */
4131 	sp->v4mapped          = 1;
4132 
4133 	/* Auto-close idle associations after the configured
4134 	 * number of seconds.  A value of 0 disables this
4135 	 * feature.  Configure through the SCTP_AUTOCLOSE socket option,
4136 	 * for UDP-style sockets only.
4137 	 */
4138 	sp->autoclose         = 0;
4139 
4140 	/* User specified fragmentation limit. */
4141 	sp->user_frag         = 0;
4142 
4143 	sp->adaptation_ind = 0;
4144 
4145 	sp->pf = sctp_get_pf_specific(sk->sk_family);
4146 
4147 	/* Control variables for partial data delivery. */
4148 	atomic_set(&sp->pd_mode, 0);
4149 	skb_queue_head_init(&sp->pd_lobby);
4150 	sp->frag_interleave = 0;
4151 
4152 	/* Create a per socket endpoint structure.  Even if we
4153 	 * change the data structure relationships, this may still
4154 	 * be useful for storing pre-connect address information.
4155 	 */
4156 	sp->ep = sctp_endpoint_new(sk, GFP_KERNEL);
4157 	if (!sp->ep)
4158 		return -ENOMEM;
4159 
4160 	sp->hmac = NULL;
4161 
4162 	sk->sk_destruct = sctp_destruct_sock;
4163 
4164 	SCTP_DBG_OBJCNT_INC(sock);
4165 
4166 	local_bh_disable();
4167 	sk_sockets_allocated_inc(sk);
4168 	sock_prot_inuse_add(net, sk->sk_prot, 1);
4169 
4170 	/* Nothing can fail after this block, otherwise
4171 	 * sctp_destroy_sock() will be called without addr_wq_lock held
4172 	 */
4173 	if (net->sctp.default_auto_asconf) {
4174 		spin_lock(&sock_net(sk)->sctp.addr_wq_lock);
4175 		list_add_tail(&sp->auto_asconf_list,
4176 		    &net->sctp.auto_asconf_splist);
4177 		sp->do_auto_asconf = 1;
4178 		spin_unlock(&sock_net(sk)->sctp.addr_wq_lock);
4179 	} else {
4180 		sp->do_auto_asconf = 0;
4181 	}
4182 
4183 	local_bh_enable();
4184 
4185 	return 0;
4186 }
4187 
4188 /* Cleanup any SCTP per socket resources. Must be called with
4189  * sock_net(sk)->sctp.addr_wq_lock held if sp->do_auto_asconf is true
4190  */
sctp_destroy_sock(struct sock * sk)4191 static void sctp_destroy_sock(struct sock *sk)
4192 {
4193 	struct sctp_sock *sp;
4194 
4195 	pr_debug("%s: sk:%p\n", __func__, sk);
4196 
4197 	/* Release our hold on the endpoint. */
4198 	sp = sctp_sk(sk);
4199 	/* This could happen during socket init, thus we bail out
4200 	 * early, since the rest of the below is not setup either.
4201 	 */
4202 	if (sp->ep == NULL)
4203 		return;
4204 
4205 	if (sp->do_auto_asconf) {
4206 		sp->do_auto_asconf = 0;
4207 		list_del(&sp->auto_asconf_list);
4208 	}
4209 	sctp_endpoint_free(sp->ep);
4210 	local_bh_disable();
4211 	sk_sockets_allocated_dec(sk);
4212 	sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
4213 	local_bh_enable();
4214 }
4215 
4216 /* Triggered when there are no references on the socket anymore */
sctp_destruct_sock(struct sock * sk)4217 static void sctp_destruct_sock(struct sock *sk)
4218 {
4219 	struct sctp_sock *sp = sctp_sk(sk);
4220 
4221 	/* Free up the HMAC transform. */
4222 	crypto_free_hash(sp->hmac);
4223 
4224 	inet_sock_destruct(sk);
4225 }
4226 
4227 /* API 4.1.7 shutdown() - TCP Style Syntax
4228  *     int shutdown(int socket, int how);
4229  *
4230  *     sd      - the socket descriptor of the association to be closed.
4231  *     how     - Specifies the type of shutdown.  The  values  are
4232  *               as follows:
4233  *               SHUT_RD
4234  *                     Disables further receive operations. No SCTP
4235  *                     protocol action is taken.
4236  *               SHUT_WR
4237  *                     Disables further send operations, and initiates
4238  *                     the SCTP shutdown sequence.
4239  *               SHUT_RDWR
4240  *                     Disables further send  and  receive  operations
4241  *                     and initiates the SCTP shutdown sequence.
4242  */
sctp_shutdown(struct sock * sk,int how)4243 static void sctp_shutdown(struct sock *sk, int how)
4244 {
4245 	struct net *net = sock_net(sk);
4246 	struct sctp_endpoint *ep;
4247 	struct sctp_association *asoc;
4248 
4249 	if (!sctp_style(sk, TCP))
4250 		return;
4251 
4252 	if (how & SEND_SHUTDOWN) {
4253 		ep = sctp_sk(sk)->ep;
4254 		if (!list_empty(&ep->asocs)) {
4255 			asoc = list_entry(ep->asocs.next,
4256 					  struct sctp_association, asocs);
4257 			sctp_primitive_SHUTDOWN(net, asoc, NULL);
4258 		}
4259 	}
4260 }
4261 
4262 /* 7.2.1 Association Status (SCTP_STATUS)
4263 
4264  * Applications can retrieve current status information about an
4265  * association, including association state, peer receiver window size,
4266  * number of unacked data chunks, and number of data chunks pending
4267  * receipt.  This information is read-only.
4268  */
sctp_getsockopt_sctp_status(struct sock * sk,int len,char __user * optval,int __user * optlen)4269 static int sctp_getsockopt_sctp_status(struct sock *sk, int len,
4270 				       char __user *optval,
4271 				       int __user *optlen)
4272 {
4273 	struct sctp_status status;
4274 	struct sctp_association *asoc = NULL;
4275 	struct sctp_transport *transport;
4276 	sctp_assoc_t associd;
4277 	int retval = 0;
4278 
4279 	if (len < sizeof(status)) {
4280 		retval = -EINVAL;
4281 		goto out;
4282 	}
4283 
4284 	len = sizeof(status);
4285 	if (copy_from_user(&status, optval, len)) {
4286 		retval = -EFAULT;
4287 		goto out;
4288 	}
4289 
4290 	associd = status.sstat_assoc_id;
4291 	asoc = sctp_id2assoc(sk, associd);
4292 	if (!asoc) {
4293 		retval = -EINVAL;
4294 		goto out;
4295 	}
4296 
4297 	transport = asoc->peer.primary_path;
4298 
4299 	status.sstat_assoc_id = sctp_assoc2id(asoc);
4300 	status.sstat_state = sctp_assoc_to_state(asoc);
4301 	status.sstat_rwnd =  asoc->peer.rwnd;
4302 	status.sstat_unackdata = asoc->unack_data;
4303 
4304 	status.sstat_penddata = sctp_tsnmap_pending(&asoc->peer.tsn_map);
4305 	status.sstat_instrms = asoc->c.sinit_max_instreams;
4306 	status.sstat_outstrms = asoc->c.sinit_num_ostreams;
4307 	status.sstat_fragmentation_point = asoc->frag_point;
4308 	status.sstat_primary.spinfo_assoc_id = sctp_assoc2id(transport->asoc);
4309 	memcpy(&status.sstat_primary.spinfo_address, &transport->ipaddr,
4310 			transport->af_specific->sockaddr_len);
4311 	/* Map ipv4 address into v4-mapped-on-v6 address.  */
4312 	sctp_get_pf_specific(sk->sk_family)->addr_to_user(sctp_sk(sk),
4313 		(union sctp_addr *)&status.sstat_primary.spinfo_address);
4314 	status.sstat_primary.spinfo_state = transport->state;
4315 	status.sstat_primary.spinfo_cwnd = transport->cwnd;
4316 	status.sstat_primary.spinfo_srtt = transport->srtt;
4317 	status.sstat_primary.spinfo_rto = jiffies_to_msecs(transport->rto);
4318 	status.sstat_primary.spinfo_mtu = transport->pathmtu;
4319 
4320 	if (status.sstat_primary.spinfo_state == SCTP_UNKNOWN)
4321 		status.sstat_primary.spinfo_state = SCTP_ACTIVE;
4322 
4323 	if (put_user(len, optlen)) {
4324 		retval = -EFAULT;
4325 		goto out;
4326 	}
4327 
4328 	pr_debug("%s: len:%d, state:%d, rwnd:%d, assoc_id:%d\n",
4329 		 __func__, len, status.sstat_state, status.sstat_rwnd,
4330 		 status.sstat_assoc_id);
4331 
4332 	if (copy_to_user(optval, &status, len)) {
4333 		retval = -EFAULT;
4334 		goto out;
4335 	}
4336 
4337 out:
4338 	return retval;
4339 }
4340 
4341 
4342 /* 7.2.2 Peer Address Information (SCTP_GET_PEER_ADDR_INFO)
4343  *
4344  * Applications can retrieve information about a specific peer address
4345  * of an association, including its reachability state, congestion
4346  * window, and retransmission timer values.  This information is
4347  * read-only.
4348  */
sctp_getsockopt_peer_addr_info(struct sock * sk,int len,char __user * optval,int __user * optlen)4349 static int sctp_getsockopt_peer_addr_info(struct sock *sk, int len,
4350 					  char __user *optval,
4351 					  int __user *optlen)
4352 {
4353 	struct sctp_paddrinfo pinfo;
4354 	struct sctp_transport *transport;
4355 	int retval = 0;
4356 
4357 	if (len < sizeof(pinfo)) {
4358 		retval = -EINVAL;
4359 		goto out;
4360 	}
4361 
4362 	len = sizeof(pinfo);
4363 	if (copy_from_user(&pinfo, optval, len)) {
4364 		retval = -EFAULT;
4365 		goto out;
4366 	}
4367 
4368 	transport = sctp_addr_id2transport(sk, &pinfo.spinfo_address,
4369 					   pinfo.spinfo_assoc_id);
4370 	if (!transport)
4371 		return -EINVAL;
4372 
4373 	pinfo.spinfo_assoc_id = sctp_assoc2id(transport->asoc);
4374 	pinfo.spinfo_state = transport->state;
4375 	pinfo.spinfo_cwnd = transport->cwnd;
4376 	pinfo.spinfo_srtt = transport->srtt;
4377 	pinfo.spinfo_rto = jiffies_to_msecs(transport->rto);
4378 	pinfo.spinfo_mtu = transport->pathmtu;
4379 
4380 	if (pinfo.spinfo_state == SCTP_UNKNOWN)
4381 		pinfo.spinfo_state = SCTP_ACTIVE;
4382 
4383 	if (put_user(len, optlen)) {
4384 		retval = -EFAULT;
4385 		goto out;
4386 	}
4387 
4388 	if (copy_to_user(optval, &pinfo, len)) {
4389 		retval = -EFAULT;
4390 		goto out;
4391 	}
4392 
4393 out:
4394 	return retval;
4395 }
4396 
4397 /* 7.1.12 Enable/Disable message fragmentation (SCTP_DISABLE_FRAGMENTS)
4398  *
4399  * This option is a on/off flag.  If enabled no SCTP message
4400  * fragmentation will be performed.  Instead if a message being sent
4401  * exceeds the current PMTU size, the message will NOT be sent and
4402  * instead a error will be indicated to the user.
4403  */
sctp_getsockopt_disable_fragments(struct sock * sk,int len,char __user * optval,int __user * optlen)4404 static int sctp_getsockopt_disable_fragments(struct sock *sk, int len,
4405 					char __user *optval, int __user *optlen)
4406 {
4407 	int val;
4408 
4409 	if (len < sizeof(int))
4410 		return -EINVAL;
4411 
4412 	len = sizeof(int);
4413 	val = (sctp_sk(sk)->disable_fragments == 1);
4414 	if (put_user(len, optlen))
4415 		return -EFAULT;
4416 	if (copy_to_user(optval, &val, len))
4417 		return -EFAULT;
4418 	return 0;
4419 }
4420 
4421 /* 7.1.15 Set notification and ancillary events (SCTP_EVENTS)
4422  *
4423  * This socket option is used to specify various notifications and
4424  * ancillary data the user wishes to receive.
4425  */
sctp_getsockopt_events(struct sock * sk,int len,char __user * optval,int __user * optlen)4426 static int sctp_getsockopt_events(struct sock *sk, int len, char __user *optval,
4427 				  int __user *optlen)
4428 {
4429 	if (len == 0)
4430 		return -EINVAL;
4431 	if (len > sizeof(struct sctp_event_subscribe))
4432 		len = sizeof(struct sctp_event_subscribe);
4433 	if (put_user(len, optlen))
4434 		return -EFAULT;
4435 	if (copy_to_user(optval, &sctp_sk(sk)->subscribe, len))
4436 		return -EFAULT;
4437 	return 0;
4438 }
4439 
4440 /* 7.1.8 Automatic Close of associations (SCTP_AUTOCLOSE)
4441  *
4442  * This socket option is applicable to the UDP-style socket only.  When
4443  * set it will cause associations that are idle for more than the
4444  * specified number of seconds to automatically close.  An association
4445  * being idle is defined an association that has NOT sent or received
4446  * user data.  The special value of '0' indicates that no automatic
4447  * close of any associations should be performed.  The option expects an
4448  * integer defining the number of seconds of idle time before an
4449  * association is closed.
4450  */
sctp_getsockopt_autoclose(struct sock * sk,int len,char __user * optval,int __user * optlen)4451 static int sctp_getsockopt_autoclose(struct sock *sk, int len, char __user *optval, int __user *optlen)
4452 {
4453 	/* Applicable to UDP-style socket only */
4454 	if (sctp_style(sk, TCP))
4455 		return -EOPNOTSUPP;
4456 	if (len < sizeof(int))
4457 		return -EINVAL;
4458 	len = sizeof(int);
4459 	if (put_user(len, optlen))
4460 		return -EFAULT;
4461 	if (copy_to_user(optval, &sctp_sk(sk)->autoclose, sizeof(int)))
4462 		return -EFAULT;
4463 	return 0;
4464 }
4465 
4466 /* Helper routine to branch off an association to a new socket.  */
sctp_do_peeloff(struct sock * sk,sctp_assoc_t id,struct socket ** sockp)4467 int sctp_do_peeloff(struct sock *sk, sctp_assoc_t id, struct socket **sockp)
4468 {
4469 	struct sctp_association *asoc = sctp_id2assoc(sk, id);
4470 	struct sctp_sock *sp = sctp_sk(sk);
4471 	struct socket *sock;
4472 	int err = 0;
4473 
4474 	/* Do not peel off from one netns to another one. */
4475 	if (!net_eq(current->nsproxy->net_ns, sock_net(sk)))
4476 		return -EINVAL;
4477 
4478 	if (!asoc)
4479 		return -EINVAL;
4480 
4481 	/* An association cannot be branched off from an already peeled-off
4482 	 * socket, nor is this supported for tcp style sockets.
4483 	 */
4484 	if (!sctp_style(sk, UDP))
4485 		return -EINVAL;
4486 
4487 	/* Create a new socket.  */
4488 	err = sock_create(sk->sk_family, SOCK_SEQPACKET, IPPROTO_SCTP, &sock);
4489 	if (err < 0)
4490 		return err;
4491 
4492 	sctp_copy_sock(sock->sk, sk, asoc);
4493 
4494 	/* Make peeled-off sockets more like 1-1 accepted sockets.
4495 	 * Set the daddr and initialize id to something more random
4496 	 */
4497 	sp->pf->to_sk_daddr(&asoc->peer.primary_addr, sk);
4498 
4499 	/* Populate the fields of the newsk from the oldsk and migrate the
4500 	 * asoc to the newsk.
4501 	 */
4502 	sctp_sock_migrate(sk, sock->sk, asoc, SCTP_SOCKET_UDP_HIGH_BANDWIDTH);
4503 
4504 	*sockp = sock;
4505 
4506 	return err;
4507 }
4508 EXPORT_SYMBOL(sctp_do_peeloff);
4509 
sctp_getsockopt_peeloff(struct sock * sk,int len,char __user * optval,int __user * optlen)4510 static int sctp_getsockopt_peeloff(struct sock *sk, int len, char __user *optval, int __user *optlen)
4511 {
4512 	sctp_peeloff_arg_t peeloff;
4513 	struct socket *newsock;
4514 	struct file *newfile;
4515 	int retval = 0;
4516 
4517 	if (len < sizeof(sctp_peeloff_arg_t))
4518 		return -EINVAL;
4519 	len = sizeof(sctp_peeloff_arg_t);
4520 	if (copy_from_user(&peeloff, optval, len))
4521 		return -EFAULT;
4522 
4523 	retval = sctp_do_peeloff(sk, peeloff.associd, &newsock);
4524 	if (retval < 0)
4525 		goto out;
4526 
4527 	/* Map the socket to an unused fd that can be returned to the user.  */
4528 	retval = get_unused_fd_flags(0);
4529 	if (retval < 0) {
4530 		sock_release(newsock);
4531 		goto out;
4532 	}
4533 
4534 	newfile = sock_alloc_file(newsock, 0, NULL);
4535 	if (unlikely(IS_ERR(newfile))) {
4536 		put_unused_fd(retval);
4537 		sock_release(newsock);
4538 		return PTR_ERR(newfile);
4539 	}
4540 
4541 	pr_debug("%s: sk:%p, newsk:%p, sd:%d\n", __func__, sk, newsock->sk,
4542 		 retval);
4543 
4544 	/* Return the fd mapped to the new socket.  */
4545 	if (put_user(len, optlen)) {
4546 		fput(newfile);
4547 		put_unused_fd(retval);
4548 		return -EFAULT;
4549 	}
4550 	peeloff.sd = retval;
4551 	if (copy_to_user(optval, &peeloff, len)) {
4552 		fput(newfile);
4553 		put_unused_fd(retval);
4554 		return -EFAULT;
4555 	}
4556 	fd_install(retval, newfile);
4557 out:
4558 	return retval;
4559 }
4560 
4561 /* 7.1.13 Peer Address Parameters (SCTP_PEER_ADDR_PARAMS)
4562  *
4563  * Applications can enable or disable heartbeats for any peer address of
4564  * an association, modify an address's heartbeat interval, force a
4565  * heartbeat to be sent immediately, and adjust the address's maximum
4566  * number of retransmissions sent before an address is considered
4567  * unreachable.  The following structure is used to access and modify an
4568  * address's parameters:
4569  *
4570  *  struct sctp_paddrparams {
4571  *     sctp_assoc_t            spp_assoc_id;
4572  *     struct sockaddr_storage spp_address;
4573  *     uint32_t                spp_hbinterval;
4574  *     uint16_t                spp_pathmaxrxt;
4575  *     uint32_t                spp_pathmtu;
4576  *     uint32_t                spp_sackdelay;
4577  *     uint32_t                spp_flags;
4578  * };
4579  *
4580  *   spp_assoc_id    - (one-to-many style socket) This is filled in the
4581  *                     application, and identifies the association for
4582  *                     this query.
4583  *   spp_address     - This specifies which address is of interest.
4584  *   spp_hbinterval  - This contains the value of the heartbeat interval,
4585  *                     in milliseconds.  If a  value of zero
4586  *                     is present in this field then no changes are to
4587  *                     be made to this parameter.
4588  *   spp_pathmaxrxt  - This contains the maximum number of
4589  *                     retransmissions before this address shall be
4590  *                     considered unreachable. If a  value of zero
4591  *                     is present in this field then no changes are to
4592  *                     be made to this parameter.
4593  *   spp_pathmtu     - When Path MTU discovery is disabled the value
4594  *                     specified here will be the "fixed" path mtu.
4595  *                     Note that if the spp_address field is empty
4596  *                     then all associations on this address will
4597  *                     have this fixed path mtu set upon them.
4598  *
4599  *   spp_sackdelay   - When delayed sack is enabled, this value specifies
4600  *                     the number of milliseconds that sacks will be delayed
4601  *                     for. This value will apply to all addresses of an
4602  *                     association if the spp_address field is empty. Note
4603  *                     also, that if delayed sack is enabled and this
4604  *                     value is set to 0, no change is made to the last
4605  *                     recorded delayed sack timer value.
4606  *
4607  *   spp_flags       - These flags are used to control various features
4608  *                     on an association. The flag field may contain
4609  *                     zero or more of the following options.
4610  *
4611  *                     SPP_HB_ENABLE  - Enable heartbeats on the
4612  *                     specified address. Note that if the address
4613  *                     field is empty all addresses for the association
4614  *                     have heartbeats enabled upon them.
4615  *
4616  *                     SPP_HB_DISABLE - Disable heartbeats on the
4617  *                     speicifed address. Note that if the address
4618  *                     field is empty all addresses for the association
4619  *                     will have their heartbeats disabled. Note also
4620  *                     that SPP_HB_ENABLE and SPP_HB_DISABLE are
4621  *                     mutually exclusive, only one of these two should
4622  *                     be specified. Enabling both fields will have
4623  *                     undetermined results.
4624  *
4625  *                     SPP_HB_DEMAND - Request a user initiated heartbeat
4626  *                     to be made immediately.
4627  *
4628  *                     SPP_PMTUD_ENABLE - This field will enable PMTU
4629  *                     discovery upon the specified address. Note that
4630  *                     if the address feild is empty then all addresses
4631  *                     on the association are effected.
4632  *
4633  *                     SPP_PMTUD_DISABLE - This field will disable PMTU
4634  *                     discovery upon the specified address. Note that
4635  *                     if the address feild is empty then all addresses
4636  *                     on the association are effected. Not also that
4637  *                     SPP_PMTUD_ENABLE and SPP_PMTUD_DISABLE are mutually
4638  *                     exclusive. Enabling both will have undetermined
4639  *                     results.
4640  *
4641  *                     SPP_SACKDELAY_ENABLE - Setting this flag turns
4642  *                     on delayed sack. The time specified in spp_sackdelay
4643  *                     is used to specify the sack delay for this address. Note
4644  *                     that if spp_address is empty then all addresses will
4645  *                     enable delayed sack and take on the sack delay
4646  *                     value specified in spp_sackdelay.
4647  *                     SPP_SACKDELAY_DISABLE - Setting this flag turns
4648  *                     off delayed sack. If the spp_address field is blank then
4649  *                     delayed sack is disabled for the entire association. Note
4650  *                     also that this field is mutually exclusive to
4651  *                     SPP_SACKDELAY_ENABLE, setting both will have undefined
4652  *                     results.
4653  */
sctp_getsockopt_peer_addr_params(struct sock * sk,int len,char __user * optval,int __user * optlen)4654 static int sctp_getsockopt_peer_addr_params(struct sock *sk, int len,
4655 					    char __user *optval, int __user *optlen)
4656 {
4657 	struct sctp_paddrparams  params;
4658 	struct sctp_transport   *trans = NULL;
4659 	struct sctp_association *asoc = NULL;
4660 	struct sctp_sock        *sp = sctp_sk(sk);
4661 
4662 	if (len < sizeof(struct sctp_paddrparams))
4663 		return -EINVAL;
4664 	len = sizeof(struct sctp_paddrparams);
4665 	if (copy_from_user(&params, optval, len))
4666 		return -EFAULT;
4667 
4668 	/* If an address other than INADDR_ANY is specified, and
4669 	 * no transport is found, then the request is invalid.
4670 	 */
4671 	if (!sctp_is_any(sk, (union sctp_addr *)&params.spp_address)) {
4672 		trans = sctp_addr_id2transport(sk, &params.spp_address,
4673 					       params.spp_assoc_id);
4674 		if (!trans) {
4675 			pr_debug("%s: failed no transport\n", __func__);
4676 			return -EINVAL;
4677 		}
4678 	}
4679 
4680 	/* Get association, if assoc_id != 0 and the socket is a one
4681 	 * to many style socket, and an association was not found, then
4682 	 * the id was invalid.
4683 	 */
4684 	asoc = sctp_id2assoc(sk, params.spp_assoc_id);
4685 	if (!asoc && params.spp_assoc_id && sctp_style(sk, UDP)) {
4686 		pr_debug("%s: failed no association\n", __func__);
4687 		return -EINVAL;
4688 	}
4689 
4690 	if (trans) {
4691 		/* Fetch transport values. */
4692 		params.spp_hbinterval = jiffies_to_msecs(trans->hbinterval);
4693 		params.spp_pathmtu    = trans->pathmtu;
4694 		params.spp_pathmaxrxt = trans->pathmaxrxt;
4695 		params.spp_sackdelay  = jiffies_to_msecs(trans->sackdelay);
4696 
4697 		/*draft-11 doesn't say what to return in spp_flags*/
4698 		params.spp_flags      = trans->param_flags;
4699 	} else if (asoc) {
4700 		/* Fetch association values. */
4701 		params.spp_hbinterval = jiffies_to_msecs(asoc->hbinterval);
4702 		params.spp_pathmtu    = asoc->pathmtu;
4703 		params.spp_pathmaxrxt = asoc->pathmaxrxt;
4704 		params.spp_sackdelay  = jiffies_to_msecs(asoc->sackdelay);
4705 
4706 		/*draft-11 doesn't say what to return in spp_flags*/
4707 		params.spp_flags      = asoc->param_flags;
4708 	} else {
4709 		/* Fetch socket values. */
4710 		params.spp_hbinterval = sp->hbinterval;
4711 		params.spp_pathmtu    = sp->pathmtu;
4712 		params.spp_sackdelay  = sp->sackdelay;
4713 		params.spp_pathmaxrxt = sp->pathmaxrxt;
4714 
4715 		/*draft-11 doesn't say what to return in spp_flags*/
4716 		params.spp_flags      = sp->param_flags;
4717 	}
4718 
4719 	if (copy_to_user(optval, &params, len))
4720 		return -EFAULT;
4721 
4722 	if (put_user(len, optlen))
4723 		return -EFAULT;
4724 
4725 	return 0;
4726 }
4727 
4728 /*
4729  * 7.1.23.  Get or set delayed ack timer (SCTP_DELAYED_SACK)
4730  *
4731  * This option will effect the way delayed acks are performed.  This
4732  * option allows you to get or set the delayed ack time, in
4733  * milliseconds.  It also allows changing the delayed ack frequency.
4734  * Changing the frequency to 1 disables the delayed sack algorithm.  If
4735  * the assoc_id is 0, then this sets or gets the endpoints default
4736  * values.  If the assoc_id field is non-zero, then the set or get
4737  * effects the specified association for the one to many model (the
4738  * assoc_id field is ignored by the one to one model).  Note that if
4739  * sack_delay or sack_freq are 0 when setting this option, then the
4740  * current values will remain unchanged.
4741  *
4742  * struct sctp_sack_info {
4743  *     sctp_assoc_t            sack_assoc_id;
4744  *     uint32_t                sack_delay;
4745  *     uint32_t                sack_freq;
4746  * };
4747  *
4748  * sack_assoc_id -  This parameter, indicates which association the user
4749  *    is performing an action upon.  Note that if this field's value is
4750  *    zero then the endpoints default value is changed (effecting future
4751  *    associations only).
4752  *
4753  * sack_delay -  This parameter contains the number of milliseconds that
4754  *    the user is requesting the delayed ACK timer be set to.  Note that
4755  *    this value is defined in the standard to be between 200 and 500
4756  *    milliseconds.
4757  *
4758  * sack_freq -  This parameter contains the number of packets that must
4759  *    be received before a sack is sent without waiting for the delay
4760  *    timer to expire.  The default value for this is 2, setting this
4761  *    value to 1 will disable the delayed sack algorithm.
4762  */
sctp_getsockopt_delayed_ack(struct sock * sk,int len,char __user * optval,int __user * optlen)4763 static int sctp_getsockopt_delayed_ack(struct sock *sk, int len,
4764 					    char __user *optval,
4765 					    int __user *optlen)
4766 {
4767 	struct sctp_sack_info    params;
4768 	struct sctp_association *asoc = NULL;
4769 	struct sctp_sock        *sp = sctp_sk(sk);
4770 
4771 	if (len >= sizeof(struct sctp_sack_info)) {
4772 		len = sizeof(struct sctp_sack_info);
4773 
4774 		if (copy_from_user(&params, optval, len))
4775 			return -EFAULT;
4776 	} else if (len == sizeof(struct sctp_assoc_value)) {
4777 		pr_warn_ratelimited(DEPRECATED
4778 				    "%s (pid %d) "
4779 				    "Use of struct sctp_assoc_value in delayed_ack socket option.\n"
4780 				    "Use struct sctp_sack_info instead\n",
4781 				    current->comm, task_pid_nr(current));
4782 		if (copy_from_user(&params, optval, len))
4783 			return -EFAULT;
4784 	} else
4785 		return -EINVAL;
4786 
4787 	/* Get association, if sack_assoc_id != 0 and the socket is a one
4788 	 * to many style socket, and an association was not found, then
4789 	 * the id was invalid.
4790 	 */
4791 	asoc = sctp_id2assoc(sk, params.sack_assoc_id);
4792 	if (!asoc && params.sack_assoc_id && sctp_style(sk, UDP))
4793 		return -EINVAL;
4794 
4795 	if (asoc) {
4796 		/* Fetch association values. */
4797 		if (asoc->param_flags & SPP_SACKDELAY_ENABLE) {
4798 			params.sack_delay = jiffies_to_msecs(
4799 				asoc->sackdelay);
4800 			params.sack_freq = asoc->sackfreq;
4801 
4802 		} else {
4803 			params.sack_delay = 0;
4804 			params.sack_freq = 1;
4805 		}
4806 	} else {
4807 		/* Fetch socket values. */
4808 		if (sp->param_flags & SPP_SACKDELAY_ENABLE) {
4809 			params.sack_delay  = sp->sackdelay;
4810 			params.sack_freq = sp->sackfreq;
4811 		} else {
4812 			params.sack_delay  = 0;
4813 			params.sack_freq = 1;
4814 		}
4815 	}
4816 
4817 	if (copy_to_user(optval, &params, len))
4818 		return -EFAULT;
4819 
4820 	if (put_user(len, optlen))
4821 		return -EFAULT;
4822 
4823 	return 0;
4824 }
4825 
4826 /* 7.1.3 Initialization Parameters (SCTP_INITMSG)
4827  *
4828  * Applications can specify protocol parameters for the default association
4829  * initialization.  The option name argument to setsockopt() and getsockopt()
4830  * is SCTP_INITMSG.
4831  *
4832  * Setting initialization parameters is effective only on an unconnected
4833  * socket (for UDP-style sockets only future associations are effected
4834  * by the change).  With TCP-style sockets, this option is inherited by
4835  * sockets derived from a listener socket.
4836  */
sctp_getsockopt_initmsg(struct sock * sk,int len,char __user * optval,int __user * optlen)4837 static int sctp_getsockopt_initmsg(struct sock *sk, int len, char __user *optval, int __user *optlen)
4838 {
4839 	if (len < sizeof(struct sctp_initmsg))
4840 		return -EINVAL;
4841 	len = sizeof(struct sctp_initmsg);
4842 	if (put_user(len, optlen))
4843 		return -EFAULT;
4844 	if (copy_to_user(optval, &sctp_sk(sk)->initmsg, len))
4845 		return -EFAULT;
4846 	return 0;
4847 }
4848 
4849 
sctp_getsockopt_peer_addrs(struct sock * sk,int len,char __user * optval,int __user * optlen)4850 static int sctp_getsockopt_peer_addrs(struct sock *sk, int len,
4851 				      char __user *optval, int __user *optlen)
4852 {
4853 	struct sctp_association *asoc;
4854 	int cnt = 0;
4855 	struct sctp_getaddrs getaddrs;
4856 	struct sctp_transport *from;
4857 	void __user *to;
4858 	union sctp_addr temp;
4859 	struct sctp_sock *sp = sctp_sk(sk);
4860 	int addrlen;
4861 	size_t space_left;
4862 	int bytes_copied;
4863 
4864 	if (len < sizeof(struct sctp_getaddrs))
4865 		return -EINVAL;
4866 
4867 	if (copy_from_user(&getaddrs, optval, sizeof(struct sctp_getaddrs)))
4868 		return -EFAULT;
4869 
4870 	/* For UDP-style sockets, id specifies the association to query.  */
4871 	asoc = sctp_id2assoc(sk, getaddrs.assoc_id);
4872 	if (!asoc)
4873 		return -EINVAL;
4874 
4875 	to = optval + offsetof(struct sctp_getaddrs, addrs);
4876 	space_left = len - offsetof(struct sctp_getaddrs, addrs);
4877 
4878 	list_for_each_entry(from, &asoc->peer.transport_addr_list,
4879 				transports) {
4880 		memcpy(&temp, &from->ipaddr, sizeof(temp));
4881 		addrlen = sctp_get_pf_specific(sk->sk_family)
4882 			      ->addr_to_user(sp, &temp);
4883 		if (space_left < addrlen)
4884 			return -ENOMEM;
4885 		if (copy_to_user(to, &temp, addrlen))
4886 			return -EFAULT;
4887 		to += addrlen;
4888 		cnt++;
4889 		space_left -= addrlen;
4890 	}
4891 
4892 	if (put_user(cnt, &((struct sctp_getaddrs __user *)optval)->addr_num))
4893 		return -EFAULT;
4894 	bytes_copied = ((char __user *)to) - optval;
4895 	if (put_user(bytes_copied, optlen))
4896 		return -EFAULT;
4897 
4898 	return 0;
4899 }
4900 
sctp_copy_laddrs(struct sock * sk,__u16 port,void * to,size_t space_left,int * bytes_copied)4901 static int sctp_copy_laddrs(struct sock *sk, __u16 port, void *to,
4902 			    size_t space_left, int *bytes_copied)
4903 {
4904 	struct sctp_sockaddr_entry *addr;
4905 	union sctp_addr temp;
4906 	int cnt = 0;
4907 	int addrlen;
4908 	struct net *net = sock_net(sk);
4909 
4910 	rcu_read_lock();
4911 	list_for_each_entry_rcu(addr, &net->sctp.local_addr_list, list) {
4912 		if (!addr->valid)
4913 			continue;
4914 
4915 		if ((PF_INET == sk->sk_family) &&
4916 		    (AF_INET6 == addr->a.sa.sa_family))
4917 			continue;
4918 		if ((PF_INET6 == sk->sk_family) &&
4919 		    inet_v6_ipv6only(sk) &&
4920 		    (AF_INET == addr->a.sa.sa_family))
4921 			continue;
4922 		memcpy(&temp, &addr->a, sizeof(temp));
4923 		if (!temp.v4.sin_port)
4924 			temp.v4.sin_port = htons(port);
4925 
4926 		addrlen = sctp_get_pf_specific(sk->sk_family)
4927 			      ->addr_to_user(sctp_sk(sk), &temp);
4928 
4929 		if (space_left < addrlen) {
4930 			cnt =  -ENOMEM;
4931 			break;
4932 		}
4933 		memcpy(to, &temp, addrlen);
4934 
4935 		to += addrlen;
4936 		cnt++;
4937 		space_left -= addrlen;
4938 		*bytes_copied += addrlen;
4939 	}
4940 	rcu_read_unlock();
4941 
4942 	return cnt;
4943 }
4944 
4945 
sctp_getsockopt_local_addrs(struct sock * sk,int len,char __user * optval,int __user * optlen)4946 static int sctp_getsockopt_local_addrs(struct sock *sk, int len,
4947 				       char __user *optval, int __user *optlen)
4948 {
4949 	struct sctp_bind_addr *bp;
4950 	struct sctp_association *asoc;
4951 	int cnt = 0;
4952 	struct sctp_getaddrs getaddrs;
4953 	struct sctp_sockaddr_entry *addr;
4954 	void __user *to;
4955 	union sctp_addr temp;
4956 	struct sctp_sock *sp = sctp_sk(sk);
4957 	int addrlen;
4958 	int err = 0;
4959 	size_t space_left;
4960 	int bytes_copied = 0;
4961 	void *addrs;
4962 	void *buf;
4963 
4964 	if (len < sizeof(struct sctp_getaddrs))
4965 		return -EINVAL;
4966 
4967 	if (copy_from_user(&getaddrs, optval, sizeof(struct sctp_getaddrs)))
4968 		return -EFAULT;
4969 
4970 	/*
4971 	 *  For UDP-style sockets, id specifies the association to query.
4972 	 *  If the id field is set to the value '0' then the locally bound
4973 	 *  addresses are returned without regard to any particular
4974 	 *  association.
4975 	 */
4976 	if (0 == getaddrs.assoc_id) {
4977 		bp = &sctp_sk(sk)->ep->base.bind_addr;
4978 	} else {
4979 		asoc = sctp_id2assoc(sk, getaddrs.assoc_id);
4980 		if (!asoc)
4981 			return -EINVAL;
4982 		bp = &asoc->base.bind_addr;
4983 	}
4984 
4985 	to = optval + offsetof(struct sctp_getaddrs, addrs);
4986 	space_left = len - offsetof(struct sctp_getaddrs, addrs);
4987 
4988 	addrs = kmalloc(space_left, GFP_KERNEL);
4989 	if (!addrs)
4990 		return -ENOMEM;
4991 
4992 	/* If the endpoint is bound to 0.0.0.0 or ::0, get the valid
4993 	 * addresses from the global local address list.
4994 	 */
4995 	if (sctp_list_single_entry(&bp->address_list)) {
4996 		addr = list_entry(bp->address_list.next,
4997 				  struct sctp_sockaddr_entry, list);
4998 		if (sctp_is_any(sk, &addr->a)) {
4999 			cnt = sctp_copy_laddrs(sk, bp->port, addrs,
5000 						space_left, &bytes_copied);
5001 			if (cnt < 0) {
5002 				err = cnt;
5003 				goto out;
5004 			}
5005 			goto copy_getaddrs;
5006 		}
5007 	}
5008 
5009 	buf = addrs;
5010 	/* Protection on the bound address list is not needed since
5011 	 * in the socket option context we hold a socket lock and
5012 	 * thus the bound address list can't change.
5013 	 */
5014 	list_for_each_entry(addr, &bp->address_list, list) {
5015 		memcpy(&temp, &addr->a, sizeof(temp));
5016 		addrlen = sctp_get_pf_specific(sk->sk_family)
5017 			      ->addr_to_user(sp, &temp);
5018 		if (space_left < addrlen) {
5019 			err =  -ENOMEM; /*fixme: right error?*/
5020 			goto out;
5021 		}
5022 		memcpy(buf, &temp, addrlen);
5023 		buf += addrlen;
5024 		bytes_copied += addrlen;
5025 		cnt++;
5026 		space_left -= addrlen;
5027 	}
5028 
5029 copy_getaddrs:
5030 	if (copy_to_user(to, addrs, bytes_copied)) {
5031 		err = -EFAULT;
5032 		goto out;
5033 	}
5034 	if (put_user(cnt, &((struct sctp_getaddrs __user *)optval)->addr_num)) {
5035 		err = -EFAULT;
5036 		goto out;
5037 	}
5038 	if (put_user(bytes_copied, optlen))
5039 		err = -EFAULT;
5040 out:
5041 	kfree(addrs);
5042 	return err;
5043 }
5044 
5045 /* 7.1.10 Set Primary Address (SCTP_PRIMARY_ADDR)
5046  *
5047  * Requests that the local SCTP stack use the enclosed peer address as
5048  * the association primary.  The enclosed address must be one of the
5049  * association peer's addresses.
5050  */
sctp_getsockopt_primary_addr(struct sock * sk,int len,char __user * optval,int __user * optlen)5051 static int sctp_getsockopt_primary_addr(struct sock *sk, int len,
5052 					char __user *optval, int __user *optlen)
5053 {
5054 	struct sctp_prim prim;
5055 	struct sctp_association *asoc;
5056 	struct sctp_sock *sp = sctp_sk(sk);
5057 
5058 	if (len < sizeof(struct sctp_prim))
5059 		return -EINVAL;
5060 
5061 	len = sizeof(struct sctp_prim);
5062 
5063 	if (copy_from_user(&prim, optval, len))
5064 		return -EFAULT;
5065 
5066 	asoc = sctp_id2assoc(sk, prim.ssp_assoc_id);
5067 	if (!asoc)
5068 		return -EINVAL;
5069 
5070 	if (!asoc->peer.primary_path)
5071 		return -ENOTCONN;
5072 
5073 	memcpy(&prim.ssp_addr, &asoc->peer.primary_path->ipaddr,
5074 		asoc->peer.primary_path->af_specific->sockaddr_len);
5075 
5076 	sctp_get_pf_specific(sk->sk_family)->addr_to_user(sp,
5077 			(union sctp_addr *)&prim.ssp_addr);
5078 
5079 	if (put_user(len, optlen))
5080 		return -EFAULT;
5081 	if (copy_to_user(optval, &prim, len))
5082 		return -EFAULT;
5083 
5084 	return 0;
5085 }
5086 
5087 /*
5088  * 7.1.11  Set Adaptation Layer Indicator (SCTP_ADAPTATION_LAYER)
5089  *
5090  * Requests that the local endpoint set the specified Adaptation Layer
5091  * Indication parameter for all future INIT and INIT-ACK exchanges.
5092  */
sctp_getsockopt_adaptation_layer(struct sock * sk,int len,char __user * optval,int __user * optlen)5093 static int sctp_getsockopt_adaptation_layer(struct sock *sk, int len,
5094 				  char __user *optval, int __user *optlen)
5095 {
5096 	struct sctp_setadaptation adaptation;
5097 
5098 	if (len < sizeof(struct sctp_setadaptation))
5099 		return -EINVAL;
5100 
5101 	len = sizeof(struct sctp_setadaptation);
5102 
5103 	adaptation.ssb_adaptation_ind = sctp_sk(sk)->adaptation_ind;
5104 
5105 	if (put_user(len, optlen))
5106 		return -EFAULT;
5107 	if (copy_to_user(optval, &adaptation, len))
5108 		return -EFAULT;
5109 
5110 	return 0;
5111 }
5112 
5113 /*
5114  *
5115  * 7.1.14 Set default send parameters (SCTP_DEFAULT_SEND_PARAM)
5116  *
5117  *   Applications that wish to use the sendto() system call may wish to
5118  *   specify a default set of parameters that would normally be supplied
5119  *   through the inclusion of ancillary data.  This socket option allows
5120  *   such an application to set the default sctp_sndrcvinfo structure.
5121 
5122 
5123  *   The application that wishes to use this socket option simply passes
5124  *   in to this call the sctp_sndrcvinfo structure defined in Section
5125  *   5.2.2) The input parameters accepted by this call include
5126  *   sinfo_stream, sinfo_flags, sinfo_ppid, sinfo_context,
5127  *   sinfo_timetolive.  The user must provide the sinfo_assoc_id field in
5128  *   to this call if the caller is using the UDP model.
5129  *
5130  *   For getsockopt, it get the default sctp_sndrcvinfo structure.
5131  */
sctp_getsockopt_default_send_param(struct sock * sk,int len,char __user * optval,int __user * optlen)5132 static int sctp_getsockopt_default_send_param(struct sock *sk,
5133 					int len, char __user *optval,
5134 					int __user *optlen)
5135 {
5136 	struct sctp_sock *sp = sctp_sk(sk);
5137 	struct sctp_association *asoc;
5138 	struct sctp_sndrcvinfo info;
5139 
5140 	if (len < sizeof(info))
5141 		return -EINVAL;
5142 
5143 	len = sizeof(info);
5144 
5145 	if (copy_from_user(&info, optval, len))
5146 		return -EFAULT;
5147 
5148 	asoc = sctp_id2assoc(sk, info.sinfo_assoc_id);
5149 	if (!asoc && info.sinfo_assoc_id && sctp_style(sk, UDP))
5150 		return -EINVAL;
5151 	if (asoc) {
5152 		info.sinfo_stream = asoc->default_stream;
5153 		info.sinfo_flags = asoc->default_flags;
5154 		info.sinfo_ppid = asoc->default_ppid;
5155 		info.sinfo_context = asoc->default_context;
5156 		info.sinfo_timetolive = asoc->default_timetolive;
5157 	} else {
5158 		info.sinfo_stream = sp->default_stream;
5159 		info.sinfo_flags = sp->default_flags;
5160 		info.sinfo_ppid = sp->default_ppid;
5161 		info.sinfo_context = sp->default_context;
5162 		info.sinfo_timetolive = sp->default_timetolive;
5163 	}
5164 
5165 	if (put_user(len, optlen))
5166 		return -EFAULT;
5167 	if (copy_to_user(optval, &info, len))
5168 		return -EFAULT;
5169 
5170 	return 0;
5171 }
5172 
5173 /* RFC6458, Section 8.1.31. Set/get Default Send Parameters
5174  * (SCTP_DEFAULT_SNDINFO)
5175  */
sctp_getsockopt_default_sndinfo(struct sock * sk,int len,char __user * optval,int __user * optlen)5176 static int sctp_getsockopt_default_sndinfo(struct sock *sk, int len,
5177 					   char __user *optval,
5178 					   int __user *optlen)
5179 {
5180 	struct sctp_sock *sp = sctp_sk(sk);
5181 	struct sctp_association *asoc;
5182 	struct sctp_sndinfo info;
5183 
5184 	if (len < sizeof(info))
5185 		return -EINVAL;
5186 
5187 	len = sizeof(info);
5188 
5189 	if (copy_from_user(&info, optval, len))
5190 		return -EFAULT;
5191 
5192 	asoc = sctp_id2assoc(sk, info.snd_assoc_id);
5193 	if (!asoc && info.snd_assoc_id && sctp_style(sk, UDP))
5194 		return -EINVAL;
5195 	if (asoc) {
5196 		info.snd_sid = asoc->default_stream;
5197 		info.snd_flags = asoc->default_flags;
5198 		info.snd_ppid = asoc->default_ppid;
5199 		info.snd_context = asoc->default_context;
5200 	} else {
5201 		info.snd_sid = sp->default_stream;
5202 		info.snd_flags = sp->default_flags;
5203 		info.snd_ppid = sp->default_ppid;
5204 		info.snd_context = sp->default_context;
5205 	}
5206 
5207 	if (put_user(len, optlen))
5208 		return -EFAULT;
5209 	if (copy_to_user(optval, &info, len))
5210 		return -EFAULT;
5211 
5212 	return 0;
5213 }
5214 
5215 /*
5216  *
5217  * 7.1.5 SCTP_NODELAY
5218  *
5219  * Turn on/off any Nagle-like algorithm.  This means that packets are
5220  * generally sent as soon as possible and no unnecessary delays are
5221  * introduced, at the cost of more packets in the network.  Expects an
5222  * integer boolean flag.
5223  */
5224 
sctp_getsockopt_nodelay(struct sock * sk,int len,char __user * optval,int __user * optlen)5225 static int sctp_getsockopt_nodelay(struct sock *sk, int len,
5226 				   char __user *optval, int __user *optlen)
5227 {
5228 	int val;
5229 
5230 	if (len < sizeof(int))
5231 		return -EINVAL;
5232 
5233 	len = sizeof(int);
5234 	val = (sctp_sk(sk)->nodelay == 1);
5235 	if (put_user(len, optlen))
5236 		return -EFAULT;
5237 	if (copy_to_user(optval, &val, len))
5238 		return -EFAULT;
5239 	return 0;
5240 }
5241 
5242 /*
5243  *
5244  * 7.1.1 SCTP_RTOINFO
5245  *
5246  * The protocol parameters used to initialize and bound retransmission
5247  * timeout (RTO) are tunable. sctp_rtoinfo structure is used to access
5248  * and modify these parameters.
5249  * All parameters are time values, in milliseconds.  A value of 0, when
5250  * modifying the parameters, indicates that the current value should not
5251  * be changed.
5252  *
5253  */
sctp_getsockopt_rtoinfo(struct sock * sk,int len,char __user * optval,int __user * optlen)5254 static int sctp_getsockopt_rtoinfo(struct sock *sk, int len,
5255 				char __user *optval,
5256 				int __user *optlen) {
5257 	struct sctp_rtoinfo rtoinfo;
5258 	struct sctp_association *asoc;
5259 
5260 	if (len < sizeof (struct sctp_rtoinfo))
5261 		return -EINVAL;
5262 
5263 	len = sizeof(struct sctp_rtoinfo);
5264 
5265 	if (copy_from_user(&rtoinfo, optval, len))
5266 		return -EFAULT;
5267 
5268 	asoc = sctp_id2assoc(sk, rtoinfo.srto_assoc_id);
5269 
5270 	if (!asoc && rtoinfo.srto_assoc_id && sctp_style(sk, UDP))
5271 		return -EINVAL;
5272 
5273 	/* Values corresponding to the specific association. */
5274 	if (asoc) {
5275 		rtoinfo.srto_initial = jiffies_to_msecs(asoc->rto_initial);
5276 		rtoinfo.srto_max = jiffies_to_msecs(asoc->rto_max);
5277 		rtoinfo.srto_min = jiffies_to_msecs(asoc->rto_min);
5278 	} else {
5279 		/* Values corresponding to the endpoint. */
5280 		struct sctp_sock *sp = sctp_sk(sk);
5281 
5282 		rtoinfo.srto_initial = sp->rtoinfo.srto_initial;
5283 		rtoinfo.srto_max = sp->rtoinfo.srto_max;
5284 		rtoinfo.srto_min = sp->rtoinfo.srto_min;
5285 	}
5286 
5287 	if (put_user(len, optlen))
5288 		return -EFAULT;
5289 
5290 	if (copy_to_user(optval, &rtoinfo, len))
5291 		return -EFAULT;
5292 
5293 	return 0;
5294 }
5295 
5296 /*
5297  *
5298  * 7.1.2 SCTP_ASSOCINFO
5299  *
5300  * This option is used to tune the maximum retransmission attempts
5301  * of the association.
5302  * Returns an error if the new association retransmission value is
5303  * greater than the sum of the retransmission value  of the peer.
5304  * See [SCTP] for more information.
5305  *
5306  */
sctp_getsockopt_associnfo(struct sock * sk,int len,char __user * optval,int __user * optlen)5307 static int sctp_getsockopt_associnfo(struct sock *sk, int len,
5308 				     char __user *optval,
5309 				     int __user *optlen)
5310 {
5311 
5312 	struct sctp_assocparams assocparams;
5313 	struct sctp_association *asoc;
5314 	struct list_head *pos;
5315 	int cnt = 0;
5316 
5317 	if (len < sizeof (struct sctp_assocparams))
5318 		return -EINVAL;
5319 
5320 	len = sizeof(struct sctp_assocparams);
5321 
5322 	if (copy_from_user(&assocparams, optval, len))
5323 		return -EFAULT;
5324 
5325 	asoc = sctp_id2assoc(sk, assocparams.sasoc_assoc_id);
5326 
5327 	if (!asoc && assocparams.sasoc_assoc_id && sctp_style(sk, UDP))
5328 		return -EINVAL;
5329 
5330 	/* Values correspoinding to the specific association */
5331 	if (asoc) {
5332 		assocparams.sasoc_asocmaxrxt = asoc->max_retrans;
5333 		assocparams.sasoc_peer_rwnd = asoc->peer.rwnd;
5334 		assocparams.sasoc_local_rwnd = asoc->a_rwnd;
5335 		assocparams.sasoc_cookie_life = ktime_to_ms(asoc->cookie_life);
5336 
5337 		list_for_each(pos, &asoc->peer.transport_addr_list) {
5338 			cnt++;
5339 		}
5340 
5341 		assocparams.sasoc_number_peer_destinations = cnt;
5342 	} else {
5343 		/* Values corresponding to the endpoint */
5344 		struct sctp_sock *sp = sctp_sk(sk);
5345 
5346 		assocparams.sasoc_asocmaxrxt = sp->assocparams.sasoc_asocmaxrxt;
5347 		assocparams.sasoc_peer_rwnd = sp->assocparams.sasoc_peer_rwnd;
5348 		assocparams.sasoc_local_rwnd = sp->assocparams.sasoc_local_rwnd;
5349 		assocparams.sasoc_cookie_life =
5350 					sp->assocparams.sasoc_cookie_life;
5351 		assocparams.sasoc_number_peer_destinations =
5352 					sp->assocparams.
5353 					sasoc_number_peer_destinations;
5354 	}
5355 
5356 	if (put_user(len, optlen))
5357 		return -EFAULT;
5358 
5359 	if (copy_to_user(optval, &assocparams, len))
5360 		return -EFAULT;
5361 
5362 	return 0;
5363 }
5364 
5365 /*
5366  * 7.1.16 Set/clear IPv4 mapped addresses (SCTP_I_WANT_MAPPED_V4_ADDR)
5367  *
5368  * This socket option is a boolean flag which turns on or off mapped V4
5369  * addresses.  If this option is turned on and the socket is type
5370  * PF_INET6, then IPv4 addresses will be mapped to V6 representation.
5371  * If this option is turned off, then no mapping will be done of V4
5372  * addresses and a user will receive both PF_INET6 and PF_INET type
5373  * addresses on the socket.
5374  */
sctp_getsockopt_mappedv4(struct sock * sk,int len,char __user * optval,int __user * optlen)5375 static int sctp_getsockopt_mappedv4(struct sock *sk, int len,
5376 				    char __user *optval, int __user *optlen)
5377 {
5378 	int val;
5379 	struct sctp_sock *sp = sctp_sk(sk);
5380 
5381 	if (len < sizeof(int))
5382 		return -EINVAL;
5383 
5384 	len = sizeof(int);
5385 	val = sp->v4mapped;
5386 	if (put_user(len, optlen))
5387 		return -EFAULT;
5388 	if (copy_to_user(optval, &val, len))
5389 		return -EFAULT;
5390 
5391 	return 0;
5392 }
5393 
5394 /*
5395  * 7.1.29.  Set or Get the default context (SCTP_CONTEXT)
5396  * (chapter and verse is quoted at sctp_setsockopt_context())
5397  */
sctp_getsockopt_context(struct sock * sk,int len,char __user * optval,int __user * optlen)5398 static int sctp_getsockopt_context(struct sock *sk, int len,
5399 				   char __user *optval, int __user *optlen)
5400 {
5401 	struct sctp_assoc_value params;
5402 	struct sctp_sock *sp;
5403 	struct sctp_association *asoc;
5404 
5405 	if (len < sizeof(struct sctp_assoc_value))
5406 		return -EINVAL;
5407 
5408 	len = sizeof(struct sctp_assoc_value);
5409 
5410 	if (copy_from_user(&params, optval, len))
5411 		return -EFAULT;
5412 
5413 	sp = sctp_sk(sk);
5414 
5415 	if (params.assoc_id != 0) {
5416 		asoc = sctp_id2assoc(sk, params.assoc_id);
5417 		if (!asoc)
5418 			return -EINVAL;
5419 		params.assoc_value = asoc->default_rcv_context;
5420 	} else {
5421 		params.assoc_value = sp->default_rcv_context;
5422 	}
5423 
5424 	if (put_user(len, optlen))
5425 		return -EFAULT;
5426 	if (copy_to_user(optval, &params, len))
5427 		return -EFAULT;
5428 
5429 	return 0;
5430 }
5431 
5432 /*
5433  * 8.1.16.  Get or Set the Maximum Fragmentation Size (SCTP_MAXSEG)
5434  * This option will get or set the maximum size to put in any outgoing
5435  * SCTP DATA chunk.  If a message is larger than this size it will be
5436  * fragmented by SCTP into the specified size.  Note that the underlying
5437  * SCTP implementation may fragment into smaller sized chunks when the
5438  * PMTU of the underlying association is smaller than the value set by
5439  * the user.  The default value for this option is '0' which indicates
5440  * the user is NOT limiting fragmentation and only the PMTU will effect
5441  * SCTP's choice of DATA chunk size.  Note also that values set larger
5442  * than the maximum size of an IP datagram will effectively let SCTP
5443  * control fragmentation (i.e. the same as setting this option to 0).
5444  *
5445  * The following structure is used to access and modify this parameter:
5446  *
5447  * struct sctp_assoc_value {
5448  *   sctp_assoc_t assoc_id;
5449  *   uint32_t assoc_value;
5450  * };
5451  *
5452  * assoc_id:  This parameter is ignored for one-to-one style sockets.
5453  *    For one-to-many style sockets this parameter indicates which
5454  *    association the user is performing an action upon.  Note that if
5455  *    this field's value is zero then the endpoints default value is
5456  *    changed (effecting future associations only).
5457  * assoc_value:  This parameter specifies the maximum size in bytes.
5458  */
sctp_getsockopt_maxseg(struct sock * sk,int len,char __user * optval,int __user * optlen)5459 static int sctp_getsockopt_maxseg(struct sock *sk, int len,
5460 				  char __user *optval, int __user *optlen)
5461 {
5462 	struct sctp_assoc_value params;
5463 	struct sctp_association *asoc;
5464 
5465 	if (len == sizeof(int)) {
5466 		pr_warn_ratelimited(DEPRECATED
5467 				    "%s (pid %d) "
5468 				    "Use of int in maxseg socket option.\n"
5469 				    "Use struct sctp_assoc_value instead\n",
5470 				    current->comm, task_pid_nr(current));
5471 		params.assoc_id = 0;
5472 	} else if (len >= sizeof(struct sctp_assoc_value)) {
5473 		len = sizeof(struct sctp_assoc_value);
5474 		if (copy_from_user(&params, optval, sizeof(params)))
5475 			return -EFAULT;
5476 	} else
5477 		return -EINVAL;
5478 
5479 	asoc = sctp_id2assoc(sk, params.assoc_id);
5480 	if (!asoc && params.assoc_id && sctp_style(sk, UDP))
5481 		return -EINVAL;
5482 
5483 	if (asoc)
5484 		params.assoc_value = asoc->frag_point;
5485 	else
5486 		params.assoc_value = sctp_sk(sk)->user_frag;
5487 
5488 	if (put_user(len, optlen))
5489 		return -EFAULT;
5490 	if (len == sizeof(int)) {
5491 		if (copy_to_user(optval, &params.assoc_value, len))
5492 			return -EFAULT;
5493 	} else {
5494 		if (copy_to_user(optval, &params, len))
5495 			return -EFAULT;
5496 	}
5497 
5498 	return 0;
5499 }
5500 
5501 /*
5502  * 7.1.24.  Get or set fragmented interleave (SCTP_FRAGMENT_INTERLEAVE)
5503  * (chapter and verse is quoted at sctp_setsockopt_fragment_interleave())
5504  */
sctp_getsockopt_fragment_interleave(struct sock * sk,int len,char __user * optval,int __user * optlen)5505 static int sctp_getsockopt_fragment_interleave(struct sock *sk, int len,
5506 					       char __user *optval, int __user *optlen)
5507 {
5508 	int val;
5509 
5510 	if (len < sizeof(int))
5511 		return -EINVAL;
5512 
5513 	len = sizeof(int);
5514 
5515 	val = sctp_sk(sk)->frag_interleave;
5516 	if (put_user(len, optlen))
5517 		return -EFAULT;
5518 	if (copy_to_user(optval, &val, len))
5519 		return -EFAULT;
5520 
5521 	return 0;
5522 }
5523 
5524 /*
5525  * 7.1.25.  Set or Get the sctp partial delivery point
5526  * (chapter and verse is quoted at sctp_setsockopt_partial_delivery_point())
5527  */
sctp_getsockopt_partial_delivery_point(struct sock * sk,int len,char __user * optval,int __user * optlen)5528 static int sctp_getsockopt_partial_delivery_point(struct sock *sk, int len,
5529 						  char __user *optval,
5530 						  int __user *optlen)
5531 {
5532 	u32 val;
5533 
5534 	if (len < sizeof(u32))
5535 		return -EINVAL;
5536 
5537 	len = sizeof(u32);
5538 
5539 	val = sctp_sk(sk)->pd_point;
5540 	if (put_user(len, optlen))
5541 		return -EFAULT;
5542 	if (copy_to_user(optval, &val, len))
5543 		return -EFAULT;
5544 
5545 	return 0;
5546 }
5547 
5548 /*
5549  * 7.1.28.  Set or Get the maximum burst (SCTP_MAX_BURST)
5550  * (chapter and verse is quoted at sctp_setsockopt_maxburst())
5551  */
sctp_getsockopt_maxburst(struct sock * sk,int len,char __user * optval,int __user * optlen)5552 static int sctp_getsockopt_maxburst(struct sock *sk, int len,
5553 				    char __user *optval,
5554 				    int __user *optlen)
5555 {
5556 	struct sctp_assoc_value params;
5557 	struct sctp_sock *sp;
5558 	struct sctp_association *asoc;
5559 
5560 	if (len == sizeof(int)) {
5561 		pr_warn_ratelimited(DEPRECATED
5562 				    "%s (pid %d) "
5563 				    "Use of int in max_burst socket option.\n"
5564 				    "Use struct sctp_assoc_value instead\n",
5565 				    current->comm, task_pid_nr(current));
5566 		params.assoc_id = 0;
5567 	} else if (len >= sizeof(struct sctp_assoc_value)) {
5568 		len = sizeof(struct sctp_assoc_value);
5569 		if (copy_from_user(&params, optval, len))
5570 			return -EFAULT;
5571 	} else
5572 		return -EINVAL;
5573 
5574 	sp = sctp_sk(sk);
5575 
5576 	if (params.assoc_id != 0) {
5577 		asoc = sctp_id2assoc(sk, params.assoc_id);
5578 		if (!asoc)
5579 			return -EINVAL;
5580 		params.assoc_value = asoc->max_burst;
5581 	} else
5582 		params.assoc_value = sp->max_burst;
5583 
5584 	if (len == sizeof(int)) {
5585 		if (copy_to_user(optval, &params.assoc_value, len))
5586 			return -EFAULT;
5587 	} else {
5588 		if (copy_to_user(optval, &params, len))
5589 			return -EFAULT;
5590 	}
5591 
5592 	return 0;
5593 
5594 }
5595 
sctp_getsockopt_hmac_ident(struct sock * sk,int len,char __user * optval,int __user * optlen)5596 static int sctp_getsockopt_hmac_ident(struct sock *sk, int len,
5597 				    char __user *optval, int __user *optlen)
5598 {
5599 	struct sctp_endpoint *ep = sctp_sk(sk)->ep;
5600 	struct sctp_hmacalgo  __user *p = (void __user *)optval;
5601 	struct sctp_hmac_algo_param *hmacs;
5602 	__u16 data_len = 0;
5603 	u32 num_idents;
5604 
5605 	if (!ep->auth_enable)
5606 		return -EACCES;
5607 
5608 	hmacs = ep->auth_hmacs_list;
5609 	data_len = ntohs(hmacs->param_hdr.length) - sizeof(sctp_paramhdr_t);
5610 
5611 	if (len < sizeof(struct sctp_hmacalgo) + data_len)
5612 		return -EINVAL;
5613 
5614 	len = sizeof(struct sctp_hmacalgo) + data_len;
5615 	num_idents = data_len / sizeof(u16);
5616 
5617 	if (put_user(len, optlen))
5618 		return -EFAULT;
5619 	if (put_user(num_idents, &p->shmac_num_idents))
5620 		return -EFAULT;
5621 	if (copy_to_user(p->shmac_idents, hmacs->hmac_ids, data_len))
5622 		return -EFAULT;
5623 	return 0;
5624 }
5625 
sctp_getsockopt_active_key(struct sock * sk,int len,char __user * optval,int __user * optlen)5626 static int sctp_getsockopt_active_key(struct sock *sk, int len,
5627 				    char __user *optval, int __user *optlen)
5628 {
5629 	struct sctp_endpoint *ep = sctp_sk(sk)->ep;
5630 	struct sctp_authkeyid val;
5631 	struct sctp_association *asoc;
5632 
5633 	if (!ep->auth_enable)
5634 		return -EACCES;
5635 
5636 	if (len < sizeof(struct sctp_authkeyid))
5637 		return -EINVAL;
5638 	if (copy_from_user(&val, optval, sizeof(struct sctp_authkeyid)))
5639 		return -EFAULT;
5640 
5641 	asoc = sctp_id2assoc(sk, val.scact_assoc_id);
5642 	if (!asoc && val.scact_assoc_id && sctp_style(sk, UDP))
5643 		return -EINVAL;
5644 
5645 	if (asoc)
5646 		val.scact_keynumber = asoc->active_key_id;
5647 	else
5648 		val.scact_keynumber = ep->active_key_id;
5649 
5650 	len = sizeof(struct sctp_authkeyid);
5651 	if (put_user(len, optlen))
5652 		return -EFAULT;
5653 	if (copy_to_user(optval, &val, len))
5654 		return -EFAULT;
5655 
5656 	return 0;
5657 }
5658 
sctp_getsockopt_peer_auth_chunks(struct sock * sk,int len,char __user * optval,int __user * optlen)5659 static int sctp_getsockopt_peer_auth_chunks(struct sock *sk, int len,
5660 				    char __user *optval, int __user *optlen)
5661 {
5662 	struct sctp_endpoint *ep = sctp_sk(sk)->ep;
5663 	struct sctp_authchunks __user *p = (void __user *)optval;
5664 	struct sctp_authchunks val;
5665 	struct sctp_association *asoc;
5666 	struct sctp_chunks_param *ch;
5667 	u32    num_chunks = 0;
5668 	char __user *to;
5669 
5670 	if (!ep->auth_enable)
5671 		return -EACCES;
5672 
5673 	if (len < sizeof(struct sctp_authchunks))
5674 		return -EINVAL;
5675 
5676 	if (copy_from_user(&val, optval, sizeof(struct sctp_authchunks)))
5677 		return -EFAULT;
5678 
5679 	to = p->gauth_chunks;
5680 	asoc = sctp_id2assoc(sk, val.gauth_assoc_id);
5681 	if (!asoc)
5682 		return -EINVAL;
5683 
5684 	ch = asoc->peer.peer_chunks;
5685 	if (!ch)
5686 		goto num;
5687 
5688 	/* See if the user provided enough room for all the data */
5689 	num_chunks = ntohs(ch->param_hdr.length) - sizeof(sctp_paramhdr_t);
5690 	if (len < num_chunks)
5691 		return -EINVAL;
5692 
5693 	if (copy_to_user(to, ch->chunks, num_chunks))
5694 		return -EFAULT;
5695 num:
5696 	len = sizeof(struct sctp_authchunks) + num_chunks;
5697 	if (put_user(len, optlen))
5698 		return -EFAULT;
5699 	if (put_user(num_chunks, &p->gauth_number_of_chunks))
5700 		return -EFAULT;
5701 	return 0;
5702 }
5703 
sctp_getsockopt_local_auth_chunks(struct sock * sk,int len,char __user * optval,int __user * optlen)5704 static int sctp_getsockopt_local_auth_chunks(struct sock *sk, int len,
5705 				    char __user *optval, int __user *optlen)
5706 {
5707 	struct sctp_endpoint *ep = sctp_sk(sk)->ep;
5708 	struct sctp_authchunks __user *p = (void __user *)optval;
5709 	struct sctp_authchunks val;
5710 	struct sctp_association *asoc;
5711 	struct sctp_chunks_param *ch;
5712 	u32    num_chunks = 0;
5713 	char __user *to;
5714 
5715 	if (!ep->auth_enable)
5716 		return -EACCES;
5717 
5718 	if (len < sizeof(struct sctp_authchunks))
5719 		return -EINVAL;
5720 
5721 	if (copy_from_user(&val, optval, sizeof(struct sctp_authchunks)))
5722 		return -EFAULT;
5723 
5724 	to = p->gauth_chunks;
5725 	asoc = sctp_id2assoc(sk, val.gauth_assoc_id);
5726 	if (!asoc && val.gauth_assoc_id && sctp_style(sk, UDP))
5727 		return -EINVAL;
5728 
5729 	if (asoc)
5730 		ch = (struct sctp_chunks_param *)asoc->c.auth_chunks;
5731 	else
5732 		ch = ep->auth_chunk_list;
5733 
5734 	if (!ch)
5735 		goto num;
5736 
5737 	num_chunks = ntohs(ch->param_hdr.length) - sizeof(sctp_paramhdr_t);
5738 	if (len < sizeof(struct sctp_authchunks) + num_chunks)
5739 		return -EINVAL;
5740 
5741 	if (copy_to_user(to, ch->chunks, num_chunks))
5742 		return -EFAULT;
5743 num:
5744 	len = sizeof(struct sctp_authchunks) + num_chunks;
5745 	if (put_user(len, optlen))
5746 		return -EFAULT;
5747 	if (put_user(num_chunks, &p->gauth_number_of_chunks))
5748 		return -EFAULT;
5749 
5750 	return 0;
5751 }
5752 
5753 /*
5754  * 8.2.5.  Get the Current Number of Associations (SCTP_GET_ASSOC_NUMBER)
5755  * This option gets the current number of associations that are attached
5756  * to a one-to-many style socket.  The option value is an uint32_t.
5757  */
sctp_getsockopt_assoc_number(struct sock * sk,int len,char __user * optval,int __user * optlen)5758 static int sctp_getsockopt_assoc_number(struct sock *sk, int len,
5759 				    char __user *optval, int __user *optlen)
5760 {
5761 	struct sctp_sock *sp = sctp_sk(sk);
5762 	struct sctp_association *asoc;
5763 	u32 val = 0;
5764 
5765 	if (sctp_style(sk, TCP))
5766 		return -EOPNOTSUPP;
5767 
5768 	if (len < sizeof(u32))
5769 		return -EINVAL;
5770 
5771 	len = sizeof(u32);
5772 
5773 	list_for_each_entry(asoc, &(sp->ep->asocs), asocs) {
5774 		val++;
5775 	}
5776 
5777 	if (put_user(len, optlen))
5778 		return -EFAULT;
5779 	if (copy_to_user(optval, &val, len))
5780 		return -EFAULT;
5781 
5782 	return 0;
5783 }
5784 
5785 /*
5786  * 8.1.23 SCTP_AUTO_ASCONF
5787  * See the corresponding setsockopt entry as description
5788  */
sctp_getsockopt_auto_asconf(struct sock * sk,int len,char __user * optval,int __user * optlen)5789 static int sctp_getsockopt_auto_asconf(struct sock *sk, int len,
5790 				   char __user *optval, int __user *optlen)
5791 {
5792 	int val = 0;
5793 
5794 	if (len < sizeof(int))
5795 		return -EINVAL;
5796 
5797 	len = sizeof(int);
5798 	if (sctp_sk(sk)->do_auto_asconf && sctp_is_ep_boundall(sk))
5799 		val = 1;
5800 	if (put_user(len, optlen))
5801 		return -EFAULT;
5802 	if (copy_to_user(optval, &val, len))
5803 		return -EFAULT;
5804 	return 0;
5805 }
5806 
5807 /*
5808  * 8.2.6. Get the Current Identifiers of Associations
5809  *        (SCTP_GET_ASSOC_ID_LIST)
5810  *
5811  * This option gets the current list of SCTP association identifiers of
5812  * the SCTP associations handled by a one-to-many style socket.
5813  */
sctp_getsockopt_assoc_ids(struct sock * sk,int len,char __user * optval,int __user * optlen)5814 static int sctp_getsockopt_assoc_ids(struct sock *sk, int len,
5815 				    char __user *optval, int __user *optlen)
5816 {
5817 	struct sctp_sock *sp = sctp_sk(sk);
5818 	struct sctp_association *asoc;
5819 	struct sctp_assoc_ids *ids;
5820 	u32 num = 0;
5821 
5822 	if (sctp_style(sk, TCP))
5823 		return -EOPNOTSUPP;
5824 
5825 	if (len < sizeof(struct sctp_assoc_ids))
5826 		return -EINVAL;
5827 
5828 	list_for_each_entry(asoc, &(sp->ep->asocs), asocs) {
5829 		num++;
5830 	}
5831 
5832 	if (len < sizeof(struct sctp_assoc_ids) + sizeof(sctp_assoc_t) * num)
5833 		return -EINVAL;
5834 
5835 	len = sizeof(struct sctp_assoc_ids) + sizeof(sctp_assoc_t) * num;
5836 
5837 	ids = kmalloc(len, GFP_KERNEL);
5838 	if (unlikely(!ids))
5839 		return -ENOMEM;
5840 
5841 	ids->gaids_number_of_ids = num;
5842 	num = 0;
5843 	list_for_each_entry(asoc, &(sp->ep->asocs), asocs) {
5844 		ids->gaids_assoc_id[num++] = asoc->assoc_id;
5845 	}
5846 
5847 	if (put_user(len, optlen) || copy_to_user(optval, ids, len)) {
5848 		kfree(ids);
5849 		return -EFAULT;
5850 	}
5851 
5852 	kfree(ids);
5853 	return 0;
5854 }
5855 
5856 /*
5857  * SCTP_PEER_ADDR_THLDS
5858  *
5859  * This option allows us to fetch the partially failed threshold for one or all
5860  * transports in an association.  See Section 6.1 of:
5861  * http://www.ietf.org/id/draft-nishida-tsvwg-sctp-failover-05.txt
5862  */
sctp_getsockopt_paddr_thresholds(struct sock * sk,char __user * optval,int len,int __user * optlen)5863 static int sctp_getsockopt_paddr_thresholds(struct sock *sk,
5864 					    char __user *optval,
5865 					    int len,
5866 					    int __user *optlen)
5867 {
5868 	struct sctp_paddrthlds val;
5869 	struct sctp_transport *trans;
5870 	struct sctp_association *asoc;
5871 
5872 	if (len < sizeof(struct sctp_paddrthlds))
5873 		return -EINVAL;
5874 	len = sizeof(struct sctp_paddrthlds);
5875 	if (copy_from_user(&val, (struct sctp_paddrthlds __user *)optval, len))
5876 		return -EFAULT;
5877 
5878 	if (sctp_is_any(sk, (const union sctp_addr *)&val.spt_address)) {
5879 		asoc = sctp_id2assoc(sk, val.spt_assoc_id);
5880 		if (!asoc)
5881 			return -ENOENT;
5882 
5883 		val.spt_pathpfthld = asoc->pf_retrans;
5884 		val.spt_pathmaxrxt = asoc->pathmaxrxt;
5885 	} else {
5886 		trans = sctp_addr_id2transport(sk, &val.spt_address,
5887 					       val.spt_assoc_id);
5888 		if (!trans)
5889 			return -ENOENT;
5890 
5891 		val.spt_pathmaxrxt = trans->pathmaxrxt;
5892 		val.spt_pathpfthld = trans->pf_retrans;
5893 	}
5894 
5895 	if (put_user(len, optlen) || copy_to_user(optval, &val, len))
5896 		return -EFAULT;
5897 
5898 	return 0;
5899 }
5900 
5901 /*
5902  * SCTP_GET_ASSOC_STATS
5903  *
5904  * This option retrieves local per endpoint statistics. It is modeled
5905  * after OpenSolaris' implementation
5906  */
sctp_getsockopt_assoc_stats(struct sock * sk,int len,char __user * optval,int __user * optlen)5907 static int sctp_getsockopt_assoc_stats(struct sock *sk, int len,
5908 				       char __user *optval,
5909 				       int __user *optlen)
5910 {
5911 	struct sctp_assoc_stats sas;
5912 	struct sctp_association *asoc = NULL;
5913 
5914 	/* User must provide at least the assoc id */
5915 	if (len < sizeof(sctp_assoc_t))
5916 		return -EINVAL;
5917 
5918 	/* Allow the struct to grow and fill in as much as possible */
5919 	len = min_t(size_t, len, sizeof(sas));
5920 
5921 	if (copy_from_user(&sas, optval, len))
5922 		return -EFAULT;
5923 
5924 	asoc = sctp_id2assoc(sk, sas.sas_assoc_id);
5925 	if (!asoc)
5926 		return -EINVAL;
5927 
5928 	sas.sas_rtxchunks = asoc->stats.rtxchunks;
5929 	sas.sas_gapcnt = asoc->stats.gapcnt;
5930 	sas.sas_outofseqtsns = asoc->stats.outofseqtsns;
5931 	sas.sas_osacks = asoc->stats.osacks;
5932 	sas.sas_isacks = asoc->stats.isacks;
5933 	sas.sas_octrlchunks = asoc->stats.octrlchunks;
5934 	sas.sas_ictrlchunks = asoc->stats.ictrlchunks;
5935 	sas.sas_oodchunks = asoc->stats.oodchunks;
5936 	sas.sas_iodchunks = asoc->stats.iodchunks;
5937 	sas.sas_ouodchunks = asoc->stats.ouodchunks;
5938 	sas.sas_iuodchunks = asoc->stats.iuodchunks;
5939 	sas.sas_idupchunks = asoc->stats.idupchunks;
5940 	sas.sas_opackets = asoc->stats.opackets;
5941 	sas.sas_ipackets = asoc->stats.ipackets;
5942 
5943 	/* New high max rto observed, will return 0 if not a single
5944 	 * RTO update took place. obs_rto_ipaddr will be bogus
5945 	 * in such a case
5946 	 */
5947 	sas.sas_maxrto = asoc->stats.max_obs_rto;
5948 	memcpy(&sas.sas_obs_rto_ipaddr, &asoc->stats.obs_rto_ipaddr,
5949 		sizeof(struct sockaddr_storage));
5950 
5951 	/* Mark beginning of a new observation period */
5952 	asoc->stats.max_obs_rto = asoc->rto_min;
5953 
5954 	if (put_user(len, optlen))
5955 		return -EFAULT;
5956 
5957 	pr_debug("%s: len:%d, assoc_id:%d\n", __func__, len, sas.sas_assoc_id);
5958 
5959 	if (copy_to_user(optval, &sas, len))
5960 		return -EFAULT;
5961 
5962 	return 0;
5963 }
5964 
sctp_getsockopt_recvrcvinfo(struct sock * sk,int len,char __user * optval,int __user * optlen)5965 static int sctp_getsockopt_recvrcvinfo(struct sock *sk,	int len,
5966 				       char __user *optval,
5967 				       int __user *optlen)
5968 {
5969 	int val = 0;
5970 
5971 	if (len < sizeof(int))
5972 		return -EINVAL;
5973 
5974 	len = sizeof(int);
5975 	if (sctp_sk(sk)->recvrcvinfo)
5976 		val = 1;
5977 	if (put_user(len, optlen))
5978 		return -EFAULT;
5979 	if (copy_to_user(optval, &val, len))
5980 		return -EFAULT;
5981 
5982 	return 0;
5983 }
5984 
sctp_getsockopt_recvnxtinfo(struct sock * sk,int len,char __user * optval,int __user * optlen)5985 static int sctp_getsockopt_recvnxtinfo(struct sock *sk,	int len,
5986 				       char __user *optval,
5987 				       int __user *optlen)
5988 {
5989 	int val = 0;
5990 
5991 	if (len < sizeof(int))
5992 		return -EINVAL;
5993 
5994 	len = sizeof(int);
5995 	if (sctp_sk(sk)->recvnxtinfo)
5996 		val = 1;
5997 	if (put_user(len, optlen))
5998 		return -EFAULT;
5999 	if (copy_to_user(optval, &val, len))
6000 		return -EFAULT;
6001 
6002 	return 0;
6003 }
6004 
sctp_getsockopt(struct sock * sk,int level,int optname,char __user * optval,int __user * optlen)6005 static int sctp_getsockopt(struct sock *sk, int level, int optname,
6006 			   char __user *optval, int __user *optlen)
6007 {
6008 	int retval = 0;
6009 	int len;
6010 
6011 	pr_debug("%s: sk:%p, optname:%d\n", __func__, sk, optname);
6012 
6013 	/* I can hardly begin to describe how wrong this is.  This is
6014 	 * so broken as to be worse than useless.  The API draft
6015 	 * REALLY is NOT helpful here...  I am not convinced that the
6016 	 * semantics of getsockopt() with a level OTHER THAN SOL_SCTP
6017 	 * are at all well-founded.
6018 	 */
6019 	if (level != SOL_SCTP) {
6020 		struct sctp_af *af = sctp_sk(sk)->pf->af;
6021 
6022 		retval = af->getsockopt(sk, level, optname, optval, optlen);
6023 		return retval;
6024 	}
6025 
6026 	if (get_user(len, optlen))
6027 		return -EFAULT;
6028 
6029 	if (len < 0)
6030 		return -EINVAL;
6031 
6032 	lock_sock(sk);
6033 
6034 	switch (optname) {
6035 	case SCTP_STATUS:
6036 		retval = sctp_getsockopt_sctp_status(sk, len, optval, optlen);
6037 		break;
6038 	case SCTP_DISABLE_FRAGMENTS:
6039 		retval = sctp_getsockopt_disable_fragments(sk, len, optval,
6040 							   optlen);
6041 		break;
6042 	case SCTP_EVENTS:
6043 		retval = sctp_getsockopt_events(sk, len, optval, optlen);
6044 		break;
6045 	case SCTP_AUTOCLOSE:
6046 		retval = sctp_getsockopt_autoclose(sk, len, optval, optlen);
6047 		break;
6048 	case SCTP_SOCKOPT_PEELOFF:
6049 		retval = sctp_getsockopt_peeloff(sk, len, optval, optlen);
6050 		break;
6051 	case SCTP_PEER_ADDR_PARAMS:
6052 		retval = sctp_getsockopt_peer_addr_params(sk, len, optval,
6053 							  optlen);
6054 		break;
6055 	case SCTP_DELAYED_SACK:
6056 		retval = sctp_getsockopt_delayed_ack(sk, len, optval,
6057 							  optlen);
6058 		break;
6059 	case SCTP_INITMSG:
6060 		retval = sctp_getsockopt_initmsg(sk, len, optval, optlen);
6061 		break;
6062 	case SCTP_GET_PEER_ADDRS:
6063 		retval = sctp_getsockopt_peer_addrs(sk, len, optval,
6064 						    optlen);
6065 		break;
6066 	case SCTP_GET_LOCAL_ADDRS:
6067 		retval = sctp_getsockopt_local_addrs(sk, len, optval,
6068 						     optlen);
6069 		break;
6070 	case SCTP_SOCKOPT_CONNECTX3:
6071 		retval = sctp_getsockopt_connectx3(sk, len, optval, optlen);
6072 		break;
6073 	case SCTP_DEFAULT_SEND_PARAM:
6074 		retval = sctp_getsockopt_default_send_param(sk, len,
6075 							    optval, optlen);
6076 		break;
6077 	case SCTP_DEFAULT_SNDINFO:
6078 		retval = sctp_getsockopt_default_sndinfo(sk, len,
6079 							 optval, optlen);
6080 		break;
6081 	case SCTP_PRIMARY_ADDR:
6082 		retval = sctp_getsockopt_primary_addr(sk, len, optval, optlen);
6083 		break;
6084 	case SCTP_NODELAY:
6085 		retval = sctp_getsockopt_nodelay(sk, len, optval, optlen);
6086 		break;
6087 	case SCTP_RTOINFO:
6088 		retval = sctp_getsockopt_rtoinfo(sk, len, optval, optlen);
6089 		break;
6090 	case SCTP_ASSOCINFO:
6091 		retval = sctp_getsockopt_associnfo(sk, len, optval, optlen);
6092 		break;
6093 	case SCTP_I_WANT_MAPPED_V4_ADDR:
6094 		retval = sctp_getsockopt_mappedv4(sk, len, optval, optlen);
6095 		break;
6096 	case SCTP_MAXSEG:
6097 		retval = sctp_getsockopt_maxseg(sk, len, optval, optlen);
6098 		break;
6099 	case SCTP_GET_PEER_ADDR_INFO:
6100 		retval = sctp_getsockopt_peer_addr_info(sk, len, optval,
6101 							optlen);
6102 		break;
6103 	case SCTP_ADAPTATION_LAYER:
6104 		retval = sctp_getsockopt_adaptation_layer(sk, len, optval,
6105 							optlen);
6106 		break;
6107 	case SCTP_CONTEXT:
6108 		retval = sctp_getsockopt_context(sk, len, optval, optlen);
6109 		break;
6110 	case SCTP_FRAGMENT_INTERLEAVE:
6111 		retval = sctp_getsockopt_fragment_interleave(sk, len, optval,
6112 							     optlen);
6113 		break;
6114 	case SCTP_PARTIAL_DELIVERY_POINT:
6115 		retval = sctp_getsockopt_partial_delivery_point(sk, len, optval,
6116 								optlen);
6117 		break;
6118 	case SCTP_MAX_BURST:
6119 		retval = sctp_getsockopt_maxburst(sk, len, optval, optlen);
6120 		break;
6121 	case SCTP_AUTH_KEY:
6122 	case SCTP_AUTH_CHUNK:
6123 	case SCTP_AUTH_DELETE_KEY:
6124 		retval = -EOPNOTSUPP;
6125 		break;
6126 	case SCTP_HMAC_IDENT:
6127 		retval = sctp_getsockopt_hmac_ident(sk, len, optval, optlen);
6128 		break;
6129 	case SCTP_AUTH_ACTIVE_KEY:
6130 		retval = sctp_getsockopt_active_key(sk, len, optval, optlen);
6131 		break;
6132 	case SCTP_PEER_AUTH_CHUNKS:
6133 		retval = sctp_getsockopt_peer_auth_chunks(sk, len, optval,
6134 							optlen);
6135 		break;
6136 	case SCTP_LOCAL_AUTH_CHUNKS:
6137 		retval = sctp_getsockopt_local_auth_chunks(sk, len, optval,
6138 							optlen);
6139 		break;
6140 	case SCTP_GET_ASSOC_NUMBER:
6141 		retval = sctp_getsockopt_assoc_number(sk, len, optval, optlen);
6142 		break;
6143 	case SCTP_GET_ASSOC_ID_LIST:
6144 		retval = sctp_getsockopt_assoc_ids(sk, len, optval, optlen);
6145 		break;
6146 	case SCTP_AUTO_ASCONF:
6147 		retval = sctp_getsockopt_auto_asconf(sk, len, optval, optlen);
6148 		break;
6149 	case SCTP_PEER_ADDR_THLDS:
6150 		retval = sctp_getsockopt_paddr_thresholds(sk, optval, len, optlen);
6151 		break;
6152 	case SCTP_GET_ASSOC_STATS:
6153 		retval = sctp_getsockopt_assoc_stats(sk, len, optval, optlen);
6154 		break;
6155 	case SCTP_RECVRCVINFO:
6156 		retval = sctp_getsockopt_recvrcvinfo(sk, len, optval, optlen);
6157 		break;
6158 	case SCTP_RECVNXTINFO:
6159 		retval = sctp_getsockopt_recvnxtinfo(sk, len, optval, optlen);
6160 		break;
6161 	default:
6162 		retval = -ENOPROTOOPT;
6163 		break;
6164 	}
6165 
6166 	release_sock(sk);
6167 	return retval;
6168 }
6169 
sctp_hash(struct sock * sk)6170 static void sctp_hash(struct sock *sk)
6171 {
6172 	/* STUB */
6173 }
6174 
sctp_unhash(struct sock * sk)6175 static void sctp_unhash(struct sock *sk)
6176 {
6177 	/* STUB */
6178 }
6179 
6180 /* Check if port is acceptable.  Possibly find first available port.
6181  *
6182  * The port hash table (contained in the 'global' SCTP protocol storage
6183  * returned by struct sctp_protocol *sctp_get_protocol()). The hash
6184  * table is an array of 4096 lists (sctp_bind_hashbucket). Each
6185  * list (the list number is the port number hashed out, so as you
6186  * would expect from a hash function, all the ports in a given list have
6187  * such a number that hashes out to the same list number; you were
6188  * expecting that, right?); so each list has a set of ports, with a
6189  * link to the socket (struct sock) that uses it, the port number and
6190  * a fastreuse flag (FIXME: NPI ipg).
6191  */
6192 static struct sctp_bind_bucket *sctp_bucket_create(
6193 	struct sctp_bind_hashbucket *head, struct net *, unsigned short snum);
6194 
sctp_get_port_local(struct sock * sk,union sctp_addr * addr)6195 static long sctp_get_port_local(struct sock *sk, union sctp_addr *addr)
6196 {
6197 	struct sctp_bind_hashbucket *head; /* hash list */
6198 	struct sctp_bind_bucket *pp;
6199 	unsigned short snum;
6200 	int ret;
6201 
6202 	snum = ntohs(addr->v4.sin_port);
6203 
6204 	pr_debug("%s: begins, snum:%d\n", __func__, snum);
6205 
6206 	local_bh_disable();
6207 
6208 	if (snum == 0) {
6209 		/* Search for an available port. */
6210 		int low, high, remaining, index;
6211 		unsigned int rover;
6212 		struct net *net = sock_net(sk);
6213 
6214 		inet_get_local_port_range(net, &low, &high);
6215 		remaining = (high - low) + 1;
6216 		rover = prandom_u32() % remaining + low;
6217 
6218 		do {
6219 			rover++;
6220 			if ((rover < low) || (rover > high))
6221 				rover = low;
6222 			if (inet_is_local_reserved_port(net, rover))
6223 				continue;
6224 			index = sctp_phashfn(sock_net(sk), rover);
6225 			head = &sctp_port_hashtable[index];
6226 			spin_lock(&head->lock);
6227 			sctp_for_each_hentry(pp, &head->chain)
6228 				if ((pp->port == rover) &&
6229 				    net_eq(sock_net(sk), pp->net))
6230 					goto next;
6231 			break;
6232 		next:
6233 			spin_unlock(&head->lock);
6234 		} while (--remaining > 0);
6235 
6236 		/* Exhausted local port range during search? */
6237 		ret = 1;
6238 		if (remaining <= 0)
6239 			goto fail;
6240 
6241 		/* OK, here is the one we will use.  HEAD (the port
6242 		 * hash table list entry) is non-NULL and we hold it's
6243 		 * mutex.
6244 		 */
6245 		snum = rover;
6246 	} else {
6247 		/* We are given an specific port number; we verify
6248 		 * that it is not being used. If it is used, we will
6249 		 * exahust the search in the hash list corresponding
6250 		 * to the port number (snum) - we detect that with the
6251 		 * port iterator, pp being NULL.
6252 		 */
6253 		head = &sctp_port_hashtable[sctp_phashfn(sock_net(sk), snum)];
6254 		spin_lock(&head->lock);
6255 		sctp_for_each_hentry(pp, &head->chain) {
6256 			if ((pp->port == snum) && net_eq(pp->net, sock_net(sk)))
6257 				goto pp_found;
6258 		}
6259 	}
6260 	pp = NULL;
6261 	goto pp_not_found;
6262 pp_found:
6263 	if (!hlist_empty(&pp->owner)) {
6264 		/* We had a port hash table hit - there is an
6265 		 * available port (pp != NULL) and it is being
6266 		 * used by other socket (pp->owner not empty); that other
6267 		 * socket is going to be sk2.
6268 		 */
6269 		int reuse = sk->sk_reuse;
6270 		struct sock *sk2;
6271 
6272 		pr_debug("%s: found a possible match\n", __func__);
6273 
6274 		if (pp->fastreuse && sk->sk_reuse &&
6275 			sk->sk_state != SCTP_SS_LISTENING)
6276 			goto success;
6277 
6278 		/* Run through the list of sockets bound to the port
6279 		 * (pp->port) [via the pointers bind_next and
6280 		 * bind_pprev in the struct sock *sk2 (pp->sk)]. On each one,
6281 		 * we get the endpoint they describe and run through
6282 		 * the endpoint's list of IP (v4 or v6) addresses,
6283 		 * comparing each of the addresses with the address of
6284 		 * the socket sk. If we find a match, then that means
6285 		 * that this port/socket (sk) combination are already
6286 		 * in an endpoint.
6287 		 */
6288 		sk_for_each_bound(sk2, &pp->owner) {
6289 			struct sctp_endpoint *ep2;
6290 			ep2 = sctp_sk(sk2)->ep;
6291 
6292 			if (sk == sk2 ||
6293 			    (reuse && sk2->sk_reuse &&
6294 			     sk2->sk_state != SCTP_SS_LISTENING))
6295 				continue;
6296 
6297 			if (sctp_bind_addr_conflict(&ep2->base.bind_addr, addr,
6298 						 sctp_sk(sk2), sctp_sk(sk))) {
6299 				ret = (long)sk2;
6300 				goto fail_unlock;
6301 			}
6302 		}
6303 
6304 		pr_debug("%s: found a match\n", __func__);
6305 	}
6306 pp_not_found:
6307 	/* If there was a hash table miss, create a new port.  */
6308 	ret = 1;
6309 	if (!pp && !(pp = sctp_bucket_create(head, sock_net(sk), snum)))
6310 		goto fail_unlock;
6311 
6312 	/* In either case (hit or miss), make sure fastreuse is 1 only
6313 	 * if sk->sk_reuse is too (that is, if the caller requested
6314 	 * SO_REUSEADDR on this socket -sk-).
6315 	 */
6316 	if (hlist_empty(&pp->owner)) {
6317 		if (sk->sk_reuse && sk->sk_state != SCTP_SS_LISTENING)
6318 			pp->fastreuse = 1;
6319 		else
6320 			pp->fastreuse = 0;
6321 	} else if (pp->fastreuse &&
6322 		(!sk->sk_reuse || sk->sk_state == SCTP_SS_LISTENING))
6323 		pp->fastreuse = 0;
6324 
6325 	/* We are set, so fill up all the data in the hash table
6326 	 * entry, tie the socket list information with the rest of the
6327 	 * sockets FIXME: Blurry, NPI (ipg).
6328 	 */
6329 success:
6330 	if (!sctp_sk(sk)->bind_hash) {
6331 		inet_sk(sk)->inet_num = snum;
6332 		sk_add_bind_node(sk, &pp->owner);
6333 		sctp_sk(sk)->bind_hash = pp;
6334 	}
6335 	ret = 0;
6336 
6337 fail_unlock:
6338 	spin_unlock(&head->lock);
6339 
6340 fail:
6341 	local_bh_enable();
6342 	return ret;
6343 }
6344 
6345 /* Assign a 'snum' port to the socket.  If snum == 0, an ephemeral
6346  * port is requested.
6347  */
sctp_get_port(struct sock * sk,unsigned short snum)6348 static int sctp_get_port(struct sock *sk, unsigned short snum)
6349 {
6350 	union sctp_addr addr;
6351 	struct sctp_af *af = sctp_sk(sk)->pf->af;
6352 
6353 	/* Set up a dummy address struct from the sk. */
6354 	af->from_sk(&addr, sk);
6355 	addr.v4.sin_port = htons(snum);
6356 
6357 	/* Note: sk->sk_num gets filled in if ephemeral port request. */
6358 	return !!sctp_get_port_local(sk, &addr);
6359 }
6360 
6361 /*
6362  *  Move a socket to LISTENING state.
6363  */
sctp_listen_start(struct sock * sk,int backlog)6364 static int sctp_listen_start(struct sock *sk, int backlog)
6365 {
6366 	struct sctp_sock *sp = sctp_sk(sk);
6367 	struct sctp_endpoint *ep = sp->ep;
6368 	struct crypto_hash *tfm = NULL;
6369 	char alg[32];
6370 
6371 	/* Allocate HMAC for generating cookie. */
6372 	if (!sp->hmac && sp->sctp_hmac_alg) {
6373 		sprintf(alg, "hmac(%s)", sp->sctp_hmac_alg);
6374 		tfm = crypto_alloc_hash(alg, 0, CRYPTO_ALG_ASYNC);
6375 		if (IS_ERR(tfm)) {
6376 			net_info_ratelimited("failed to load transform for %s: %ld\n",
6377 					     sp->sctp_hmac_alg, PTR_ERR(tfm));
6378 			return -ENOSYS;
6379 		}
6380 		sctp_sk(sk)->hmac = tfm;
6381 	}
6382 
6383 	/*
6384 	 * If a bind() or sctp_bindx() is not called prior to a listen()
6385 	 * call that allows new associations to be accepted, the system
6386 	 * picks an ephemeral port and will choose an address set equivalent
6387 	 * to binding with a wildcard address.
6388 	 *
6389 	 * This is not currently spelled out in the SCTP sockets
6390 	 * extensions draft, but follows the practice as seen in TCP
6391 	 * sockets.
6392 	 *
6393 	 */
6394 	sk->sk_state = SCTP_SS_LISTENING;
6395 	if (!ep->base.bind_addr.port) {
6396 		if (sctp_autobind(sk))
6397 			return -EAGAIN;
6398 	} else {
6399 		if (sctp_get_port(sk, inet_sk(sk)->inet_num)) {
6400 			sk->sk_state = SCTP_SS_CLOSED;
6401 			return -EADDRINUSE;
6402 		}
6403 	}
6404 
6405 	sk->sk_max_ack_backlog = backlog;
6406 	sctp_hash_endpoint(ep);
6407 	return 0;
6408 }
6409 
6410 /*
6411  * 4.1.3 / 5.1.3 listen()
6412  *
6413  *   By default, new associations are not accepted for UDP style sockets.
6414  *   An application uses listen() to mark a socket as being able to
6415  *   accept new associations.
6416  *
6417  *   On TCP style sockets, applications use listen() to ready the SCTP
6418  *   endpoint for accepting inbound associations.
6419  *
6420  *   On both types of endpoints a backlog of '0' disables listening.
6421  *
6422  *  Move a socket to LISTENING state.
6423  */
sctp_inet_listen(struct socket * sock,int backlog)6424 int sctp_inet_listen(struct socket *sock, int backlog)
6425 {
6426 	struct sock *sk = sock->sk;
6427 	struct sctp_endpoint *ep = sctp_sk(sk)->ep;
6428 	int err = -EINVAL;
6429 
6430 	if (unlikely(backlog < 0))
6431 		return err;
6432 
6433 	lock_sock(sk);
6434 
6435 	/* Peeled-off sockets are not allowed to listen().  */
6436 	if (sctp_style(sk, UDP_HIGH_BANDWIDTH))
6437 		goto out;
6438 
6439 	if (sock->state != SS_UNCONNECTED)
6440 		goto out;
6441 
6442 	if (!sctp_sstate(sk, LISTENING) && !sctp_sstate(sk, CLOSED))
6443 		goto out;
6444 
6445 	/* If backlog is zero, disable listening. */
6446 	if (!backlog) {
6447 		if (sctp_sstate(sk, CLOSED))
6448 			goto out;
6449 
6450 		err = 0;
6451 		sctp_unhash_endpoint(ep);
6452 		sk->sk_state = SCTP_SS_CLOSED;
6453 		if (sk->sk_reuse)
6454 			sctp_sk(sk)->bind_hash->fastreuse = 1;
6455 		goto out;
6456 	}
6457 
6458 	/* If we are already listening, just update the backlog */
6459 	if (sctp_sstate(sk, LISTENING))
6460 		sk->sk_max_ack_backlog = backlog;
6461 	else {
6462 		err = sctp_listen_start(sk, backlog);
6463 		if (err)
6464 			goto out;
6465 	}
6466 
6467 	err = 0;
6468 out:
6469 	release_sock(sk);
6470 	return err;
6471 }
6472 
6473 /*
6474  * This function is done by modeling the current datagram_poll() and the
6475  * tcp_poll().  Note that, based on these implementations, we don't
6476  * lock the socket in this function, even though it seems that,
6477  * ideally, locking or some other mechanisms can be used to ensure
6478  * the integrity of the counters (sndbuf and wmem_alloc) used
6479  * in this place.  We assume that we don't need locks either until proven
6480  * otherwise.
6481  *
6482  * Another thing to note is that we include the Async I/O support
6483  * here, again, by modeling the current TCP/UDP code.  We don't have
6484  * a good way to test with it yet.
6485  */
sctp_poll(struct file * file,struct socket * sock,poll_table * wait)6486 unsigned int sctp_poll(struct file *file, struct socket *sock, poll_table *wait)
6487 {
6488 	struct sock *sk = sock->sk;
6489 	struct sctp_sock *sp = sctp_sk(sk);
6490 	unsigned int mask;
6491 
6492 	poll_wait(file, sk_sleep(sk), wait);
6493 
6494 	/* A TCP-style listening socket becomes readable when the accept queue
6495 	 * is not empty.
6496 	 */
6497 	if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING))
6498 		return (!list_empty(&sp->ep->asocs)) ?
6499 			(POLLIN | POLLRDNORM) : 0;
6500 
6501 	mask = 0;
6502 
6503 	/* Is there any exceptional events?  */
6504 	if (sk->sk_err || !skb_queue_empty(&sk->sk_error_queue))
6505 		mask |= POLLERR |
6506 			(sock_flag(sk, SOCK_SELECT_ERR_QUEUE) ? POLLPRI : 0);
6507 	if (sk->sk_shutdown & RCV_SHUTDOWN)
6508 		mask |= POLLRDHUP | POLLIN | POLLRDNORM;
6509 	if (sk->sk_shutdown == SHUTDOWN_MASK)
6510 		mask |= POLLHUP;
6511 
6512 	/* Is it readable?  Reconsider this code with TCP-style support.  */
6513 	if (!skb_queue_empty(&sk->sk_receive_queue))
6514 		mask |= POLLIN | POLLRDNORM;
6515 
6516 	/* The association is either gone or not ready.  */
6517 	if (!sctp_style(sk, UDP) && sctp_sstate(sk, CLOSED))
6518 		return mask;
6519 
6520 	/* Is it writable?  */
6521 	if (sctp_writeable(sk)) {
6522 		mask |= POLLOUT | POLLWRNORM;
6523 	} else {
6524 		set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags);
6525 		/*
6526 		 * Since the socket is not locked, the buffer
6527 		 * might be made available after the writeable check and
6528 		 * before the bit is set.  This could cause a lost I/O
6529 		 * signal.  tcp_poll() has a race breaker for this race
6530 		 * condition.  Based on their implementation, we put
6531 		 * in the following code to cover it as well.
6532 		 */
6533 		if (sctp_writeable(sk))
6534 			mask |= POLLOUT | POLLWRNORM;
6535 	}
6536 	return mask;
6537 }
6538 
6539 /********************************************************************
6540  * 2nd Level Abstractions
6541  ********************************************************************/
6542 
sctp_bucket_create(struct sctp_bind_hashbucket * head,struct net * net,unsigned short snum)6543 static struct sctp_bind_bucket *sctp_bucket_create(
6544 	struct sctp_bind_hashbucket *head, struct net *net, unsigned short snum)
6545 {
6546 	struct sctp_bind_bucket *pp;
6547 
6548 	pp = kmem_cache_alloc(sctp_bucket_cachep, GFP_ATOMIC);
6549 	if (pp) {
6550 		SCTP_DBG_OBJCNT_INC(bind_bucket);
6551 		pp->port = snum;
6552 		pp->fastreuse = 0;
6553 		INIT_HLIST_HEAD(&pp->owner);
6554 		pp->net = net;
6555 		hlist_add_head(&pp->node, &head->chain);
6556 	}
6557 	return pp;
6558 }
6559 
6560 /* Caller must hold hashbucket lock for this tb with local BH disabled */
sctp_bucket_destroy(struct sctp_bind_bucket * pp)6561 static void sctp_bucket_destroy(struct sctp_bind_bucket *pp)
6562 {
6563 	if (pp && hlist_empty(&pp->owner)) {
6564 		__hlist_del(&pp->node);
6565 		kmem_cache_free(sctp_bucket_cachep, pp);
6566 		SCTP_DBG_OBJCNT_DEC(bind_bucket);
6567 	}
6568 }
6569 
6570 /* Release this socket's reference to a local port.  */
__sctp_put_port(struct sock * sk)6571 static inline void __sctp_put_port(struct sock *sk)
6572 {
6573 	struct sctp_bind_hashbucket *head =
6574 		&sctp_port_hashtable[sctp_phashfn(sock_net(sk),
6575 						  inet_sk(sk)->inet_num)];
6576 	struct sctp_bind_bucket *pp;
6577 
6578 	spin_lock(&head->lock);
6579 	pp = sctp_sk(sk)->bind_hash;
6580 	__sk_del_bind_node(sk);
6581 	sctp_sk(sk)->bind_hash = NULL;
6582 	inet_sk(sk)->inet_num = 0;
6583 	sctp_bucket_destroy(pp);
6584 	spin_unlock(&head->lock);
6585 }
6586 
sctp_put_port(struct sock * sk)6587 void sctp_put_port(struct sock *sk)
6588 {
6589 	local_bh_disable();
6590 	__sctp_put_port(sk);
6591 	local_bh_enable();
6592 }
6593 
6594 /*
6595  * The system picks an ephemeral port and choose an address set equivalent
6596  * to binding with a wildcard address.
6597  * One of those addresses will be the primary address for the association.
6598  * This automatically enables the multihoming capability of SCTP.
6599  */
sctp_autobind(struct sock * sk)6600 static int sctp_autobind(struct sock *sk)
6601 {
6602 	union sctp_addr autoaddr;
6603 	struct sctp_af *af;
6604 	__be16 port;
6605 
6606 	/* Initialize a local sockaddr structure to INADDR_ANY. */
6607 	af = sctp_sk(sk)->pf->af;
6608 
6609 	port = htons(inet_sk(sk)->inet_num);
6610 	af->inaddr_any(&autoaddr, port);
6611 
6612 	return sctp_do_bind(sk, &autoaddr, af->sockaddr_len);
6613 }
6614 
6615 /* Parse out IPPROTO_SCTP CMSG headers.  Perform only minimal validation.
6616  *
6617  * From RFC 2292
6618  * 4.2 The cmsghdr Structure *
6619  *
6620  * When ancillary data is sent or received, any number of ancillary data
6621  * objects can be specified by the msg_control and msg_controllen members of
6622  * the msghdr structure, because each object is preceded by
6623  * a cmsghdr structure defining the object's length (the cmsg_len member).
6624  * Historically Berkeley-derived implementations have passed only one object
6625  * at a time, but this API allows multiple objects to be
6626  * passed in a single call to sendmsg() or recvmsg(). The following example
6627  * shows two ancillary data objects in a control buffer.
6628  *
6629  *   |<--------------------------- msg_controllen -------------------------->|
6630  *   |                                                                       |
6631  *
6632  *   |<----- ancillary data object ----->|<----- ancillary data object ----->|
6633  *
6634  *   |<---------- CMSG_SPACE() --------->|<---------- CMSG_SPACE() --------->|
6635  *   |                                   |                                   |
6636  *
6637  *   |<---------- cmsg_len ---------->|  |<--------- cmsg_len ----------->|  |
6638  *
6639  *   |<--------- CMSG_LEN() --------->|  |<-------- CMSG_LEN() ---------->|  |
6640  *   |                                |  |                                |  |
6641  *
6642  *   +-----+-----+-----+--+-----------+--+-----+-----+-----+--+-----------+--+
6643  *   |cmsg_|cmsg_|cmsg_|XX|           |XX|cmsg_|cmsg_|cmsg_|XX|           |XX|
6644  *
6645  *   |len  |level|type |XX|cmsg_data[]|XX|len  |level|type |XX|cmsg_data[]|XX|
6646  *
6647  *   +-----+-----+-----+--+-----------+--+-----+-----+-----+--+-----------+--+
6648  *    ^
6649  *    |
6650  *
6651  * msg_control
6652  * points here
6653  */
sctp_msghdr_parse(const struct msghdr * msg,sctp_cmsgs_t * cmsgs)6654 static int sctp_msghdr_parse(const struct msghdr *msg, sctp_cmsgs_t *cmsgs)
6655 {
6656 	struct cmsghdr *cmsg;
6657 	struct msghdr *my_msg = (struct msghdr *)msg;
6658 
6659 	for (cmsg = CMSG_FIRSTHDR(msg); cmsg != NULL;
6660 	     cmsg = CMSG_NXTHDR(my_msg, cmsg)) {
6661 		if (!CMSG_OK(my_msg, cmsg))
6662 			return -EINVAL;
6663 
6664 		/* Should we parse this header or ignore?  */
6665 		if (cmsg->cmsg_level != IPPROTO_SCTP)
6666 			continue;
6667 
6668 		/* Strictly check lengths following example in SCM code.  */
6669 		switch (cmsg->cmsg_type) {
6670 		case SCTP_INIT:
6671 			/* SCTP Socket API Extension
6672 			 * 5.3.1 SCTP Initiation Structure (SCTP_INIT)
6673 			 *
6674 			 * This cmsghdr structure provides information for
6675 			 * initializing new SCTP associations with sendmsg().
6676 			 * The SCTP_INITMSG socket option uses this same data
6677 			 * structure.  This structure is not used for
6678 			 * recvmsg().
6679 			 *
6680 			 * cmsg_level    cmsg_type      cmsg_data[]
6681 			 * ------------  ------------   ----------------------
6682 			 * IPPROTO_SCTP  SCTP_INIT      struct sctp_initmsg
6683 			 */
6684 			if (cmsg->cmsg_len != CMSG_LEN(sizeof(struct sctp_initmsg)))
6685 				return -EINVAL;
6686 
6687 			cmsgs->init = CMSG_DATA(cmsg);
6688 			break;
6689 
6690 		case SCTP_SNDRCV:
6691 			/* SCTP Socket API Extension
6692 			 * 5.3.2 SCTP Header Information Structure(SCTP_SNDRCV)
6693 			 *
6694 			 * This cmsghdr structure specifies SCTP options for
6695 			 * sendmsg() and describes SCTP header information
6696 			 * about a received message through recvmsg().
6697 			 *
6698 			 * cmsg_level    cmsg_type      cmsg_data[]
6699 			 * ------------  ------------   ----------------------
6700 			 * IPPROTO_SCTP  SCTP_SNDRCV    struct sctp_sndrcvinfo
6701 			 */
6702 			if (cmsg->cmsg_len != CMSG_LEN(sizeof(struct sctp_sndrcvinfo)))
6703 				return -EINVAL;
6704 
6705 			cmsgs->srinfo = CMSG_DATA(cmsg);
6706 
6707 			if (cmsgs->srinfo->sinfo_flags &
6708 			    ~(SCTP_UNORDERED | SCTP_ADDR_OVER |
6709 			      SCTP_ABORT | SCTP_EOF))
6710 				return -EINVAL;
6711 			break;
6712 
6713 		case SCTP_SNDINFO:
6714 			/* SCTP Socket API Extension
6715 			 * 5.3.4 SCTP Send Information Structure (SCTP_SNDINFO)
6716 			 *
6717 			 * This cmsghdr structure specifies SCTP options for
6718 			 * sendmsg(). This structure and SCTP_RCVINFO replaces
6719 			 * SCTP_SNDRCV which has been deprecated.
6720 			 *
6721 			 * cmsg_level    cmsg_type      cmsg_data[]
6722 			 * ------------  ------------   ---------------------
6723 			 * IPPROTO_SCTP  SCTP_SNDINFO    struct sctp_sndinfo
6724 			 */
6725 			if (cmsg->cmsg_len != CMSG_LEN(sizeof(struct sctp_sndinfo)))
6726 				return -EINVAL;
6727 
6728 			cmsgs->sinfo = CMSG_DATA(cmsg);
6729 
6730 			if (cmsgs->sinfo->snd_flags &
6731 			    ~(SCTP_UNORDERED | SCTP_ADDR_OVER |
6732 			      SCTP_ABORT | SCTP_EOF))
6733 				return -EINVAL;
6734 			break;
6735 		default:
6736 			return -EINVAL;
6737 		}
6738 	}
6739 
6740 	return 0;
6741 }
6742 
6743 /*
6744  * Wait for a packet..
6745  * Note: This function is the same function as in core/datagram.c
6746  * with a few modifications to make lksctp work.
6747  */
sctp_wait_for_packet(struct sock * sk,int * err,long * timeo_p)6748 static int sctp_wait_for_packet(struct sock *sk, int *err, long *timeo_p)
6749 {
6750 	int error;
6751 	DEFINE_WAIT(wait);
6752 
6753 	prepare_to_wait_exclusive(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
6754 
6755 	/* Socket errors? */
6756 	error = sock_error(sk);
6757 	if (error)
6758 		goto out;
6759 
6760 	if (!skb_queue_empty(&sk->sk_receive_queue))
6761 		goto ready;
6762 
6763 	/* Socket shut down?  */
6764 	if (sk->sk_shutdown & RCV_SHUTDOWN)
6765 		goto out;
6766 
6767 	/* Sequenced packets can come disconnected.  If so we report the
6768 	 * problem.
6769 	 */
6770 	error = -ENOTCONN;
6771 
6772 	/* Is there a good reason to think that we may receive some data?  */
6773 	if (list_empty(&sctp_sk(sk)->ep->asocs) && !sctp_sstate(sk, LISTENING))
6774 		goto out;
6775 
6776 	/* Handle signals.  */
6777 	if (signal_pending(current))
6778 		goto interrupted;
6779 
6780 	/* Let another process have a go.  Since we are going to sleep
6781 	 * anyway.  Note: This may cause odd behaviors if the message
6782 	 * does not fit in the user's buffer, but this seems to be the
6783 	 * only way to honor MSG_DONTWAIT realistically.
6784 	 */
6785 	release_sock(sk);
6786 	*timeo_p = schedule_timeout(*timeo_p);
6787 	lock_sock(sk);
6788 
6789 ready:
6790 	finish_wait(sk_sleep(sk), &wait);
6791 	return 0;
6792 
6793 interrupted:
6794 	error = sock_intr_errno(*timeo_p);
6795 
6796 out:
6797 	finish_wait(sk_sleep(sk), &wait);
6798 	*err = error;
6799 	return error;
6800 }
6801 
6802 /* Receive a datagram.
6803  * Note: This is pretty much the same routine as in core/datagram.c
6804  * with a few changes to make lksctp work.
6805  */
sctp_skb_recv_datagram(struct sock * sk,int flags,int noblock,int * err)6806 struct sk_buff *sctp_skb_recv_datagram(struct sock *sk, int flags,
6807 				       int noblock, int *err)
6808 {
6809 	int error;
6810 	struct sk_buff *skb;
6811 	long timeo;
6812 
6813 	timeo = sock_rcvtimeo(sk, noblock);
6814 
6815 	pr_debug("%s: timeo:%ld, max:%ld\n", __func__, timeo,
6816 		 MAX_SCHEDULE_TIMEOUT);
6817 
6818 	do {
6819 		/* Again only user level code calls this function,
6820 		 * so nothing interrupt level
6821 		 * will suddenly eat the receive_queue.
6822 		 *
6823 		 *  Look at current nfs client by the way...
6824 		 *  However, this function was correct in any case. 8)
6825 		 */
6826 		if (flags & MSG_PEEK) {
6827 			spin_lock_bh(&sk->sk_receive_queue.lock);
6828 			skb = skb_peek(&sk->sk_receive_queue);
6829 			if (skb)
6830 				atomic_inc(&skb->users);
6831 			spin_unlock_bh(&sk->sk_receive_queue.lock);
6832 		} else {
6833 			skb = skb_dequeue(&sk->sk_receive_queue);
6834 		}
6835 
6836 		if (skb)
6837 			return skb;
6838 
6839 		/* Caller is allowed not to check sk->sk_err before calling. */
6840 		error = sock_error(sk);
6841 		if (error)
6842 			goto no_packet;
6843 
6844 		if (sk->sk_shutdown & RCV_SHUTDOWN)
6845 			break;
6846 
6847 		if (sk_can_busy_loop(sk) &&
6848 		    sk_busy_loop(sk, noblock))
6849 			continue;
6850 
6851 		/* User doesn't want to wait.  */
6852 		error = -EAGAIN;
6853 		if (!timeo)
6854 			goto no_packet;
6855 	} while (sctp_wait_for_packet(sk, err, &timeo) == 0);
6856 
6857 	return NULL;
6858 
6859 no_packet:
6860 	*err = error;
6861 	return NULL;
6862 }
6863 
6864 /* If sndbuf has changed, wake up per association sndbuf waiters.  */
__sctp_write_space(struct sctp_association * asoc)6865 static void __sctp_write_space(struct sctp_association *asoc)
6866 {
6867 	struct sock *sk = asoc->base.sk;
6868 	struct socket *sock = sk->sk_socket;
6869 
6870 	if ((sctp_wspace(asoc) > 0) && sock) {
6871 		if (waitqueue_active(&asoc->wait))
6872 			wake_up_interruptible(&asoc->wait);
6873 
6874 		if (sctp_writeable(sk)) {
6875 			wait_queue_head_t *wq = sk_sleep(sk);
6876 
6877 			if (wq && waitqueue_active(wq))
6878 				wake_up_interruptible(wq);
6879 
6880 			/* Note that we try to include the Async I/O support
6881 			 * here by modeling from the current TCP/UDP code.
6882 			 * We have not tested with it yet.
6883 			 */
6884 			if (!(sk->sk_shutdown & SEND_SHUTDOWN))
6885 				sock_wake_async(sock,
6886 						SOCK_WAKE_SPACE, POLL_OUT);
6887 		}
6888 	}
6889 }
6890 
sctp_wake_up_waiters(struct sock * sk,struct sctp_association * asoc)6891 static void sctp_wake_up_waiters(struct sock *sk,
6892 				 struct sctp_association *asoc)
6893 {
6894 	struct sctp_association *tmp = asoc;
6895 
6896 	/* We do accounting for the sndbuf space per association,
6897 	 * so we only need to wake our own association.
6898 	 */
6899 	if (asoc->ep->sndbuf_policy)
6900 		return __sctp_write_space(asoc);
6901 
6902 	/* If association goes down and is just flushing its
6903 	 * outq, then just normally notify others.
6904 	 */
6905 	if (asoc->base.dead)
6906 		return sctp_write_space(sk);
6907 
6908 	/* Accounting for the sndbuf space is per socket, so we
6909 	 * need to wake up others, try to be fair and in case of
6910 	 * other associations, let them have a go first instead
6911 	 * of just doing a sctp_write_space() call.
6912 	 *
6913 	 * Note that we reach sctp_wake_up_waiters() only when
6914 	 * associations free up queued chunks, thus we are under
6915 	 * lock and the list of associations on a socket is
6916 	 * guaranteed not to change.
6917 	 */
6918 	for (tmp = list_next_entry(tmp, asocs); 1;
6919 	     tmp = list_next_entry(tmp, asocs)) {
6920 		/* Manually skip the head element. */
6921 		if (&tmp->asocs == &((sctp_sk(sk))->ep->asocs))
6922 			continue;
6923 		/* Wake up association. */
6924 		__sctp_write_space(tmp);
6925 		/* We've reached the end. */
6926 		if (tmp == asoc)
6927 			break;
6928 	}
6929 }
6930 
6931 /* Do accounting for the sndbuf space.
6932  * Decrement the used sndbuf space of the corresponding association by the
6933  * data size which was just transmitted(freed).
6934  */
sctp_wfree(struct sk_buff * skb)6935 static void sctp_wfree(struct sk_buff *skb)
6936 {
6937 	struct sctp_association *asoc;
6938 	struct sctp_chunk *chunk;
6939 	struct sock *sk;
6940 
6941 	/* Get the saved chunk pointer.  */
6942 	chunk = *((struct sctp_chunk **)(skb->cb));
6943 	asoc = chunk->asoc;
6944 	sk = asoc->base.sk;
6945 	asoc->sndbuf_used -= SCTP_DATA_SNDSIZE(chunk) +
6946 				sizeof(struct sk_buff) +
6947 				sizeof(struct sctp_chunk);
6948 
6949 	atomic_sub(sizeof(struct sctp_chunk), &sk->sk_wmem_alloc);
6950 
6951 	/*
6952 	 * This undoes what is done via sctp_set_owner_w and sk_mem_charge
6953 	 */
6954 	sk->sk_wmem_queued   -= skb->truesize;
6955 	sk_mem_uncharge(sk, skb->truesize);
6956 
6957 	sock_wfree(skb);
6958 	sctp_wake_up_waiters(sk, asoc);
6959 
6960 	sctp_association_put(asoc);
6961 }
6962 
6963 /* Do accounting for the receive space on the socket.
6964  * Accounting for the association is done in ulpevent.c
6965  * We set this as a destructor for the cloned data skbs so that
6966  * accounting is done at the correct time.
6967  */
sctp_sock_rfree(struct sk_buff * skb)6968 void sctp_sock_rfree(struct sk_buff *skb)
6969 {
6970 	struct sock *sk = skb->sk;
6971 	struct sctp_ulpevent *event = sctp_skb2event(skb);
6972 
6973 	atomic_sub(event->rmem_len, &sk->sk_rmem_alloc);
6974 
6975 	/*
6976 	 * Mimic the behavior of sock_rfree
6977 	 */
6978 	sk_mem_uncharge(sk, event->rmem_len);
6979 }
6980 
6981 
6982 /* Helper function to wait for space in the sndbuf.  */
sctp_wait_for_sndbuf(struct sctp_association * asoc,long * timeo_p,size_t msg_len)6983 static int sctp_wait_for_sndbuf(struct sctp_association *asoc, long *timeo_p,
6984 				size_t msg_len)
6985 {
6986 	struct sock *sk = asoc->base.sk;
6987 	long current_timeo = *timeo_p;
6988 	DEFINE_WAIT(wait);
6989 	int err = 0;
6990 
6991 	pr_debug("%s: asoc:%p, timeo:%ld, msg_len:%zu\n", __func__, asoc,
6992 		 *timeo_p, msg_len);
6993 
6994 	/* Increment the association's refcnt.  */
6995 	sctp_association_hold(asoc);
6996 
6997 	/* Wait on the association specific sndbuf space. */
6998 	for (;;) {
6999 		prepare_to_wait_exclusive(&asoc->wait, &wait,
7000 					  TASK_INTERRUPTIBLE);
7001 		if (asoc->base.dead)
7002 			goto do_dead;
7003 		if (!*timeo_p)
7004 			goto do_nonblock;
7005 		if (sk->sk_err || asoc->state >= SCTP_STATE_SHUTDOWN_PENDING)
7006 			goto do_error;
7007 		if (signal_pending(current))
7008 			goto do_interrupted;
7009 		if (msg_len <= sctp_wspace(asoc))
7010 			break;
7011 
7012 		/* Let another process have a go.  Since we are going
7013 		 * to sleep anyway.
7014 		 */
7015 		release_sock(sk);
7016 		current_timeo = schedule_timeout(current_timeo);
7017 		lock_sock(sk);
7018 		if (sk != asoc->base.sk)
7019 			goto do_error;
7020 
7021 		*timeo_p = current_timeo;
7022 	}
7023 
7024 out:
7025 	finish_wait(&asoc->wait, &wait);
7026 
7027 	/* Release the association's refcnt.  */
7028 	sctp_association_put(asoc);
7029 
7030 	return err;
7031 
7032 do_dead:
7033 	err = -ESRCH;
7034 	goto out;
7035 
7036 do_error:
7037 	err = -EPIPE;
7038 	goto out;
7039 
7040 do_interrupted:
7041 	err = sock_intr_errno(*timeo_p);
7042 	goto out;
7043 
7044 do_nonblock:
7045 	err = -EAGAIN;
7046 	goto out;
7047 }
7048 
sctp_data_ready(struct sock * sk)7049 void sctp_data_ready(struct sock *sk)
7050 {
7051 	struct socket_wq *wq;
7052 
7053 	rcu_read_lock();
7054 	wq = rcu_dereference(sk->sk_wq);
7055 	if (wq_has_sleeper(wq))
7056 		wake_up_interruptible_sync_poll(&wq->wait, POLLIN |
7057 						POLLRDNORM | POLLRDBAND);
7058 	sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN);
7059 	rcu_read_unlock();
7060 }
7061 
7062 /* If socket sndbuf has changed, wake up all per association waiters.  */
sctp_write_space(struct sock * sk)7063 void sctp_write_space(struct sock *sk)
7064 {
7065 	struct sctp_association *asoc;
7066 
7067 	/* Wake up the tasks in each wait queue.  */
7068 	list_for_each_entry(asoc, &((sctp_sk(sk))->ep->asocs), asocs) {
7069 		__sctp_write_space(asoc);
7070 	}
7071 }
7072 
7073 /* Is there any sndbuf space available on the socket?
7074  *
7075  * Note that sk_wmem_alloc is the sum of the send buffers on all of the
7076  * associations on the same socket.  For a UDP-style socket with
7077  * multiple associations, it is possible for it to be "unwriteable"
7078  * prematurely.  I assume that this is acceptable because
7079  * a premature "unwriteable" is better than an accidental "writeable" which
7080  * would cause an unwanted block under certain circumstances.  For the 1-1
7081  * UDP-style sockets or TCP-style sockets, this code should work.
7082  *  - Daisy
7083  */
sctp_writeable(struct sock * sk)7084 static int sctp_writeable(struct sock *sk)
7085 {
7086 	int amt = 0;
7087 
7088 	amt = sk->sk_sndbuf - sk_wmem_alloc_get(sk);
7089 	if (amt < 0)
7090 		amt = 0;
7091 	return amt;
7092 }
7093 
7094 /* Wait for an association to go into ESTABLISHED state. If timeout is 0,
7095  * returns immediately with EINPROGRESS.
7096  */
sctp_wait_for_connect(struct sctp_association * asoc,long * timeo_p)7097 static int sctp_wait_for_connect(struct sctp_association *asoc, long *timeo_p)
7098 {
7099 	struct sock *sk = asoc->base.sk;
7100 	int err = 0;
7101 	long current_timeo = *timeo_p;
7102 	DEFINE_WAIT(wait);
7103 
7104 	pr_debug("%s: asoc:%p, timeo:%ld\n", __func__, asoc, *timeo_p);
7105 
7106 	/* Increment the association's refcnt.  */
7107 	sctp_association_hold(asoc);
7108 
7109 	for (;;) {
7110 		prepare_to_wait_exclusive(&asoc->wait, &wait,
7111 					  TASK_INTERRUPTIBLE);
7112 		if (!*timeo_p)
7113 			goto do_nonblock;
7114 		if (sk->sk_shutdown & RCV_SHUTDOWN)
7115 			break;
7116 		if (sk->sk_err || asoc->state >= SCTP_STATE_SHUTDOWN_PENDING ||
7117 		    asoc->base.dead)
7118 			goto do_error;
7119 		if (signal_pending(current))
7120 			goto do_interrupted;
7121 
7122 		if (sctp_state(asoc, ESTABLISHED))
7123 			break;
7124 
7125 		/* Let another process have a go.  Since we are going
7126 		 * to sleep anyway.
7127 		 */
7128 		release_sock(sk);
7129 		current_timeo = schedule_timeout(current_timeo);
7130 		lock_sock(sk);
7131 
7132 		*timeo_p = current_timeo;
7133 	}
7134 
7135 out:
7136 	finish_wait(&asoc->wait, &wait);
7137 
7138 	/* Release the association's refcnt.  */
7139 	sctp_association_put(asoc);
7140 
7141 	return err;
7142 
7143 do_error:
7144 	if (asoc->init_err_counter + 1 > asoc->max_init_attempts)
7145 		err = -ETIMEDOUT;
7146 	else
7147 		err = -ECONNREFUSED;
7148 	goto out;
7149 
7150 do_interrupted:
7151 	err = sock_intr_errno(*timeo_p);
7152 	goto out;
7153 
7154 do_nonblock:
7155 	err = -EINPROGRESS;
7156 	goto out;
7157 }
7158 
sctp_wait_for_accept(struct sock * sk,long timeo)7159 static int sctp_wait_for_accept(struct sock *sk, long timeo)
7160 {
7161 	struct sctp_endpoint *ep;
7162 	int err = 0;
7163 	DEFINE_WAIT(wait);
7164 
7165 	ep = sctp_sk(sk)->ep;
7166 
7167 
7168 	for (;;) {
7169 		prepare_to_wait_exclusive(sk_sleep(sk), &wait,
7170 					  TASK_INTERRUPTIBLE);
7171 
7172 		if (list_empty(&ep->asocs)) {
7173 			release_sock(sk);
7174 			timeo = schedule_timeout(timeo);
7175 			lock_sock(sk);
7176 		}
7177 
7178 		err = -EINVAL;
7179 		if (!sctp_sstate(sk, LISTENING))
7180 			break;
7181 
7182 		err = 0;
7183 		if (!list_empty(&ep->asocs))
7184 			break;
7185 
7186 		err = sock_intr_errno(timeo);
7187 		if (signal_pending(current))
7188 			break;
7189 
7190 		err = -EAGAIN;
7191 		if (!timeo)
7192 			break;
7193 	}
7194 
7195 	finish_wait(sk_sleep(sk), &wait);
7196 
7197 	return err;
7198 }
7199 
sctp_wait_for_close(struct sock * sk,long timeout)7200 static void sctp_wait_for_close(struct sock *sk, long timeout)
7201 {
7202 	DEFINE_WAIT(wait);
7203 
7204 	do {
7205 		prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
7206 		if (list_empty(&sctp_sk(sk)->ep->asocs))
7207 			break;
7208 		release_sock(sk);
7209 		timeout = schedule_timeout(timeout);
7210 		lock_sock(sk);
7211 	} while (!signal_pending(current) && timeout);
7212 
7213 	finish_wait(sk_sleep(sk), &wait);
7214 }
7215 
sctp_skb_set_owner_r_frag(struct sk_buff * skb,struct sock * sk)7216 static void sctp_skb_set_owner_r_frag(struct sk_buff *skb, struct sock *sk)
7217 {
7218 	struct sk_buff *frag;
7219 
7220 	if (!skb->data_len)
7221 		goto done;
7222 
7223 	/* Don't forget the fragments. */
7224 	skb_walk_frags(skb, frag)
7225 		sctp_skb_set_owner_r_frag(frag, sk);
7226 
7227 done:
7228 	sctp_skb_set_owner_r(skb, sk);
7229 }
7230 
sctp_copy_sock(struct sock * newsk,struct sock * sk,struct sctp_association * asoc)7231 void sctp_copy_sock(struct sock *newsk, struct sock *sk,
7232 		    struct sctp_association *asoc)
7233 {
7234 	struct inet_sock *inet = inet_sk(sk);
7235 	struct inet_sock *newinet;
7236 
7237 	newsk->sk_type = sk->sk_type;
7238 	newsk->sk_bound_dev_if = sk->sk_bound_dev_if;
7239 	newsk->sk_flags = sk->sk_flags;
7240 	newsk->sk_tsflags = sk->sk_tsflags;
7241 	newsk->sk_no_check_tx = sk->sk_no_check_tx;
7242 	newsk->sk_no_check_rx = sk->sk_no_check_rx;
7243 	newsk->sk_reuse = sk->sk_reuse;
7244 
7245 	newsk->sk_shutdown = sk->sk_shutdown;
7246 	newsk->sk_destruct = sctp_destruct_sock;
7247 	newsk->sk_family = sk->sk_family;
7248 	newsk->sk_protocol = IPPROTO_SCTP;
7249 	newsk->sk_backlog_rcv = sk->sk_prot->backlog_rcv;
7250 	newsk->sk_sndbuf = sk->sk_sndbuf;
7251 	newsk->sk_rcvbuf = sk->sk_rcvbuf;
7252 	newsk->sk_lingertime = sk->sk_lingertime;
7253 	newsk->sk_rcvtimeo = sk->sk_rcvtimeo;
7254 	newsk->sk_sndtimeo = sk->sk_sndtimeo;
7255 
7256 	newinet = inet_sk(newsk);
7257 
7258 	/* Initialize sk's sport, dport, rcv_saddr and daddr for
7259 	 * getsockname() and getpeername()
7260 	 */
7261 	newinet->inet_sport = inet->inet_sport;
7262 	newinet->inet_saddr = inet->inet_saddr;
7263 	newinet->inet_rcv_saddr = inet->inet_rcv_saddr;
7264 	newinet->inet_dport = htons(asoc->peer.port);
7265 	newinet->pmtudisc = inet->pmtudisc;
7266 	newinet->inet_id = asoc->next_tsn ^ jiffies;
7267 
7268 	newinet->uc_ttl = inet->uc_ttl;
7269 	newinet->mc_loop = 1;
7270 	newinet->mc_ttl = 1;
7271 	newinet->mc_index = 0;
7272 	newinet->mc_list = NULL;
7273 
7274 	if (newsk->sk_flags & SK_FLAGS_TIMESTAMP)
7275 		net_enable_timestamp();
7276 }
7277 
sctp_copy_descendant(struct sock * sk_to,const struct sock * sk_from)7278 static inline void sctp_copy_descendant(struct sock *sk_to,
7279 					const struct sock *sk_from)
7280 {
7281 	int ancestor_size = sizeof(struct inet_sock) +
7282 			    sizeof(struct sctp_sock) -
7283 			    offsetof(struct sctp_sock, auto_asconf_list);
7284 
7285 	if (sk_from->sk_family == PF_INET6)
7286 		ancestor_size += sizeof(struct ipv6_pinfo);
7287 
7288 	__inet_sk_copy_descendant(sk_to, sk_from, ancestor_size);
7289 }
7290 
7291 /* Populate the fields of the newsk from the oldsk and migrate the assoc
7292  * and its messages to the newsk.
7293  */
sctp_sock_migrate(struct sock * oldsk,struct sock * newsk,struct sctp_association * assoc,sctp_socket_type_t type)7294 static void sctp_sock_migrate(struct sock *oldsk, struct sock *newsk,
7295 			      struct sctp_association *assoc,
7296 			      sctp_socket_type_t type)
7297 {
7298 	struct sctp_sock *oldsp = sctp_sk(oldsk);
7299 	struct sctp_sock *newsp = sctp_sk(newsk);
7300 	struct sctp_bind_bucket *pp; /* hash list port iterator */
7301 	struct sctp_endpoint *newep = newsp->ep;
7302 	struct sk_buff *skb, *tmp;
7303 	struct sctp_ulpevent *event;
7304 	struct sctp_bind_hashbucket *head;
7305 
7306 	/* Migrate socket buffer sizes and all the socket level options to the
7307 	 * new socket.
7308 	 */
7309 	newsk->sk_sndbuf = oldsk->sk_sndbuf;
7310 	newsk->sk_rcvbuf = oldsk->sk_rcvbuf;
7311 	/* Brute force copy old sctp opt. */
7312 	sctp_copy_descendant(newsk, oldsk);
7313 
7314 	/* Restore the ep value that was overwritten with the above structure
7315 	 * copy.
7316 	 */
7317 	newsp->ep = newep;
7318 	newsp->hmac = NULL;
7319 
7320 	/* Hook this new socket in to the bind_hash list. */
7321 	head = &sctp_port_hashtable[sctp_phashfn(sock_net(oldsk),
7322 						 inet_sk(oldsk)->inet_num)];
7323 	local_bh_disable();
7324 	spin_lock(&head->lock);
7325 	pp = sctp_sk(oldsk)->bind_hash;
7326 	sk_add_bind_node(newsk, &pp->owner);
7327 	sctp_sk(newsk)->bind_hash = pp;
7328 	inet_sk(newsk)->inet_num = inet_sk(oldsk)->inet_num;
7329 	spin_unlock(&head->lock);
7330 	local_bh_enable();
7331 
7332 	/* Copy the bind_addr list from the original endpoint to the new
7333 	 * endpoint so that we can handle restarts properly
7334 	 */
7335 	sctp_bind_addr_dup(&newsp->ep->base.bind_addr,
7336 				&oldsp->ep->base.bind_addr, GFP_KERNEL);
7337 
7338 	/* Move any messages in the old socket's receive queue that are for the
7339 	 * peeled off association to the new socket's receive queue.
7340 	 */
7341 	sctp_skb_for_each(skb, &oldsk->sk_receive_queue, tmp) {
7342 		event = sctp_skb2event(skb);
7343 		if (event->asoc == assoc) {
7344 			__skb_unlink(skb, &oldsk->sk_receive_queue);
7345 			__skb_queue_tail(&newsk->sk_receive_queue, skb);
7346 			sctp_skb_set_owner_r_frag(skb, newsk);
7347 		}
7348 	}
7349 
7350 	/* Clean up any messages pending delivery due to partial
7351 	 * delivery.   Three cases:
7352 	 * 1) No partial deliver;  no work.
7353 	 * 2) Peeling off partial delivery; keep pd_lobby in new pd_lobby.
7354 	 * 3) Peeling off non-partial delivery; move pd_lobby to receive_queue.
7355 	 */
7356 	skb_queue_head_init(&newsp->pd_lobby);
7357 	atomic_set(&sctp_sk(newsk)->pd_mode, assoc->ulpq.pd_mode);
7358 
7359 	if (atomic_read(&sctp_sk(oldsk)->pd_mode)) {
7360 		struct sk_buff_head *queue;
7361 
7362 		/* Decide which queue to move pd_lobby skbs to. */
7363 		if (assoc->ulpq.pd_mode) {
7364 			queue = &newsp->pd_lobby;
7365 		} else
7366 			queue = &newsk->sk_receive_queue;
7367 
7368 		/* Walk through the pd_lobby, looking for skbs that
7369 		 * need moved to the new socket.
7370 		 */
7371 		sctp_skb_for_each(skb, &oldsp->pd_lobby, tmp) {
7372 			event = sctp_skb2event(skb);
7373 			if (event->asoc == assoc) {
7374 				__skb_unlink(skb, &oldsp->pd_lobby);
7375 				__skb_queue_tail(queue, skb);
7376 				sctp_skb_set_owner_r_frag(skb, newsk);
7377 			}
7378 		}
7379 
7380 		/* Clear up any skbs waiting for the partial
7381 		 * delivery to finish.
7382 		 */
7383 		if (assoc->ulpq.pd_mode)
7384 			sctp_clear_pd(oldsk, NULL);
7385 
7386 	}
7387 
7388 	sctp_skb_for_each(skb, &assoc->ulpq.reasm, tmp)
7389 		sctp_skb_set_owner_r_frag(skb, newsk);
7390 
7391 	sctp_skb_for_each(skb, &assoc->ulpq.lobby, tmp)
7392 		sctp_skb_set_owner_r_frag(skb, newsk);
7393 
7394 	/* Set the type of socket to indicate that it is peeled off from the
7395 	 * original UDP-style socket or created with the accept() call on a
7396 	 * TCP-style socket..
7397 	 */
7398 	newsp->type = type;
7399 
7400 	/* Mark the new socket "in-use" by the user so that any packets
7401 	 * that may arrive on the association after we've moved it are
7402 	 * queued to the backlog.  This prevents a potential race between
7403 	 * backlog processing on the old socket and new-packet processing
7404 	 * on the new socket.
7405 	 *
7406 	 * The caller has just allocated newsk so we can guarantee that other
7407 	 * paths won't try to lock it and then oldsk.
7408 	 */
7409 	lock_sock_nested(newsk, SINGLE_DEPTH_NESTING);
7410 	sctp_for_each_tx_datachunk(assoc, sctp_clear_owner_w);
7411 	sctp_assoc_migrate(assoc, newsk);
7412 	sctp_for_each_tx_datachunk(assoc, sctp_set_owner_w);
7413 
7414 	/* If the association on the newsk is already closed before accept()
7415 	 * is called, set RCV_SHUTDOWN flag.
7416 	 */
7417 	if (sctp_state(assoc, CLOSED) && sctp_style(newsk, TCP))
7418 		newsk->sk_shutdown |= RCV_SHUTDOWN;
7419 
7420 	newsk->sk_state = SCTP_SS_ESTABLISHED;
7421 	release_sock(newsk);
7422 }
7423 
7424 
7425 /* This proto struct describes the ULP interface for SCTP.  */
7426 struct proto sctp_prot = {
7427 	.name        =	"SCTP",
7428 	.owner       =	THIS_MODULE,
7429 	.close       =	sctp_close,
7430 	.connect     =	sctp_connect,
7431 	.disconnect  =	sctp_disconnect,
7432 	.accept      =	sctp_accept,
7433 	.ioctl       =	sctp_ioctl,
7434 	.init        =	sctp_init_sock,
7435 	.destroy     =	sctp_destroy_sock,
7436 	.shutdown    =	sctp_shutdown,
7437 	.setsockopt  =	sctp_setsockopt,
7438 	.getsockopt  =	sctp_getsockopt,
7439 	.sendmsg     =	sctp_sendmsg,
7440 	.recvmsg     =	sctp_recvmsg,
7441 	.bind        =	sctp_bind,
7442 	.backlog_rcv =	sctp_backlog_rcv,
7443 	.hash        =	sctp_hash,
7444 	.unhash      =	sctp_unhash,
7445 	.get_port    =	sctp_get_port,
7446 	.obj_size    =  sizeof(struct sctp_sock),
7447 	.sysctl_mem  =  sysctl_sctp_mem,
7448 	.sysctl_rmem =  sysctl_sctp_rmem,
7449 	.sysctl_wmem =  sysctl_sctp_wmem,
7450 	.memory_pressure = &sctp_memory_pressure,
7451 	.enter_memory_pressure = sctp_enter_memory_pressure,
7452 	.memory_allocated = &sctp_memory_allocated,
7453 	.sockets_allocated = &sctp_sockets_allocated,
7454 };
7455 
7456 #if IS_ENABLED(CONFIG_IPV6)
7457 
7458 #include <net/transp_v6.h>
sctp_v6_destroy_sock(struct sock * sk)7459 static void sctp_v6_destroy_sock(struct sock *sk)
7460 {
7461 	sctp_destroy_sock(sk);
7462 	inet6_destroy_sock(sk);
7463 }
7464 
7465 struct proto sctpv6_prot = {
7466 	.name		= "SCTPv6",
7467 	.owner		= THIS_MODULE,
7468 	.close		= sctp_close,
7469 	.connect	= sctp_connect,
7470 	.disconnect	= sctp_disconnect,
7471 	.accept		= sctp_accept,
7472 	.ioctl		= sctp_ioctl,
7473 	.init		= sctp_init_sock,
7474 	.destroy	= sctp_v6_destroy_sock,
7475 	.shutdown	= sctp_shutdown,
7476 	.setsockopt	= sctp_setsockopt,
7477 	.getsockopt	= sctp_getsockopt,
7478 	.sendmsg	= sctp_sendmsg,
7479 	.recvmsg	= sctp_recvmsg,
7480 	.bind		= sctp_bind,
7481 	.backlog_rcv	= sctp_backlog_rcv,
7482 	.hash		= sctp_hash,
7483 	.unhash		= sctp_unhash,
7484 	.get_port	= sctp_get_port,
7485 	.obj_size	= sizeof(struct sctp6_sock),
7486 	.sysctl_mem	= sysctl_sctp_mem,
7487 	.sysctl_rmem	= sysctl_sctp_rmem,
7488 	.sysctl_wmem	= sysctl_sctp_wmem,
7489 	.memory_pressure = &sctp_memory_pressure,
7490 	.enter_memory_pressure = sctp_enter_memory_pressure,
7491 	.memory_allocated = &sctp_memory_allocated,
7492 	.sockets_allocated = &sctp_sockets_allocated,
7493 };
7494 #endif /* IS_ENABLED(CONFIG_IPV6) */
7495