1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /* SCTP kernel implementation
3  * (C) Copyright IBM Corp. 2001, 2004
4  * Copyright (c) 1999-2000 Cisco, Inc.
5  * Copyright (c) 1999-2001 Motorola, Inc.
6  * Copyright (c) 2001-2003 Intel Corp.
7  * Copyright (c) 2001-2002 Nokia, Inc.
8  * Copyright (c) 2001 La Monte H.P. Yarroll
9  *
10  * This file is part of the SCTP kernel implementation
11  *
12  * These functions interface with the sockets layer to implement the
13  * SCTP Extensions for the Sockets API.
14  *
15  * Note that the descriptions from the specification are USER level
16  * functions--this file is the functions which populate the struct proto
17  * for SCTP which is the BOTTOM of the sockets interface.
18  *
19  * Please send any bug reports or fixes you make to the
20  * email address(es):
21  *    lksctp developers <[email protected]>
22  *
23  * Written or modified by:
24  *    La Monte H.P. Yarroll <[email protected]>
25  *    Narasimha Budihal     <[email protected]>
26  *    Karl Knutson          <[email protected]>
27  *    Jon Grimm             <[email protected]>
28  *    Xingang Guo           <[email protected]>
29  *    Daisy Chang           <[email protected]>
30  *    Sridhar Samudrala     <[email protected]>
31  *    Inaky Perez-Gonzalez  <[email protected]>
32  *    Ardelle Fan	    <[email protected]>
33  *    Ryan Layer	    <[email protected]>
34  *    Anup Pemmaiah         <[email protected]>
35  *    Kevin Gao             <[email protected]>
36  */
37 
38 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
39 
40 #include <crypto/hash.h>
41 #include <linux/types.h>
42 #include <linux/kernel.h>
43 #include <linux/wait.h>
44 #include <linux/time.h>
45 #include <linux/sched/signal.h>
46 #include <linux/ip.h>
47 #include <linux/capability.h>
48 #include <linux/fcntl.h>
49 #include <linux/poll.h>
50 #include <linux/init.h>
51 #include <linux/slab.h>
52 #include <linux/file.h>
53 #include <linux/compat.h>
54 #include <linux/rhashtable.h>
55 
56 #include <net/ip.h>
57 #include <net/icmp.h>
58 #include <net/route.h>
59 #include <net/ipv6.h>
60 #include <net/inet_common.h>
61 #include <net/busy_poll.h>
62 #include <trace/events/sock.h>
63 
64 #include <linux/socket.h> /* for sa_family_t */
65 #include <linux/export.h>
66 #include <net/sock.h>
67 #include <net/sctp/sctp.h>
68 #include <net/sctp/sm.h>
69 #include <net/sctp/stream_sched.h>
70 #include <net/rps.h>
71 
72 /* Forward declarations for internal helper functions. */
73 static bool sctp_writeable(const struct sock *sk);
74 static void sctp_wfree(struct sk_buff *skb);
75 static int sctp_wait_for_sndbuf(struct sctp_association *asoc,
76 				struct sctp_transport *transport,
77 				long *timeo_p, size_t msg_len);
78 static int sctp_wait_for_packet(struct sock *sk, int *err, long *timeo_p);
79 static int sctp_wait_for_connect(struct sctp_association *, long *timeo_p);
80 static int sctp_wait_for_accept(struct sock *sk, long timeo);
81 static void sctp_wait_for_close(struct sock *sk, long timeo);
82 static void sctp_destruct_sock(struct sock *sk);
83 static struct sctp_af *sctp_sockaddr_af(struct sctp_sock *opt,
84 					union sctp_addr *addr, int len);
85 static int sctp_bindx_add(struct sock *, struct sockaddr *, int);
86 static int sctp_bindx_rem(struct sock *, struct sockaddr *, int);
87 static int sctp_send_asconf_add_ip(struct sock *, struct sockaddr *, int);
88 static int sctp_send_asconf_del_ip(struct sock *, struct sockaddr *, int);
89 static int sctp_send_asconf(struct sctp_association *asoc,
90 			    struct sctp_chunk *chunk);
91 static int sctp_do_bind(struct sock *, union sctp_addr *, int);
92 static int sctp_autobind(struct sock *sk);
93 static int sctp_sock_migrate(struct sock *oldsk, struct sock *newsk,
94 			     struct sctp_association *assoc,
95 			     enum sctp_socket_type type);
96 
97 static unsigned long sctp_memory_pressure;
98 static atomic_long_t sctp_memory_allocated;
99 static DEFINE_PER_CPU(int, sctp_memory_per_cpu_fw_alloc);
100 struct percpu_counter sctp_sockets_allocated;
101 
sctp_enter_memory_pressure(struct sock * sk)102 static void sctp_enter_memory_pressure(struct sock *sk)
103 {
104 	WRITE_ONCE(sctp_memory_pressure, 1);
105 }
106 
107 
108 /* Get the sndbuf space available at the time on the association.  */
sctp_wspace(struct sctp_association * asoc)109 static inline int sctp_wspace(struct sctp_association *asoc)
110 {
111 	struct sock *sk = asoc->base.sk;
112 
113 	return asoc->ep->sndbuf_policy ? sk->sk_sndbuf - asoc->sndbuf_used
114 				       : sk_stream_wspace(sk);
115 }
116 
117 /* Increment the used sndbuf space count of the corresponding association by
118  * the size of the outgoing data chunk.
119  * Also, set the skb destructor for sndbuf accounting later.
120  *
121  * Since it is always 1-1 between chunk and skb, and also a new skb is always
122  * allocated for chunk bundling in sctp_packet_transmit(), we can use the
123  * destructor in the data chunk skb for the purpose of the sndbuf space
124  * tracking.
125  */
sctp_set_owner_w(struct sctp_chunk * chunk)126 static inline void sctp_set_owner_w(struct sctp_chunk *chunk)
127 {
128 	struct sctp_association *asoc = chunk->asoc;
129 	struct sock *sk = asoc->base.sk;
130 
131 	/* The sndbuf space is tracked per association.  */
132 	sctp_association_hold(asoc);
133 
134 	if (chunk->shkey)
135 		sctp_auth_shkey_hold(chunk->shkey);
136 
137 	skb_set_owner_w(chunk->skb, sk);
138 
139 	chunk->skb->destructor = sctp_wfree;
140 	/* Save the chunk pointer in skb for sctp_wfree to use later.  */
141 	skb_shinfo(chunk->skb)->destructor_arg = chunk;
142 
143 	refcount_add(sizeof(struct sctp_chunk), &sk->sk_wmem_alloc);
144 	asoc->sndbuf_used += chunk->skb->truesize + sizeof(struct sctp_chunk);
145 	sk_wmem_queued_add(sk, chunk->skb->truesize + sizeof(struct sctp_chunk));
146 	sk_mem_charge(sk, chunk->skb->truesize);
147 }
148 
sctp_clear_owner_w(struct sctp_chunk * chunk)149 static void sctp_clear_owner_w(struct sctp_chunk *chunk)
150 {
151 	skb_orphan(chunk->skb);
152 }
153 
154 #define traverse_and_process()	\
155 do {				\
156 	msg = chunk->msg;	\
157 	if (msg == prev_msg)	\
158 		continue;	\
159 	list_for_each_entry(c, &msg->chunks, frag_list) {	\
160 		if ((clear && asoc->base.sk == c->skb->sk) ||	\
161 		    (!clear && asoc->base.sk != c->skb->sk))	\
162 			cb(c);	\
163 	}			\
164 	prev_msg = msg;		\
165 } while (0)
166 
sctp_for_each_tx_datachunk(struct sctp_association * asoc,bool clear,void (* cb)(struct sctp_chunk *))167 static void sctp_for_each_tx_datachunk(struct sctp_association *asoc,
168 				       bool clear,
169 				       void (*cb)(struct sctp_chunk *))
170 
171 {
172 	struct sctp_datamsg *msg, *prev_msg = NULL;
173 	struct sctp_outq *q = &asoc->outqueue;
174 	struct sctp_chunk *chunk, *c;
175 	struct sctp_transport *t;
176 
177 	list_for_each_entry(t, &asoc->peer.transport_addr_list, transports)
178 		list_for_each_entry(chunk, &t->transmitted, transmitted_list)
179 			traverse_and_process();
180 
181 	list_for_each_entry(chunk, &q->retransmit, transmitted_list)
182 		traverse_and_process();
183 
184 	list_for_each_entry(chunk, &q->sacked, transmitted_list)
185 		traverse_and_process();
186 
187 	list_for_each_entry(chunk, &q->abandoned, transmitted_list)
188 		traverse_and_process();
189 
190 	list_for_each_entry(chunk, &q->out_chunk_list, list)
191 		traverse_and_process();
192 }
193 
sctp_for_each_rx_skb(struct sctp_association * asoc,struct sock * sk,void (* cb)(struct sk_buff *,struct sock *))194 static void sctp_for_each_rx_skb(struct sctp_association *asoc, struct sock *sk,
195 				 void (*cb)(struct sk_buff *, struct sock *))
196 
197 {
198 	struct sk_buff *skb, *tmp;
199 
200 	sctp_skb_for_each(skb, &asoc->ulpq.lobby, tmp)
201 		cb(skb, sk);
202 
203 	sctp_skb_for_each(skb, &asoc->ulpq.reasm, tmp)
204 		cb(skb, sk);
205 
206 	sctp_skb_for_each(skb, &asoc->ulpq.reasm_uo, tmp)
207 		cb(skb, sk);
208 }
209 
210 /* Verify that this is a valid address. */
sctp_verify_addr(struct sock * sk,union sctp_addr * addr,int len)211 static inline int sctp_verify_addr(struct sock *sk, union sctp_addr *addr,
212 				   int len)
213 {
214 	struct sctp_af *af;
215 
216 	/* Verify basic sockaddr. */
217 	af = sctp_sockaddr_af(sctp_sk(sk), addr, len);
218 	if (!af)
219 		return -EINVAL;
220 
221 	/* Is this a valid SCTP address?  */
222 	if (!af->addr_valid(addr, sctp_sk(sk), NULL))
223 		return -EINVAL;
224 
225 	if (!sctp_sk(sk)->pf->send_verify(sctp_sk(sk), (addr)))
226 		return -EINVAL;
227 
228 	return 0;
229 }
230 
231 /* Look up the association by its id.  If this is not a UDP-style
232  * socket, the ID field is always ignored.
233  */
sctp_id2assoc(struct sock * sk,sctp_assoc_t id)234 struct sctp_association *sctp_id2assoc(struct sock *sk, sctp_assoc_t id)
235 {
236 	struct sctp_association *asoc = NULL;
237 
238 	/* If this is not a UDP-style socket, assoc id should be ignored. */
239 	if (!sctp_style(sk, UDP)) {
240 		/* Return NULL if the socket state is not ESTABLISHED. It
241 		 * could be a TCP-style listening socket or a socket which
242 		 * hasn't yet called connect() to establish an association.
243 		 */
244 		if (!sctp_sstate(sk, ESTABLISHED) && !sctp_sstate(sk, CLOSING))
245 			return NULL;
246 
247 		/* Get the first and the only association from the list. */
248 		if (!list_empty(&sctp_sk(sk)->ep->asocs))
249 			asoc = list_entry(sctp_sk(sk)->ep->asocs.next,
250 					  struct sctp_association, asocs);
251 		return asoc;
252 	}
253 
254 	/* Otherwise this is a UDP-style socket. */
255 	if (id <= SCTP_ALL_ASSOC)
256 		return NULL;
257 
258 	spin_lock_bh(&sctp_assocs_id_lock);
259 	asoc = (struct sctp_association *)idr_find(&sctp_assocs_id, (int)id);
260 	if (asoc && (asoc->base.sk != sk || asoc->base.dead))
261 		asoc = NULL;
262 	spin_unlock_bh(&sctp_assocs_id_lock);
263 
264 	return asoc;
265 }
266 
267 /* Look up the transport from an address and an assoc id. If both address and
268  * id are specified, the associations matching the address and the id should be
269  * the same.
270  */
sctp_addr_id2transport(struct sock * sk,struct sockaddr_storage * addr,sctp_assoc_t id)271 static struct sctp_transport *sctp_addr_id2transport(struct sock *sk,
272 					      struct sockaddr_storage *addr,
273 					      sctp_assoc_t id)
274 {
275 	struct sctp_association *addr_asoc = NULL, *id_asoc = NULL;
276 	struct sctp_af *af = sctp_get_af_specific(addr->ss_family);
277 	union sctp_addr *laddr = (union sctp_addr *)addr;
278 	struct sctp_transport *transport;
279 
280 	if (!af || sctp_verify_addr(sk, laddr, af->sockaddr_len))
281 		return NULL;
282 
283 	addr_asoc = sctp_endpoint_lookup_assoc(sctp_sk(sk)->ep,
284 					       laddr,
285 					       &transport);
286 
287 	if (!addr_asoc)
288 		return NULL;
289 
290 	id_asoc = sctp_id2assoc(sk, id);
291 	if (id_asoc && (id_asoc != addr_asoc))
292 		return NULL;
293 
294 	sctp_get_pf_specific(sk->sk_family)->addr_to_user(sctp_sk(sk),
295 						(union sctp_addr *)addr);
296 
297 	return transport;
298 }
299 
300 /* API 3.1.2 bind() - UDP Style Syntax
301  * The syntax of bind() is,
302  *
303  *   ret = bind(int sd, struct sockaddr *addr, int addrlen);
304  *
305  *   sd      - the socket descriptor returned by socket().
306  *   addr    - the address structure (struct sockaddr_in or struct
307  *             sockaddr_in6 [RFC 2553]),
308  *   addr_len - the size of the address structure.
309  */
sctp_bind(struct sock * sk,struct sockaddr * addr,int addr_len)310 static int sctp_bind(struct sock *sk, struct sockaddr *addr, int addr_len)
311 {
312 	int retval = 0;
313 
314 	lock_sock(sk);
315 
316 	pr_debug("%s: sk:%p, addr:%p, addr_len:%d\n", __func__, sk,
317 		 addr, addr_len);
318 
319 	/* Disallow binding twice. */
320 	if (!sctp_sk(sk)->ep->base.bind_addr.port)
321 		retval = sctp_do_bind(sk, (union sctp_addr *)addr,
322 				      addr_len);
323 	else
324 		retval = -EINVAL;
325 
326 	release_sock(sk);
327 
328 	return retval;
329 }
330 
331 static int sctp_get_port_local(struct sock *, union sctp_addr *);
332 
333 /* Verify this is a valid sockaddr. */
sctp_sockaddr_af(struct sctp_sock * opt,union sctp_addr * addr,int len)334 static struct sctp_af *sctp_sockaddr_af(struct sctp_sock *opt,
335 					union sctp_addr *addr, int len)
336 {
337 	struct sctp_af *af;
338 
339 	/* Check minimum size.  */
340 	if (len < sizeof (struct sockaddr))
341 		return NULL;
342 
343 	if (!opt->pf->af_supported(addr->sa.sa_family, opt))
344 		return NULL;
345 
346 	if (addr->sa.sa_family == AF_INET6) {
347 		if (len < SIN6_LEN_RFC2133)
348 			return NULL;
349 		/* V4 mapped address are really of AF_INET family */
350 		if (ipv6_addr_v4mapped(&addr->v6.sin6_addr) &&
351 		    !opt->pf->af_supported(AF_INET, opt))
352 			return NULL;
353 	}
354 
355 	/* If we get this far, af is valid. */
356 	af = sctp_get_af_specific(addr->sa.sa_family);
357 
358 	if (len < af->sockaddr_len)
359 		return NULL;
360 
361 	return af;
362 }
363 
sctp_auto_asconf_init(struct sctp_sock * sp)364 static void sctp_auto_asconf_init(struct sctp_sock *sp)
365 {
366 	struct net *net = sock_net(&sp->inet.sk);
367 
368 	if (net->sctp.default_auto_asconf) {
369 		spin_lock_bh(&net->sctp.addr_wq_lock);
370 		list_add_tail(&sp->auto_asconf_list, &net->sctp.auto_asconf_splist);
371 		spin_unlock_bh(&net->sctp.addr_wq_lock);
372 		sp->do_auto_asconf = 1;
373 	}
374 }
375 
376 /* Bind a local address either to an endpoint or to an association.  */
sctp_do_bind(struct sock * sk,union sctp_addr * addr,int len)377 static int sctp_do_bind(struct sock *sk, union sctp_addr *addr, int len)
378 {
379 	struct net *net = sock_net(sk);
380 	struct sctp_sock *sp = sctp_sk(sk);
381 	struct sctp_endpoint *ep = sp->ep;
382 	struct sctp_bind_addr *bp = &ep->base.bind_addr;
383 	struct sctp_af *af;
384 	unsigned short snum;
385 	int ret = 0;
386 
387 	/* Common sockaddr verification. */
388 	af = sctp_sockaddr_af(sp, addr, len);
389 	if (!af) {
390 		pr_debug("%s: sk:%p, newaddr:%p, len:%d EINVAL\n",
391 			 __func__, sk, addr, len);
392 		return -EINVAL;
393 	}
394 
395 	snum = ntohs(addr->v4.sin_port);
396 
397 	pr_debug("%s: sk:%p, new addr:%pISc, port:%d, new port:%d, len:%d\n",
398 		 __func__, sk, &addr->sa, bp->port, snum, len);
399 
400 	/* PF specific bind() address verification. */
401 	if (!sp->pf->bind_verify(sp, addr))
402 		return -EADDRNOTAVAIL;
403 
404 	/* We must either be unbound, or bind to the same port.
405 	 * It's OK to allow 0 ports if we are already bound.
406 	 * We'll just inhert an already bound port in this case
407 	 */
408 	if (bp->port) {
409 		if (!snum)
410 			snum = bp->port;
411 		else if (snum != bp->port) {
412 			pr_debug("%s: new port %d doesn't match existing port "
413 				 "%d\n", __func__, snum, bp->port);
414 			return -EINVAL;
415 		}
416 	}
417 
418 	if (snum && inet_port_requires_bind_service(net, snum) &&
419 	    !ns_capable(net->user_ns, CAP_NET_BIND_SERVICE))
420 		return -EACCES;
421 
422 	/* See if the address matches any of the addresses we may have
423 	 * already bound before checking against other endpoints.
424 	 */
425 	if (sctp_bind_addr_match(bp, addr, sp))
426 		return -EINVAL;
427 
428 	/* Make sure we are allowed to bind here.
429 	 * The function sctp_get_port_local() does duplicate address
430 	 * detection.
431 	 */
432 	addr->v4.sin_port = htons(snum);
433 	if (sctp_get_port_local(sk, addr))
434 		return -EADDRINUSE;
435 
436 	/* Refresh ephemeral port.  */
437 	if (!bp->port) {
438 		bp->port = inet_sk(sk)->inet_num;
439 		sctp_auto_asconf_init(sp);
440 	}
441 
442 	/* Add the address to the bind address list.
443 	 * Use GFP_ATOMIC since BHs will be disabled.
444 	 */
445 	ret = sctp_add_bind_addr(bp, addr, af->sockaddr_len,
446 				 SCTP_ADDR_SRC, GFP_ATOMIC);
447 
448 	if (ret) {
449 		sctp_put_port(sk);
450 		return ret;
451 	}
452 	/* Copy back into socket for getsockname() use. */
453 	inet_sk(sk)->inet_sport = htons(inet_sk(sk)->inet_num);
454 	sp->pf->to_sk_saddr(addr, sk);
455 
456 	return ret;
457 }
458 
459  /* ADDIP Section 4.1.1 Congestion Control of ASCONF Chunks
460  *
461  * R1) One and only one ASCONF Chunk MAY be in transit and unacknowledged
462  * at any one time.  If a sender, after sending an ASCONF chunk, decides
463  * it needs to transfer another ASCONF Chunk, it MUST wait until the
464  * ASCONF-ACK Chunk returns from the previous ASCONF Chunk before sending a
465  * subsequent ASCONF. Note this restriction binds each side, so at any
466  * time two ASCONF may be in-transit on any given association (one sent
467  * from each endpoint).
468  */
sctp_send_asconf(struct sctp_association * asoc,struct sctp_chunk * chunk)469 static int sctp_send_asconf(struct sctp_association *asoc,
470 			    struct sctp_chunk *chunk)
471 {
472 	int retval = 0;
473 
474 	/* If there is an outstanding ASCONF chunk, queue it for later
475 	 * transmission.
476 	 */
477 	if (asoc->addip_last_asconf) {
478 		list_add_tail(&chunk->list, &asoc->addip_chunk_list);
479 		goto out;
480 	}
481 
482 	/* Hold the chunk until an ASCONF_ACK is received. */
483 	sctp_chunk_hold(chunk);
484 	retval = sctp_primitive_ASCONF(asoc->base.net, asoc, chunk);
485 	if (retval)
486 		sctp_chunk_free(chunk);
487 	else
488 		asoc->addip_last_asconf = chunk;
489 
490 out:
491 	return retval;
492 }
493 
494 /* Add a list of addresses as bind addresses to local endpoint or
495  * association.
496  *
497  * Basically run through each address specified in the addrs/addrcnt
498  * array/length pair, determine if it is IPv6 or IPv4 and call
499  * sctp_do_bind() on it.
500  *
501  * If any of them fails, then the operation will be reversed and the
502  * ones that were added will be removed.
503  *
504  * Only sctp_setsockopt_bindx() is supposed to call this function.
505  */
sctp_bindx_add(struct sock * sk,struct sockaddr * addrs,int addrcnt)506 static int sctp_bindx_add(struct sock *sk, struct sockaddr *addrs, int addrcnt)
507 {
508 	int cnt;
509 	int retval = 0;
510 	void *addr_buf;
511 	struct sockaddr *sa_addr;
512 	struct sctp_af *af;
513 
514 	pr_debug("%s: sk:%p, addrs:%p, addrcnt:%d\n", __func__, sk,
515 		 addrs, addrcnt);
516 
517 	addr_buf = addrs;
518 	for (cnt = 0; cnt < addrcnt; cnt++) {
519 		/* The list may contain either IPv4 or IPv6 address;
520 		 * determine the address length for walking thru the list.
521 		 */
522 		sa_addr = addr_buf;
523 		af = sctp_get_af_specific(sa_addr->sa_family);
524 		if (!af) {
525 			retval = -EINVAL;
526 			goto err_bindx_add;
527 		}
528 
529 		retval = sctp_do_bind(sk, (union sctp_addr *)sa_addr,
530 				      af->sockaddr_len);
531 
532 		addr_buf += af->sockaddr_len;
533 
534 err_bindx_add:
535 		if (retval < 0) {
536 			/* Failed. Cleanup the ones that have been added */
537 			if (cnt > 0)
538 				sctp_bindx_rem(sk, addrs, cnt);
539 			return retval;
540 		}
541 	}
542 
543 	return retval;
544 }
545 
546 /* Send an ASCONF chunk with Add IP address parameters to all the peers of the
547  * associations that are part of the endpoint indicating that a list of local
548  * addresses are added to the endpoint.
549  *
550  * If any of the addresses is already in the bind address list of the
551  * association, we do not send the chunk for that association.  But it will not
552  * affect other associations.
553  *
554  * Only sctp_setsockopt_bindx() is supposed to call this function.
555  */
sctp_send_asconf_add_ip(struct sock * sk,struct sockaddr * addrs,int addrcnt)556 static int sctp_send_asconf_add_ip(struct sock		*sk,
557 				   struct sockaddr	*addrs,
558 				   int 			addrcnt)
559 {
560 	struct sctp_sock		*sp;
561 	struct sctp_endpoint		*ep;
562 	struct sctp_association		*asoc;
563 	struct sctp_bind_addr		*bp;
564 	struct sctp_chunk		*chunk;
565 	struct sctp_sockaddr_entry	*laddr;
566 	union sctp_addr			*addr;
567 	union sctp_addr			saveaddr;
568 	void				*addr_buf;
569 	struct sctp_af			*af;
570 	struct list_head		*p;
571 	int 				i;
572 	int 				retval = 0;
573 
574 	sp = sctp_sk(sk);
575 	ep = sp->ep;
576 
577 	if (!ep->asconf_enable)
578 		return retval;
579 
580 	pr_debug("%s: sk:%p, addrs:%p, addrcnt:%d\n",
581 		 __func__, sk, addrs, addrcnt);
582 
583 	list_for_each_entry(asoc, &ep->asocs, asocs) {
584 		if (!asoc->peer.asconf_capable)
585 			continue;
586 
587 		if (asoc->peer.addip_disabled_mask & SCTP_PARAM_ADD_IP)
588 			continue;
589 
590 		if (!sctp_state(asoc, ESTABLISHED))
591 			continue;
592 
593 		/* Check if any address in the packed array of addresses is
594 		 * in the bind address list of the association. If so,
595 		 * do not send the asconf chunk to its peer, but continue with
596 		 * other associations.
597 		 */
598 		addr_buf = addrs;
599 		for (i = 0; i < addrcnt; i++) {
600 			addr = addr_buf;
601 			af = sctp_get_af_specific(addr->v4.sin_family);
602 			if (!af) {
603 				retval = -EINVAL;
604 				goto out;
605 			}
606 
607 			if (sctp_assoc_lookup_laddr(asoc, addr))
608 				break;
609 
610 			addr_buf += af->sockaddr_len;
611 		}
612 		if (i < addrcnt)
613 			continue;
614 
615 		/* Use the first valid address in bind addr list of
616 		 * association as Address Parameter of ASCONF CHUNK.
617 		 */
618 		bp = &asoc->base.bind_addr;
619 		p = bp->address_list.next;
620 		laddr = list_entry(p, struct sctp_sockaddr_entry, list);
621 		chunk = sctp_make_asconf_update_ip(asoc, &laddr->a, addrs,
622 						   addrcnt, SCTP_PARAM_ADD_IP);
623 		if (!chunk) {
624 			retval = -ENOMEM;
625 			goto out;
626 		}
627 
628 		/* Add the new addresses to the bind address list with
629 		 * use_as_src set to 0.
630 		 */
631 		addr_buf = addrs;
632 		for (i = 0; i < addrcnt; i++) {
633 			addr = addr_buf;
634 			af = sctp_get_af_specific(addr->v4.sin_family);
635 			memcpy(&saveaddr, addr, af->sockaddr_len);
636 			retval = sctp_add_bind_addr(bp, &saveaddr,
637 						    sizeof(saveaddr),
638 						    SCTP_ADDR_NEW, GFP_ATOMIC);
639 			addr_buf += af->sockaddr_len;
640 		}
641 		if (asoc->src_out_of_asoc_ok) {
642 			struct sctp_transport *trans;
643 
644 			list_for_each_entry(trans,
645 			    &asoc->peer.transport_addr_list, transports) {
646 				trans->cwnd = min(4*asoc->pathmtu, max_t(__u32,
647 				    2*asoc->pathmtu, 4380));
648 				trans->ssthresh = asoc->peer.i.a_rwnd;
649 				trans->rto = asoc->rto_initial;
650 				sctp_max_rto(asoc, trans);
651 				trans->rtt = trans->srtt = trans->rttvar = 0;
652 				/* Clear the source and route cache */
653 				sctp_transport_route(trans, NULL,
654 						     sctp_sk(asoc->base.sk));
655 			}
656 		}
657 		retval = sctp_send_asconf(asoc, chunk);
658 	}
659 
660 out:
661 	return retval;
662 }
663 
664 /* Remove a list of addresses from bind addresses list.  Do not remove the
665  * last address.
666  *
667  * Basically run through each address specified in the addrs/addrcnt
668  * array/length pair, determine if it is IPv6 or IPv4 and call
669  * sctp_del_bind() on it.
670  *
671  * If any of them fails, then the operation will be reversed and the
672  * ones that were removed will be added back.
673  *
674  * At least one address has to be left; if only one address is
675  * available, the operation will return -EBUSY.
676  *
677  * Only sctp_setsockopt_bindx() is supposed to call this function.
678  */
sctp_bindx_rem(struct sock * sk,struct sockaddr * addrs,int addrcnt)679 static int sctp_bindx_rem(struct sock *sk, struct sockaddr *addrs, int addrcnt)
680 {
681 	struct sctp_sock *sp = sctp_sk(sk);
682 	struct sctp_endpoint *ep = sp->ep;
683 	int cnt;
684 	struct sctp_bind_addr *bp = &ep->base.bind_addr;
685 	int retval = 0;
686 	void *addr_buf;
687 	union sctp_addr *sa_addr;
688 	struct sctp_af *af;
689 
690 	pr_debug("%s: sk:%p, addrs:%p, addrcnt:%d\n",
691 		 __func__, sk, addrs, addrcnt);
692 
693 	addr_buf = addrs;
694 	for (cnt = 0; cnt < addrcnt; cnt++) {
695 		/* If the bind address list is empty or if there is only one
696 		 * bind address, there is nothing more to be removed (we need
697 		 * at least one address here).
698 		 */
699 		if (list_empty(&bp->address_list) ||
700 		    (sctp_list_single_entry(&bp->address_list))) {
701 			retval = -EBUSY;
702 			goto err_bindx_rem;
703 		}
704 
705 		sa_addr = addr_buf;
706 		af = sctp_get_af_specific(sa_addr->sa.sa_family);
707 		if (!af) {
708 			retval = -EINVAL;
709 			goto err_bindx_rem;
710 		}
711 
712 		if (!af->addr_valid(sa_addr, sp, NULL)) {
713 			retval = -EADDRNOTAVAIL;
714 			goto err_bindx_rem;
715 		}
716 
717 		if (sa_addr->v4.sin_port &&
718 		    sa_addr->v4.sin_port != htons(bp->port)) {
719 			retval = -EINVAL;
720 			goto err_bindx_rem;
721 		}
722 
723 		if (!sa_addr->v4.sin_port)
724 			sa_addr->v4.sin_port = htons(bp->port);
725 
726 		/* FIXME - There is probably a need to check if sk->sk_saddr and
727 		 * sk->sk_rcv_addr are currently set to one of the addresses to
728 		 * be removed. This is something which needs to be looked into
729 		 * when we are fixing the outstanding issues with multi-homing
730 		 * socket routing and failover schemes. Refer to comments in
731 		 * sctp_do_bind(). -daisy
732 		 */
733 		retval = sctp_del_bind_addr(bp, sa_addr);
734 
735 		addr_buf += af->sockaddr_len;
736 err_bindx_rem:
737 		if (retval < 0) {
738 			/* Failed. Add the ones that has been removed back */
739 			if (cnt > 0)
740 				sctp_bindx_add(sk, addrs, cnt);
741 			return retval;
742 		}
743 	}
744 
745 	return retval;
746 }
747 
748 /* Send an ASCONF chunk with Delete IP address parameters to all the peers of
749  * the associations that are part of the endpoint indicating that a list of
750  * local addresses are removed from the endpoint.
751  *
752  * If any of the addresses is already in the bind address list of the
753  * association, we do not send the chunk for that association.  But it will not
754  * affect other associations.
755  *
756  * Only sctp_setsockopt_bindx() is supposed to call this function.
757  */
sctp_send_asconf_del_ip(struct sock * sk,struct sockaddr * addrs,int addrcnt)758 static int sctp_send_asconf_del_ip(struct sock		*sk,
759 				   struct sockaddr	*addrs,
760 				   int			addrcnt)
761 {
762 	struct sctp_sock	*sp;
763 	struct sctp_endpoint	*ep;
764 	struct sctp_association	*asoc;
765 	struct sctp_transport	*transport;
766 	struct sctp_bind_addr	*bp;
767 	struct sctp_chunk	*chunk;
768 	union sctp_addr		*laddr;
769 	void			*addr_buf;
770 	struct sctp_af		*af;
771 	struct sctp_sockaddr_entry *saddr;
772 	int 			i;
773 	int 			retval = 0;
774 	int			stored = 0;
775 
776 	chunk = NULL;
777 	sp = sctp_sk(sk);
778 	ep = sp->ep;
779 
780 	if (!ep->asconf_enable)
781 		return retval;
782 
783 	pr_debug("%s: sk:%p, addrs:%p, addrcnt:%d\n",
784 		 __func__, sk, addrs, addrcnt);
785 
786 	list_for_each_entry(asoc, &ep->asocs, asocs) {
787 
788 		if (!asoc->peer.asconf_capable)
789 			continue;
790 
791 		if (asoc->peer.addip_disabled_mask & SCTP_PARAM_DEL_IP)
792 			continue;
793 
794 		if (!sctp_state(asoc, ESTABLISHED))
795 			continue;
796 
797 		/* Check if any address in the packed array of addresses is
798 		 * not present in the bind address list of the association.
799 		 * If so, do not send the asconf chunk to its peer, but
800 		 * continue with other associations.
801 		 */
802 		addr_buf = addrs;
803 		for (i = 0; i < addrcnt; i++) {
804 			laddr = addr_buf;
805 			af = sctp_get_af_specific(laddr->v4.sin_family);
806 			if (!af) {
807 				retval = -EINVAL;
808 				goto out;
809 			}
810 
811 			if (!sctp_assoc_lookup_laddr(asoc, laddr))
812 				break;
813 
814 			addr_buf += af->sockaddr_len;
815 		}
816 		if (i < addrcnt)
817 			continue;
818 
819 		/* Find one address in the association's bind address list
820 		 * that is not in the packed array of addresses. This is to
821 		 * make sure that we do not delete all the addresses in the
822 		 * association.
823 		 */
824 		bp = &asoc->base.bind_addr;
825 		laddr = sctp_find_unmatch_addr(bp, (union sctp_addr *)addrs,
826 					       addrcnt, sp);
827 		if ((laddr == NULL) && (addrcnt == 1)) {
828 			if (asoc->asconf_addr_del_pending)
829 				continue;
830 			asoc->asconf_addr_del_pending =
831 			    kzalloc(sizeof(union sctp_addr), GFP_ATOMIC);
832 			if (asoc->asconf_addr_del_pending == NULL) {
833 				retval = -ENOMEM;
834 				goto out;
835 			}
836 			asoc->asconf_addr_del_pending->sa.sa_family =
837 				    addrs->sa_family;
838 			asoc->asconf_addr_del_pending->v4.sin_port =
839 				    htons(bp->port);
840 			if (addrs->sa_family == AF_INET) {
841 				struct sockaddr_in *sin;
842 
843 				sin = (struct sockaddr_in *)addrs;
844 				asoc->asconf_addr_del_pending->v4.sin_addr.s_addr = sin->sin_addr.s_addr;
845 			} else if (addrs->sa_family == AF_INET6) {
846 				struct sockaddr_in6 *sin6;
847 
848 				sin6 = (struct sockaddr_in6 *)addrs;
849 				asoc->asconf_addr_del_pending->v6.sin6_addr = sin6->sin6_addr;
850 			}
851 
852 			pr_debug("%s: keep the last address asoc:%p %pISc at %p\n",
853 				 __func__, asoc, &asoc->asconf_addr_del_pending->sa,
854 				 asoc->asconf_addr_del_pending);
855 
856 			asoc->src_out_of_asoc_ok = 1;
857 			stored = 1;
858 			goto skip_mkasconf;
859 		}
860 
861 		if (laddr == NULL)
862 			return -EINVAL;
863 
864 		/* We do not need RCU protection throughout this loop
865 		 * because this is done under a socket lock from the
866 		 * setsockopt call.
867 		 */
868 		chunk = sctp_make_asconf_update_ip(asoc, laddr, addrs, addrcnt,
869 						   SCTP_PARAM_DEL_IP);
870 		if (!chunk) {
871 			retval = -ENOMEM;
872 			goto out;
873 		}
874 
875 skip_mkasconf:
876 		/* Reset use_as_src flag for the addresses in the bind address
877 		 * list that are to be deleted.
878 		 */
879 		addr_buf = addrs;
880 		for (i = 0; i < addrcnt; i++) {
881 			laddr = addr_buf;
882 			af = sctp_get_af_specific(laddr->v4.sin_family);
883 			list_for_each_entry(saddr, &bp->address_list, list) {
884 				if (sctp_cmp_addr_exact(&saddr->a, laddr))
885 					saddr->state = SCTP_ADDR_DEL;
886 			}
887 			addr_buf += af->sockaddr_len;
888 		}
889 
890 		/* Update the route and saddr entries for all the transports
891 		 * as some of the addresses in the bind address list are
892 		 * about to be deleted and cannot be used as source addresses.
893 		 */
894 		list_for_each_entry(transport, &asoc->peer.transport_addr_list,
895 					transports) {
896 			sctp_transport_route(transport, NULL,
897 					     sctp_sk(asoc->base.sk));
898 		}
899 
900 		if (stored)
901 			/* We don't need to transmit ASCONF */
902 			continue;
903 		retval = sctp_send_asconf(asoc, chunk);
904 	}
905 out:
906 	return retval;
907 }
908 
909 /* 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)910 int sctp_asconf_mgmt(struct sctp_sock *sp, struct sctp_sockaddr_entry *addrw)
911 {
912 	struct sock *sk = sctp_opt2sk(sp);
913 	union sctp_addr *addr;
914 	struct sctp_af *af;
915 
916 	/* It is safe to write port space in caller. */
917 	addr = &addrw->a;
918 	addr->v4.sin_port = htons(sp->ep->base.bind_addr.port);
919 	af = sctp_get_af_specific(addr->sa.sa_family);
920 	if (!af)
921 		return -EINVAL;
922 	if (sctp_verify_addr(sk, addr, af->sockaddr_len))
923 		return -EINVAL;
924 
925 	if (addrw->state == SCTP_ADDR_NEW)
926 		return sctp_send_asconf_add_ip(sk, (struct sockaddr *)addr, 1);
927 	else
928 		return sctp_send_asconf_del_ip(sk, (struct sockaddr *)addr, 1);
929 }
930 
931 /* Helper for tunneling sctp_bindx() requests through sctp_setsockopt()
932  *
933  * API 8.1
934  * int sctp_bindx(int sd, struct sockaddr *addrs, int addrcnt,
935  *                int flags);
936  *
937  * If sd is an IPv4 socket, the addresses passed must be IPv4 addresses.
938  * If the sd is an IPv6 socket, the addresses passed can either be IPv4
939  * or IPv6 addresses.
940  *
941  * A single address may be specified as INADDR_ANY or IN6ADDR_ANY, see
942  * Section 3.1.2 for this usage.
943  *
944  * addrs is a pointer to an array of one or more socket addresses. Each
945  * address is contained in its appropriate structure (i.e. struct
946  * sockaddr_in or struct sockaddr_in6) the family of the address type
947  * must be used to distinguish the address length (note that this
948  * representation is termed a "packed array" of addresses). The caller
949  * specifies the number of addresses in the array with addrcnt.
950  *
951  * On success, sctp_bindx() returns 0. On failure, sctp_bindx() returns
952  * -1, and sets errno to the appropriate error code.
953  *
954  * For SCTP, the port given in each socket address must be the same, or
955  * sctp_bindx() will fail, setting errno to EINVAL.
956  *
957  * The flags parameter is formed from the bitwise OR of zero or more of
958  * the following currently defined flags:
959  *
960  * SCTP_BINDX_ADD_ADDR
961  *
962  * SCTP_BINDX_REM_ADDR
963  *
964  * SCTP_BINDX_ADD_ADDR directs SCTP to add the given addresses to the
965  * association, and SCTP_BINDX_REM_ADDR directs SCTP to remove the given
966  * addresses from the association. The two flags are mutually exclusive;
967  * if both are given, sctp_bindx() will fail with EINVAL. A caller may
968  * not remove all addresses from an association; sctp_bindx() will
969  * reject such an attempt with EINVAL.
970  *
971  * An application can use sctp_bindx(SCTP_BINDX_ADD_ADDR) to associate
972  * additional addresses with an endpoint after calling bind().  Or use
973  * sctp_bindx(SCTP_BINDX_REM_ADDR) to remove some addresses a listening
974  * socket is associated with so that no new association accepted will be
975  * associated with those addresses. If the endpoint supports dynamic
976  * address a SCTP_BINDX_REM_ADDR or SCTP_BINDX_ADD_ADDR may cause a
977  * endpoint to send the appropriate message to the peer to change the
978  * peers address lists.
979  *
980  * Adding and removing addresses from a connected association is
981  * optional functionality. Implementations that do not support this
982  * functionality should return EOPNOTSUPP.
983  *
984  * Basically do nothing but copying the addresses from user to kernel
985  * land and invoking either sctp_bindx_add() or sctp_bindx_rem() on the sk.
986  * This is used for tunneling the sctp_bindx() request through sctp_setsockopt()
987  * from userspace.
988  *
989  * On exit there is no need to do sockfd_put(), sys_setsockopt() does
990  * it.
991  *
992  * sk        The sk of the socket
993  * addrs     The pointer to the addresses
994  * addrssize Size of the addrs buffer
995  * op        Operation to perform (add or remove, see the flags of
996  *           sctp_bindx)
997  *
998  * Returns 0 if ok, <0 errno code on error.
999  */
sctp_setsockopt_bindx(struct sock * sk,struct sockaddr * addrs,int addrs_size,int op)1000 static int sctp_setsockopt_bindx(struct sock *sk, struct sockaddr *addrs,
1001 				 int addrs_size, int op)
1002 {
1003 	int err;
1004 	int addrcnt = 0;
1005 	int walk_size = 0;
1006 	struct sockaddr *sa_addr;
1007 	void *addr_buf = addrs;
1008 	struct sctp_af *af;
1009 
1010 	pr_debug("%s: sk:%p addrs:%p addrs_size:%d opt:%d\n",
1011 		 __func__, sk, addr_buf, addrs_size, op);
1012 
1013 	if (unlikely(addrs_size <= 0))
1014 		return -EINVAL;
1015 
1016 	/* Walk through the addrs buffer and count the number of addresses. */
1017 	while (walk_size < addrs_size) {
1018 		if (walk_size + sizeof(sa_family_t) > addrs_size)
1019 			return -EINVAL;
1020 
1021 		sa_addr = addr_buf;
1022 		af = sctp_get_af_specific(sa_addr->sa_family);
1023 
1024 		/* If the address family is not supported or if this address
1025 		 * causes the address buffer to overflow return EINVAL.
1026 		 */
1027 		if (!af || (walk_size + af->sockaddr_len) > addrs_size)
1028 			return -EINVAL;
1029 		addrcnt++;
1030 		addr_buf += af->sockaddr_len;
1031 		walk_size += af->sockaddr_len;
1032 	}
1033 
1034 	/* Do the work. */
1035 	switch (op) {
1036 	case SCTP_BINDX_ADD_ADDR:
1037 		/* Allow security module to validate bindx addresses. */
1038 		err = security_sctp_bind_connect(sk, SCTP_SOCKOPT_BINDX_ADD,
1039 						 addrs, addrs_size);
1040 		if (err)
1041 			return err;
1042 		err = sctp_bindx_add(sk, addrs, addrcnt);
1043 		if (err)
1044 			return err;
1045 		return sctp_send_asconf_add_ip(sk, addrs, addrcnt);
1046 	case SCTP_BINDX_REM_ADDR:
1047 		err = sctp_bindx_rem(sk, addrs, addrcnt);
1048 		if (err)
1049 			return err;
1050 		return sctp_send_asconf_del_ip(sk, addrs, addrcnt);
1051 
1052 	default:
1053 		return -EINVAL;
1054 	}
1055 }
1056 
sctp_bind_add(struct sock * sk,struct sockaddr * addrs,int addrlen)1057 static int sctp_bind_add(struct sock *sk, struct sockaddr *addrs,
1058 		int addrlen)
1059 {
1060 	int err;
1061 
1062 	lock_sock(sk);
1063 	err = sctp_setsockopt_bindx(sk, addrs, addrlen, SCTP_BINDX_ADD_ADDR);
1064 	release_sock(sk);
1065 	return err;
1066 }
1067 
sctp_connect_new_asoc(struct sctp_endpoint * ep,const union sctp_addr * daddr,const struct sctp_initmsg * init,struct sctp_transport ** tp)1068 static int sctp_connect_new_asoc(struct sctp_endpoint *ep,
1069 				 const union sctp_addr *daddr,
1070 				 const struct sctp_initmsg *init,
1071 				 struct sctp_transport **tp)
1072 {
1073 	struct sctp_association *asoc;
1074 	struct sock *sk = ep->base.sk;
1075 	struct net *net = sock_net(sk);
1076 	enum sctp_scope scope;
1077 	int err;
1078 
1079 	if (sctp_endpoint_is_peeled_off(ep, daddr))
1080 		return -EADDRNOTAVAIL;
1081 
1082 	if (!ep->base.bind_addr.port) {
1083 		if (sctp_autobind(sk))
1084 			return -EAGAIN;
1085 	} else {
1086 		if (inet_port_requires_bind_service(net, ep->base.bind_addr.port) &&
1087 		    !ns_capable(net->user_ns, CAP_NET_BIND_SERVICE))
1088 			return -EACCES;
1089 	}
1090 
1091 	scope = sctp_scope(daddr);
1092 	asoc = sctp_association_new(ep, sk, scope, GFP_KERNEL);
1093 	if (!asoc)
1094 		return -ENOMEM;
1095 
1096 	err = sctp_assoc_set_bind_addr_from_ep(asoc, scope, GFP_KERNEL);
1097 	if (err < 0)
1098 		goto free;
1099 
1100 	*tp = sctp_assoc_add_peer(asoc, daddr, GFP_KERNEL, SCTP_UNKNOWN);
1101 	if (!*tp) {
1102 		err = -ENOMEM;
1103 		goto free;
1104 	}
1105 
1106 	if (!init)
1107 		return 0;
1108 
1109 	if (init->sinit_num_ostreams) {
1110 		__u16 outcnt = init->sinit_num_ostreams;
1111 
1112 		asoc->c.sinit_num_ostreams = outcnt;
1113 		/* outcnt has been changed, need to re-init stream */
1114 		err = sctp_stream_init(&asoc->stream, outcnt, 0, GFP_KERNEL);
1115 		if (err)
1116 			goto free;
1117 	}
1118 
1119 	if (init->sinit_max_instreams)
1120 		asoc->c.sinit_max_instreams = init->sinit_max_instreams;
1121 
1122 	if (init->sinit_max_attempts)
1123 		asoc->max_init_attempts = init->sinit_max_attempts;
1124 
1125 	if (init->sinit_max_init_timeo)
1126 		asoc->max_init_timeo =
1127 			msecs_to_jiffies(init->sinit_max_init_timeo);
1128 
1129 	return 0;
1130 free:
1131 	sctp_association_free(asoc);
1132 	return err;
1133 }
1134 
sctp_connect_add_peer(struct sctp_association * asoc,union sctp_addr * daddr,int addr_len)1135 static int sctp_connect_add_peer(struct sctp_association *asoc,
1136 				 union sctp_addr *daddr, int addr_len)
1137 {
1138 	struct sctp_endpoint *ep = asoc->ep;
1139 	struct sctp_association *old;
1140 	struct sctp_transport *t;
1141 	int err;
1142 
1143 	err = sctp_verify_addr(ep->base.sk, daddr, addr_len);
1144 	if (err)
1145 		return err;
1146 
1147 	old = sctp_endpoint_lookup_assoc(ep, daddr, &t);
1148 	if (old && old != asoc)
1149 		return old->state >= SCTP_STATE_ESTABLISHED ? -EISCONN
1150 							    : -EALREADY;
1151 
1152 	if (sctp_endpoint_is_peeled_off(ep, daddr))
1153 		return -EADDRNOTAVAIL;
1154 
1155 	t = sctp_assoc_add_peer(asoc, daddr, GFP_KERNEL, SCTP_UNKNOWN);
1156 	if (!t)
1157 		return -ENOMEM;
1158 
1159 	return 0;
1160 }
1161 
1162 /* __sctp_connect(struct sock* sk, struct sockaddr *kaddrs, int addrs_size)
1163  *
1164  * Common routine for handling connect() and sctp_connectx().
1165  * Connect will come in with just a single address.
1166  */
__sctp_connect(struct sock * sk,struct sockaddr * kaddrs,int addrs_size,int flags,sctp_assoc_t * assoc_id)1167 static int __sctp_connect(struct sock *sk, struct sockaddr *kaddrs,
1168 			  int addrs_size, int flags, sctp_assoc_t *assoc_id)
1169 {
1170 	struct sctp_sock *sp = sctp_sk(sk);
1171 	struct sctp_endpoint *ep = sp->ep;
1172 	struct sctp_transport *transport;
1173 	struct sctp_association *asoc;
1174 	void *addr_buf = kaddrs;
1175 	union sctp_addr *daddr;
1176 	struct sctp_af *af;
1177 	int walk_size, err;
1178 	long timeo;
1179 
1180 	if (sctp_sstate(sk, ESTABLISHED) || sctp_sstate(sk, CLOSING) ||
1181 	    (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING)))
1182 		return -EISCONN;
1183 
1184 	daddr = addr_buf;
1185 	af = sctp_get_af_specific(daddr->sa.sa_family);
1186 	if (!af || af->sockaddr_len > addrs_size)
1187 		return -EINVAL;
1188 
1189 	err = sctp_verify_addr(sk, daddr, af->sockaddr_len);
1190 	if (err)
1191 		return err;
1192 
1193 	asoc = sctp_endpoint_lookup_assoc(ep, daddr, &transport);
1194 	if (asoc)
1195 		return asoc->state >= SCTP_STATE_ESTABLISHED ? -EISCONN
1196 							     : -EALREADY;
1197 
1198 	err = sctp_connect_new_asoc(ep, daddr, NULL, &transport);
1199 	if (err)
1200 		return err;
1201 	asoc = transport->asoc;
1202 
1203 	addr_buf += af->sockaddr_len;
1204 	walk_size = af->sockaddr_len;
1205 	while (walk_size < addrs_size) {
1206 		err = -EINVAL;
1207 		if (walk_size + sizeof(sa_family_t) > addrs_size)
1208 			goto out_free;
1209 
1210 		daddr = addr_buf;
1211 		af = sctp_get_af_specific(daddr->sa.sa_family);
1212 		if (!af || af->sockaddr_len + walk_size > addrs_size)
1213 			goto out_free;
1214 
1215 		if (asoc->peer.port != ntohs(daddr->v4.sin_port))
1216 			goto out_free;
1217 
1218 		err = sctp_connect_add_peer(asoc, daddr, af->sockaddr_len);
1219 		if (err)
1220 			goto out_free;
1221 
1222 		addr_buf  += af->sockaddr_len;
1223 		walk_size += af->sockaddr_len;
1224 	}
1225 
1226 	/* In case the user of sctp_connectx() wants an association
1227 	 * id back, assign one now.
1228 	 */
1229 	if (assoc_id) {
1230 		err = sctp_assoc_set_id(asoc, GFP_KERNEL);
1231 		if (err < 0)
1232 			goto out_free;
1233 	}
1234 
1235 	err = sctp_primitive_ASSOCIATE(sock_net(sk), asoc, NULL);
1236 	if (err < 0)
1237 		goto out_free;
1238 
1239 	/* Initialize sk's dport and daddr for getpeername() */
1240 	inet_sk(sk)->inet_dport = htons(asoc->peer.port);
1241 	sp->pf->to_sk_daddr(daddr, sk);
1242 	sk->sk_err = 0;
1243 
1244 	if (assoc_id)
1245 		*assoc_id = asoc->assoc_id;
1246 
1247 	timeo = sock_sndtimeo(sk, flags & O_NONBLOCK);
1248 	return sctp_wait_for_connect(asoc, &timeo);
1249 
1250 out_free:
1251 	pr_debug("%s: took out_free path with asoc:%p kaddrs:%p err:%d\n",
1252 		 __func__, asoc, kaddrs, err);
1253 	sctp_association_free(asoc);
1254 	return err;
1255 }
1256 
1257 /* Helper for tunneling sctp_connectx() requests through sctp_setsockopt()
1258  *
1259  * API 8.9
1260  * int sctp_connectx(int sd, struct sockaddr *addrs, int addrcnt,
1261  * 			sctp_assoc_t *asoc);
1262  *
1263  * If sd is an IPv4 socket, the addresses passed must be IPv4 addresses.
1264  * If the sd is an IPv6 socket, the addresses passed can either be IPv4
1265  * or IPv6 addresses.
1266  *
1267  * A single address may be specified as INADDR_ANY or IN6ADDR_ANY, see
1268  * Section 3.1.2 for this usage.
1269  *
1270  * addrs is a pointer to an array of one or more socket addresses. Each
1271  * address is contained in its appropriate structure (i.e. struct
1272  * sockaddr_in or struct sockaddr_in6) the family of the address type
1273  * must be used to distengish the address length (note that this
1274  * representation is termed a "packed array" of addresses). The caller
1275  * specifies the number of addresses in the array with addrcnt.
1276  *
1277  * On success, sctp_connectx() returns 0. It also sets the assoc_id to
1278  * the association id of the new association.  On failure, sctp_connectx()
1279  * returns -1, and sets errno to the appropriate error code.  The assoc_id
1280  * is not touched by the kernel.
1281  *
1282  * For SCTP, the port given in each socket address must be the same, or
1283  * sctp_connectx() will fail, setting errno to EINVAL.
1284  *
1285  * An application can use sctp_connectx to initiate an association with
1286  * an endpoint that is multi-homed.  Much like sctp_bindx() this call
1287  * allows a caller to specify multiple addresses at which a peer can be
1288  * reached.  The way the SCTP stack uses the list of addresses to set up
1289  * the association is implementation dependent.  This function only
1290  * specifies that the stack will try to make use of all the addresses in
1291  * the list when needed.
1292  *
1293  * Note that the list of addresses passed in is only used for setting up
1294  * the association.  It does not necessarily equal the set of addresses
1295  * the peer uses for the resulting association.  If the caller wants to
1296  * find out the set of peer addresses, it must use sctp_getpaddrs() to
1297  * retrieve them after the association has been set up.
1298  *
1299  * Basically do nothing but copying the addresses from user to kernel
1300  * land and invoking either sctp_connectx(). This is used for tunneling
1301  * the sctp_connectx() request through sctp_setsockopt() from userspace.
1302  *
1303  * On exit there is no need to do sockfd_put(), sys_setsockopt() does
1304  * it.
1305  *
1306  * sk        The sk of the socket
1307  * addrs     The pointer to the addresses
1308  * addrssize Size of the addrs buffer
1309  *
1310  * Returns >=0 if ok, <0 errno code on error.
1311  */
__sctp_setsockopt_connectx(struct sock * sk,struct sockaddr * kaddrs,int addrs_size,sctp_assoc_t * assoc_id)1312 static int __sctp_setsockopt_connectx(struct sock *sk, struct sockaddr *kaddrs,
1313 				      int addrs_size, sctp_assoc_t *assoc_id)
1314 {
1315 	int err = 0, flags = 0;
1316 
1317 	pr_debug("%s: sk:%p addrs:%p addrs_size:%d\n",
1318 		 __func__, sk, kaddrs, addrs_size);
1319 
1320 	/* make sure the 1st addr's sa_family is accessible later */
1321 	if (unlikely(addrs_size < sizeof(sa_family_t)))
1322 		return -EINVAL;
1323 
1324 	/* Allow security module to validate connectx addresses. */
1325 	err = security_sctp_bind_connect(sk, SCTP_SOCKOPT_CONNECTX,
1326 					 (struct sockaddr *)kaddrs,
1327 					  addrs_size);
1328 	if (err)
1329 		return err;
1330 
1331 	/* in-kernel sockets don't generally have a file allocated to them
1332 	 * if all they do is call sock_create_kern().
1333 	 */
1334 	if (sk->sk_socket->file)
1335 		flags = sk->sk_socket->file->f_flags;
1336 
1337 	return __sctp_connect(sk, kaddrs, addrs_size, flags, assoc_id);
1338 }
1339 
1340 /*
1341  * This is an older interface.  It's kept for backward compatibility
1342  * to the option that doesn't provide association id.
1343  */
sctp_setsockopt_connectx_old(struct sock * sk,struct sockaddr * kaddrs,int addrs_size)1344 static int sctp_setsockopt_connectx_old(struct sock *sk,
1345 					struct sockaddr *kaddrs,
1346 					int addrs_size)
1347 {
1348 	return __sctp_setsockopt_connectx(sk, kaddrs, addrs_size, NULL);
1349 }
1350 
1351 /*
1352  * New interface for the API.  The since the API is done with a socket
1353  * option, to make it simple we feed back the association id is as a return
1354  * indication to the call.  Error is always negative and association id is
1355  * always positive.
1356  */
sctp_setsockopt_connectx(struct sock * sk,struct sockaddr * kaddrs,int addrs_size)1357 static int sctp_setsockopt_connectx(struct sock *sk,
1358 				    struct sockaddr *kaddrs,
1359 				    int addrs_size)
1360 {
1361 	sctp_assoc_t assoc_id = 0;
1362 	int err = 0;
1363 
1364 	err = __sctp_setsockopt_connectx(sk, kaddrs, addrs_size, &assoc_id);
1365 
1366 	if (err)
1367 		return err;
1368 	else
1369 		return assoc_id;
1370 }
1371 
1372 /*
1373  * New (hopefully final) interface for the API.
1374  * We use the sctp_getaddrs_old structure so that use-space library
1375  * can avoid any unnecessary allocations. The only different part
1376  * is that we store the actual length of the address buffer into the
1377  * addrs_num structure member. That way we can re-use the existing
1378  * code.
1379  */
1380 #ifdef CONFIG_COMPAT
1381 struct compat_sctp_getaddrs_old {
1382 	sctp_assoc_t	assoc_id;
1383 	s32		addr_num;
1384 	compat_uptr_t	addrs;		/* struct sockaddr * */
1385 };
1386 #endif
1387 
sctp_getsockopt_connectx3(struct sock * sk,int len,char __user * optval,int __user * optlen)1388 static int sctp_getsockopt_connectx3(struct sock *sk, int len,
1389 				     char __user *optval,
1390 				     int __user *optlen)
1391 {
1392 	struct sctp_getaddrs_old param;
1393 	sctp_assoc_t assoc_id = 0;
1394 	struct sockaddr *kaddrs;
1395 	int err = 0;
1396 
1397 #ifdef CONFIG_COMPAT
1398 	if (in_compat_syscall()) {
1399 		struct compat_sctp_getaddrs_old param32;
1400 
1401 		if (len < sizeof(param32))
1402 			return -EINVAL;
1403 		if (copy_from_user(&param32, optval, sizeof(param32)))
1404 			return -EFAULT;
1405 
1406 		param.assoc_id = param32.assoc_id;
1407 		param.addr_num = param32.addr_num;
1408 		param.addrs = compat_ptr(param32.addrs);
1409 	} else
1410 #endif
1411 	{
1412 		if (len < sizeof(param))
1413 			return -EINVAL;
1414 		if (copy_from_user(&param, optval, sizeof(param)))
1415 			return -EFAULT;
1416 	}
1417 
1418 	kaddrs = memdup_user(param.addrs, param.addr_num);
1419 	if (IS_ERR(kaddrs))
1420 		return PTR_ERR(kaddrs);
1421 
1422 	err = __sctp_setsockopt_connectx(sk, kaddrs, param.addr_num, &assoc_id);
1423 	kfree(kaddrs);
1424 	if (err == 0 || err == -EINPROGRESS) {
1425 		if (copy_to_user(optval, &assoc_id, sizeof(assoc_id)))
1426 			return -EFAULT;
1427 		if (put_user(sizeof(assoc_id), optlen))
1428 			return -EFAULT;
1429 	}
1430 
1431 	return err;
1432 }
1433 
1434 /* API 3.1.4 close() - UDP Style Syntax
1435  * Applications use close() to perform graceful shutdown (as described in
1436  * Section 10.1 of [SCTP]) on ALL the associations currently represented
1437  * by a UDP-style socket.
1438  *
1439  * The syntax is
1440  *
1441  *   ret = close(int sd);
1442  *
1443  *   sd      - the socket descriptor of the associations to be closed.
1444  *
1445  * To gracefully shutdown a specific association represented by the
1446  * UDP-style socket, an application should use the sendmsg() call,
1447  * passing no user data, but including the appropriate flag in the
1448  * ancillary data (see Section xxxx).
1449  *
1450  * If sd in the close() call is a branched-off socket representing only
1451  * one association, the shutdown is performed on that association only.
1452  *
1453  * 4.1.6 close() - TCP Style Syntax
1454  *
1455  * Applications use close() to gracefully close down an association.
1456  *
1457  * The syntax is:
1458  *
1459  *    int close(int sd);
1460  *
1461  *      sd      - the socket descriptor of the association to be closed.
1462  *
1463  * After an application calls close() on a socket descriptor, no further
1464  * socket operations will succeed on that descriptor.
1465  *
1466  * API 7.1.4 SO_LINGER
1467  *
1468  * An application using the TCP-style socket can use this option to
1469  * perform the SCTP ABORT primitive.  The linger option structure is:
1470  *
1471  *  struct  linger {
1472  *     int     l_onoff;                // option on/off
1473  *     int     l_linger;               // linger time
1474  * };
1475  *
1476  * To enable the option, set l_onoff to 1.  If the l_linger value is set
1477  * to 0, calling close() is the same as the ABORT primitive.  If the
1478  * value is set to a negative value, the setsockopt() call will return
1479  * an error.  If the value is set to a positive value linger_time, the
1480  * close() can be blocked for at most linger_time ms.  If the graceful
1481  * shutdown phase does not finish during this period, close() will
1482  * return but the graceful shutdown phase continues in the system.
1483  */
sctp_close(struct sock * sk,long timeout)1484 static void sctp_close(struct sock *sk, long timeout)
1485 {
1486 	struct net *net = sock_net(sk);
1487 	struct sctp_endpoint *ep;
1488 	struct sctp_association *asoc;
1489 	struct list_head *pos, *temp;
1490 	unsigned int data_was_unread;
1491 
1492 	pr_debug("%s: sk:%p, timeout:%ld\n", __func__, sk, timeout);
1493 
1494 	lock_sock_nested(sk, SINGLE_DEPTH_NESTING);
1495 	sk->sk_shutdown = SHUTDOWN_MASK;
1496 	inet_sk_set_state(sk, SCTP_SS_CLOSING);
1497 
1498 	ep = sctp_sk(sk)->ep;
1499 
1500 	/* Clean up any skbs sitting on the receive queue.  */
1501 	data_was_unread = sctp_queue_purge_ulpevents(&sk->sk_receive_queue);
1502 	data_was_unread += sctp_queue_purge_ulpevents(&sctp_sk(sk)->pd_lobby);
1503 
1504 	/* Walk all associations on an endpoint.  */
1505 	list_for_each_safe(pos, temp, &ep->asocs) {
1506 		asoc = list_entry(pos, struct sctp_association, asocs);
1507 
1508 		if (sctp_style(sk, TCP)) {
1509 			/* A closed association can still be in the list if
1510 			 * it belongs to a TCP-style listening socket that is
1511 			 * not yet accepted. If so, free it. If not, send an
1512 			 * ABORT or SHUTDOWN based on the linger options.
1513 			 */
1514 			if (sctp_state(asoc, CLOSED)) {
1515 				sctp_association_free(asoc);
1516 				continue;
1517 			}
1518 		}
1519 
1520 		if (data_was_unread || !skb_queue_empty(&asoc->ulpq.lobby) ||
1521 		    !skb_queue_empty(&asoc->ulpq.reasm) ||
1522 		    !skb_queue_empty(&asoc->ulpq.reasm_uo) ||
1523 		    (sock_flag(sk, SOCK_LINGER) && !sk->sk_lingertime)) {
1524 			struct sctp_chunk *chunk;
1525 
1526 			chunk = sctp_make_abort_user(asoc, NULL, 0);
1527 			sctp_primitive_ABORT(net, asoc, chunk);
1528 		} else
1529 			sctp_primitive_SHUTDOWN(net, asoc, NULL);
1530 	}
1531 
1532 	/* On a TCP-style socket, block for at most linger_time if set. */
1533 	if (sctp_style(sk, TCP) && timeout)
1534 		sctp_wait_for_close(sk, timeout);
1535 
1536 	/* This will run the backlog queue.  */
1537 	release_sock(sk);
1538 
1539 	/* Supposedly, no process has access to the socket, but
1540 	 * the net layers still may.
1541 	 * Also, sctp_destroy_sock() needs to be called with addr_wq_lock
1542 	 * held and that should be grabbed before socket lock.
1543 	 */
1544 	spin_lock_bh(&net->sctp.addr_wq_lock);
1545 	bh_lock_sock_nested(sk);
1546 
1547 	/* Hold the sock, since sk_common_release() will put sock_put()
1548 	 * and we have just a little more cleanup.
1549 	 */
1550 	sock_hold(sk);
1551 	sk_common_release(sk);
1552 
1553 	bh_unlock_sock(sk);
1554 	spin_unlock_bh(&net->sctp.addr_wq_lock);
1555 
1556 	sock_put(sk);
1557 
1558 	SCTP_DBG_OBJCNT_DEC(sock);
1559 }
1560 
1561 /* Handle EPIPE error. */
sctp_error(struct sock * sk,int flags,int err)1562 static int sctp_error(struct sock *sk, int flags, int err)
1563 {
1564 	if (err == -EPIPE)
1565 		err = sock_error(sk) ? : -EPIPE;
1566 	if (err == -EPIPE && !(flags & MSG_NOSIGNAL))
1567 		send_sig(SIGPIPE, current, 0);
1568 	return err;
1569 }
1570 
1571 /* API 3.1.3 sendmsg() - UDP Style Syntax
1572  *
1573  * An application uses sendmsg() and recvmsg() calls to transmit data to
1574  * and receive data from its peer.
1575  *
1576  *  ssize_t sendmsg(int socket, const struct msghdr *message,
1577  *                  int flags);
1578  *
1579  *  socket  - the socket descriptor of the endpoint.
1580  *  message - pointer to the msghdr structure which contains a single
1581  *            user message and possibly some ancillary data.
1582  *
1583  *            See Section 5 for complete description of the data
1584  *            structures.
1585  *
1586  *  flags   - flags sent or received with the user message, see Section
1587  *            5 for complete description of the flags.
1588  *
1589  * Note:  This function could use a rewrite especially when explicit
1590  * connect support comes in.
1591  */
1592 /* BUG:  We do not implement the equivalent of sk_stream_wait_memory(). */
1593 
1594 static int sctp_msghdr_parse(const struct msghdr *msg,
1595 			     struct sctp_cmsgs *cmsgs);
1596 
sctp_sendmsg_parse(struct sock * sk,struct sctp_cmsgs * cmsgs,struct sctp_sndrcvinfo * srinfo,const struct msghdr * msg,size_t msg_len)1597 static int sctp_sendmsg_parse(struct sock *sk, struct sctp_cmsgs *cmsgs,
1598 			      struct sctp_sndrcvinfo *srinfo,
1599 			      const struct msghdr *msg, size_t msg_len)
1600 {
1601 	__u16 sflags;
1602 	int err;
1603 
1604 	if (sctp_sstate(sk, LISTENING) && sctp_style(sk, TCP))
1605 		return -EPIPE;
1606 
1607 	if (msg_len > sk->sk_sndbuf)
1608 		return -EMSGSIZE;
1609 
1610 	memset(cmsgs, 0, sizeof(*cmsgs));
1611 	err = sctp_msghdr_parse(msg, cmsgs);
1612 	if (err) {
1613 		pr_debug("%s: msghdr parse err:%x\n", __func__, err);
1614 		return err;
1615 	}
1616 
1617 	memset(srinfo, 0, sizeof(*srinfo));
1618 	if (cmsgs->srinfo) {
1619 		srinfo->sinfo_stream = cmsgs->srinfo->sinfo_stream;
1620 		srinfo->sinfo_flags = cmsgs->srinfo->sinfo_flags;
1621 		srinfo->sinfo_ppid = cmsgs->srinfo->sinfo_ppid;
1622 		srinfo->sinfo_context = cmsgs->srinfo->sinfo_context;
1623 		srinfo->sinfo_assoc_id = cmsgs->srinfo->sinfo_assoc_id;
1624 		srinfo->sinfo_timetolive = cmsgs->srinfo->sinfo_timetolive;
1625 	}
1626 
1627 	if (cmsgs->sinfo) {
1628 		srinfo->sinfo_stream = cmsgs->sinfo->snd_sid;
1629 		srinfo->sinfo_flags = cmsgs->sinfo->snd_flags;
1630 		srinfo->sinfo_ppid = cmsgs->sinfo->snd_ppid;
1631 		srinfo->sinfo_context = cmsgs->sinfo->snd_context;
1632 		srinfo->sinfo_assoc_id = cmsgs->sinfo->snd_assoc_id;
1633 	}
1634 
1635 	if (cmsgs->prinfo) {
1636 		srinfo->sinfo_timetolive = cmsgs->prinfo->pr_value;
1637 		SCTP_PR_SET_POLICY(srinfo->sinfo_flags,
1638 				   cmsgs->prinfo->pr_policy);
1639 	}
1640 
1641 	sflags = srinfo->sinfo_flags;
1642 	if (!sflags && msg_len)
1643 		return 0;
1644 
1645 	if (sctp_style(sk, TCP) && (sflags & (SCTP_EOF | SCTP_ABORT)))
1646 		return -EINVAL;
1647 
1648 	if (((sflags & SCTP_EOF) && msg_len > 0) ||
1649 	    (!(sflags & (SCTP_EOF | SCTP_ABORT)) && msg_len == 0))
1650 		return -EINVAL;
1651 
1652 	if ((sflags & SCTP_ADDR_OVER) && !msg->msg_name)
1653 		return -EINVAL;
1654 
1655 	return 0;
1656 }
1657 
sctp_sendmsg_new_asoc(struct sock * sk,__u16 sflags,struct sctp_cmsgs * cmsgs,union sctp_addr * daddr,struct sctp_transport ** tp)1658 static int sctp_sendmsg_new_asoc(struct sock *sk, __u16 sflags,
1659 				 struct sctp_cmsgs *cmsgs,
1660 				 union sctp_addr *daddr,
1661 				 struct sctp_transport **tp)
1662 {
1663 	struct sctp_endpoint *ep = sctp_sk(sk)->ep;
1664 	struct sctp_association *asoc;
1665 	struct cmsghdr *cmsg;
1666 	__be32 flowinfo = 0;
1667 	struct sctp_af *af;
1668 	int err;
1669 
1670 	*tp = NULL;
1671 
1672 	if (sflags & (SCTP_EOF | SCTP_ABORT))
1673 		return -EINVAL;
1674 
1675 	if (sctp_style(sk, TCP) && (sctp_sstate(sk, ESTABLISHED) ||
1676 				    sctp_sstate(sk, CLOSING)))
1677 		return -EADDRNOTAVAIL;
1678 
1679 	/* Label connection socket for first association 1-to-many
1680 	 * style for client sequence socket()->sendmsg(). This
1681 	 * needs to be done before sctp_assoc_add_peer() as that will
1682 	 * set up the initial packet that needs to account for any
1683 	 * security ip options (CIPSO/CALIPSO) added to the packet.
1684 	 */
1685 	af = sctp_get_af_specific(daddr->sa.sa_family);
1686 	if (!af)
1687 		return -EINVAL;
1688 	err = security_sctp_bind_connect(sk, SCTP_SENDMSG_CONNECT,
1689 					 (struct sockaddr *)daddr,
1690 					 af->sockaddr_len);
1691 	if (err < 0)
1692 		return err;
1693 
1694 	err = sctp_connect_new_asoc(ep, daddr, cmsgs->init, tp);
1695 	if (err)
1696 		return err;
1697 	asoc = (*tp)->asoc;
1698 
1699 	if (!cmsgs->addrs_msg)
1700 		return 0;
1701 
1702 	if (daddr->sa.sa_family == AF_INET6)
1703 		flowinfo = daddr->v6.sin6_flowinfo;
1704 
1705 	/* sendv addr list parse */
1706 	for_each_cmsghdr(cmsg, cmsgs->addrs_msg) {
1707 		union sctp_addr _daddr;
1708 		int dlen;
1709 
1710 		if (cmsg->cmsg_level != IPPROTO_SCTP ||
1711 		    (cmsg->cmsg_type != SCTP_DSTADDRV4 &&
1712 		     cmsg->cmsg_type != SCTP_DSTADDRV6))
1713 			continue;
1714 
1715 		daddr = &_daddr;
1716 		memset(daddr, 0, sizeof(*daddr));
1717 		dlen = cmsg->cmsg_len - sizeof(struct cmsghdr);
1718 		if (cmsg->cmsg_type == SCTP_DSTADDRV4) {
1719 			if (dlen < sizeof(struct in_addr)) {
1720 				err = -EINVAL;
1721 				goto free;
1722 			}
1723 
1724 			dlen = sizeof(struct in_addr);
1725 			daddr->v4.sin_family = AF_INET;
1726 			daddr->v4.sin_port = htons(asoc->peer.port);
1727 			memcpy(&daddr->v4.sin_addr, CMSG_DATA(cmsg), dlen);
1728 		} else {
1729 			if (dlen < sizeof(struct in6_addr)) {
1730 				err = -EINVAL;
1731 				goto free;
1732 			}
1733 
1734 			dlen = sizeof(struct in6_addr);
1735 			daddr->v6.sin6_flowinfo = flowinfo;
1736 			daddr->v6.sin6_family = AF_INET6;
1737 			daddr->v6.sin6_port = htons(asoc->peer.port);
1738 			memcpy(&daddr->v6.sin6_addr, CMSG_DATA(cmsg), dlen);
1739 		}
1740 
1741 		err = sctp_connect_add_peer(asoc, daddr, sizeof(*daddr));
1742 		if (err)
1743 			goto free;
1744 	}
1745 
1746 	return 0;
1747 
1748 free:
1749 	sctp_association_free(asoc);
1750 	return err;
1751 }
1752 
sctp_sendmsg_check_sflags(struct sctp_association * asoc,__u16 sflags,struct msghdr * msg,size_t msg_len)1753 static int sctp_sendmsg_check_sflags(struct sctp_association *asoc,
1754 				     __u16 sflags, struct msghdr *msg,
1755 				     size_t msg_len)
1756 {
1757 	struct sock *sk = asoc->base.sk;
1758 	struct net *net = sock_net(sk);
1759 
1760 	if (sctp_state(asoc, CLOSED) && sctp_style(sk, TCP))
1761 		return -EPIPE;
1762 
1763 	if ((sflags & SCTP_SENDALL) && sctp_style(sk, UDP) &&
1764 	    !sctp_state(asoc, ESTABLISHED))
1765 		return 0;
1766 
1767 	if (sflags & SCTP_EOF) {
1768 		pr_debug("%s: shutting down association:%p\n", __func__, asoc);
1769 		sctp_primitive_SHUTDOWN(net, asoc, NULL);
1770 
1771 		return 0;
1772 	}
1773 
1774 	if (sflags & SCTP_ABORT) {
1775 		struct sctp_chunk *chunk;
1776 
1777 		chunk = sctp_make_abort_user(asoc, msg, msg_len);
1778 		if (!chunk)
1779 			return -ENOMEM;
1780 
1781 		pr_debug("%s: aborting association:%p\n", __func__, asoc);
1782 		sctp_primitive_ABORT(net, asoc, chunk);
1783 		iov_iter_revert(&msg->msg_iter, msg_len);
1784 
1785 		return 0;
1786 	}
1787 
1788 	return 1;
1789 }
1790 
sctp_sendmsg_to_asoc(struct sctp_association * asoc,struct msghdr * msg,size_t msg_len,struct sctp_transport * transport,struct sctp_sndrcvinfo * sinfo)1791 static int sctp_sendmsg_to_asoc(struct sctp_association *asoc,
1792 				struct msghdr *msg, size_t msg_len,
1793 				struct sctp_transport *transport,
1794 				struct sctp_sndrcvinfo *sinfo)
1795 {
1796 	struct sock *sk = asoc->base.sk;
1797 	struct sctp_sock *sp = sctp_sk(sk);
1798 	struct net *net = sock_net(sk);
1799 	struct sctp_datamsg *datamsg;
1800 	bool wait_connect = false;
1801 	struct sctp_chunk *chunk;
1802 	long timeo;
1803 	int err;
1804 
1805 	if (sinfo->sinfo_stream >= asoc->stream.outcnt) {
1806 		err = -EINVAL;
1807 		goto err;
1808 	}
1809 
1810 	if (unlikely(!SCTP_SO(&asoc->stream, sinfo->sinfo_stream)->ext)) {
1811 		err = sctp_stream_init_ext(&asoc->stream, sinfo->sinfo_stream);
1812 		if (err)
1813 			goto err;
1814 	}
1815 
1816 	if (sp->disable_fragments && msg_len > asoc->frag_point) {
1817 		err = -EMSGSIZE;
1818 		goto err;
1819 	}
1820 
1821 	if (asoc->pmtu_pending) {
1822 		if (sp->param_flags & SPP_PMTUD_ENABLE)
1823 			sctp_assoc_sync_pmtu(asoc);
1824 		asoc->pmtu_pending = 0;
1825 	}
1826 
1827 	if (sctp_wspace(asoc) < (int)msg_len)
1828 		sctp_prsctp_prune(asoc, sinfo, msg_len - sctp_wspace(asoc));
1829 
1830 	if (sctp_wspace(asoc) <= 0 || !sk_wmem_schedule(sk, msg_len)) {
1831 		timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
1832 		err = sctp_wait_for_sndbuf(asoc, transport, &timeo, msg_len);
1833 		if (err)
1834 			goto err;
1835 		if (unlikely(sinfo->sinfo_stream >= asoc->stream.outcnt)) {
1836 			err = -EINVAL;
1837 			goto err;
1838 		}
1839 	}
1840 
1841 	if (sctp_state(asoc, CLOSED)) {
1842 		err = sctp_primitive_ASSOCIATE(net, asoc, NULL);
1843 		if (err)
1844 			goto err;
1845 
1846 		if (asoc->ep->intl_enable) {
1847 			timeo = sock_sndtimeo(sk, 0);
1848 			err = sctp_wait_for_connect(asoc, &timeo);
1849 			if (err) {
1850 				err = -ESRCH;
1851 				goto err;
1852 			}
1853 		} else {
1854 			wait_connect = true;
1855 		}
1856 
1857 		pr_debug("%s: we associated primitively\n", __func__);
1858 	}
1859 
1860 	datamsg = sctp_datamsg_from_user(asoc, sinfo, &msg->msg_iter);
1861 	if (IS_ERR(datamsg)) {
1862 		err = PTR_ERR(datamsg);
1863 		goto err;
1864 	}
1865 
1866 	asoc->force_delay = !!(msg->msg_flags & MSG_MORE);
1867 
1868 	list_for_each_entry(chunk, &datamsg->chunks, frag_list) {
1869 		sctp_chunk_hold(chunk);
1870 		sctp_set_owner_w(chunk);
1871 		chunk->transport = transport;
1872 	}
1873 
1874 	err = sctp_primitive_SEND(net, asoc, datamsg);
1875 	if (err) {
1876 		sctp_datamsg_free(datamsg);
1877 		goto err;
1878 	}
1879 
1880 	pr_debug("%s: we sent primitively\n", __func__);
1881 
1882 	sctp_datamsg_put(datamsg);
1883 
1884 	if (unlikely(wait_connect)) {
1885 		timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
1886 		sctp_wait_for_connect(asoc, &timeo);
1887 	}
1888 
1889 	err = msg_len;
1890 
1891 err:
1892 	return err;
1893 }
1894 
sctp_sendmsg_get_daddr(struct sock * sk,const struct msghdr * msg,struct sctp_cmsgs * cmsgs)1895 static union sctp_addr *sctp_sendmsg_get_daddr(struct sock *sk,
1896 					       const struct msghdr *msg,
1897 					       struct sctp_cmsgs *cmsgs)
1898 {
1899 	union sctp_addr *daddr = NULL;
1900 	int err;
1901 
1902 	if (!sctp_style(sk, UDP_HIGH_BANDWIDTH) && msg->msg_name) {
1903 		int len = msg->msg_namelen;
1904 
1905 		if (len > sizeof(*daddr))
1906 			len = sizeof(*daddr);
1907 
1908 		daddr = (union sctp_addr *)msg->msg_name;
1909 
1910 		err = sctp_verify_addr(sk, daddr, len);
1911 		if (err)
1912 			return ERR_PTR(err);
1913 	}
1914 
1915 	return daddr;
1916 }
1917 
sctp_sendmsg_update_sinfo(struct sctp_association * asoc,struct sctp_sndrcvinfo * sinfo,struct sctp_cmsgs * cmsgs)1918 static void sctp_sendmsg_update_sinfo(struct sctp_association *asoc,
1919 				      struct sctp_sndrcvinfo *sinfo,
1920 				      struct sctp_cmsgs *cmsgs)
1921 {
1922 	if (!cmsgs->srinfo && !cmsgs->sinfo) {
1923 		sinfo->sinfo_stream = asoc->default_stream;
1924 		sinfo->sinfo_ppid = asoc->default_ppid;
1925 		sinfo->sinfo_context = asoc->default_context;
1926 		sinfo->sinfo_assoc_id = sctp_assoc2id(asoc);
1927 
1928 		if (!cmsgs->prinfo)
1929 			sinfo->sinfo_flags = asoc->default_flags;
1930 	}
1931 
1932 	if (!cmsgs->srinfo && !cmsgs->prinfo)
1933 		sinfo->sinfo_timetolive = asoc->default_timetolive;
1934 
1935 	if (cmsgs->authinfo) {
1936 		/* Reuse sinfo_tsn to indicate that authinfo was set and
1937 		 * sinfo_ssn to save the keyid on tx path.
1938 		 */
1939 		sinfo->sinfo_tsn = 1;
1940 		sinfo->sinfo_ssn = cmsgs->authinfo->auth_keynumber;
1941 	}
1942 }
1943 
sctp_sendmsg(struct sock * sk,struct msghdr * msg,size_t msg_len)1944 static int sctp_sendmsg(struct sock *sk, struct msghdr *msg, size_t msg_len)
1945 {
1946 	struct sctp_endpoint *ep = sctp_sk(sk)->ep;
1947 	struct sctp_transport *transport = NULL;
1948 	struct sctp_sndrcvinfo _sinfo, *sinfo;
1949 	struct sctp_association *asoc, *tmp;
1950 	struct sctp_cmsgs cmsgs;
1951 	union sctp_addr *daddr;
1952 	bool new = false;
1953 	__u16 sflags;
1954 	int err;
1955 
1956 	/* Parse and get snd_info */
1957 	err = sctp_sendmsg_parse(sk, &cmsgs, &_sinfo, msg, msg_len);
1958 	if (err)
1959 		goto out;
1960 
1961 	sinfo  = &_sinfo;
1962 	sflags = sinfo->sinfo_flags;
1963 
1964 	/* Get daddr from msg */
1965 	daddr = sctp_sendmsg_get_daddr(sk, msg, &cmsgs);
1966 	if (IS_ERR(daddr)) {
1967 		err = PTR_ERR(daddr);
1968 		goto out;
1969 	}
1970 
1971 	lock_sock(sk);
1972 
1973 	/* SCTP_SENDALL process */
1974 	if ((sflags & SCTP_SENDALL) && sctp_style(sk, UDP)) {
1975 		list_for_each_entry_safe(asoc, tmp, &ep->asocs, asocs) {
1976 			err = sctp_sendmsg_check_sflags(asoc, sflags, msg,
1977 							msg_len);
1978 			if (err == 0)
1979 				continue;
1980 			if (err < 0)
1981 				goto out_unlock;
1982 
1983 			sctp_sendmsg_update_sinfo(asoc, sinfo, &cmsgs);
1984 
1985 			err = sctp_sendmsg_to_asoc(asoc, msg, msg_len,
1986 						   NULL, sinfo);
1987 			if (err < 0)
1988 				goto out_unlock;
1989 
1990 			iov_iter_revert(&msg->msg_iter, err);
1991 		}
1992 
1993 		goto out_unlock;
1994 	}
1995 
1996 	/* Get and check or create asoc */
1997 	if (daddr) {
1998 		asoc = sctp_endpoint_lookup_assoc(ep, daddr, &transport);
1999 		if (asoc) {
2000 			err = sctp_sendmsg_check_sflags(asoc, sflags, msg,
2001 							msg_len);
2002 			if (err <= 0)
2003 				goto out_unlock;
2004 		} else {
2005 			err = sctp_sendmsg_new_asoc(sk, sflags, &cmsgs, daddr,
2006 						    &transport);
2007 			if (err)
2008 				goto out_unlock;
2009 
2010 			asoc = transport->asoc;
2011 			new = true;
2012 		}
2013 
2014 		if (!sctp_style(sk, TCP) && !(sflags & SCTP_ADDR_OVER))
2015 			transport = NULL;
2016 	} else {
2017 		asoc = sctp_id2assoc(sk, sinfo->sinfo_assoc_id);
2018 		if (!asoc) {
2019 			err = -EPIPE;
2020 			goto out_unlock;
2021 		}
2022 
2023 		err = sctp_sendmsg_check_sflags(asoc, sflags, msg, msg_len);
2024 		if (err <= 0)
2025 			goto out_unlock;
2026 	}
2027 
2028 	/* Update snd_info with the asoc */
2029 	sctp_sendmsg_update_sinfo(asoc, sinfo, &cmsgs);
2030 
2031 	/* Send msg to the asoc */
2032 	err = sctp_sendmsg_to_asoc(asoc, msg, msg_len, transport, sinfo);
2033 	if (err < 0 && err != -ESRCH && new)
2034 		sctp_association_free(asoc);
2035 
2036 out_unlock:
2037 	release_sock(sk);
2038 out:
2039 	return sctp_error(sk, msg->msg_flags, err);
2040 }
2041 
2042 /* This is an extended version of skb_pull() that removes the data from the
2043  * start of a skb even when data is spread across the list of skb's in the
2044  * frag_list. len specifies the total amount of data that needs to be removed.
2045  * when 'len' bytes could be removed from the skb, it returns 0.
2046  * If 'len' exceeds the total skb length,  it returns the no. of bytes that
2047  * could not be removed.
2048  */
sctp_skb_pull(struct sk_buff * skb,int len)2049 static int sctp_skb_pull(struct sk_buff *skb, int len)
2050 {
2051 	struct sk_buff *list;
2052 	int skb_len = skb_headlen(skb);
2053 	int rlen;
2054 
2055 	if (len <= skb_len) {
2056 		__skb_pull(skb, len);
2057 		return 0;
2058 	}
2059 	len -= skb_len;
2060 	__skb_pull(skb, skb_len);
2061 
2062 	skb_walk_frags(skb, list) {
2063 		rlen = sctp_skb_pull(list, len);
2064 		skb->len -= (len-rlen);
2065 		skb->data_len -= (len-rlen);
2066 
2067 		if (!rlen)
2068 			return 0;
2069 
2070 		len = rlen;
2071 	}
2072 
2073 	return len;
2074 }
2075 
2076 /* API 3.1.3  recvmsg() - UDP Style Syntax
2077  *
2078  *  ssize_t recvmsg(int socket, struct msghdr *message,
2079  *                    int flags);
2080  *
2081  *  socket  - the socket descriptor of the endpoint.
2082  *  message - pointer to the msghdr structure which contains a single
2083  *            user message and possibly some ancillary data.
2084  *
2085  *            See Section 5 for complete description of the data
2086  *            structures.
2087  *
2088  *  flags   - flags sent or received with the user message, see Section
2089  *            5 for complete description of the flags.
2090  */
sctp_recvmsg(struct sock * sk,struct msghdr * msg,size_t len,int flags,int * addr_len)2091 static int sctp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len,
2092 			int flags, int *addr_len)
2093 {
2094 	struct sctp_ulpevent *event = NULL;
2095 	struct sctp_sock *sp = sctp_sk(sk);
2096 	struct sk_buff *skb, *head_skb;
2097 	int copied;
2098 	int err = 0;
2099 	int skb_len;
2100 
2101 	pr_debug("%s: sk:%p, msghdr:%p, len:%zd, flags:0x%x, addr_len:%p)\n",
2102 		 __func__, sk, msg, len, flags, addr_len);
2103 
2104 	if (unlikely(flags & MSG_ERRQUEUE))
2105 		return inet_recv_error(sk, msg, len, addr_len);
2106 
2107 	if (sk_can_busy_loop(sk) &&
2108 	    skb_queue_empty_lockless(&sk->sk_receive_queue))
2109 		sk_busy_loop(sk, flags & MSG_DONTWAIT);
2110 
2111 	lock_sock(sk);
2112 
2113 	if (sctp_style(sk, TCP) && !sctp_sstate(sk, ESTABLISHED) &&
2114 	    !sctp_sstate(sk, CLOSING) && !sctp_sstate(sk, CLOSED)) {
2115 		err = -ENOTCONN;
2116 		goto out;
2117 	}
2118 
2119 	skb = sctp_skb_recv_datagram(sk, flags, &err);
2120 	if (!skb)
2121 		goto out;
2122 
2123 	/* Get the total length of the skb including any skb's in the
2124 	 * frag_list.
2125 	 */
2126 	skb_len = skb->len;
2127 
2128 	copied = skb_len;
2129 	if (copied > len)
2130 		copied = len;
2131 
2132 	err = skb_copy_datagram_msg(skb, 0, msg, copied);
2133 
2134 	event = sctp_skb2event(skb);
2135 
2136 	if (err)
2137 		goto out_free;
2138 
2139 	if (event->chunk && event->chunk->head_skb)
2140 		head_skb = event->chunk->head_skb;
2141 	else
2142 		head_skb = skb;
2143 	sock_recv_cmsgs(msg, sk, head_skb);
2144 	if (sctp_ulpevent_is_notification(event)) {
2145 		msg->msg_flags |= MSG_NOTIFICATION;
2146 		sp->pf->event_msgname(event, msg->msg_name, addr_len);
2147 	} else {
2148 		sp->pf->skb_msgname(head_skb, msg->msg_name, addr_len);
2149 	}
2150 
2151 	/* Check if we allow SCTP_NXTINFO. */
2152 	if (sp->recvnxtinfo)
2153 		sctp_ulpevent_read_nxtinfo(event, msg, sk);
2154 	/* Check if we allow SCTP_RCVINFO. */
2155 	if (sp->recvrcvinfo)
2156 		sctp_ulpevent_read_rcvinfo(event, msg);
2157 	/* Check if we allow SCTP_SNDRCVINFO. */
2158 	if (sctp_ulpevent_type_enabled(sp->subscribe, SCTP_DATA_IO_EVENT))
2159 		sctp_ulpevent_read_sndrcvinfo(event, msg);
2160 
2161 	err = copied;
2162 
2163 	/* If skb's length exceeds the user's buffer, update the skb and
2164 	 * push it back to the receive_queue so that the next call to
2165 	 * recvmsg() will return the remaining data. Don't set MSG_EOR.
2166 	 */
2167 	if (skb_len > copied) {
2168 		msg->msg_flags &= ~MSG_EOR;
2169 		if (flags & MSG_PEEK)
2170 			goto out_free;
2171 		sctp_skb_pull(skb, copied);
2172 		skb_queue_head(&sk->sk_receive_queue, skb);
2173 
2174 		/* When only partial message is copied to the user, increase
2175 		 * rwnd by that amount. If all the data in the skb is read,
2176 		 * rwnd is updated when the event is freed.
2177 		 */
2178 		if (!sctp_ulpevent_is_notification(event))
2179 			sctp_assoc_rwnd_increase(event->asoc, copied);
2180 		goto out;
2181 	} else if ((event->msg_flags & MSG_NOTIFICATION) ||
2182 		   (event->msg_flags & MSG_EOR))
2183 		msg->msg_flags |= MSG_EOR;
2184 	else
2185 		msg->msg_flags &= ~MSG_EOR;
2186 
2187 out_free:
2188 	if (flags & MSG_PEEK) {
2189 		/* Release the skb reference acquired after peeking the skb in
2190 		 * sctp_skb_recv_datagram().
2191 		 */
2192 		kfree_skb(skb);
2193 	} else {
2194 		/* Free the event which includes releasing the reference to
2195 		 * the owner of the skb, freeing the skb and updating the
2196 		 * rwnd.
2197 		 */
2198 		sctp_ulpevent_free(event);
2199 	}
2200 out:
2201 	release_sock(sk);
2202 	return err;
2203 }
2204 
2205 /* 7.1.12 Enable/Disable message fragmentation (SCTP_DISABLE_FRAGMENTS)
2206  *
2207  * This option is a on/off flag.  If enabled no SCTP message
2208  * fragmentation will be performed.  Instead if a message being sent
2209  * exceeds the current PMTU size, the message will NOT be sent and
2210  * instead a error will be indicated to the user.
2211  */
sctp_setsockopt_disable_fragments(struct sock * sk,int * val,unsigned int optlen)2212 static int sctp_setsockopt_disable_fragments(struct sock *sk, int *val,
2213 					     unsigned int optlen)
2214 {
2215 	if (optlen < sizeof(int))
2216 		return -EINVAL;
2217 	sctp_sk(sk)->disable_fragments = (*val == 0) ? 0 : 1;
2218 	return 0;
2219 }
2220 
sctp_setsockopt_events(struct sock * sk,__u8 * sn_type,unsigned int optlen)2221 static int sctp_setsockopt_events(struct sock *sk, __u8 *sn_type,
2222 				  unsigned int optlen)
2223 {
2224 	struct sctp_sock *sp = sctp_sk(sk);
2225 	struct sctp_association *asoc;
2226 	int i;
2227 
2228 	if (optlen > sizeof(struct sctp_event_subscribe))
2229 		return -EINVAL;
2230 
2231 	for (i = 0; i < optlen; i++)
2232 		sctp_ulpevent_type_set(&sp->subscribe, SCTP_SN_TYPE_BASE + i,
2233 				       sn_type[i]);
2234 
2235 	list_for_each_entry(asoc, &sp->ep->asocs, asocs)
2236 		asoc->subscribe = sctp_sk(sk)->subscribe;
2237 
2238 	/* At the time when a user app subscribes to SCTP_SENDER_DRY_EVENT,
2239 	 * if there is no data to be sent or retransmit, the stack will
2240 	 * immediately send up this notification.
2241 	 */
2242 	if (sctp_ulpevent_type_enabled(sp->subscribe, SCTP_SENDER_DRY_EVENT)) {
2243 		struct sctp_ulpevent *event;
2244 
2245 		asoc = sctp_id2assoc(sk, 0);
2246 		if (asoc && sctp_outq_is_empty(&asoc->outqueue)) {
2247 			event = sctp_ulpevent_make_sender_dry_event(asoc,
2248 					GFP_USER | __GFP_NOWARN);
2249 			if (!event)
2250 				return -ENOMEM;
2251 
2252 			asoc->stream.si->enqueue_event(&asoc->ulpq, event);
2253 		}
2254 	}
2255 
2256 	return 0;
2257 }
2258 
2259 /* 7.1.8 Automatic Close of associations (SCTP_AUTOCLOSE)
2260  *
2261  * This socket option is applicable to the UDP-style socket only.  When
2262  * set it will cause associations that are idle for more than the
2263  * specified number of seconds to automatically close.  An association
2264  * being idle is defined an association that has NOT sent or received
2265  * user data.  The special value of '0' indicates that no automatic
2266  * close of any associations should be performed.  The option expects an
2267  * integer defining the number of seconds of idle time before an
2268  * association is closed.
2269  */
sctp_setsockopt_autoclose(struct sock * sk,u32 * optval,unsigned int optlen)2270 static int sctp_setsockopt_autoclose(struct sock *sk, u32 *optval,
2271 				     unsigned int optlen)
2272 {
2273 	struct sctp_sock *sp = sctp_sk(sk);
2274 	struct net *net = sock_net(sk);
2275 
2276 	/* Applicable to UDP-style socket only */
2277 	if (sctp_style(sk, TCP))
2278 		return -EOPNOTSUPP;
2279 	if (optlen != sizeof(int))
2280 		return -EINVAL;
2281 
2282 	sp->autoclose = *optval;
2283 	if (sp->autoclose > net->sctp.max_autoclose)
2284 		sp->autoclose = net->sctp.max_autoclose;
2285 
2286 	return 0;
2287 }
2288 
2289 /* 7.1.13 Peer Address Parameters (SCTP_PEER_ADDR_PARAMS)
2290  *
2291  * Applications can enable or disable heartbeats for any peer address of
2292  * an association, modify an address's heartbeat interval, force a
2293  * heartbeat to be sent immediately, and adjust the address's maximum
2294  * number of retransmissions sent before an address is considered
2295  * unreachable.  The following structure is used to access and modify an
2296  * address's parameters:
2297  *
2298  *  struct sctp_paddrparams {
2299  *     sctp_assoc_t            spp_assoc_id;
2300  *     struct sockaddr_storage spp_address;
2301  *     uint32_t                spp_hbinterval;
2302  *     uint16_t                spp_pathmaxrxt;
2303  *     uint32_t                spp_pathmtu;
2304  *     uint32_t                spp_sackdelay;
2305  *     uint32_t                spp_flags;
2306  *     uint32_t                spp_ipv6_flowlabel;
2307  *     uint8_t                 spp_dscp;
2308  * };
2309  *
2310  *   spp_assoc_id    - (one-to-many style socket) This is filled in the
2311  *                     application, and identifies the association for
2312  *                     this query.
2313  *   spp_address     - This specifies which address is of interest.
2314  *   spp_hbinterval  - This contains the value of the heartbeat interval,
2315  *                     in milliseconds.  If a  value of zero
2316  *                     is present in this field then no changes are to
2317  *                     be made to this parameter.
2318  *   spp_pathmaxrxt  - This contains the maximum number of
2319  *                     retransmissions before this address shall be
2320  *                     considered unreachable. If a  value of zero
2321  *                     is present in this field then no changes are to
2322  *                     be made to this parameter.
2323  *   spp_pathmtu     - When Path MTU discovery is disabled the value
2324  *                     specified here will be the "fixed" path mtu.
2325  *                     Note that if the spp_address field is empty
2326  *                     then all associations on this address will
2327  *                     have this fixed path mtu set upon them.
2328  *
2329  *   spp_sackdelay   - When delayed sack is enabled, this value specifies
2330  *                     the number of milliseconds that sacks will be delayed
2331  *                     for. This value will apply to all addresses of an
2332  *                     association if the spp_address field is empty. Note
2333  *                     also, that if delayed sack is enabled and this
2334  *                     value is set to 0, no change is made to the last
2335  *                     recorded delayed sack timer value.
2336  *
2337  *   spp_flags       - These flags are used to control various features
2338  *                     on an association. The flag field may contain
2339  *                     zero or more of the following options.
2340  *
2341  *                     SPP_HB_ENABLE  - Enable heartbeats on the
2342  *                     specified address. Note that if the address
2343  *                     field is empty all addresses for the association
2344  *                     have heartbeats enabled upon them.
2345  *
2346  *                     SPP_HB_DISABLE - Disable heartbeats on the
2347  *                     speicifed address. Note that if the address
2348  *                     field is empty all addresses for the association
2349  *                     will have their heartbeats disabled. Note also
2350  *                     that SPP_HB_ENABLE and SPP_HB_DISABLE are
2351  *                     mutually exclusive, only one of these two should
2352  *                     be specified. Enabling both fields will have
2353  *                     undetermined results.
2354  *
2355  *                     SPP_HB_DEMAND - Request a user initiated heartbeat
2356  *                     to be made immediately.
2357  *
2358  *                     SPP_HB_TIME_IS_ZERO - Specify's that the time for
2359  *                     heartbeat delayis to be set to the value of 0
2360  *                     milliseconds.
2361  *
2362  *                     SPP_PMTUD_ENABLE - This field will enable PMTU
2363  *                     discovery upon the specified address. Note that
2364  *                     if the address feild is empty then all addresses
2365  *                     on the association are effected.
2366  *
2367  *                     SPP_PMTUD_DISABLE - This field will disable PMTU
2368  *                     discovery upon the specified address. Note that
2369  *                     if the address feild is empty then all addresses
2370  *                     on the association are effected. Not also that
2371  *                     SPP_PMTUD_ENABLE and SPP_PMTUD_DISABLE are mutually
2372  *                     exclusive. Enabling both will have undetermined
2373  *                     results.
2374  *
2375  *                     SPP_SACKDELAY_ENABLE - Setting this flag turns
2376  *                     on delayed sack. The time specified in spp_sackdelay
2377  *                     is used to specify the sack delay for this address. Note
2378  *                     that if spp_address is empty then all addresses will
2379  *                     enable delayed sack and take on the sack delay
2380  *                     value specified in spp_sackdelay.
2381  *                     SPP_SACKDELAY_DISABLE - Setting this flag turns
2382  *                     off delayed sack. If the spp_address field is blank then
2383  *                     delayed sack is disabled for the entire association. Note
2384  *                     also that this field is mutually exclusive to
2385  *                     SPP_SACKDELAY_ENABLE, setting both will have undefined
2386  *                     results.
2387  *
2388  *                     SPP_IPV6_FLOWLABEL:  Setting this flag enables the
2389  *                     setting of the IPV6 flow label value.  The value is
2390  *                     contained in the spp_ipv6_flowlabel field.
2391  *                     Upon retrieval, this flag will be set to indicate that
2392  *                     the spp_ipv6_flowlabel field has a valid value returned.
2393  *                     If a specific destination address is set (in the
2394  *                     spp_address field), then the value returned is that of
2395  *                     the address.  If just an association is specified (and
2396  *                     no address), then the association's default flow label
2397  *                     is returned.  If neither an association nor a destination
2398  *                     is specified, then the socket's default flow label is
2399  *                     returned.  For non-IPv6 sockets, this flag will be left
2400  *                     cleared.
2401  *
2402  *                     SPP_DSCP:  Setting this flag enables the setting of the
2403  *                     Differentiated Services Code Point (DSCP) value
2404  *                     associated with either the association or a specific
2405  *                     address.  The value is obtained in the spp_dscp field.
2406  *                     Upon retrieval, this flag will be set to indicate that
2407  *                     the spp_dscp field has a valid value returned.  If a
2408  *                     specific destination address is set when called (in the
2409  *                     spp_address field), then that specific destination
2410  *                     address's DSCP value is returned.  If just an association
2411  *                     is specified, then the association's default DSCP is
2412  *                     returned.  If neither an association nor a destination is
2413  *                     specified, then the socket's default DSCP is returned.
2414  *
2415  *   spp_ipv6_flowlabel
2416  *                   - This field is used in conjunction with the
2417  *                     SPP_IPV6_FLOWLABEL flag and contains the IPv6 flow label.
2418  *                     The 20 least significant bits are used for the flow
2419  *                     label.  This setting has precedence over any IPv6-layer
2420  *                     setting.
2421  *
2422  *   spp_dscp        - This field is used in conjunction with the SPP_DSCP flag
2423  *                     and contains the DSCP.  The 6 most significant bits are
2424  *                     used for the DSCP.  This setting has precedence over any
2425  *                     IPv4- or IPv6- layer setting.
2426  */
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)2427 static int sctp_apply_peer_addr_params(struct sctp_paddrparams *params,
2428 				       struct sctp_transport   *trans,
2429 				       struct sctp_association *asoc,
2430 				       struct sctp_sock        *sp,
2431 				       int                      hb_change,
2432 				       int                      pmtud_change,
2433 				       int                      sackdelay_change)
2434 {
2435 	int error;
2436 
2437 	if (params->spp_flags & SPP_HB_DEMAND && trans) {
2438 		error = sctp_primitive_REQUESTHEARTBEAT(trans->asoc->base.net,
2439 							trans->asoc, trans);
2440 		if (error)
2441 			return error;
2442 	}
2443 
2444 	/* Note that unless the spp_flag is set to SPP_HB_ENABLE the value of
2445 	 * this field is ignored.  Note also that a value of zero indicates
2446 	 * the current setting should be left unchanged.
2447 	 */
2448 	if (params->spp_flags & SPP_HB_ENABLE) {
2449 
2450 		/* Re-zero the interval if the SPP_HB_TIME_IS_ZERO is
2451 		 * set.  This lets us use 0 value when this flag
2452 		 * is set.
2453 		 */
2454 		if (params->spp_flags & SPP_HB_TIME_IS_ZERO)
2455 			params->spp_hbinterval = 0;
2456 
2457 		if (params->spp_hbinterval ||
2458 		    (params->spp_flags & SPP_HB_TIME_IS_ZERO)) {
2459 			if (trans) {
2460 				trans->hbinterval =
2461 				    msecs_to_jiffies(params->spp_hbinterval);
2462 				sctp_transport_reset_hb_timer(trans);
2463 			} else if (asoc) {
2464 				asoc->hbinterval =
2465 				    msecs_to_jiffies(params->spp_hbinterval);
2466 			} else {
2467 				sp->hbinterval = params->spp_hbinterval;
2468 			}
2469 		}
2470 	}
2471 
2472 	if (hb_change) {
2473 		if (trans) {
2474 			trans->param_flags =
2475 				(trans->param_flags & ~SPP_HB) | hb_change;
2476 		} else if (asoc) {
2477 			asoc->param_flags =
2478 				(asoc->param_flags & ~SPP_HB) | hb_change;
2479 		} else {
2480 			sp->param_flags =
2481 				(sp->param_flags & ~SPP_HB) | hb_change;
2482 		}
2483 	}
2484 
2485 	/* When Path MTU discovery is disabled the value specified here will
2486 	 * be the "fixed" path mtu (i.e. the value of the spp_flags field must
2487 	 * include the flag SPP_PMTUD_DISABLE for this field to have any
2488 	 * effect).
2489 	 */
2490 	if ((params->spp_flags & SPP_PMTUD_DISABLE) && params->spp_pathmtu) {
2491 		if (trans) {
2492 			trans->pathmtu = params->spp_pathmtu;
2493 			sctp_assoc_sync_pmtu(asoc);
2494 		} else if (asoc) {
2495 			sctp_assoc_set_pmtu(asoc, params->spp_pathmtu);
2496 		} else {
2497 			sp->pathmtu = params->spp_pathmtu;
2498 		}
2499 	}
2500 
2501 	if (pmtud_change) {
2502 		if (trans) {
2503 			int update = (trans->param_flags & SPP_PMTUD_DISABLE) &&
2504 				(params->spp_flags & SPP_PMTUD_ENABLE);
2505 			trans->param_flags =
2506 				(trans->param_flags & ~SPP_PMTUD) | pmtud_change;
2507 			if (update) {
2508 				sctp_transport_pmtu(trans, sctp_opt2sk(sp));
2509 				sctp_assoc_sync_pmtu(asoc);
2510 			}
2511 			sctp_transport_pl_reset(trans);
2512 		} else if (asoc) {
2513 			asoc->param_flags =
2514 				(asoc->param_flags & ~SPP_PMTUD) | pmtud_change;
2515 		} else {
2516 			sp->param_flags =
2517 				(sp->param_flags & ~SPP_PMTUD) | pmtud_change;
2518 		}
2519 	}
2520 
2521 	/* Note that unless the spp_flag is set to SPP_SACKDELAY_ENABLE the
2522 	 * value of this field is ignored.  Note also that a value of zero
2523 	 * indicates the current setting should be left unchanged.
2524 	 */
2525 	if ((params->spp_flags & SPP_SACKDELAY_ENABLE) && params->spp_sackdelay) {
2526 		if (trans) {
2527 			trans->sackdelay =
2528 				msecs_to_jiffies(params->spp_sackdelay);
2529 		} else if (asoc) {
2530 			asoc->sackdelay =
2531 				msecs_to_jiffies(params->spp_sackdelay);
2532 		} else {
2533 			sp->sackdelay = params->spp_sackdelay;
2534 		}
2535 	}
2536 
2537 	if (sackdelay_change) {
2538 		if (trans) {
2539 			trans->param_flags =
2540 				(trans->param_flags & ~SPP_SACKDELAY) |
2541 				sackdelay_change;
2542 		} else if (asoc) {
2543 			asoc->param_flags =
2544 				(asoc->param_flags & ~SPP_SACKDELAY) |
2545 				sackdelay_change;
2546 		} else {
2547 			sp->param_flags =
2548 				(sp->param_flags & ~SPP_SACKDELAY) |
2549 				sackdelay_change;
2550 		}
2551 	}
2552 
2553 	/* Note that a value of zero indicates the current setting should be
2554 	   left unchanged.
2555 	 */
2556 	if (params->spp_pathmaxrxt) {
2557 		if (trans) {
2558 			trans->pathmaxrxt = params->spp_pathmaxrxt;
2559 		} else if (asoc) {
2560 			asoc->pathmaxrxt = params->spp_pathmaxrxt;
2561 		} else {
2562 			sp->pathmaxrxt = params->spp_pathmaxrxt;
2563 		}
2564 	}
2565 
2566 	if (params->spp_flags & SPP_IPV6_FLOWLABEL) {
2567 		if (trans) {
2568 			if (trans->ipaddr.sa.sa_family == AF_INET6) {
2569 				trans->flowlabel = params->spp_ipv6_flowlabel &
2570 						   SCTP_FLOWLABEL_VAL_MASK;
2571 				trans->flowlabel |= SCTP_FLOWLABEL_SET_MASK;
2572 			}
2573 		} else if (asoc) {
2574 			struct sctp_transport *t;
2575 
2576 			list_for_each_entry(t, &asoc->peer.transport_addr_list,
2577 					    transports) {
2578 				if (t->ipaddr.sa.sa_family != AF_INET6)
2579 					continue;
2580 				t->flowlabel = params->spp_ipv6_flowlabel &
2581 					       SCTP_FLOWLABEL_VAL_MASK;
2582 				t->flowlabel |= SCTP_FLOWLABEL_SET_MASK;
2583 			}
2584 			asoc->flowlabel = params->spp_ipv6_flowlabel &
2585 					  SCTP_FLOWLABEL_VAL_MASK;
2586 			asoc->flowlabel |= SCTP_FLOWLABEL_SET_MASK;
2587 		} else if (sctp_opt2sk(sp)->sk_family == AF_INET6) {
2588 			sp->flowlabel = params->spp_ipv6_flowlabel &
2589 					SCTP_FLOWLABEL_VAL_MASK;
2590 			sp->flowlabel |= SCTP_FLOWLABEL_SET_MASK;
2591 		}
2592 	}
2593 
2594 	if (params->spp_flags & SPP_DSCP) {
2595 		if (trans) {
2596 			trans->dscp = params->spp_dscp & SCTP_DSCP_VAL_MASK;
2597 			trans->dscp |= SCTP_DSCP_SET_MASK;
2598 		} else if (asoc) {
2599 			struct sctp_transport *t;
2600 
2601 			list_for_each_entry(t, &asoc->peer.transport_addr_list,
2602 					    transports) {
2603 				t->dscp = params->spp_dscp &
2604 					  SCTP_DSCP_VAL_MASK;
2605 				t->dscp |= SCTP_DSCP_SET_MASK;
2606 			}
2607 			asoc->dscp = params->spp_dscp & SCTP_DSCP_VAL_MASK;
2608 			asoc->dscp |= SCTP_DSCP_SET_MASK;
2609 		} else {
2610 			sp->dscp = params->spp_dscp & SCTP_DSCP_VAL_MASK;
2611 			sp->dscp |= SCTP_DSCP_SET_MASK;
2612 		}
2613 	}
2614 
2615 	return 0;
2616 }
2617 
sctp_setsockopt_peer_addr_params(struct sock * sk,struct sctp_paddrparams * params,unsigned int optlen)2618 static int sctp_setsockopt_peer_addr_params(struct sock *sk,
2619 					    struct sctp_paddrparams *params,
2620 					    unsigned int optlen)
2621 {
2622 	struct sctp_transport   *trans = NULL;
2623 	struct sctp_association *asoc = NULL;
2624 	struct sctp_sock        *sp = sctp_sk(sk);
2625 	int error;
2626 	int hb_change, pmtud_change, sackdelay_change;
2627 
2628 	if (optlen == ALIGN(offsetof(struct sctp_paddrparams,
2629 					    spp_ipv6_flowlabel), 4)) {
2630 		if (params->spp_flags & (SPP_DSCP | SPP_IPV6_FLOWLABEL))
2631 			return -EINVAL;
2632 	} else if (optlen != sizeof(*params)) {
2633 		return -EINVAL;
2634 	}
2635 
2636 	/* Validate flags and value parameters. */
2637 	hb_change        = params->spp_flags & SPP_HB;
2638 	pmtud_change     = params->spp_flags & SPP_PMTUD;
2639 	sackdelay_change = params->spp_flags & SPP_SACKDELAY;
2640 
2641 	if (hb_change        == SPP_HB ||
2642 	    pmtud_change     == SPP_PMTUD ||
2643 	    sackdelay_change == SPP_SACKDELAY ||
2644 	    params->spp_sackdelay > 500 ||
2645 	    (params->spp_pathmtu &&
2646 	     params->spp_pathmtu < SCTP_DEFAULT_MINSEGMENT))
2647 		return -EINVAL;
2648 
2649 	/* If an address other than INADDR_ANY is specified, and
2650 	 * no transport is found, then the request is invalid.
2651 	 */
2652 	if (!sctp_is_any(sk, (union sctp_addr *)&params->spp_address)) {
2653 		trans = sctp_addr_id2transport(sk, &params->spp_address,
2654 					       params->spp_assoc_id);
2655 		if (!trans)
2656 			return -EINVAL;
2657 	}
2658 
2659 	/* Get association, if assoc_id != SCTP_FUTURE_ASSOC and the
2660 	 * socket is a one to many style socket, and an association
2661 	 * was not found, then the id was invalid.
2662 	 */
2663 	asoc = sctp_id2assoc(sk, params->spp_assoc_id);
2664 	if (!asoc && params->spp_assoc_id != SCTP_FUTURE_ASSOC &&
2665 	    sctp_style(sk, UDP))
2666 		return -EINVAL;
2667 
2668 	/* Heartbeat demand can only be sent on a transport or
2669 	 * association, but not a socket.
2670 	 */
2671 	if (params->spp_flags & SPP_HB_DEMAND && !trans && !asoc)
2672 		return -EINVAL;
2673 
2674 	/* Process parameters. */
2675 	error = sctp_apply_peer_addr_params(params, trans, asoc, sp,
2676 					    hb_change, pmtud_change,
2677 					    sackdelay_change);
2678 
2679 	if (error)
2680 		return error;
2681 
2682 	/* If changes are for association, also apply parameters to each
2683 	 * transport.
2684 	 */
2685 	if (!trans && asoc) {
2686 		list_for_each_entry(trans, &asoc->peer.transport_addr_list,
2687 				transports) {
2688 			sctp_apply_peer_addr_params(params, trans, asoc, sp,
2689 						    hb_change, pmtud_change,
2690 						    sackdelay_change);
2691 		}
2692 	}
2693 
2694 	return 0;
2695 }
2696 
sctp_spp_sackdelay_enable(__u32 param_flags)2697 static inline __u32 sctp_spp_sackdelay_enable(__u32 param_flags)
2698 {
2699 	return (param_flags & ~SPP_SACKDELAY) | SPP_SACKDELAY_ENABLE;
2700 }
2701 
sctp_spp_sackdelay_disable(__u32 param_flags)2702 static inline __u32 sctp_spp_sackdelay_disable(__u32 param_flags)
2703 {
2704 	return (param_flags & ~SPP_SACKDELAY) | SPP_SACKDELAY_DISABLE;
2705 }
2706 
sctp_apply_asoc_delayed_ack(struct sctp_sack_info * params,struct sctp_association * asoc)2707 static void sctp_apply_asoc_delayed_ack(struct sctp_sack_info *params,
2708 					struct sctp_association *asoc)
2709 {
2710 	struct sctp_transport *trans;
2711 
2712 	if (params->sack_delay) {
2713 		asoc->sackdelay = msecs_to_jiffies(params->sack_delay);
2714 		asoc->param_flags =
2715 			sctp_spp_sackdelay_enable(asoc->param_flags);
2716 	}
2717 	if (params->sack_freq == 1) {
2718 		asoc->param_flags =
2719 			sctp_spp_sackdelay_disable(asoc->param_flags);
2720 	} else if (params->sack_freq > 1) {
2721 		asoc->sackfreq = params->sack_freq;
2722 		asoc->param_flags =
2723 			sctp_spp_sackdelay_enable(asoc->param_flags);
2724 	}
2725 
2726 	list_for_each_entry(trans, &asoc->peer.transport_addr_list,
2727 			    transports) {
2728 		if (params->sack_delay) {
2729 			trans->sackdelay = msecs_to_jiffies(params->sack_delay);
2730 			trans->param_flags =
2731 				sctp_spp_sackdelay_enable(trans->param_flags);
2732 		}
2733 		if (params->sack_freq == 1) {
2734 			trans->param_flags =
2735 				sctp_spp_sackdelay_disable(trans->param_flags);
2736 		} else if (params->sack_freq > 1) {
2737 			trans->sackfreq = params->sack_freq;
2738 			trans->param_flags =
2739 				sctp_spp_sackdelay_enable(trans->param_flags);
2740 		}
2741 	}
2742 }
2743 
2744 /*
2745  * 7.1.23.  Get or set delayed ack timer (SCTP_DELAYED_SACK)
2746  *
2747  * This option will effect the way delayed acks are performed.  This
2748  * option allows you to get or set the delayed ack time, in
2749  * milliseconds.  It also allows changing the delayed ack frequency.
2750  * Changing the frequency to 1 disables the delayed sack algorithm.  If
2751  * the assoc_id is 0, then this sets or gets the endpoints default
2752  * values.  If the assoc_id field is non-zero, then the set or get
2753  * effects the specified association for the one to many model (the
2754  * assoc_id field is ignored by the one to one model).  Note that if
2755  * sack_delay or sack_freq are 0 when setting this option, then the
2756  * current values will remain unchanged.
2757  *
2758  * struct sctp_sack_info {
2759  *     sctp_assoc_t            sack_assoc_id;
2760  *     uint32_t                sack_delay;
2761  *     uint32_t                sack_freq;
2762  * };
2763  *
2764  * sack_assoc_id -  This parameter, indicates which association the user
2765  *    is performing an action upon.  Note that if this field's value is
2766  *    zero then the endpoints default value is changed (effecting future
2767  *    associations only).
2768  *
2769  * sack_delay -  This parameter contains the number of milliseconds that
2770  *    the user is requesting the delayed ACK timer be set to.  Note that
2771  *    this value is defined in the standard to be between 200 and 500
2772  *    milliseconds.
2773  *
2774  * sack_freq -  This parameter contains the number of packets that must
2775  *    be received before a sack is sent without waiting for the delay
2776  *    timer to expire.  The default value for this is 2, setting this
2777  *    value to 1 will disable the delayed sack algorithm.
2778  */
__sctp_setsockopt_delayed_ack(struct sock * sk,struct sctp_sack_info * params)2779 static int __sctp_setsockopt_delayed_ack(struct sock *sk,
2780 					 struct sctp_sack_info *params)
2781 {
2782 	struct sctp_sock *sp = sctp_sk(sk);
2783 	struct sctp_association *asoc;
2784 
2785 	/* Validate value parameter. */
2786 	if (params->sack_delay > 500)
2787 		return -EINVAL;
2788 
2789 	/* Get association, if sack_assoc_id != SCTP_FUTURE_ASSOC and the
2790 	 * socket is a one to many style socket, and an association
2791 	 * was not found, then the id was invalid.
2792 	 */
2793 	asoc = sctp_id2assoc(sk, params->sack_assoc_id);
2794 	if (!asoc && params->sack_assoc_id > SCTP_ALL_ASSOC &&
2795 	    sctp_style(sk, UDP))
2796 		return -EINVAL;
2797 
2798 	if (asoc) {
2799 		sctp_apply_asoc_delayed_ack(params, asoc);
2800 
2801 		return 0;
2802 	}
2803 
2804 	if (sctp_style(sk, TCP))
2805 		params->sack_assoc_id = SCTP_FUTURE_ASSOC;
2806 
2807 	if (params->sack_assoc_id == SCTP_FUTURE_ASSOC ||
2808 	    params->sack_assoc_id == SCTP_ALL_ASSOC) {
2809 		if (params->sack_delay) {
2810 			sp->sackdelay = params->sack_delay;
2811 			sp->param_flags =
2812 				sctp_spp_sackdelay_enable(sp->param_flags);
2813 		}
2814 		if (params->sack_freq == 1) {
2815 			sp->param_flags =
2816 				sctp_spp_sackdelay_disable(sp->param_flags);
2817 		} else if (params->sack_freq > 1) {
2818 			sp->sackfreq = params->sack_freq;
2819 			sp->param_flags =
2820 				sctp_spp_sackdelay_enable(sp->param_flags);
2821 		}
2822 	}
2823 
2824 	if (params->sack_assoc_id == SCTP_CURRENT_ASSOC ||
2825 	    params->sack_assoc_id == SCTP_ALL_ASSOC)
2826 		list_for_each_entry(asoc, &sp->ep->asocs, asocs)
2827 			sctp_apply_asoc_delayed_ack(params, asoc);
2828 
2829 	return 0;
2830 }
2831 
sctp_setsockopt_delayed_ack(struct sock * sk,struct sctp_sack_info * params,unsigned int optlen)2832 static int sctp_setsockopt_delayed_ack(struct sock *sk,
2833 				       struct sctp_sack_info *params,
2834 				       unsigned int optlen)
2835 {
2836 	if (optlen == sizeof(struct sctp_assoc_value)) {
2837 		struct sctp_assoc_value *v = (struct sctp_assoc_value *)params;
2838 		struct sctp_sack_info p;
2839 
2840 		pr_warn_ratelimited(DEPRECATED
2841 				    "%s (pid %d) "
2842 				    "Use of struct sctp_assoc_value in delayed_ack socket option.\n"
2843 				    "Use struct sctp_sack_info instead\n",
2844 				    current->comm, task_pid_nr(current));
2845 
2846 		p.sack_assoc_id = v->assoc_id;
2847 		p.sack_delay = v->assoc_value;
2848 		p.sack_freq = v->assoc_value ? 0 : 1;
2849 		return __sctp_setsockopt_delayed_ack(sk, &p);
2850 	}
2851 
2852 	if (optlen != sizeof(struct sctp_sack_info))
2853 		return -EINVAL;
2854 	if (params->sack_delay == 0 && params->sack_freq == 0)
2855 		return 0;
2856 	return __sctp_setsockopt_delayed_ack(sk, params);
2857 }
2858 
2859 /* 7.1.3 Initialization Parameters (SCTP_INITMSG)
2860  *
2861  * Applications can specify protocol parameters for the default association
2862  * initialization.  The option name argument to setsockopt() and getsockopt()
2863  * is SCTP_INITMSG.
2864  *
2865  * Setting initialization parameters is effective only on an unconnected
2866  * socket (for UDP-style sockets only future associations are effected
2867  * by the change).  With TCP-style sockets, this option is inherited by
2868  * sockets derived from a listener socket.
2869  */
sctp_setsockopt_initmsg(struct sock * sk,struct sctp_initmsg * sinit,unsigned int optlen)2870 static int sctp_setsockopt_initmsg(struct sock *sk, struct sctp_initmsg *sinit,
2871 				   unsigned int optlen)
2872 {
2873 	struct sctp_sock *sp = sctp_sk(sk);
2874 
2875 	if (optlen != sizeof(struct sctp_initmsg))
2876 		return -EINVAL;
2877 
2878 	if (sinit->sinit_num_ostreams)
2879 		sp->initmsg.sinit_num_ostreams = sinit->sinit_num_ostreams;
2880 	if (sinit->sinit_max_instreams)
2881 		sp->initmsg.sinit_max_instreams = sinit->sinit_max_instreams;
2882 	if (sinit->sinit_max_attempts)
2883 		sp->initmsg.sinit_max_attempts = sinit->sinit_max_attempts;
2884 	if (sinit->sinit_max_init_timeo)
2885 		sp->initmsg.sinit_max_init_timeo = sinit->sinit_max_init_timeo;
2886 
2887 	return 0;
2888 }
2889 
2890 /*
2891  * 7.1.14 Set default send parameters (SCTP_DEFAULT_SEND_PARAM)
2892  *
2893  *   Applications that wish to use the sendto() system call may wish to
2894  *   specify a default set of parameters that would normally be supplied
2895  *   through the inclusion of ancillary data.  This socket option allows
2896  *   such an application to set the default sctp_sndrcvinfo structure.
2897  *   The application that wishes to use this socket option simply passes
2898  *   in to this call the sctp_sndrcvinfo structure defined in Section
2899  *   5.2.2) The input parameters accepted by this call include
2900  *   sinfo_stream, sinfo_flags, sinfo_ppid, sinfo_context,
2901  *   sinfo_timetolive.  The user must provide the sinfo_assoc_id field in
2902  *   to this call if the caller is using the UDP model.
2903  */
sctp_setsockopt_default_send_param(struct sock * sk,struct sctp_sndrcvinfo * info,unsigned int optlen)2904 static int sctp_setsockopt_default_send_param(struct sock *sk,
2905 					      struct sctp_sndrcvinfo *info,
2906 					      unsigned int optlen)
2907 {
2908 	struct sctp_sock *sp = sctp_sk(sk);
2909 	struct sctp_association *asoc;
2910 
2911 	if (optlen != sizeof(*info))
2912 		return -EINVAL;
2913 	if (info->sinfo_flags &
2914 	    ~(SCTP_UNORDERED | SCTP_ADDR_OVER |
2915 	      SCTP_ABORT | SCTP_EOF))
2916 		return -EINVAL;
2917 
2918 	asoc = sctp_id2assoc(sk, info->sinfo_assoc_id);
2919 	if (!asoc && info->sinfo_assoc_id > SCTP_ALL_ASSOC &&
2920 	    sctp_style(sk, UDP))
2921 		return -EINVAL;
2922 
2923 	if (asoc) {
2924 		asoc->default_stream = info->sinfo_stream;
2925 		asoc->default_flags = info->sinfo_flags;
2926 		asoc->default_ppid = info->sinfo_ppid;
2927 		asoc->default_context = info->sinfo_context;
2928 		asoc->default_timetolive = info->sinfo_timetolive;
2929 
2930 		return 0;
2931 	}
2932 
2933 	if (sctp_style(sk, TCP))
2934 		info->sinfo_assoc_id = SCTP_FUTURE_ASSOC;
2935 
2936 	if (info->sinfo_assoc_id == SCTP_FUTURE_ASSOC ||
2937 	    info->sinfo_assoc_id == SCTP_ALL_ASSOC) {
2938 		sp->default_stream = info->sinfo_stream;
2939 		sp->default_flags = info->sinfo_flags;
2940 		sp->default_ppid = info->sinfo_ppid;
2941 		sp->default_context = info->sinfo_context;
2942 		sp->default_timetolive = info->sinfo_timetolive;
2943 	}
2944 
2945 	if (info->sinfo_assoc_id == SCTP_CURRENT_ASSOC ||
2946 	    info->sinfo_assoc_id == SCTP_ALL_ASSOC) {
2947 		list_for_each_entry(asoc, &sp->ep->asocs, asocs) {
2948 			asoc->default_stream = info->sinfo_stream;
2949 			asoc->default_flags = info->sinfo_flags;
2950 			asoc->default_ppid = info->sinfo_ppid;
2951 			asoc->default_context = info->sinfo_context;
2952 			asoc->default_timetolive = info->sinfo_timetolive;
2953 		}
2954 	}
2955 
2956 	return 0;
2957 }
2958 
2959 /* RFC6458, Section 8.1.31. Set/get Default Send Parameters
2960  * (SCTP_DEFAULT_SNDINFO)
2961  */
sctp_setsockopt_default_sndinfo(struct sock * sk,struct sctp_sndinfo * info,unsigned int optlen)2962 static int sctp_setsockopt_default_sndinfo(struct sock *sk,
2963 					   struct sctp_sndinfo *info,
2964 					   unsigned int optlen)
2965 {
2966 	struct sctp_sock *sp = sctp_sk(sk);
2967 	struct sctp_association *asoc;
2968 
2969 	if (optlen != sizeof(*info))
2970 		return -EINVAL;
2971 	if (info->snd_flags &
2972 	    ~(SCTP_UNORDERED | SCTP_ADDR_OVER |
2973 	      SCTP_ABORT | SCTP_EOF))
2974 		return -EINVAL;
2975 
2976 	asoc = sctp_id2assoc(sk, info->snd_assoc_id);
2977 	if (!asoc && info->snd_assoc_id > SCTP_ALL_ASSOC &&
2978 	    sctp_style(sk, UDP))
2979 		return -EINVAL;
2980 
2981 	if (asoc) {
2982 		asoc->default_stream = info->snd_sid;
2983 		asoc->default_flags = info->snd_flags;
2984 		asoc->default_ppid = info->snd_ppid;
2985 		asoc->default_context = info->snd_context;
2986 
2987 		return 0;
2988 	}
2989 
2990 	if (sctp_style(sk, TCP))
2991 		info->snd_assoc_id = SCTP_FUTURE_ASSOC;
2992 
2993 	if (info->snd_assoc_id == SCTP_FUTURE_ASSOC ||
2994 	    info->snd_assoc_id == SCTP_ALL_ASSOC) {
2995 		sp->default_stream = info->snd_sid;
2996 		sp->default_flags = info->snd_flags;
2997 		sp->default_ppid = info->snd_ppid;
2998 		sp->default_context = info->snd_context;
2999 	}
3000 
3001 	if (info->snd_assoc_id == SCTP_CURRENT_ASSOC ||
3002 	    info->snd_assoc_id == SCTP_ALL_ASSOC) {
3003 		list_for_each_entry(asoc, &sp->ep->asocs, asocs) {
3004 			asoc->default_stream = info->snd_sid;
3005 			asoc->default_flags = info->snd_flags;
3006 			asoc->default_ppid = info->snd_ppid;
3007 			asoc->default_context = info->snd_context;
3008 		}
3009 	}
3010 
3011 	return 0;
3012 }
3013 
3014 /* 7.1.10 Set Primary Address (SCTP_PRIMARY_ADDR)
3015  *
3016  * Requests that the local SCTP stack use the enclosed peer address as
3017  * the association primary.  The enclosed address must be one of the
3018  * association peer's addresses.
3019  */
sctp_setsockopt_primary_addr(struct sock * sk,struct sctp_prim * prim,unsigned int optlen)3020 static int sctp_setsockopt_primary_addr(struct sock *sk, struct sctp_prim *prim,
3021 					unsigned int optlen)
3022 {
3023 	struct sctp_transport *trans;
3024 	struct sctp_af *af;
3025 	int err;
3026 
3027 	if (optlen != sizeof(struct sctp_prim))
3028 		return -EINVAL;
3029 
3030 	/* Allow security module to validate address but need address len. */
3031 	af = sctp_get_af_specific(prim->ssp_addr.ss_family);
3032 	if (!af)
3033 		return -EINVAL;
3034 
3035 	err = security_sctp_bind_connect(sk, SCTP_PRIMARY_ADDR,
3036 					 (struct sockaddr *)&prim->ssp_addr,
3037 					 af->sockaddr_len);
3038 	if (err)
3039 		return err;
3040 
3041 	trans = sctp_addr_id2transport(sk, &prim->ssp_addr, prim->ssp_assoc_id);
3042 	if (!trans)
3043 		return -EINVAL;
3044 
3045 	sctp_assoc_set_primary(trans->asoc, trans);
3046 
3047 	return 0;
3048 }
3049 
3050 /*
3051  * 7.1.5 SCTP_NODELAY
3052  *
3053  * Turn on/off any Nagle-like algorithm.  This means that packets are
3054  * generally sent as soon as possible and no unnecessary delays are
3055  * introduced, at the cost of more packets in the network.  Expects an
3056  *  integer boolean flag.
3057  */
sctp_setsockopt_nodelay(struct sock * sk,int * val,unsigned int optlen)3058 static int sctp_setsockopt_nodelay(struct sock *sk, int *val,
3059 				   unsigned int optlen)
3060 {
3061 	if (optlen < sizeof(int))
3062 		return -EINVAL;
3063 	sctp_sk(sk)->nodelay = (*val == 0) ? 0 : 1;
3064 	return 0;
3065 }
3066 
3067 /*
3068  *
3069  * 7.1.1 SCTP_RTOINFO
3070  *
3071  * The protocol parameters used to initialize and bound retransmission
3072  * timeout (RTO) are tunable. sctp_rtoinfo structure is used to access
3073  * and modify these parameters.
3074  * All parameters are time values, in milliseconds.  A value of 0, when
3075  * modifying the parameters, indicates that the current value should not
3076  * be changed.
3077  *
3078  */
sctp_setsockopt_rtoinfo(struct sock * sk,struct sctp_rtoinfo * rtoinfo,unsigned int optlen)3079 static int sctp_setsockopt_rtoinfo(struct sock *sk,
3080 				   struct sctp_rtoinfo *rtoinfo,
3081 				   unsigned int optlen)
3082 {
3083 	struct sctp_association *asoc;
3084 	unsigned long rto_min, rto_max;
3085 	struct sctp_sock *sp = sctp_sk(sk);
3086 
3087 	if (optlen != sizeof (struct sctp_rtoinfo))
3088 		return -EINVAL;
3089 
3090 	asoc = sctp_id2assoc(sk, rtoinfo->srto_assoc_id);
3091 
3092 	/* Set the values to the specific association */
3093 	if (!asoc && rtoinfo->srto_assoc_id != SCTP_FUTURE_ASSOC &&
3094 	    sctp_style(sk, UDP))
3095 		return -EINVAL;
3096 
3097 	rto_max = rtoinfo->srto_max;
3098 	rto_min = rtoinfo->srto_min;
3099 
3100 	if (rto_max)
3101 		rto_max = asoc ? msecs_to_jiffies(rto_max) : rto_max;
3102 	else
3103 		rto_max = asoc ? asoc->rto_max : sp->rtoinfo.srto_max;
3104 
3105 	if (rto_min)
3106 		rto_min = asoc ? msecs_to_jiffies(rto_min) : rto_min;
3107 	else
3108 		rto_min = asoc ? asoc->rto_min : sp->rtoinfo.srto_min;
3109 
3110 	if (rto_min > rto_max)
3111 		return -EINVAL;
3112 
3113 	if (asoc) {
3114 		if (rtoinfo->srto_initial != 0)
3115 			asoc->rto_initial =
3116 				msecs_to_jiffies(rtoinfo->srto_initial);
3117 		asoc->rto_max = rto_max;
3118 		asoc->rto_min = rto_min;
3119 	} else {
3120 		/* If there is no association or the association-id = 0
3121 		 * set the values to the endpoint.
3122 		 */
3123 		if (rtoinfo->srto_initial != 0)
3124 			sp->rtoinfo.srto_initial = rtoinfo->srto_initial;
3125 		sp->rtoinfo.srto_max = rto_max;
3126 		sp->rtoinfo.srto_min = rto_min;
3127 	}
3128 
3129 	return 0;
3130 }
3131 
3132 /*
3133  *
3134  * 7.1.2 SCTP_ASSOCINFO
3135  *
3136  * This option is used to tune the maximum retransmission attempts
3137  * of the association.
3138  * Returns an error if the new association retransmission value is
3139  * greater than the sum of the retransmission value  of the peer.
3140  * See [SCTP] for more information.
3141  *
3142  */
sctp_setsockopt_associnfo(struct sock * sk,struct sctp_assocparams * assocparams,unsigned int optlen)3143 static int sctp_setsockopt_associnfo(struct sock *sk,
3144 				     struct sctp_assocparams *assocparams,
3145 				     unsigned int optlen)
3146 {
3147 
3148 	struct sctp_association *asoc;
3149 
3150 	if (optlen != sizeof(struct sctp_assocparams))
3151 		return -EINVAL;
3152 
3153 	asoc = sctp_id2assoc(sk, assocparams->sasoc_assoc_id);
3154 
3155 	if (!asoc && assocparams->sasoc_assoc_id != SCTP_FUTURE_ASSOC &&
3156 	    sctp_style(sk, UDP))
3157 		return -EINVAL;
3158 
3159 	/* Set the values to the specific association */
3160 	if (asoc) {
3161 		if (assocparams->sasoc_asocmaxrxt != 0) {
3162 			__u32 path_sum = 0;
3163 			int   paths = 0;
3164 			struct sctp_transport *peer_addr;
3165 
3166 			list_for_each_entry(peer_addr, &asoc->peer.transport_addr_list,
3167 					transports) {
3168 				path_sum += peer_addr->pathmaxrxt;
3169 				paths++;
3170 			}
3171 
3172 			/* Only validate asocmaxrxt if we have more than
3173 			 * one path/transport.  We do this because path
3174 			 * retransmissions are only counted when we have more
3175 			 * then one path.
3176 			 */
3177 			if (paths > 1 &&
3178 			    assocparams->sasoc_asocmaxrxt > path_sum)
3179 				return -EINVAL;
3180 
3181 			asoc->max_retrans = assocparams->sasoc_asocmaxrxt;
3182 		}
3183 
3184 		if (assocparams->sasoc_cookie_life != 0)
3185 			asoc->cookie_life =
3186 				ms_to_ktime(assocparams->sasoc_cookie_life);
3187 	} else {
3188 		/* Set the values to the endpoint */
3189 		struct sctp_sock *sp = sctp_sk(sk);
3190 
3191 		if (assocparams->sasoc_asocmaxrxt != 0)
3192 			sp->assocparams.sasoc_asocmaxrxt =
3193 						assocparams->sasoc_asocmaxrxt;
3194 		if (assocparams->sasoc_cookie_life != 0)
3195 			sp->assocparams.sasoc_cookie_life =
3196 						assocparams->sasoc_cookie_life;
3197 	}
3198 	return 0;
3199 }
3200 
3201 /*
3202  * 7.1.16 Set/clear IPv4 mapped addresses (SCTP_I_WANT_MAPPED_V4_ADDR)
3203  *
3204  * This socket option is a boolean flag which turns on or off mapped V4
3205  * addresses.  If this option is turned on and the socket is type
3206  * PF_INET6, then IPv4 addresses will be mapped to V6 representation.
3207  * If this option is turned off, then no mapping will be done of V4
3208  * addresses and a user will receive both PF_INET6 and PF_INET type
3209  * addresses on the socket.
3210  */
sctp_setsockopt_mappedv4(struct sock * sk,int * val,unsigned int optlen)3211 static int sctp_setsockopt_mappedv4(struct sock *sk, int *val,
3212 				    unsigned int optlen)
3213 {
3214 	struct sctp_sock *sp = sctp_sk(sk);
3215 
3216 	if (optlen < sizeof(int))
3217 		return -EINVAL;
3218 	if (*val)
3219 		sp->v4mapped = 1;
3220 	else
3221 		sp->v4mapped = 0;
3222 
3223 	return 0;
3224 }
3225 
3226 /*
3227  * 8.1.16.  Get or Set the Maximum Fragmentation Size (SCTP_MAXSEG)
3228  * This option will get or set the maximum size to put in any outgoing
3229  * SCTP DATA chunk.  If a message is larger than this size it will be
3230  * fragmented by SCTP into the specified size.  Note that the underlying
3231  * SCTP implementation may fragment into smaller sized chunks when the
3232  * PMTU of the underlying association is smaller than the value set by
3233  * the user.  The default value for this option is '0' which indicates
3234  * the user is NOT limiting fragmentation and only the PMTU will effect
3235  * SCTP's choice of DATA chunk size.  Note also that values set larger
3236  * than the maximum size of an IP datagram will effectively let SCTP
3237  * control fragmentation (i.e. the same as setting this option to 0).
3238  *
3239  * The following structure is used to access and modify this parameter:
3240  *
3241  * struct sctp_assoc_value {
3242  *   sctp_assoc_t assoc_id;
3243  *   uint32_t assoc_value;
3244  * };
3245  *
3246  * assoc_id:  This parameter is ignored for one-to-one style sockets.
3247  *    For one-to-many style sockets this parameter indicates which
3248  *    association the user is performing an action upon.  Note that if
3249  *    this field's value is zero then the endpoints default value is
3250  *    changed (effecting future associations only).
3251  * assoc_value:  This parameter specifies the maximum size in bytes.
3252  */
sctp_setsockopt_maxseg(struct sock * sk,struct sctp_assoc_value * params,unsigned int optlen)3253 static int sctp_setsockopt_maxseg(struct sock *sk,
3254 				  struct sctp_assoc_value *params,
3255 				  unsigned int optlen)
3256 {
3257 	struct sctp_sock *sp = sctp_sk(sk);
3258 	struct sctp_association *asoc;
3259 	sctp_assoc_t assoc_id;
3260 	int val;
3261 
3262 	if (optlen == sizeof(int)) {
3263 		pr_warn_ratelimited(DEPRECATED
3264 				    "%s (pid %d) "
3265 				    "Use of int in maxseg socket option.\n"
3266 				    "Use struct sctp_assoc_value instead\n",
3267 				    current->comm, task_pid_nr(current));
3268 		assoc_id = SCTP_FUTURE_ASSOC;
3269 		val = *(int *)params;
3270 	} else if (optlen == sizeof(struct sctp_assoc_value)) {
3271 		assoc_id = params->assoc_id;
3272 		val = params->assoc_value;
3273 	} else {
3274 		return -EINVAL;
3275 	}
3276 
3277 	asoc = sctp_id2assoc(sk, assoc_id);
3278 	if (!asoc && assoc_id != SCTP_FUTURE_ASSOC &&
3279 	    sctp_style(sk, UDP))
3280 		return -EINVAL;
3281 
3282 	if (val) {
3283 		int min_len, max_len;
3284 		__u16 datasize = asoc ? sctp_datachk_len(&asoc->stream) :
3285 				 sizeof(struct sctp_data_chunk);
3286 
3287 		min_len = sctp_min_frag_point(sp, datasize);
3288 		max_len = SCTP_MAX_CHUNK_LEN - datasize;
3289 
3290 		if (val < min_len || val > max_len)
3291 			return -EINVAL;
3292 	}
3293 
3294 	if (asoc) {
3295 		asoc->user_frag = val;
3296 		sctp_assoc_update_frag_point(asoc);
3297 	} else {
3298 		sp->user_frag = val;
3299 	}
3300 
3301 	return 0;
3302 }
3303 
3304 
3305 /*
3306  *  7.1.9 Set Peer Primary Address (SCTP_SET_PEER_PRIMARY_ADDR)
3307  *
3308  *   Requests that the peer mark the enclosed address as the association
3309  *   primary. The enclosed address must be one of the association's
3310  *   locally bound addresses. The following structure is used to make a
3311  *   set primary request:
3312  */
sctp_setsockopt_peer_primary_addr(struct sock * sk,struct sctp_setpeerprim * prim,unsigned int optlen)3313 static int sctp_setsockopt_peer_primary_addr(struct sock *sk,
3314 					     struct sctp_setpeerprim *prim,
3315 					     unsigned int optlen)
3316 {
3317 	struct sctp_sock	*sp;
3318 	struct sctp_association	*asoc = NULL;
3319 	struct sctp_chunk	*chunk;
3320 	struct sctp_af		*af;
3321 	int 			err;
3322 
3323 	sp = sctp_sk(sk);
3324 
3325 	if (!sp->ep->asconf_enable)
3326 		return -EPERM;
3327 
3328 	if (optlen != sizeof(struct sctp_setpeerprim))
3329 		return -EINVAL;
3330 
3331 	asoc = sctp_id2assoc(sk, prim->sspp_assoc_id);
3332 	if (!asoc)
3333 		return -EINVAL;
3334 
3335 	if (!asoc->peer.asconf_capable)
3336 		return -EPERM;
3337 
3338 	if (asoc->peer.addip_disabled_mask & SCTP_PARAM_SET_PRIMARY)
3339 		return -EPERM;
3340 
3341 	if (!sctp_state(asoc, ESTABLISHED))
3342 		return -ENOTCONN;
3343 
3344 	af = sctp_get_af_specific(prim->sspp_addr.ss_family);
3345 	if (!af)
3346 		return -EINVAL;
3347 
3348 	if (!af->addr_valid((union sctp_addr *)&prim->sspp_addr, sp, NULL))
3349 		return -EADDRNOTAVAIL;
3350 
3351 	if (!sctp_assoc_lookup_laddr(asoc, (union sctp_addr *)&prim->sspp_addr))
3352 		return -EADDRNOTAVAIL;
3353 
3354 	/* Allow security module to validate address. */
3355 	err = security_sctp_bind_connect(sk, SCTP_SET_PEER_PRIMARY_ADDR,
3356 					 (struct sockaddr *)&prim->sspp_addr,
3357 					 af->sockaddr_len);
3358 	if (err)
3359 		return err;
3360 
3361 	/* Create an ASCONF chunk with SET_PRIMARY parameter	*/
3362 	chunk = sctp_make_asconf_set_prim(asoc,
3363 					  (union sctp_addr *)&prim->sspp_addr);
3364 	if (!chunk)
3365 		return -ENOMEM;
3366 
3367 	err = sctp_send_asconf(asoc, chunk);
3368 
3369 	pr_debug("%s: we set peer primary addr primitively\n", __func__);
3370 
3371 	return err;
3372 }
3373 
sctp_setsockopt_adaptation_layer(struct sock * sk,struct sctp_setadaptation * adapt,unsigned int optlen)3374 static int sctp_setsockopt_adaptation_layer(struct sock *sk,
3375 					    struct sctp_setadaptation *adapt,
3376 					    unsigned int optlen)
3377 {
3378 	if (optlen != sizeof(struct sctp_setadaptation))
3379 		return -EINVAL;
3380 
3381 	sctp_sk(sk)->adaptation_ind = adapt->ssb_adaptation_ind;
3382 
3383 	return 0;
3384 }
3385 
3386 /*
3387  * 7.1.29.  Set or Get the default context (SCTP_CONTEXT)
3388  *
3389  * The context field in the sctp_sndrcvinfo structure is normally only
3390  * used when a failed message is retrieved holding the value that was
3391  * sent down on the actual send call.  This option allows the setting of
3392  * a default context on an association basis that will be received on
3393  * reading messages from the peer.  This is especially helpful in the
3394  * one-2-many model for an application to keep some reference to an
3395  * internal state machine that is processing messages on the
3396  * association.  Note that the setting of this value only effects
3397  * received messages from the peer and does not effect the value that is
3398  * saved with outbound messages.
3399  */
sctp_setsockopt_context(struct sock * sk,struct sctp_assoc_value * params,unsigned int optlen)3400 static int sctp_setsockopt_context(struct sock *sk,
3401 				   struct sctp_assoc_value *params,
3402 				   unsigned int optlen)
3403 {
3404 	struct sctp_sock *sp = sctp_sk(sk);
3405 	struct sctp_association *asoc;
3406 
3407 	if (optlen != sizeof(struct sctp_assoc_value))
3408 		return -EINVAL;
3409 
3410 	asoc = sctp_id2assoc(sk, params->assoc_id);
3411 	if (!asoc && params->assoc_id > SCTP_ALL_ASSOC &&
3412 	    sctp_style(sk, UDP))
3413 		return -EINVAL;
3414 
3415 	if (asoc) {
3416 		asoc->default_rcv_context = params->assoc_value;
3417 
3418 		return 0;
3419 	}
3420 
3421 	if (sctp_style(sk, TCP))
3422 		params->assoc_id = SCTP_FUTURE_ASSOC;
3423 
3424 	if (params->assoc_id == SCTP_FUTURE_ASSOC ||
3425 	    params->assoc_id == SCTP_ALL_ASSOC)
3426 		sp->default_rcv_context = params->assoc_value;
3427 
3428 	if (params->assoc_id == SCTP_CURRENT_ASSOC ||
3429 	    params->assoc_id == SCTP_ALL_ASSOC)
3430 		list_for_each_entry(asoc, &sp->ep->asocs, asocs)
3431 			asoc->default_rcv_context = params->assoc_value;
3432 
3433 	return 0;
3434 }
3435 
3436 /*
3437  * 7.1.24.  Get or set fragmented interleave (SCTP_FRAGMENT_INTERLEAVE)
3438  *
3439  * This options will at a minimum specify if the implementation is doing
3440  * fragmented interleave.  Fragmented interleave, for a one to many
3441  * socket, is when subsequent calls to receive a message may return
3442  * parts of messages from different associations.  Some implementations
3443  * may allow you to turn this value on or off.  If so, when turned off,
3444  * no fragment interleave will occur (which will cause a head of line
3445  * blocking amongst multiple associations sharing the same one to many
3446  * socket).  When this option is turned on, then each receive call may
3447  * come from a different association (thus the user must receive data
3448  * with the extended calls (e.g. sctp_recvmsg) to keep track of which
3449  * association each receive belongs to.
3450  *
3451  * This option takes a boolean value.  A non-zero value indicates that
3452  * fragmented interleave is on.  A value of zero indicates that
3453  * fragmented interleave is off.
3454  *
3455  * Note that it is important that an implementation that allows this
3456  * option to be turned on, have it off by default.  Otherwise an unaware
3457  * application using the one to many model may become confused and act
3458  * incorrectly.
3459  */
sctp_setsockopt_fragment_interleave(struct sock * sk,int * val,unsigned int optlen)3460 static int sctp_setsockopt_fragment_interleave(struct sock *sk, int *val,
3461 					       unsigned int optlen)
3462 {
3463 	if (optlen != sizeof(int))
3464 		return -EINVAL;
3465 
3466 	sctp_sk(sk)->frag_interleave = !!*val;
3467 
3468 	if (!sctp_sk(sk)->frag_interleave)
3469 		sctp_sk(sk)->ep->intl_enable = 0;
3470 
3471 	return 0;
3472 }
3473 
3474 /*
3475  * 8.1.21.  Set or Get the SCTP Partial Delivery Point
3476  *       (SCTP_PARTIAL_DELIVERY_POINT)
3477  *
3478  * This option will set or get the SCTP partial delivery point.  This
3479  * point is the size of a message where the partial delivery API will be
3480  * invoked to help free up rwnd space for the peer.  Setting this to a
3481  * lower value will cause partial deliveries to happen more often.  The
3482  * calls argument is an integer that sets or gets the partial delivery
3483  * point.  Note also that the call will fail if the user attempts to set
3484  * this value larger than the socket receive buffer size.
3485  *
3486  * Note that any single message having a length smaller than or equal to
3487  * the SCTP partial delivery point will be delivered in one single read
3488  * call as long as the user provided buffer is large enough to hold the
3489  * message.
3490  */
sctp_setsockopt_partial_delivery_point(struct sock * sk,u32 * val,unsigned int optlen)3491 static int sctp_setsockopt_partial_delivery_point(struct sock *sk, u32 *val,
3492 						  unsigned int optlen)
3493 {
3494 	if (optlen != sizeof(u32))
3495 		return -EINVAL;
3496 
3497 	/* Note: We double the receive buffer from what the user sets
3498 	 * it to be, also initial rwnd is based on rcvbuf/2.
3499 	 */
3500 	if (*val > (sk->sk_rcvbuf >> 1))
3501 		return -EINVAL;
3502 
3503 	sctp_sk(sk)->pd_point = *val;
3504 
3505 	return 0; /* is this the right error code? */
3506 }
3507 
3508 /*
3509  * 7.1.28.  Set or Get the maximum burst (SCTP_MAX_BURST)
3510  *
3511  * This option will allow a user to change the maximum burst of packets
3512  * that can be emitted by this association.  Note that the default value
3513  * is 4, and some implementations may restrict this setting so that it
3514  * can only be lowered.
3515  *
3516  * NOTE: This text doesn't seem right.  Do this on a socket basis with
3517  * future associations inheriting the socket value.
3518  */
sctp_setsockopt_maxburst(struct sock * sk,struct sctp_assoc_value * params,unsigned int optlen)3519 static int sctp_setsockopt_maxburst(struct sock *sk,
3520 				    struct sctp_assoc_value *params,
3521 				    unsigned int optlen)
3522 {
3523 	struct sctp_sock *sp = sctp_sk(sk);
3524 	struct sctp_association *asoc;
3525 	sctp_assoc_t assoc_id;
3526 	u32 assoc_value;
3527 
3528 	if (optlen == sizeof(int)) {
3529 		pr_warn_ratelimited(DEPRECATED
3530 				    "%s (pid %d) "
3531 				    "Use of int in max_burst socket option deprecated.\n"
3532 				    "Use struct sctp_assoc_value instead\n",
3533 				    current->comm, task_pid_nr(current));
3534 		assoc_id = SCTP_FUTURE_ASSOC;
3535 		assoc_value = *((int *)params);
3536 	} else if (optlen == sizeof(struct sctp_assoc_value)) {
3537 		assoc_id = params->assoc_id;
3538 		assoc_value = params->assoc_value;
3539 	} else
3540 		return -EINVAL;
3541 
3542 	asoc = sctp_id2assoc(sk, assoc_id);
3543 	if (!asoc && assoc_id > SCTP_ALL_ASSOC && sctp_style(sk, UDP))
3544 		return -EINVAL;
3545 
3546 	if (asoc) {
3547 		asoc->max_burst = assoc_value;
3548 
3549 		return 0;
3550 	}
3551 
3552 	if (sctp_style(sk, TCP))
3553 		assoc_id = SCTP_FUTURE_ASSOC;
3554 
3555 	if (assoc_id == SCTP_FUTURE_ASSOC || assoc_id == SCTP_ALL_ASSOC)
3556 		sp->max_burst = assoc_value;
3557 
3558 	if (assoc_id == SCTP_CURRENT_ASSOC || assoc_id == SCTP_ALL_ASSOC)
3559 		list_for_each_entry(asoc, &sp->ep->asocs, asocs)
3560 			asoc->max_burst = assoc_value;
3561 
3562 	return 0;
3563 }
3564 
3565 /*
3566  * 7.1.18.  Add a chunk that must be authenticated (SCTP_AUTH_CHUNK)
3567  *
3568  * This set option adds a chunk type that the user is requesting to be
3569  * received only in an authenticated way.  Changes to the list of chunks
3570  * will only effect future associations on the socket.
3571  */
sctp_setsockopt_auth_chunk(struct sock * sk,struct sctp_authchunk * val,unsigned int optlen)3572 static int sctp_setsockopt_auth_chunk(struct sock *sk,
3573 				      struct sctp_authchunk *val,
3574 				      unsigned int optlen)
3575 {
3576 	struct sctp_endpoint *ep = sctp_sk(sk)->ep;
3577 
3578 	if (!ep->auth_enable)
3579 		return -EACCES;
3580 
3581 	if (optlen != sizeof(struct sctp_authchunk))
3582 		return -EINVAL;
3583 
3584 	switch (val->sauth_chunk) {
3585 	case SCTP_CID_INIT:
3586 	case SCTP_CID_INIT_ACK:
3587 	case SCTP_CID_SHUTDOWN_COMPLETE:
3588 	case SCTP_CID_AUTH:
3589 		return -EINVAL;
3590 	}
3591 
3592 	/* add this chunk id to the endpoint */
3593 	return sctp_auth_ep_add_chunkid(ep, val->sauth_chunk);
3594 }
3595 
3596 /*
3597  * 7.1.19.  Get or set the list of supported HMAC Identifiers (SCTP_HMAC_IDENT)
3598  *
3599  * This option gets or sets the list of HMAC algorithms that the local
3600  * endpoint requires the peer to use.
3601  */
sctp_setsockopt_hmac_ident(struct sock * sk,struct sctp_hmacalgo * hmacs,unsigned int optlen)3602 static int sctp_setsockopt_hmac_ident(struct sock *sk,
3603 				      struct sctp_hmacalgo *hmacs,
3604 				      unsigned int optlen)
3605 {
3606 	struct sctp_endpoint *ep = sctp_sk(sk)->ep;
3607 	u32 idents;
3608 
3609 	if (!ep->auth_enable)
3610 		return -EACCES;
3611 
3612 	if (optlen < sizeof(struct sctp_hmacalgo))
3613 		return -EINVAL;
3614 	optlen = min_t(unsigned int, optlen, sizeof(struct sctp_hmacalgo) +
3615 					     SCTP_AUTH_NUM_HMACS * sizeof(u16));
3616 
3617 	idents = hmacs->shmac_num_idents;
3618 	if (idents == 0 || idents > SCTP_AUTH_NUM_HMACS ||
3619 	    (idents * sizeof(u16)) > (optlen - sizeof(struct sctp_hmacalgo)))
3620 		return -EINVAL;
3621 
3622 	return sctp_auth_ep_set_hmacs(ep, hmacs);
3623 }
3624 
3625 /*
3626  * 7.1.20.  Set a shared key (SCTP_AUTH_KEY)
3627  *
3628  * This option will set a shared secret key which is used to build an
3629  * association shared key.
3630  */
sctp_setsockopt_auth_key(struct sock * sk,struct sctp_authkey * authkey,unsigned int optlen)3631 static int sctp_setsockopt_auth_key(struct sock *sk,
3632 				    struct sctp_authkey *authkey,
3633 				    unsigned int optlen)
3634 {
3635 	struct sctp_endpoint *ep = sctp_sk(sk)->ep;
3636 	struct sctp_association *asoc;
3637 	int ret = -EINVAL;
3638 
3639 	if (optlen <= sizeof(struct sctp_authkey))
3640 		return -EINVAL;
3641 	/* authkey->sca_keylength is u16, so optlen can't be bigger than
3642 	 * this.
3643 	 */
3644 	optlen = min_t(unsigned int, optlen, USHRT_MAX + sizeof(*authkey));
3645 
3646 	if (authkey->sca_keylength > optlen - sizeof(*authkey))
3647 		goto out;
3648 
3649 	asoc = sctp_id2assoc(sk, authkey->sca_assoc_id);
3650 	if (!asoc && authkey->sca_assoc_id > SCTP_ALL_ASSOC &&
3651 	    sctp_style(sk, UDP))
3652 		goto out;
3653 
3654 	if (asoc) {
3655 		ret = sctp_auth_set_key(ep, asoc, authkey);
3656 		goto out;
3657 	}
3658 
3659 	if (sctp_style(sk, TCP))
3660 		authkey->sca_assoc_id = SCTP_FUTURE_ASSOC;
3661 
3662 	if (authkey->sca_assoc_id == SCTP_FUTURE_ASSOC ||
3663 	    authkey->sca_assoc_id == SCTP_ALL_ASSOC) {
3664 		ret = sctp_auth_set_key(ep, asoc, authkey);
3665 		if (ret)
3666 			goto out;
3667 	}
3668 
3669 	ret = 0;
3670 
3671 	if (authkey->sca_assoc_id == SCTP_CURRENT_ASSOC ||
3672 	    authkey->sca_assoc_id == SCTP_ALL_ASSOC) {
3673 		list_for_each_entry(asoc, &ep->asocs, asocs) {
3674 			int res = sctp_auth_set_key(ep, asoc, authkey);
3675 
3676 			if (res && !ret)
3677 				ret = res;
3678 		}
3679 	}
3680 
3681 out:
3682 	memzero_explicit(authkey, optlen);
3683 	return ret;
3684 }
3685 
3686 /*
3687  * 7.1.21.  Get or set the active shared key (SCTP_AUTH_ACTIVE_KEY)
3688  *
3689  * This option will get or set the active shared key to be used to build
3690  * the association shared key.
3691  */
sctp_setsockopt_active_key(struct sock * sk,struct sctp_authkeyid * val,unsigned int optlen)3692 static int sctp_setsockopt_active_key(struct sock *sk,
3693 				      struct sctp_authkeyid *val,
3694 				      unsigned int optlen)
3695 {
3696 	struct sctp_endpoint *ep = sctp_sk(sk)->ep;
3697 	struct sctp_association *asoc;
3698 	int ret = 0;
3699 
3700 	if (optlen != sizeof(struct sctp_authkeyid))
3701 		return -EINVAL;
3702 
3703 	asoc = sctp_id2assoc(sk, val->scact_assoc_id);
3704 	if (!asoc && val->scact_assoc_id > SCTP_ALL_ASSOC &&
3705 	    sctp_style(sk, UDP))
3706 		return -EINVAL;
3707 
3708 	if (asoc)
3709 		return sctp_auth_set_active_key(ep, asoc, val->scact_keynumber);
3710 
3711 	if (sctp_style(sk, TCP))
3712 		val->scact_assoc_id = SCTP_FUTURE_ASSOC;
3713 
3714 	if (val->scact_assoc_id == SCTP_FUTURE_ASSOC ||
3715 	    val->scact_assoc_id == SCTP_ALL_ASSOC) {
3716 		ret = sctp_auth_set_active_key(ep, asoc, val->scact_keynumber);
3717 		if (ret)
3718 			return ret;
3719 	}
3720 
3721 	if (val->scact_assoc_id == SCTP_CURRENT_ASSOC ||
3722 	    val->scact_assoc_id == SCTP_ALL_ASSOC) {
3723 		list_for_each_entry(asoc, &ep->asocs, asocs) {
3724 			int res = sctp_auth_set_active_key(ep, asoc,
3725 							   val->scact_keynumber);
3726 
3727 			if (res && !ret)
3728 				ret = res;
3729 		}
3730 	}
3731 
3732 	return ret;
3733 }
3734 
3735 /*
3736  * 7.1.22.  Delete a shared key (SCTP_AUTH_DELETE_KEY)
3737  *
3738  * This set option will delete a shared secret key from use.
3739  */
sctp_setsockopt_del_key(struct sock * sk,struct sctp_authkeyid * val,unsigned int optlen)3740 static int sctp_setsockopt_del_key(struct sock *sk,
3741 				   struct sctp_authkeyid *val,
3742 				   unsigned int optlen)
3743 {
3744 	struct sctp_endpoint *ep = sctp_sk(sk)->ep;
3745 	struct sctp_association *asoc;
3746 	int ret = 0;
3747 
3748 	if (optlen != sizeof(struct sctp_authkeyid))
3749 		return -EINVAL;
3750 
3751 	asoc = sctp_id2assoc(sk, val->scact_assoc_id);
3752 	if (!asoc && val->scact_assoc_id > SCTP_ALL_ASSOC &&
3753 	    sctp_style(sk, UDP))
3754 		return -EINVAL;
3755 
3756 	if (asoc)
3757 		return sctp_auth_del_key_id(ep, asoc, val->scact_keynumber);
3758 
3759 	if (sctp_style(sk, TCP))
3760 		val->scact_assoc_id = SCTP_FUTURE_ASSOC;
3761 
3762 	if (val->scact_assoc_id == SCTP_FUTURE_ASSOC ||
3763 	    val->scact_assoc_id == SCTP_ALL_ASSOC) {
3764 		ret = sctp_auth_del_key_id(ep, asoc, val->scact_keynumber);
3765 		if (ret)
3766 			return ret;
3767 	}
3768 
3769 	if (val->scact_assoc_id == SCTP_CURRENT_ASSOC ||
3770 	    val->scact_assoc_id == SCTP_ALL_ASSOC) {
3771 		list_for_each_entry(asoc, &ep->asocs, asocs) {
3772 			int res = sctp_auth_del_key_id(ep, asoc,
3773 						       val->scact_keynumber);
3774 
3775 			if (res && !ret)
3776 				ret = res;
3777 		}
3778 	}
3779 
3780 	return ret;
3781 }
3782 
3783 /*
3784  * 8.3.4  Deactivate a Shared Key (SCTP_AUTH_DEACTIVATE_KEY)
3785  *
3786  * This set option will deactivate a shared secret key.
3787  */
sctp_setsockopt_deactivate_key(struct sock * sk,struct sctp_authkeyid * val,unsigned int optlen)3788 static int sctp_setsockopt_deactivate_key(struct sock *sk,
3789 					  struct sctp_authkeyid *val,
3790 					  unsigned int optlen)
3791 {
3792 	struct sctp_endpoint *ep = sctp_sk(sk)->ep;
3793 	struct sctp_association *asoc;
3794 	int ret = 0;
3795 
3796 	if (optlen != sizeof(struct sctp_authkeyid))
3797 		return -EINVAL;
3798 
3799 	asoc = sctp_id2assoc(sk, val->scact_assoc_id);
3800 	if (!asoc && val->scact_assoc_id > SCTP_ALL_ASSOC &&
3801 	    sctp_style(sk, UDP))
3802 		return -EINVAL;
3803 
3804 	if (asoc)
3805 		return sctp_auth_deact_key_id(ep, asoc, val->scact_keynumber);
3806 
3807 	if (sctp_style(sk, TCP))
3808 		val->scact_assoc_id = SCTP_FUTURE_ASSOC;
3809 
3810 	if (val->scact_assoc_id == SCTP_FUTURE_ASSOC ||
3811 	    val->scact_assoc_id == SCTP_ALL_ASSOC) {
3812 		ret = sctp_auth_deact_key_id(ep, asoc, val->scact_keynumber);
3813 		if (ret)
3814 			return ret;
3815 	}
3816 
3817 	if (val->scact_assoc_id == SCTP_CURRENT_ASSOC ||
3818 	    val->scact_assoc_id == SCTP_ALL_ASSOC) {
3819 		list_for_each_entry(asoc, &ep->asocs, asocs) {
3820 			int res = sctp_auth_deact_key_id(ep, asoc,
3821 							 val->scact_keynumber);
3822 
3823 			if (res && !ret)
3824 				ret = res;
3825 		}
3826 	}
3827 
3828 	return ret;
3829 }
3830 
3831 /*
3832  * 8.1.23 SCTP_AUTO_ASCONF
3833  *
3834  * This option will enable or disable the use of the automatic generation of
3835  * ASCONF chunks to add and delete addresses to an existing association.  Note
3836  * that this option has two caveats namely: a) it only affects sockets that
3837  * are bound to all addresses available to the SCTP stack, and b) the system
3838  * administrator may have an overriding control that turns the ASCONF feature
3839  * off no matter what setting the socket option may have.
3840  * This option expects an integer boolean flag, where a non-zero value turns on
3841  * the option, and a zero value turns off the option.
3842  * Note. In this implementation, socket operation overrides default parameter
3843  * being set by sysctl as well as FreeBSD implementation
3844  */
sctp_setsockopt_auto_asconf(struct sock * sk,int * val,unsigned int optlen)3845 static int sctp_setsockopt_auto_asconf(struct sock *sk, int *val,
3846 					unsigned int optlen)
3847 {
3848 	struct sctp_sock *sp = sctp_sk(sk);
3849 
3850 	if (optlen < sizeof(int))
3851 		return -EINVAL;
3852 	if (!sctp_is_ep_boundall(sk) && *val)
3853 		return -EINVAL;
3854 	if ((*val && sp->do_auto_asconf) || (!*val && !sp->do_auto_asconf))
3855 		return 0;
3856 
3857 	spin_lock_bh(&sock_net(sk)->sctp.addr_wq_lock);
3858 	if (*val == 0 && sp->do_auto_asconf) {
3859 		list_del(&sp->auto_asconf_list);
3860 		sp->do_auto_asconf = 0;
3861 	} else if (*val && !sp->do_auto_asconf) {
3862 		list_add_tail(&sp->auto_asconf_list,
3863 		    &sock_net(sk)->sctp.auto_asconf_splist);
3864 		sp->do_auto_asconf = 1;
3865 	}
3866 	spin_unlock_bh(&sock_net(sk)->sctp.addr_wq_lock);
3867 	return 0;
3868 }
3869 
3870 /*
3871  * SCTP_PEER_ADDR_THLDS
3872  *
3873  * This option allows us to alter the partially failed threshold for one or all
3874  * transports in an association.  See Section 6.1 of:
3875  * http://www.ietf.org/id/draft-nishida-tsvwg-sctp-failover-05.txt
3876  */
sctp_setsockopt_paddr_thresholds(struct sock * sk,struct sctp_paddrthlds_v2 * val,unsigned int optlen,bool v2)3877 static int sctp_setsockopt_paddr_thresholds(struct sock *sk,
3878 					    struct sctp_paddrthlds_v2 *val,
3879 					    unsigned int optlen, bool v2)
3880 {
3881 	struct sctp_transport *trans;
3882 	struct sctp_association *asoc;
3883 	int len;
3884 
3885 	len = v2 ? sizeof(*val) : sizeof(struct sctp_paddrthlds);
3886 	if (optlen < len)
3887 		return -EINVAL;
3888 
3889 	if (v2 && val->spt_pathpfthld > val->spt_pathcpthld)
3890 		return -EINVAL;
3891 
3892 	if (!sctp_is_any(sk, (const union sctp_addr *)&val->spt_address)) {
3893 		trans = sctp_addr_id2transport(sk, &val->spt_address,
3894 					       val->spt_assoc_id);
3895 		if (!trans)
3896 			return -ENOENT;
3897 
3898 		if (val->spt_pathmaxrxt)
3899 			trans->pathmaxrxt = val->spt_pathmaxrxt;
3900 		if (v2)
3901 			trans->ps_retrans = val->spt_pathcpthld;
3902 		trans->pf_retrans = val->spt_pathpfthld;
3903 
3904 		return 0;
3905 	}
3906 
3907 	asoc = sctp_id2assoc(sk, val->spt_assoc_id);
3908 	if (!asoc && val->spt_assoc_id != SCTP_FUTURE_ASSOC &&
3909 	    sctp_style(sk, UDP))
3910 		return -EINVAL;
3911 
3912 	if (asoc) {
3913 		list_for_each_entry(trans, &asoc->peer.transport_addr_list,
3914 				    transports) {
3915 			if (val->spt_pathmaxrxt)
3916 				trans->pathmaxrxt = val->spt_pathmaxrxt;
3917 			if (v2)
3918 				trans->ps_retrans = val->spt_pathcpthld;
3919 			trans->pf_retrans = val->spt_pathpfthld;
3920 		}
3921 
3922 		if (val->spt_pathmaxrxt)
3923 			asoc->pathmaxrxt = val->spt_pathmaxrxt;
3924 		if (v2)
3925 			asoc->ps_retrans = val->spt_pathcpthld;
3926 		asoc->pf_retrans = val->spt_pathpfthld;
3927 	} else {
3928 		struct sctp_sock *sp = sctp_sk(sk);
3929 
3930 		if (val->spt_pathmaxrxt)
3931 			sp->pathmaxrxt = val->spt_pathmaxrxt;
3932 		if (v2)
3933 			sp->ps_retrans = val->spt_pathcpthld;
3934 		sp->pf_retrans = val->spt_pathpfthld;
3935 	}
3936 
3937 	return 0;
3938 }
3939 
sctp_setsockopt_recvrcvinfo(struct sock * sk,int * val,unsigned int optlen)3940 static int sctp_setsockopt_recvrcvinfo(struct sock *sk, int *val,
3941 				       unsigned int optlen)
3942 {
3943 	if (optlen < sizeof(int))
3944 		return -EINVAL;
3945 
3946 	sctp_sk(sk)->recvrcvinfo = (*val == 0) ? 0 : 1;
3947 
3948 	return 0;
3949 }
3950 
sctp_setsockopt_recvnxtinfo(struct sock * sk,int * val,unsigned int optlen)3951 static int sctp_setsockopt_recvnxtinfo(struct sock *sk, int *val,
3952 				       unsigned int optlen)
3953 {
3954 	if (optlen < sizeof(int))
3955 		return -EINVAL;
3956 
3957 	sctp_sk(sk)->recvnxtinfo = (*val == 0) ? 0 : 1;
3958 
3959 	return 0;
3960 }
3961 
sctp_setsockopt_pr_supported(struct sock * sk,struct sctp_assoc_value * params,unsigned int optlen)3962 static int sctp_setsockopt_pr_supported(struct sock *sk,
3963 					struct sctp_assoc_value *params,
3964 					unsigned int optlen)
3965 {
3966 	struct sctp_association *asoc;
3967 
3968 	if (optlen != sizeof(*params))
3969 		return -EINVAL;
3970 
3971 	asoc = sctp_id2assoc(sk, params->assoc_id);
3972 	if (!asoc && params->assoc_id != SCTP_FUTURE_ASSOC &&
3973 	    sctp_style(sk, UDP))
3974 		return -EINVAL;
3975 
3976 	sctp_sk(sk)->ep->prsctp_enable = !!params->assoc_value;
3977 
3978 	return 0;
3979 }
3980 
sctp_setsockopt_default_prinfo(struct sock * sk,struct sctp_default_prinfo * info,unsigned int optlen)3981 static int sctp_setsockopt_default_prinfo(struct sock *sk,
3982 					  struct sctp_default_prinfo *info,
3983 					  unsigned int optlen)
3984 {
3985 	struct sctp_sock *sp = sctp_sk(sk);
3986 	struct sctp_association *asoc;
3987 	int retval = -EINVAL;
3988 
3989 	if (optlen != sizeof(*info))
3990 		goto out;
3991 
3992 	if (info->pr_policy & ~SCTP_PR_SCTP_MASK)
3993 		goto out;
3994 
3995 	if (info->pr_policy == SCTP_PR_SCTP_NONE)
3996 		info->pr_value = 0;
3997 
3998 	asoc = sctp_id2assoc(sk, info->pr_assoc_id);
3999 	if (!asoc && info->pr_assoc_id > SCTP_ALL_ASSOC &&
4000 	    sctp_style(sk, UDP))
4001 		goto out;
4002 
4003 	retval = 0;
4004 
4005 	if (asoc) {
4006 		SCTP_PR_SET_POLICY(asoc->default_flags, info->pr_policy);
4007 		asoc->default_timetolive = info->pr_value;
4008 		goto out;
4009 	}
4010 
4011 	if (sctp_style(sk, TCP))
4012 		info->pr_assoc_id = SCTP_FUTURE_ASSOC;
4013 
4014 	if (info->pr_assoc_id == SCTP_FUTURE_ASSOC ||
4015 	    info->pr_assoc_id == SCTP_ALL_ASSOC) {
4016 		SCTP_PR_SET_POLICY(sp->default_flags, info->pr_policy);
4017 		sp->default_timetolive = info->pr_value;
4018 	}
4019 
4020 	if (info->pr_assoc_id == SCTP_CURRENT_ASSOC ||
4021 	    info->pr_assoc_id == SCTP_ALL_ASSOC) {
4022 		list_for_each_entry(asoc, &sp->ep->asocs, asocs) {
4023 			SCTP_PR_SET_POLICY(asoc->default_flags,
4024 					   info->pr_policy);
4025 			asoc->default_timetolive = info->pr_value;
4026 		}
4027 	}
4028 
4029 out:
4030 	return retval;
4031 }
4032 
sctp_setsockopt_reconfig_supported(struct sock * sk,struct sctp_assoc_value * params,unsigned int optlen)4033 static int sctp_setsockopt_reconfig_supported(struct sock *sk,
4034 					      struct sctp_assoc_value *params,
4035 					      unsigned int optlen)
4036 {
4037 	struct sctp_association *asoc;
4038 	int retval = -EINVAL;
4039 
4040 	if (optlen != sizeof(*params))
4041 		goto out;
4042 
4043 	asoc = sctp_id2assoc(sk, params->assoc_id);
4044 	if (!asoc && params->assoc_id != SCTP_FUTURE_ASSOC &&
4045 	    sctp_style(sk, UDP))
4046 		goto out;
4047 
4048 	sctp_sk(sk)->ep->reconf_enable = !!params->assoc_value;
4049 
4050 	retval = 0;
4051 
4052 out:
4053 	return retval;
4054 }
4055 
sctp_setsockopt_enable_strreset(struct sock * sk,struct sctp_assoc_value * params,unsigned int optlen)4056 static int sctp_setsockopt_enable_strreset(struct sock *sk,
4057 					   struct sctp_assoc_value *params,
4058 					   unsigned int optlen)
4059 {
4060 	struct sctp_endpoint *ep = sctp_sk(sk)->ep;
4061 	struct sctp_association *asoc;
4062 	int retval = -EINVAL;
4063 
4064 	if (optlen != sizeof(*params))
4065 		goto out;
4066 
4067 	if (params->assoc_value & (~SCTP_ENABLE_STRRESET_MASK))
4068 		goto out;
4069 
4070 	asoc = sctp_id2assoc(sk, params->assoc_id);
4071 	if (!asoc && params->assoc_id > SCTP_ALL_ASSOC &&
4072 	    sctp_style(sk, UDP))
4073 		goto out;
4074 
4075 	retval = 0;
4076 
4077 	if (asoc) {
4078 		asoc->strreset_enable = params->assoc_value;
4079 		goto out;
4080 	}
4081 
4082 	if (sctp_style(sk, TCP))
4083 		params->assoc_id = SCTP_FUTURE_ASSOC;
4084 
4085 	if (params->assoc_id == SCTP_FUTURE_ASSOC ||
4086 	    params->assoc_id == SCTP_ALL_ASSOC)
4087 		ep->strreset_enable = params->assoc_value;
4088 
4089 	if (params->assoc_id == SCTP_CURRENT_ASSOC ||
4090 	    params->assoc_id == SCTP_ALL_ASSOC)
4091 		list_for_each_entry(asoc, &ep->asocs, asocs)
4092 			asoc->strreset_enable = params->assoc_value;
4093 
4094 out:
4095 	return retval;
4096 }
4097 
sctp_setsockopt_reset_streams(struct sock * sk,struct sctp_reset_streams * params,unsigned int optlen)4098 static int sctp_setsockopt_reset_streams(struct sock *sk,
4099 					 struct sctp_reset_streams *params,
4100 					 unsigned int optlen)
4101 {
4102 	struct sctp_association *asoc;
4103 
4104 	if (optlen < sizeof(*params))
4105 		return -EINVAL;
4106 	/* srs_number_streams is u16, so optlen can't be bigger than this. */
4107 	optlen = min_t(unsigned int, optlen, USHRT_MAX +
4108 					     sizeof(__u16) * sizeof(*params));
4109 
4110 	if (params->srs_number_streams * sizeof(__u16) >
4111 	    optlen - sizeof(*params))
4112 		return -EINVAL;
4113 
4114 	asoc = sctp_id2assoc(sk, params->srs_assoc_id);
4115 	if (!asoc)
4116 		return -EINVAL;
4117 
4118 	return sctp_send_reset_streams(asoc, params);
4119 }
4120 
sctp_setsockopt_reset_assoc(struct sock * sk,sctp_assoc_t * associd,unsigned int optlen)4121 static int sctp_setsockopt_reset_assoc(struct sock *sk, sctp_assoc_t *associd,
4122 				       unsigned int optlen)
4123 {
4124 	struct sctp_association *asoc;
4125 
4126 	if (optlen != sizeof(*associd))
4127 		return -EINVAL;
4128 
4129 	asoc = sctp_id2assoc(sk, *associd);
4130 	if (!asoc)
4131 		return -EINVAL;
4132 
4133 	return sctp_send_reset_assoc(asoc);
4134 }
4135 
sctp_setsockopt_add_streams(struct sock * sk,struct sctp_add_streams * params,unsigned int optlen)4136 static int sctp_setsockopt_add_streams(struct sock *sk,
4137 				       struct sctp_add_streams *params,
4138 				       unsigned int optlen)
4139 {
4140 	struct sctp_association *asoc;
4141 
4142 	if (optlen != sizeof(*params))
4143 		return -EINVAL;
4144 
4145 	asoc = sctp_id2assoc(sk, params->sas_assoc_id);
4146 	if (!asoc)
4147 		return -EINVAL;
4148 
4149 	return sctp_send_add_streams(asoc, params);
4150 }
4151 
sctp_setsockopt_scheduler(struct sock * sk,struct sctp_assoc_value * params,unsigned int optlen)4152 static int sctp_setsockopt_scheduler(struct sock *sk,
4153 				     struct sctp_assoc_value *params,
4154 				     unsigned int optlen)
4155 {
4156 	struct sctp_sock *sp = sctp_sk(sk);
4157 	struct sctp_association *asoc;
4158 	int retval = 0;
4159 
4160 	if (optlen < sizeof(*params))
4161 		return -EINVAL;
4162 
4163 	if (params->assoc_value > SCTP_SS_MAX)
4164 		return -EINVAL;
4165 
4166 	asoc = sctp_id2assoc(sk, params->assoc_id);
4167 	if (!asoc && params->assoc_id > SCTP_ALL_ASSOC &&
4168 	    sctp_style(sk, UDP))
4169 		return -EINVAL;
4170 
4171 	if (asoc)
4172 		return sctp_sched_set_sched(asoc, params->assoc_value);
4173 
4174 	if (sctp_style(sk, TCP))
4175 		params->assoc_id = SCTP_FUTURE_ASSOC;
4176 
4177 	if (params->assoc_id == SCTP_FUTURE_ASSOC ||
4178 	    params->assoc_id == SCTP_ALL_ASSOC)
4179 		sp->default_ss = params->assoc_value;
4180 
4181 	if (params->assoc_id == SCTP_CURRENT_ASSOC ||
4182 	    params->assoc_id == SCTP_ALL_ASSOC) {
4183 		list_for_each_entry(asoc, &sp->ep->asocs, asocs) {
4184 			int ret = sctp_sched_set_sched(asoc,
4185 						       params->assoc_value);
4186 
4187 			if (ret && !retval)
4188 				retval = ret;
4189 		}
4190 	}
4191 
4192 	return retval;
4193 }
4194 
sctp_setsockopt_scheduler_value(struct sock * sk,struct sctp_stream_value * params,unsigned int optlen)4195 static int sctp_setsockopt_scheduler_value(struct sock *sk,
4196 					   struct sctp_stream_value *params,
4197 					   unsigned int optlen)
4198 {
4199 	struct sctp_association *asoc;
4200 	int retval = -EINVAL;
4201 
4202 	if (optlen < sizeof(*params))
4203 		goto out;
4204 
4205 	asoc = sctp_id2assoc(sk, params->assoc_id);
4206 	if (!asoc && params->assoc_id != SCTP_CURRENT_ASSOC &&
4207 	    sctp_style(sk, UDP))
4208 		goto out;
4209 
4210 	if (asoc) {
4211 		retval = sctp_sched_set_value(asoc, params->stream_id,
4212 					      params->stream_value, GFP_KERNEL);
4213 		goto out;
4214 	}
4215 
4216 	retval = 0;
4217 
4218 	list_for_each_entry(asoc, &sctp_sk(sk)->ep->asocs, asocs) {
4219 		int ret = sctp_sched_set_value(asoc, params->stream_id,
4220 					       params->stream_value,
4221 					       GFP_KERNEL);
4222 		if (ret && !retval) /* try to return the 1st error. */
4223 			retval = ret;
4224 	}
4225 
4226 out:
4227 	return retval;
4228 }
4229 
sctp_setsockopt_interleaving_supported(struct sock * sk,struct sctp_assoc_value * p,unsigned int optlen)4230 static int sctp_setsockopt_interleaving_supported(struct sock *sk,
4231 						  struct sctp_assoc_value *p,
4232 						  unsigned int optlen)
4233 {
4234 	struct sctp_sock *sp = sctp_sk(sk);
4235 	struct sctp_association *asoc;
4236 
4237 	if (optlen < sizeof(*p))
4238 		return -EINVAL;
4239 
4240 	asoc = sctp_id2assoc(sk, p->assoc_id);
4241 	if (!asoc && p->assoc_id != SCTP_FUTURE_ASSOC && sctp_style(sk, UDP))
4242 		return -EINVAL;
4243 
4244 	if (!sock_net(sk)->sctp.intl_enable || !sp->frag_interleave) {
4245 		return -EPERM;
4246 	}
4247 
4248 	sp->ep->intl_enable = !!p->assoc_value;
4249 	return 0;
4250 }
4251 
sctp_setsockopt_reuse_port(struct sock * sk,int * val,unsigned int optlen)4252 static int sctp_setsockopt_reuse_port(struct sock *sk, int *val,
4253 				      unsigned int optlen)
4254 {
4255 	if (!sctp_style(sk, TCP))
4256 		return -EOPNOTSUPP;
4257 
4258 	if (sctp_sk(sk)->ep->base.bind_addr.port)
4259 		return -EFAULT;
4260 
4261 	if (optlen < sizeof(int))
4262 		return -EINVAL;
4263 
4264 	sctp_sk(sk)->reuse = !!*val;
4265 
4266 	return 0;
4267 }
4268 
sctp_assoc_ulpevent_type_set(struct sctp_event * param,struct sctp_association * asoc)4269 static int sctp_assoc_ulpevent_type_set(struct sctp_event *param,
4270 					struct sctp_association *asoc)
4271 {
4272 	struct sctp_ulpevent *event;
4273 
4274 	sctp_ulpevent_type_set(&asoc->subscribe, param->se_type, param->se_on);
4275 
4276 	if (param->se_type == SCTP_SENDER_DRY_EVENT && param->se_on) {
4277 		if (sctp_outq_is_empty(&asoc->outqueue)) {
4278 			event = sctp_ulpevent_make_sender_dry_event(asoc,
4279 					GFP_USER | __GFP_NOWARN);
4280 			if (!event)
4281 				return -ENOMEM;
4282 
4283 			asoc->stream.si->enqueue_event(&asoc->ulpq, event);
4284 		}
4285 	}
4286 
4287 	return 0;
4288 }
4289 
sctp_setsockopt_event(struct sock * sk,struct sctp_event * param,unsigned int optlen)4290 static int sctp_setsockopt_event(struct sock *sk, struct sctp_event *param,
4291 				 unsigned int optlen)
4292 {
4293 	struct sctp_sock *sp = sctp_sk(sk);
4294 	struct sctp_association *asoc;
4295 	int retval = 0;
4296 
4297 	if (optlen < sizeof(*param))
4298 		return -EINVAL;
4299 
4300 	if (param->se_type < SCTP_SN_TYPE_BASE ||
4301 	    param->se_type > SCTP_SN_TYPE_MAX)
4302 		return -EINVAL;
4303 
4304 	asoc = sctp_id2assoc(sk, param->se_assoc_id);
4305 	if (!asoc && param->se_assoc_id > SCTP_ALL_ASSOC &&
4306 	    sctp_style(sk, UDP))
4307 		return -EINVAL;
4308 
4309 	if (asoc)
4310 		return sctp_assoc_ulpevent_type_set(param, asoc);
4311 
4312 	if (sctp_style(sk, TCP))
4313 		param->se_assoc_id = SCTP_FUTURE_ASSOC;
4314 
4315 	if (param->se_assoc_id == SCTP_FUTURE_ASSOC ||
4316 	    param->se_assoc_id == SCTP_ALL_ASSOC)
4317 		sctp_ulpevent_type_set(&sp->subscribe,
4318 				       param->se_type, param->se_on);
4319 
4320 	if (param->se_assoc_id == SCTP_CURRENT_ASSOC ||
4321 	    param->se_assoc_id == SCTP_ALL_ASSOC) {
4322 		list_for_each_entry(asoc, &sp->ep->asocs, asocs) {
4323 			int ret = sctp_assoc_ulpevent_type_set(param, asoc);
4324 
4325 			if (ret && !retval)
4326 				retval = ret;
4327 		}
4328 	}
4329 
4330 	return retval;
4331 }
4332 
sctp_setsockopt_asconf_supported(struct sock * sk,struct sctp_assoc_value * params,unsigned int optlen)4333 static int sctp_setsockopt_asconf_supported(struct sock *sk,
4334 					    struct sctp_assoc_value *params,
4335 					    unsigned int optlen)
4336 {
4337 	struct sctp_association *asoc;
4338 	struct sctp_endpoint *ep;
4339 	int retval = -EINVAL;
4340 
4341 	if (optlen != sizeof(*params))
4342 		goto out;
4343 
4344 	asoc = sctp_id2assoc(sk, params->assoc_id);
4345 	if (!asoc && params->assoc_id != SCTP_FUTURE_ASSOC &&
4346 	    sctp_style(sk, UDP))
4347 		goto out;
4348 
4349 	ep = sctp_sk(sk)->ep;
4350 	ep->asconf_enable = !!params->assoc_value;
4351 
4352 	if (ep->asconf_enable && ep->auth_enable) {
4353 		sctp_auth_ep_add_chunkid(ep, SCTP_CID_ASCONF);
4354 		sctp_auth_ep_add_chunkid(ep, SCTP_CID_ASCONF_ACK);
4355 	}
4356 
4357 	retval = 0;
4358 
4359 out:
4360 	return retval;
4361 }
4362 
sctp_setsockopt_auth_supported(struct sock * sk,struct sctp_assoc_value * params,unsigned int optlen)4363 static int sctp_setsockopt_auth_supported(struct sock *sk,
4364 					  struct sctp_assoc_value *params,
4365 					  unsigned int optlen)
4366 {
4367 	struct sctp_association *asoc;
4368 	struct sctp_endpoint *ep;
4369 	int retval = -EINVAL;
4370 
4371 	if (optlen != sizeof(*params))
4372 		goto out;
4373 
4374 	asoc = sctp_id2assoc(sk, params->assoc_id);
4375 	if (!asoc && params->assoc_id != SCTP_FUTURE_ASSOC &&
4376 	    sctp_style(sk, UDP))
4377 		goto out;
4378 
4379 	ep = sctp_sk(sk)->ep;
4380 	if (params->assoc_value) {
4381 		retval = sctp_auth_init(ep, GFP_KERNEL);
4382 		if (retval)
4383 			goto out;
4384 		if (ep->asconf_enable) {
4385 			sctp_auth_ep_add_chunkid(ep, SCTP_CID_ASCONF);
4386 			sctp_auth_ep_add_chunkid(ep, SCTP_CID_ASCONF_ACK);
4387 		}
4388 	}
4389 
4390 	ep->auth_enable = !!params->assoc_value;
4391 	retval = 0;
4392 
4393 out:
4394 	return retval;
4395 }
4396 
sctp_setsockopt_ecn_supported(struct sock * sk,struct sctp_assoc_value * params,unsigned int optlen)4397 static int sctp_setsockopt_ecn_supported(struct sock *sk,
4398 					 struct sctp_assoc_value *params,
4399 					 unsigned int optlen)
4400 {
4401 	struct sctp_association *asoc;
4402 	int retval = -EINVAL;
4403 
4404 	if (optlen != sizeof(*params))
4405 		goto out;
4406 
4407 	asoc = sctp_id2assoc(sk, params->assoc_id);
4408 	if (!asoc && params->assoc_id != SCTP_FUTURE_ASSOC &&
4409 	    sctp_style(sk, UDP))
4410 		goto out;
4411 
4412 	sctp_sk(sk)->ep->ecn_enable = !!params->assoc_value;
4413 	retval = 0;
4414 
4415 out:
4416 	return retval;
4417 }
4418 
sctp_setsockopt_pf_expose(struct sock * sk,struct sctp_assoc_value * params,unsigned int optlen)4419 static int sctp_setsockopt_pf_expose(struct sock *sk,
4420 				     struct sctp_assoc_value *params,
4421 				     unsigned int optlen)
4422 {
4423 	struct sctp_association *asoc;
4424 	int retval = -EINVAL;
4425 
4426 	if (optlen != sizeof(*params))
4427 		goto out;
4428 
4429 	if (params->assoc_value > SCTP_PF_EXPOSE_MAX)
4430 		goto out;
4431 
4432 	asoc = sctp_id2assoc(sk, params->assoc_id);
4433 	if (!asoc && params->assoc_id != SCTP_FUTURE_ASSOC &&
4434 	    sctp_style(sk, UDP))
4435 		goto out;
4436 
4437 	if (asoc)
4438 		asoc->pf_expose = params->assoc_value;
4439 	else
4440 		sctp_sk(sk)->pf_expose = params->assoc_value;
4441 	retval = 0;
4442 
4443 out:
4444 	return retval;
4445 }
4446 
sctp_setsockopt_encap_port(struct sock * sk,struct sctp_udpencaps * encap,unsigned int optlen)4447 static int sctp_setsockopt_encap_port(struct sock *sk,
4448 				      struct sctp_udpencaps *encap,
4449 				      unsigned int optlen)
4450 {
4451 	struct sctp_association *asoc;
4452 	struct sctp_transport *t;
4453 	__be16 encap_port;
4454 
4455 	if (optlen != sizeof(*encap))
4456 		return -EINVAL;
4457 
4458 	/* If an address other than INADDR_ANY is specified, and
4459 	 * no transport is found, then the request is invalid.
4460 	 */
4461 	encap_port = (__force __be16)encap->sue_port;
4462 	if (!sctp_is_any(sk, (union sctp_addr *)&encap->sue_address)) {
4463 		t = sctp_addr_id2transport(sk, &encap->sue_address,
4464 					   encap->sue_assoc_id);
4465 		if (!t)
4466 			return -EINVAL;
4467 
4468 		t->encap_port = encap_port;
4469 		return 0;
4470 	}
4471 
4472 	/* Get association, if assoc_id != SCTP_FUTURE_ASSOC and the
4473 	 * socket is a one to many style socket, and an association
4474 	 * was not found, then the id was invalid.
4475 	 */
4476 	asoc = sctp_id2assoc(sk, encap->sue_assoc_id);
4477 	if (!asoc && encap->sue_assoc_id != SCTP_FUTURE_ASSOC &&
4478 	    sctp_style(sk, UDP))
4479 		return -EINVAL;
4480 
4481 	/* If changes are for association, also apply encap_port to
4482 	 * each transport.
4483 	 */
4484 	if (asoc) {
4485 		list_for_each_entry(t, &asoc->peer.transport_addr_list,
4486 				    transports)
4487 			t->encap_port = encap_port;
4488 
4489 		asoc->encap_port = encap_port;
4490 		return 0;
4491 	}
4492 
4493 	sctp_sk(sk)->encap_port = encap_port;
4494 	return 0;
4495 }
4496 
sctp_setsockopt_probe_interval(struct sock * sk,struct sctp_probeinterval * params,unsigned int optlen)4497 static int sctp_setsockopt_probe_interval(struct sock *sk,
4498 					  struct sctp_probeinterval *params,
4499 					  unsigned int optlen)
4500 {
4501 	struct sctp_association *asoc;
4502 	struct sctp_transport *t;
4503 	__u32 probe_interval;
4504 
4505 	if (optlen != sizeof(*params))
4506 		return -EINVAL;
4507 
4508 	probe_interval = params->spi_interval;
4509 	if (probe_interval && probe_interval < SCTP_PROBE_TIMER_MIN)
4510 		return -EINVAL;
4511 
4512 	/* If an address other than INADDR_ANY is specified, and
4513 	 * no transport is found, then the request is invalid.
4514 	 */
4515 	if (!sctp_is_any(sk, (union sctp_addr *)&params->spi_address)) {
4516 		t = sctp_addr_id2transport(sk, &params->spi_address,
4517 					   params->spi_assoc_id);
4518 		if (!t)
4519 			return -EINVAL;
4520 
4521 		t->probe_interval = msecs_to_jiffies(probe_interval);
4522 		sctp_transport_pl_reset(t);
4523 		return 0;
4524 	}
4525 
4526 	/* Get association, if assoc_id != SCTP_FUTURE_ASSOC and the
4527 	 * socket is a one to many style socket, and an association
4528 	 * was not found, then the id was invalid.
4529 	 */
4530 	asoc = sctp_id2assoc(sk, params->spi_assoc_id);
4531 	if (!asoc && params->spi_assoc_id != SCTP_FUTURE_ASSOC &&
4532 	    sctp_style(sk, UDP))
4533 		return -EINVAL;
4534 
4535 	/* If changes are for association, also apply probe_interval to
4536 	 * each transport.
4537 	 */
4538 	if (asoc) {
4539 		list_for_each_entry(t, &asoc->peer.transport_addr_list, transports) {
4540 			t->probe_interval = msecs_to_jiffies(probe_interval);
4541 			sctp_transport_pl_reset(t);
4542 		}
4543 
4544 		asoc->probe_interval = msecs_to_jiffies(probe_interval);
4545 		return 0;
4546 	}
4547 
4548 	sctp_sk(sk)->probe_interval = probe_interval;
4549 	return 0;
4550 }
4551 
4552 /* API 6.2 setsockopt(), getsockopt()
4553  *
4554  * Applications use setsockopt() and getsockopt() to set or retrieve
4555  * socket options.  Socket options are used to change the default
4556  * behavior of sockets calls.  They are described in Section 7.
4557  *
4558  * The syntax is:
4559  *
4560  *   ret = getsockopt(int sd, int level, int optname, void __user *optval,
4561  *                    int __user *optlen);
4562  *   ret = setsockopt(int sd, int level, int optname, const void __user *optval,
4563  *                    int optlen);
4564  *
4565  *   sd      - the socket descript.
4566  *   level   - set to IPPROTO_SCTP for all SCTP options.
4567  *   optname - the option name.
4568  *   optval  - the buffer to store the value of the option.
4569  *   optlen  - the size of the buffer.
4570  */
sctp_setsockopt(struct sock * sk,int level,int optname,sockptr_t optval,unsigned int optlen)4571 static int sctp_setsockopt(struct sock *sk, int level, int optname,
4572 			   sockptr_t optval, unsigned int optlen)
4573 {
4574 	void *kopt = NULL;
4575 	int retval = 0;
4576 
4577 	pr_debug("%s: sk:%p, optname:%d\n", __func__, sk, optname);
4578 
4579 	/* I can hardly begin to describe how wrong this is.  This is
4580 	 * so broken as to be worse than useless.  The API draft
4581 	 * REALLY is NOT helpful here...  I am not convinced that the
4582 	 * semantics of setsockopt() with a level OTHER THAN SOL_SCTP
4583 	 * are at all well-founded.
4584 	 */
4585 	if (level != SOL_SCTP) {
4586 		struct sctp_af *af = sctp_sk(sk)->pf->af;
4587 
4588 		return af->setsockopt(sk, level, optname, optval, optlen);
4589 	}
4590 
4591 	if (optlen > 0) {
4592 		/* Trim it to the biggest size sctp sockopt may need if necessary */
4593 		optlen = min_t(unsigned int, optlen,
4594 			       PAGE_ALIGN(USHRT_MAX +
4595 					  sizeof(__u16) * sizeof(struct sctp_reset_streams)));
4596 		kopt = memdup_sockptr(optval, optlen);
4597 		if (IS_ERR(kopt))
4598 			return PTR_ERR(kopt);
4599 	}
4600 
4601 	lock_sock(sk);
4602 
4603 	switch (optname) {
4604 	case SCTP_SOCKOPT_BINDX_ADD:
4605 		/* 'optlen' is the size of the addresses buffer. */
4606 		retval = sctp_setsockopt_bindx(sk, kopt, optlen,
4607 					       SCTP_BINDX_ADD_ADDR);
4608 		break;
4609 
4610 	case SCTP_SOCKOPT_BINDX_REM:
4611 		/* 'optlen' is the size of the addresses buffer. */
4612 		retval = sctp_setsockopt_bindx(sk, kopt, optlen,
4613 					       SCTP_BINDX_REM_ADDR);
4614 		break;
4615 
4616 	case SCTP_SOCKOPT_CONNECTX_OLD:
4617 		/* 'optlen' is the size of the addresses buffer. */
4618 		retval = sctp_setsockopt_connectx_old(sk, kopt, optlen);
4619 		break;
4620 
4621 	case SCTP_SOCKOPT_CONNECTX:
4622 		/* 'optlen' is the size of the addresses buffer. */
4623 		retval = sctp_setsockopt_connectx(sk, kopt, optlen);
4624 		break;
4625 
4626 	case SCTP_DISABLE_FRAGMENTS:
4627 		retval = sctp_setsockopt_disable_fragments(sk, kopt, optlen);
4628 		break;
4629 
4630 	case SCTP_EVENTS:
4631 		retval = sctp_setsockopt_events(sk, kopt, optlen);
4632 		break;
4633 
4634 	case SCTP_AUTOCLOSE:
4635 		retval = sctp_setsockopt_autoclose(sk, kopt, optlen);
4636 		break;
4637 
4638 	case SCTP_PEER_ADDR_PARAMS:
4639 		retval = sctp_setsockopt_peer_addr_params(sk, kopt, optlen);
4640 		break;
4641 
4642 	case SCTP_DELAYED_SACK:
4643 		retval = sctp_setsockopt_delayed_ack(sk, kopt, optlen);
4644 		break;
4645 	case SCTP_PARTIAL_DELIVERY_POINT:
4646 		retval = sctp_setsockopt_partial_delivery_point(sk, kopt, optlen);
4647 		break;
4648 
4649 	case SCTP_INITMSG:
4650 		retval = sctp_setsockopt_initmsg(sk, kopt, optlen);
4651 		break;
4652 	case SCTP_DEFAULT_SEND_PARAM:
4653 		retval = sctp_setsockopt_default_send_param(sk, kopt, optlen);
4654 		break;
4655 	case SCTP_DEFAULT_SNDINFO:
4656 		retval = sctp_setsockopt_default_sndinfo(sk, kopt, optlen);
4657 		break;
4658 	case SCTP_PRIMARY_ADDR:
4659 		retval = sctp_setsockopt_primary_addr(sk, kopt, optlen);
4660 		break;
4661 	case SCTP_SET_PEER_PRIMARY_ADDR:
4662 		retval = sctp_setsockopt_peer_primary_addr(sk, kopt, optlen);
4663 		break;
4664 	case SCTP_NODELAY:
4665 		retval = sctp_setsockopt_nodelay(sk, kopt, optlen);
4666 		break;
4667 	case SCTP_RTOINFO:
4668 		retval = sctp_setsockopt_rtoinfo(sk, kopt, optlen);
4669 		break;
4670 	case SCTP_ASSOCINFO:
4671 		retval = sctp_setsockopt_associnfo(sk, kopt, optlen);
4672 		break;
4673 	case SCTP_I_WANT_MAPPED_V4_ADDR:
4674 		retval = sctp_setsockopt_mappedv4(sk, kopt, optlen);
4675 		break;
4676 	case SCTP_MAXSEG:
4677 		retval = sctp_setsockopt_maxseg(sk, kopt, optlen);
4678 		break;
4679 	case SCTP_ADAPTATION_LAYER:
4680 		retval = sctp_setsockopt_adaptation_layer(sk, kopt, optlen);
4681 		break;
4682 	case SCTP_CONTEXT:
4683 		retval = sctp_setsockopt_context(sk, kopt, optlen);
4684 		break;
4685 	case SCTP_FRAGMENT_INTERLEAVE:
4686 		retval = sctp_setsockopt_fragment_interleave(sk, kopt, optlen);
4687 		break;
4688 	case SCTP_MAX_BURST:
4689 		retval = sctp_setsockopt_maxburst(sk, kopt, optlen);
4690 		break;
4691 	case SCTP_AUTH_CHUNK:
4692 		retval = sctp_setsockopt_auth_chunk(sk, kopt, optlen);
4693 		break;
4694 	case SCTP_HMAC_IDENT:
4695 		retval = sctp_setsockopt_hmac_ident(sk, kopt, optlen);
4696 		break;
4697 	case SCTP_AUTH_KEY:
4698 		retval = sctp_setsockopt_auth_key(sk, kopt, optlen);
4699 		break;
4700 	case SCTP_AUTH_ACTIVE_KEY:
4701 		retval = sctp_setsockopt_active_key(sk, kopt, optlen);
4702 		break;
4703 	case SCTP_AUTH_DELETE_KEY:
4704 		retval = sctp_setsockopt_del_key(sk, kopt, optlen);
4705 		break;
4706 	case SCTP_AUTH_DEACTIVATE_KEY:
4707 		retval = sctp_setsockopt_deactivate_key(sk, kopt, optlen);
4708 		break;
4709 	case SCTP_AUTO_ASCONF:
4710 		retval = sctp_setsockopt_auto_asconf(sk, kopt, optlen);
4711 		break;
4712 	case SCTP_PEER_ADDR_THLDS:
4713 		retval = sctp_setsockopt_paddr_thresholds(sk, kopt, optlen,
4714 							  false);
4715 		break;
4716 	case SCTP_PEER_ADDR_THLDS_V2:
4717 		retval = sctp_setsockopt_paddr_thresholds(sk, kopt, optlen,
4718 							  true);
4719 		break;
4720 	case SCTP_RECVRCVINFO:
4721 		retval = sctp_setsockopt_recvrcvinfo(sk, kopt, optlen);
4722 		break;
4723 	case SCTP_RECVNXTINFO:
4724 		retval = sctp_setsockopt_recvnxtinfo(sk, kopt, optlen);
4725 		break;
4726 	case SCTP_PR_SUPPORTED:
4727 		retval = sctp_setsockopt_pr_supported(sk, kopt, optlen);
4728 		break;
4729 	case SCTP_DEFAULT_PRINFO:
4730 		retval = sctp_setsockopt_default_prinfo(sk, kopt, optlen);
4731 		break;
4732 	case SCTP_RECONFIG_SUPPORTED:
4733 		retval = sctp_setsockopt_reconfig_supported(sk, kopt, optlen);
4734 		break;
4735 	case SCTP_ENABLE_STREAM_RESET:
4736 		retval = sctp_setsockopt_enable_strreset(sk, kopt, optlen);
4737 		break;
4738 	case SCTP_RESET_STREAMS:
4739 		retval = sctp_setsockopt_reset_streams(sk, kopt, optlen);
4740 		break;
4741 	case SCTP_RESET_ASSOC:
4742 		retval = sctp_setsockopt_reset_assoc(sk, kopt, optlen);
4743 		break;
4744 	case SCTP_ADD_STREAMS:
4745 		retval = sctp_setsockopt_add_streams(sk, kopt, optlen);
4746 		break;
4747 	case SCTP_STREAM_SCHEDULER:
4748 		retval = sctp_setsockopt_scheduler(sk, kopt, optlen);
4749 		break;
4750 	case SCTP_STREAM_SCHEDULER_VALUE:
4751 		retval = sctp_setsockopt_scheduler_value(sk, kopt, optlen);
4752 		break;
4753 	case SCTP_INTERLEAVING_SUPPORTED:
4754 		retval = sctp_setsockopt_interleaving_supported(sk, kopt,
4755 								optlen);
4756 		break;
4757 	case SCTP_REUSE_PORT:
4758 		retval = sctp_setsockopt_reuse_port(sk, kopt, optlen);
4759 		break;
4760 	case SCTP_EVENT:
4761 		retval = sctp_setsockopt_event(sk, kopt, optlen);
4762 		break;
4763 	case SCTP_ASCONF_SUPPORTED:
4764 		retval = sctp_setsockopt_asconf_supported(sk, kopt, optlen);
4765 		break;
4766 	case SCTP_AUTH_SUPPORTED:
4767 		retval = sctp_setsockopt_auth_supported(sk, kopt, optlen);
4768 		break;
4769 	case SCTP_ECN_SUPPORTED:
4770 		retval = sctp_setsockopt_ecn_supported(sk, kopt, optlen);
4771 		break;
4772 	case SCTP_EXPOSE_POTENTIALLY_FAILED_STATE:
4773 		retval = sctp_setsockopt_pf_expose(sk, kopt, optlen);
4774 		break;
4775 	case SCTP_REMOTE_UDP_ENCAPS_PORT:
4776 		retval = sctp_setsockopt_encap_port(sk, kopt, optlen);
4777 		break;
4778 	case SCTP_PLPMTUD_PROBE_INTERVAL:
4779 		retval = sctp_setsockopt_probe_interval(sk, kopt, optlen);
4780 		break;
4781 	default:
4782 		retval = -ENOPROTOOPT;
4783 		break;
4784 	}
4785 
4786 	release_sock(sk);
4787 	kfree(kopt);
4788 	return retval;
4789 }
4790 
4791 /* API 3.1.6 connect() - UDP Style Syntax
4792  *
4793  * An application may use the connect() call in the UDP model to initiate an
4794  * association without sending data.
4795  *
4796  * The syntax is:
4797  *
4798  * ret = connect(int sd, const struct sockaddr *nam, socklen_t len);
4799  *
4800  * sd: the socket descriptor to have a new association added to.
4801  *
4802  * nam: the address structure (either struct sockaddr_in or struct
4803  *    sockaddr_in6 defined in RFC2553 [7]).
4804  *
4805  * len: the size of the address.
4806  */
sctp_connect(struct sock * sk,struct sockaddr * addr,int addr_len,int flags)4807 static int sctp_connect(struct sock *sk, struct sockaddr *addr,
4808 			int addr_len, int flags)
4809 {
4810 	struct sctp_af *af;
4811 	int err = -EINVAL;
4812 
4813 	lock_sock(sk);
4814 	pr_debug("%s: sk:%p, sockaddr:%p, addr_len:%d\n", __func__, sk,
4815 		 addr, addr_len);
4816 
4817 	/* Validate addr_len before calling common connect/connectx routine. */
4818 	af = sctp_get_af_specific(addr->sa_family);
4819 	if (af && addr_len >= af->sockaddr_len)
4820 		err = __sctp_connect(sk, addr, af->sockaddr_len, flags, NULL);
4821 
4822 	release_sock(sk);
4823 	return err;
4824 }
4825 
sctp_inet_connect(struct socket * sock,struct sockaddr * uaddr,int addr_len,int flags)4826 int sctp_inet_connect(struct socket *sock, struct sockaddr *uaddr,
4827 		      int addr_len, int flags)
4828 {
4829 	if (addr_len < sizeof(uaddr->sa_family))
4830 		return -EINVAL;
4831 
4832 	if (uaddr->sa_family == AF_UNSPEC)
4833 		return -EOPNOTSUPP;
4834 
4835 	return sctp_connect(sock->sk, uaddr, addr_len, flags);
4836 }
4837 
4838 /* Only called when shutdown a listening SCTP socket. */
sctp_disconnect(struct sock * sk,int flags)4839 static int sctp_disconnect(struct sock *sk, int flags)
4840 {
4841 	if (!sctp_style(sk, TCP))
4842 		return -EOPNOTSUPP;
4843 
4844 	sk->sk_shutdown |= RCV_SHUTDOWN;
4845 	return 0;
4846 }
4847 
4848 /* 4.1.4 accept() - TCP Style Syntax
4849  *
4850  * Applications use accept() call to remove an established SCTP
4851  * association from the accept queue of the endpoint.  A new socket
4852  * descriptor will be returned from accept() to represent the newly
4853  * formed association.
4854  */
sctp_accept(struct sock * sk,struct proto_accept_arg * arg)4855 static struct sock *sctp_accept(struct sock *sk, struct proto_accept_arg *arg)
4856 {
4857 	struct sctp_sock *sp;
4858 	struct sctp_endpoint *ep;
4859 	struct sock *newsk = NULL;
4860 	struct sctp_association *asoc;
4861 	long timeo;
4862 	int error = 0;
4863 
4864 	lock_sock(sk);
4865 
4866 	sp = sctp_sk(sk);
4867 	ep = sp->ep;
4868 
4869 	if (!sctp_style(sk, TCP)) {
4870 		error = -EOPNOTSUPP;
4871 		goto out;
4872 	}
4873 
4874 	if (!sctp_sstate(sk, LISTENING) ||
4875 	    (sk->sk_shutdown & RCV_SHUTDOWN)) {
4876 		error = -EINVAL;
4877 		goto out;
4878 	}
4879 
4880 	timeo = sock_rcvtimeo(sk, arg->flags & O_NONBLOCK);
4881 
4882 	error = sctp_wait_for_accept(sk, timeo);
4883 	if (error)
4884 		goto out;
4885 
4886 	/* We treat the list of associations on the endpoint as the accept
4887 	 * queue and pick the first association on the list.
4888 	 */
4889 	asoc = list_entry(ep->asocs.next, struct sctp_association, asocs);
4890 
4891 	newsk = sp->pf->create_accept_sk(sk, asoc, arg->kern);
4892 	if (!newsk) {
4893 		error = -ENOMEM;
4894 		goto out;
4895 	}
4896 
4897 	/* Populate the fields of the newsk from the oldsk and migrate the
4898 	 * asoc to the newsk.
4899 	 */
4900 	error = sctp_sock_migrate(sk, newsk, asoc, SCTP_SOCKET_TCP);
4901 	if (error) {
4902 		sk_common_release(newsk);
4903 		newsk = NULL;
4904 	}
4905 
4906 out:
4907 	release_sock(sk);
4908 	arg->err = error;
4909 	return newsk;
4910 }
4911 
4912 /* The SCTP ioctl handler. */
sctp_ioctl(struct sock * sk,int cmd,int * karg)4913 static int sctp_ioctl(struct sock *sk, int cmd, int *karg)
4914 {
4915 	int rc = -ENOTCONN;
4916 
4917 	lock_sock(sk);
4918 
4919 	/*
4920 	 * SEQPACKET-style sockets in LISTENING state are valid, for
4921 	 * SCTP, so only discard TCP-style sockets in LISTENING state.
4922 	 */
4923 	if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING))
4924 		goto out;
4925 
4926 	switch (cmd) {
4927 	case SIOCINQ: {
4928 		struct sk_buff *skb;
4929 		*karg = 0;
4930 
4931 		skb = skb_peek(&sk->sk_receive_queue);
4932 		if (skb != NULL) {
4933 			/*
4934 			 * We will only return the amount of this packet since
4935 			 * that is all that will be read.
4936 			 */
4937 			*karg = skb->len;
4938 		}
4939 		rc = 0;
4940 		break;
4941 	}
4942 	default:
4943 		rc = -ENOIOCTLCMD;
4944 		break;
4945 	}
4946 out:
4947 	release_sock(sk);
4948 	return rc;
4949 }
4950 
4951 /* This is the function which gets called during socket creation to
4952  * initialized the SCTP-specific portion of the sock.
4953  * The sock structure should already be zero-filled memory.
4954  */
sctp_init_sock(struct sock * sk)4955 static int sctp_init_sock(struct sock *sk)
4956 {
4957 	struct net *net = sock_net(sk);
4958 	struct sctp_sock *sp;
4959 
4960 	pr_debug("%s: sk:%p\n", __func__, sk);
4961 
4962 	sp = sctp_sk(sk);
4963 
4964 	/* Initialize the SCTP per socket area.  */
4965 	switch (sk->sk_type) {
4966 	case SOCK_SEQPACKET:
4967 		sp->type = SCTP_SOCKET_UDP;
4968 		break;
4969 	case SOCK_STREAM:
4970 		sp->type = SCTP_SOCKET_TCP;
4971 		break;
4972 	default:
4973 		return -ESOCKTNOSUPPORT;
4974 	}
4975 
4976 	sk->sk_gso_type = SKB_GSO_SCTP;
4977 
4978 	/* Initialize default send parameters. These parameters can be
4979 	 * modified with the SCTP_DEFAULT_SEND_PARAM socket option.
4980 	 */
4981 	sp->default_stream = 0;
4982 	sp->default_ppid = 0;
4983 	sp->default_flags = 0;
4984 	sp->default_context = 0;
4985 	sp->default_timetolive = 0;
4986 
4987 	sp->default_rcv_context = 0;
4988 	sp->max_burst = net->sctp.max_burst;
4989 
4990 	sp->sctp_hmac_alg = net->sctp.sctp_hmac_alg;
4991 
4992 	/* Initialize default setup parameters. These parameters
4993 	 * can be modified with the SCTP_INITMSG socket option or
4994 	 * overridden by the SCTP_INIT CMSG.
4995 	 */
4996 	sp->initmsg.sinit_num_ostreams   = sctp_max_outstreams;
4997 	sp->initmsg.sinit_max_instreams  = sctp_max_instreams;
4998 	sp->initmsg.sinit_max_attempts   = net->sctp.max_retrans_init;
4999 	sp->initmsg.sinit_max_init_timeo = net->sctp.rto_max;
5000 
5001 	/* Initialize default RTO related parameters.  These parameters can
5002 	 * be modified for with the SCTP_RTOINFO socket option.
5003 	 */
5004 	sp->rtoinfo.srto_initial = net->sctp.rto_initial;
5005 	sp->rtoinfo.srto_max     = net->sctp.rto_max;
5006 	sp->rtoinfo.srto_min     = net->sctp.rto_min;
5007 
5008 	/* Initialize default association related parameters. These parameters
5009 	 * can be modified with the SCTP_ASSOCINFO socket option.
5010 	 */
5011 	sp->assocparams.sasoc_asocmaxrxt = net->sctp.max_retrans_association;
5012 	sp->assocparams.sasoc_number_peer_destinations = 0;
5013 	sp->assocparams.sasoc_peer_rwnd = 0;
5014 	sp->assocparams.sasoc_local_rwnd = 0;
5015 	sp->assocparams.sasoc_cookie_life = net->sctp.valid_cookie_life;
5016 
5017 	/* Initialize default event subscriptions. By default, all the
5018 	 * options are off.
5019 	 */
5020 	sp->subscribe = 0;
5021 
5022 	/* Default Peer Address Parameters.  These defaults can
5023 	 * be modified via SCTP_PEER_ADDR_PARAMS
5024 	 */
5025 	sp->hbinterval  = net->sctp.hb_interval;
5026 	sp->udp_port    = htons(net->sctp.udp_port);
5027 	sp->encap_port  = htons(net->sctp.encap_port);
5028 	sp->pathmaxrxt  = net->sctp.max_retrans_path;
5029 	sp->pf_retrans  = net->sctp.pf_retrans;
5030 	sp->ps_retrans  = net->sctp.ps_retrans;
5031 	sp->pf_expose   = net->sctp.pf_expose;
5032 	sp->pathmtu     = 0; /* allow default discovery */
5033 	sp->sackdelay   = net->sctp.sack_timeout;
5034 	sp->sackfreq	= 2;
5035 	sp->param_flags = SPP_HB_ENABLE |
5036 			  SPP_PMTUD_ENABLE |
5037 			  SPP_SACKDELAY_ENABLE;
5038 	sp->default_ss = SCTP_SS_DEFAULT;
5039 
5040 	/* If enabled no SCTP message fragmentation will be performed.
5041 	 * Configure through SCTP_DISABLE_FRAGMENTS socket option.
5042 	 */
5043 	sp->disable_fragments = 0;
5044 
5045 	/* Enable Nagle algorithm by default.  */
5046 	sp->nodelay           = 0;
5047 
5048 	sp->recvrcvinfo = 0;
5049 	sp->recvnxtinfo = 0;
5050 
5051 	/* Enable by default. */
5052 	sp->v4mapped          = 1;
5053 
5054 	/* Auto-close idle associations after the configured
5055 	 * number of seconds.  A value of 0 disables this
5056 	 * feature.  Configure through the SCTP_AUTOCLOSE socket option,
5057 	 * for UDP-style sockets only.
5058 	 */
5059 	sp->autoclose         = 0;
5060 
5061 	/* User specified fragmentation limit. */
5062 	sp->user_frag         = 0;
5063 
5064 	sp->adaptation_ind = 0;
5065 
5066 	sp->pf = sctp_get_pf_specific(sk->sk_family);
5067 
5068 	/* Control variables for partial data delivery. */
5069 	atomic_set(&sp->pd_mode, 0);
5070 	skb_queue_head_init(&sp->pd_lobby);
5071 	sp->frag_interleave = 0;
5072 	sp->probe_interval = net->sctp.probe_interval;
5073 
5074 	/* Create a per socket endpoint structure.  Even if we
5075 	 * change the data structure relationships, this may still
5076 	 * be useful for storing pre-connect address information.
5077 	 */
5078 	sp->ep = sctp_endpoint_new(sk, GFP_KERNEL);
5079 	if (!sp->ep)
5080 		return -ENOMEM;
5081 
5082 	sp->hmac = NULL;
5083 
5084 	sk->sk_destruct = sctp_destruct_sock;
5085 
5086 	SCTP_DBG_OBJCNT_INC(sock);
5087 
5088 	sk_sockets_allocated_inc(sk);
5089 	sock_prot_inuse_add(net, sk->sk_prot, 1);
5090 
5091 	return 0;
5092 }
5093 
5094 /* Cleanup any SCTP per socket resources. Must be called with
5095  * sock_net(sk)->sctp.addr_wq_lock held if sp->do_auto_asconf is true
5096  */
sctp_destroy_sock(struct sock * sk)5097 static void sctp_destroy_sock(struct sock *sk)
5098 {
5099 	struct sctp_sock *sp;
5100 
5101 	pr_debug("%s: sk:%p\n", __func__, sk);
5102 
5103 	/* Release our hold on the endpoint. */
5104 	sp = sctp_sk(sk);
5105 	/* This could happen during socket init, thus we bail out
5106 	 * early, since the rest of the below is not setup either.
5107 	 */
5108 	if (sp->ep == NULL)
5109 		return;
5110 
5111 	if (sp->do_auto_asconf) {
5112 		sp->do_auto_asconf = 0;
5113 		list_del(&sp->auto_asconf_list);
5114 	}
5115 	sctp_endpoint_free(sp->ep);
5116 	sk_sockets_allocated_dec(sk);
5117 	sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
5118 }
5119 
5120 /* Triggered when there are no references on the socket anymore */
sctp_destruct_common(struct sock * sk)5121 static void sctp_destruct_common(struct sock *sk)
5122 {
5123 	struct sctp_sock *sp = sctp_sk(sk);
5124 
5125 	/* Free up the HMAC transform. */
5126 	crypto_free_shash(sp->hmac);
5127 }
5128 
sctp_destruct_sock(struct sock * sk)5129 static void sctp_destruct_sock(struct sock *sk)
5130 {
5131 	sctp_destruct_common(sk);
5132 	inet_sock_destruct(sk);
5133 }
5134 
5135 /* API 4.1.7 shutdown() - TCP Style Syntax
5136  *     int shutdown(int socket, int how);
5137  *
5138  *     sd      - the socket descriptor of the association to be closed.
5139  *     how     - Specifies the type of shutdown.  The  values  are
5140  *               as follows:
5141  *               SHUT_RD
5142  *                     Disables further receive operations. No SCTP
5143  *                     protocol action is taken.
5144  *               SHUT_WR
5145  *                     Disables further send operations, and initiates
5146  *                     the SCTP shutdown sequence.
5147  *               SHUT_RDWR
5148  *                     Disables further send  and  receive  operations
5149  *                     and initiates the SCTP shutdown sequence.
5150  */
sctp_shutdown(struct sock * sk,int how)5151 static void sctp_shutdown(struct sock *sk, int how)
5152 {
5153 	struct net *net = sock_net(sk);
5154 	struct sctp_endpoint *ep;
5155 
5156 	if (!sctp_style(sk, TCP))
5157 		return;
5158 
5159 	ep = sctp_sk(sk)->ep;
5160 	if (how & SEND_SHUTDOWN && !list_empty(&ep->asocs)) {
5161 		struct sctp_association *asoc;
5162 
5163 		inet_sk_set_state(sk, SCTP_SS_CLOSING);
5164 		asoc = list_entry(ep->asocs.next,
5165 				  struct sctp_association, asocs);
5166 		sctp_primitive_SHUTDOWN(net, asoc, NULL);
5167 	}
5168 }
5169 
sctp_get_sctp_info(struct sock * sk,struct sctp_association * asoc,struct sctp_info * info)5170 int sctp_get_sctp_info(struct sock *sk, struct sctp_association *asoc,
5171 		       struct sctp_info *info)
5172 {
5173 	struct sctp_transport *prim;
5174 	struct list_head *pos;
5175 	int mask;
5176 
5177 	memset(info, 0, sizeof(*info));
5178 	if (!asoc) {
5179 		struct sctp_sock *sp = sctp_sk(sk);
5180 
5181 		info->sctpi_s_autoclose = sp->autoclose;
5182 		info->sctpi_s_adaptation_ind = sp->adaptation_ind;
5183 		info->sctpi_s_pd_point = sp->pd_point;
5184 		info->sctpi_s_nodelay = sp->nodelay;
5185 		info->sctpi_s_disable_fragments = sp->disable_fragments;
5186 		info->sctpi_s_v4mapped = sp->v4mapped;
5187 		info->sctpi_s_frag_interleave = sp->frag_interleave;
5188 		info->sctpi_s_type = sp->type;
5189 
5190 		return 0;
5191 	}
5192 
5193 	info->sctpi_tag = asoc->c.my_vtag;
5194 	info->sctpi_state = asoc->state;
5195 	info->sctpi_rwnd = asoc->a_rwnd;
5196 	info->sctpi_unackdata = asoc->unack_data;
5197 	info->sctpi_penddata = sctp_tsnmap_pending(&asoc->peer.tsn_map);
5198 	info->sctpi_instrms = asoc->stream.incnt;
5199 	info->sctpi_outstrms = asoc->stream.outcnt;
5200 	list_for_each(pos, &asoc->base.inqueue.in_chunk_list)
5201 		info->sctpi_inqueue++;
5202 	list_for_each(pos, &asoc->outqueue.out_chunk_list)
5203 		info->sctpi_outqueue++;
5204 	info->sctpi_overall_error = asoc->overall_error_count;
5205 	info->sctpi_max_burst = asoc->max_burst;
5206 	info->sctpi_maxseg = asoc->frag_point;
5207 	info->sctpi_peer_rwnd = asoc->peer.rwnd;
5208 	info->sctpi_peer_tag = asoc->c.peer_vtag;
5209 
5210 	mask = asoc->peer.intl_capable << 1;
5211 	mask = (mask | asoc->peer.ecn_capable) << 1;
5212 	mask = (mask | asoc->peer.ipv4_address) << 1;
5213 	mask = (mask | asoc->peer.ipv6_address) << 1;
5214 	mask = (mask | asoc->peer.reconf_capable) << 1;
5215 	mask = (mask | asoc->peer.asconf_capable) << 1;
5216 	mask = (mask | asoc->peer.prsctp_capable) << 1;
5217 	mask = (mask | asoc->peer.auth_capable);
5218 	info->sctpi_peer_capable = mask;
5219 	mask = asoc->peer.sack_needed << 1;
5220 	mask = (mask | asoc->peer.sack_generation) << 1;
5221 	mask = (mask | asoc->peer.zero_window_announced);
5222 	info->sctpi_peer_sack = mask;
5223 
5224 	info->sctpi_isacks = asoc->stats.isacks;
5225 	info->sctpi_osacks = asoc->stats.osacks;
5226 	info->sctpi_opackets = asoc->stats.opackets;
5227 	info->sctpi_ipackets = asoc->stats.ipackets;
5228 	info->sctpi_rtxchunks = asoc->stats.rtxchunks;
5229 	info->sctpi_outofseqtsns = asoc->stats.outofseqtsns;
5230 	info->sctpi_idupchunks = asoc->stats.idupchunks;
5231 	info->sctpi_gapcnt = asoc->stats.gapcnt;
5232 	info->sctpi_ouodchunks = asoc->stats.ouodchunks;
5233 	info->sctpi_iuodchunks = asoc->stats.iuodchunks;
5234 	info->sctpi_oodchunks = asoc->stats.oodchunks;
5235 	info->sctpi_iodchunks = asoc->stats.iodchunks;
5236 	info->sctpi_octrlchunks = asoc->stats.octrlchunks;
5237 	info->sctpi_ictrlchunks = asoc->stats.ictrlchunks;
5238 
5239 	prim = asoc->peer.primary_path;
5240 	memcpy(&info->sctpi_p_address, &prim->ipaddr, sizeof(prim->ipaddr));
5241 	info->sctpi_p_state = prim->state;
5242 	info->sctpi_p_cwnd = prim->cwnd;
5243 	info->sctpi_p_srtt = prim->srtt;
5244 	info->sctpi_p_rto = jiffies_to_msecs(prim->rto);
5245 	info->sctpi_p_hbinterval = prim->hbinterval;
5246 	info->sctpi_p_pathmaxrxt = prim->pathmaxrxt;
5247 	info->sctpi_p_sackdelay = jiffies_to_msecs(prim->sackdelay);
5248 	info->sctpi_p_ssthresh = prim->ssthresh;
5249 	info->sctpi_p_partial_bytes_acked = prim->partial_bytes_acked;
5250 	info->sctpi_p_flight_size = prim->flight_size;
5251 	info->sctpi_p_error = prim->error_count;
5252 
5253 	return 0;
5254 }
5255 EXPORT_SYMBOL_GPL(sctp_get_sctp_info);
5256 
5257 /* use callback to avoid exporting the core structure */
sctp_transport_walk_start(struct rhashtable_iter * iter)5258 void sctp_transport_walk_start(struct rhashtable_iter *iter) __acquires(RCU)
5259 {
5260 	rhltable_walk_enter(&sctp_transport_hashtable, iter);
5261 
5262 	rhashtable_walk_start(iter);
5263 }
5264 
sctp_transport_walk_stop(struct rhashtable_iter * iter)5265 void sctp_transport_walk_stop(struct rhashtable_iter *iter) __releases(RCU)
5266 {
5267 	rhashtable_walk_stop(iter);
5268 	rhashtable_walk_exit(iter);
5269 }
5270 
sctp_transport_get_next(struct net * net,struct rhashtable_iter * iter)5271 struct sctp_transport *sctp_transport_get_next(struct net *net,
5272 					       struct rhashtable_iter *iter)
5273 {
5274 	struct sctp_transport *t;
5275 
5276 	t = rhashtable_walk_next(iter);
5277 	for (; t; t = rhashtable_walk_next(iter)) {
5278 		if (IS_ERR(t)) {
5279 			if (PTR_ERR(t) == -EAGAIN)
5280 				continue;
5281 			break;
5282 		}
5283 
5284 		if (!sctp_transport_hold(t))
5285 			continue;
5286 
5287 		if (net_eq(t->asoc->base.net, net) &&
5288 		    t->asoc->peer.primary_path == t)
5289 			break;
5290 
5291 		sctp_transport_put(t);
5292 	}
5293 
5294 	return t;
5295 }
5296 
sctp_transport_get_idx(struct net * net,struct rhashtable_iter * iter,int pos)5297 struct sctp_transport *sctp_transport_get_idx(struct net *net,
5298 					      struct rhashtable_iter *iter,
5299 					      int pos)
5300 {
5301 	struct sctp_transport *t;
5302 
5303 	if (!pos)
5304 		return SEQ_START_TOKEN;
5305 
5306 	while ((t = sctp_transport_get_next(net, iter)) && !IS_ERR(t)) {
5307 		if (!--pos)
5308 			break;
5309 		sctp_transport_put(t);
5310 	}
5311 
5312 	return t;
5313 }
5314 
sctp_for_each_endpoint(int (* cb)(struct sctp_endpoint *,void *),void * p)5315 int sctp_for_each_endpoint(int (*cb)(struct sctp_endpoint *, void *),
5316 			   void *p) {
5317 	int err = 0;
5318 	int hash = 0;
5319 	struct sctp_endpoint *ep;
5320 	struct sctp_hashbucket *head;
5321 
5322 	for (head = sctp_ep_hashtable; hash < sctp_ep_hashsize;
5323 	     hash++, head++) {
5324 		read_lock_bh(&head->lock);
5325 		sctp_for_each_hentry(ep, &head->chain) {
5326 			err = cb(ep, p);
5327 			if (err)
5328 				break;
5329 		}
5330 		read_unlock_bh(&head->lock);
5331 	}
5332 
5333 	return err;
5334 }
5335 EXPORT_SYMBOL_GPL(sctp_for_each_endpoint);
5336 
sctp_transport_lookup_process(sctp_callback_t cb,struct net * net,const union sctp_addr * laddr,const union sctp_addr * paddr,void * p,int dif)5337 int sctp_transport_lookup_process(sctp_callback_t cb, struct net *net,
5338 				  const union sctp_addr *laddr,
5339 				  const union sctp_addr *paddr, void *p, int dif)
5340 {
5341 	struct sctp_transport *transport;
5342 	struct sctp_endpoint *ep;
5343 	int err = -ENOENT;
5344 
5345 	rcu_read_lock();
5346 	transport = sctp_addrs_lookup_transport(net, laddr, paddr, dif, dif);
5347 	if (!transport) {
5348 		rcu_read_unlock();
5349 		return err;
5350 	}
5351 	ep = transport->asoc->ep;
5352 	if (!sctp_endpoint_hold(ep)) { /* asoc can be peeled off */
5353 		sctp_transport_put(transport);
5354 		rcu_read_unlock();
5355 		return err;
5356 	}
5357 	rcu_read_unlock();
5358 
5359 	err = cb(ep, transport, p);
5360 	sctp_endpoint_put(ep);
5361 	sctp_transport_put(transport);
5362 	return err;
5363 }
5364 EXPORT_SYMBOL_GPL(sctp_transport_lookup_process);
5365 
sctp_transport_traverse_process(sctp_callback_t cb,sctp_callback_t cb_done,struct net * net,int * pos,void * p)5366 int sctp_transport_traverse_process(sctp_callback_t cb, sctp_callback_t cb_done,
5367 				    struct net *net, int *pos, void *p)
5368 {
5369 	struct rhashtable_iter hti;
5370 	struct sctp_transport *tsp;
5371 	struct sctp_endpoint *ep;
5372 	int ret;
5373 
5374 again:
5375 	ret = 0;
5376 	sctp_transport_walk_start(&hti);
5377 
5378 	tsp = sctp_transport_get_idx(net, &hti, *pos + 1);
5379 	for (; !IS_ERR_OR_NULL(tsp); tsp = sctp_transport_get_next(net, &hti)) {
5380 		ep = tsp->asoc->ep;
5381 		if (sctp_endpoint_hold(ep)) { /* asoc can be peeled off */
5382 			ret = cb(ep, tsp, p);
5383 			if (ret)
5384 				break;
5385 			sctp_endpoint_put(ep);
5386 		}
5387 		(*pos)++;
5388 		sctp_transport_put(tsp);
5389 	}
5390 	sctp_transport_walk_stop(&hti);
5391 
5392 	if (ret) {
5393 		if (cb_done && !cb_done(ep, tsp, p)) {
5394 			(*pos)++;
5395 			sctp_endpoint_put(ep);
5396 			sctp_transport_put(tsp);
5397 			goto again;
5398 		}
5399 		sctp_endpoint_put(ep);
5400 		sctp_transport_put(tsp);
5401 	}
5402 
5403 	return ret;
5404 }
5405 EXPORT_SYMBOL_GPL(sctp_transport_traverse_process);
5406 
5407 /* 7.2.1 Association Status (SCTP_STATUS)
5408 
5409  * Applications can retrieve current status information about an
5410  * association, including association state, peer receiver window size,
5411  * number of unacked data chunks, and number of data chunks pending
5412  * receipt.  This information is read-only.
5413  */
sctp_getsockopt_sctp_status(struct sock * sk,int len,char __user * optval,int __user * optlen)5414 static int sctp_getsockopt_sctp_status(struct sock *sk, int len,
5415 				       char __user *optval,
5416 				       int __user *optlen)
5417 {
5418 	struct sctp_status status;
5419 	struct sctp_association *asoc = NULL;
5420 	struct sctp_transport *transport;
5421 	sctp_assoc_t associd;
5422 	int retval = 0;
5423 
5424 	if (len < sizeof(status)) {
5425 		retval = -EINVAL;
5426 		goto out;
5427 	}
5428 
5429 	len = sizeof(status);
5430 	if (copy_from_user(&status, optval, len)) {
5431 		retval = -EFAULT;
5432 		goto out;
5433 	}
5434 
5435 	associd = status.sstat_assoc_id;
5436 	asoc = sctp_id2assoc(sk, associd);
5437 	if (!asoc) {
5438 		retval = -EINVAL;
5439 		goto out;
5440 	}
5441 
5442 	transport = asoc->peer.primary_path;
5443 
5444 	status.sstat_assoc_id = sctp_assoc2id(asoc);
5445 	status.sstat_state = sctp_assoc_to_state(asoc);
5446 	status.sstat_rwnd =  asoc->peer.rwnd;
5447 	status.sstat_unackdata = asoc->unack_data;
5448 
5449 	status.sstat_penddata = sctp_tsnmap_pending(&asoc->peer.tsn_map);
5450 	status.sstat_instrms = asoc->stream.incnt;
5451 	status.sstat_outstrms = asoc->stream.outcnt;
5452 	status.sstat_fragmentation_point = asoc->frag_point;
5453 	status.sstat_primary.spinfo_assoc_id = sctp_assoc2id(transport->asoc);
5454 	memcpy(&status.sstat_primary.spinfo_address, &transport->ipaddr,
5455 			transport->af_specific->sockaddr_len);
5456 	/* Map ipv4 address into v4-mapped-on-v6 address.  */
5457 	sctp_get_pf_specific(sk->sk_family)->addr_to_user(sctp_sk(sk),
5458 		(union sctp_addr *)&status.sstat_primary.spinfo_address);
5459 	status.sstat_primary.spinfo_state = transport->state;
5460 	status.sstat_primary.spinfo_cwnd = transport->cwnd;
5461 	status.sstat_primary.spinfo_srtt = transport->srtt;
5462 	status.sstat_primary.spinfo_rto = jiffies_to_msecs(transport->rto);
5463 	status.sstat_primary.spinfo_mtu = transport->pathmtu;
5464 
5465 	if (status.sstat_primary.spinfo_state == SCTP_UNKNOWN)
5466 		status.sstat_primary.spinfo_state = SCTP_ACTIVE;
5467 
5468 	if (put_user(len, optlen)) {
5469 		retval = -EFAULT;
5470 		goto out;
5471 	}
5472 
5473 	pr_debug("%s: len:%d, state:%d, rwnd:%d, assoc_id:%d\n",
5474 		 __func__, len, status.sstat_state, status.sstat_rwnd,
5475 		 status.sstat_assoc_id);
5476 
5477 	if (copy_to_user(optval, &status, len)) {
5478 		retval = -EFAULT;
5479 		goto out;
5480 	}
5481 
5482 out:
5483 	return retval;
5484 }
5485 
5486 
5487 /* 7.2.2 Peer Address Information (SCTP_GET_PEER_ADDR_INFO)
5488  *
5489  * Applications can retrieve information about a specific peer address
5490  * of an association, including its reachability state, congestion
5491  * window, and retransmission timer values.  This information is
5492  * read-only.
5493  */
sctp_getsockopt_peer_addr_info(struct sock * sk,int len,char __user * optval,int __user * optlen)5494 static int sctp_getsockopt_peer_addr_info(struct sock *sk, int len,
5495 					  char __user *optval,
5496 					  int __user *optlen)
5497 {
5498 	struct sctp_paddrinfo pinfo;
5499 	struct sctp_transport *transport;
5500 	int retval = 0;
5501 
5502 	if (len < sizeof(pinfo)) {
5503 		retval = -EINVAL;
5504 		goto out;
5505 	}
5506 
5507 	len = sizeof(pinfo);
5508 	if (copy_from_user(&pinfo, optval, len)) {
5509 		retval = -EFAULT;
5510 		goto out;
5511 	}
5512 
5513 	transport = sctp_addr_id2transport(sk, &pinfo.spinfo_address,
5514 					   pinfo.spinfo_assoc_id);
5515 	if (!transport) {
5516 		retval = -EINVAL;
5517 		goto out;
5518 	}
5519 
5520 	if (transport->state == SCTP_PF &&
5521 	    transport->asoc->pf_expose == SCTP_PF_EXPOSE_DISABLE) {
5522 		retval = -EACCES;
5523 		goto out;
5524 	}
5525 
5526 	pinfo.spinfo_assoc_id = sctp_assoc2id(transport->asoc);
5527 	pinfo.spinfo_state = transport->state;
5528 	pinfo.spinfo_cwnd = transport->cwnd;
5529 	pinfo.spinfo_srtt = transport->srtt;
5530 	pinfo.spinfo_rto = jiffies_to_msecs(transport->rto);
5531 	pinfo.spinfo_mtu = transport->pathmtu;
5532 
5533 	if (pinfo.spinfo_state == SCTP_UNKNOWN)
5534 		pinfo.spinfo_state = SCTP_ACTIVE;
5535 
5536 	if (put_user(len, optlen)) {
5537 		retval = -EFAULT;
5538 		goto out;
5539 	}
5540 
5541 	if (copy_to_user(optval, &pinfo, len)) {
5542 		retval = -EFAULT;
5543 		goto out;
5544 	}
5545 
5546 out:
5547 	return retval;
5548 }
5549 
5550 /* 7.1.12 Enable/Disable message fragmentation (SCTP_DISABLE_FRAGMENTS)
5551  *
5552  * This option is a on/off flag.  If enabled no SCTP message
5553  * fragmentation will be performed.  Instead if a message being sent
5554  * exceeds the current PMTU size, the message will NOT be sent and
5555  * instead a error will be indicated to the user.
5556  */
sctp_getsockopt_disable_fragments(struct sock * sk,int len,char __user * optval,int __user * optlen)5557 static int sctp_getsockopt_disable_fragments(struct sock *sk, int len,
5558 					char __user *optval, int __user *optlen)
5559 {
5560 	int val;
5561 
5562 	if (len < sizeof(int))
5563 		return -EINVAL;
5564 
5565 	len = sizeof(int);
5566 	val = (sctp_sk(sk)->disable_fragments == 1);
5567 	if (put_user(len, optlen))
5568 		return -EFAULT;
5569 	if (copy_to_user(optval, &val, len))
5570 		return -EFAULT;
5571 	return 0;
5572 }
5573 
5574 /* 7.1.15 Set notification and ancillary events (SCTP_EVENTS)
5575  *
5576  * This socket option is used to specify various notifications and
5577  * ancillary data the user wishes to receive.
5578  */
sctp_getsockopt_events(struct sock * sk,int len,char __user * optval,int __user * optlen)5579 static int sctp_getsockopt_events(struct sock *sk, int len, char __user *optval,
5580 				  int __user *optlen)
5581 {
5582 	struct sctp_event_subscribe subscribe;
5583 	__u8 *sn_type = (__u8 *)&subscribe;
5584 	int i;
5585 
5586 	if (len == 0)
5587 		return -EINVAL;
5588 	if (len > sizeof(struct sctp_event_subscribe))
5589 		len = sizeof(struct sctp_event_subscribe);
5590 	if (put_user(len, optlen))
5591 		return -EFAULT;
5592 
5593 	for (i = 0; i < len; i++)
5594 		sn_type[i] = sctp_ulpevent_type_enabled(sctp_sk(sk)->subscribe,
5595 							SCTP_SN_TYPE_BASE + i);
5596 
5597 	if (copy_to_user(optval, &subscribe, len))
5598 		return -EFAULT;
5599 
5600 	return 0;
5601 }
5602 
5603 /* 7.1.8 Automatic Close of associations (SCTP_AUTOCLOSE)
5604  *
5605  * This socket option is applicable to the UDP-style socket only.  When
5606  * set it will cause associations that are idle for more than the
5607  * specified number of seconds to automatically close.  An association
5608  * being idle is defined an association that has NOT sent or received
5609  * user data.  The special value of '0' indicates that no automatic
5610  * close of any associations should be performed.  The option expects an
5611  * integer defining the number of seconds of idle time before an
5612  * association is closed.
5613  */
sctp_getsockopt_autoclose(struct sock * sk,int len,char __user * optval,int __user * optlen)5614 static int sctp_getsockopt_autoclose(struct sock *sk, int len, char __user *optval, int __user *optlen)
5615 {
5616 	/* Applicable to UDP-style socket only */
5617 	if (sctp_style(sk, TCP))
5618 		return -EOPNOTSUPP;
5619 	if (len < sizeof(int))
5620 		return -EINVAL;
5621 	len = sizeof(int);
5622 	if (put_user(len, optlen))
5623 		return -EFAULT;
5624 	if (put_user(sctp_sk(sk)->autoclose, (int __user *)optval))
5625 		return -EFAULT;
5626 	return 0;
5627 }
5628 
5629 /* Helper routine to branch off an association to a new socket.  */
sctp_do_peeloff(struct sock * sk,sctp_assoc_t id,struct socket ** sockp)5630 int sctp_do_peeloff(struct sock *sk, sctp_assoc_t id, struct socket **sockp)
5631 {
5632 	struct sctp_association *asoc = sctp_id2assoc(sk, id);
5633 	struct sctp_sock *sp = sctp_sk(sk);
5634 	struct socket *sock;
5635 	int err = 0;
5636 
5637 	/* Do not peel off from one netns to another one. */
5638 	if (!net_eq(current->nsproxy->net_ns, sock_net(sk)))
5639 		return -EINVAL;
5640 
5641 	if (!asoc)
5642 		return -EINVAL;
5643 
5644 	/* An association cannot be branched off from an already peeled-off
5645 	 * socket, nor is this supported for tcp style sockets.
5646 	 */
5647 	if (!sctp_style(sk, UDP))
5648 		return -EINVAL;
5649 
5650 	/* Create a new socket.  */
5651 	err = sock_create(sk->sk_family, SOCK_SEQPACKET, IPPROTO_SCTP, &sock);
5652 	if (err < 0)
5653 		return err;
5654 
5655 	sctp_copy_sock(sock->sk, sk, asoc);
5656 
5657 	/* Make peeled-off sockets more like 1-1 accepted sockets.
5658 	 * Set the daddr and initialize id to something more random and also
5659 	 * copy over any ip options.
5660 	 */
5661 	sp->pf->to_sk_daddr(&asoc->peer.primary_addr, sock->sk);
5662 	sp->pf->copy_ip_options(sk, sock->sk);
5663 
5664 	/* Populate the fields of the newsk from the oldsk and migrate the
5665 	 * asoc to the newsk.
5666 	 */
5667 	err = sctp_sock_migrate(sk, sock->sk, asoc,
5668 				SCTP_SOCKET_UDP_HIGH_BANDWIDTH);
5669 	if (err) {
5670 		sock_release(sock);
5671 		sock = NULL;
5672 	}
5673 
5674 	*sockp = sock;
5675 
5676 	return err;
5677 }
5678 EXPORT_SYMBOL(sctp_do_peeloff);
5679 
sctp_getsockopt_peeloff_common(struct sock * sk,sctp_peeloff_arg_t * peeloff,struct file ** newfile,unsigned flags)5680 static int sctp_getsockopt_peeloff_common(struct sock *sk, sctp_peeloff_arg_t *peeloff,
5681 					  struct file **newfile, unsigned flags)
5682 {
5683 	struct socket *newsock;
5684 	int retval;
5685 
5686 	retval = sctp_do_peeloff(sk, peeloff->associd, &newsock);
5687 	if (retval < 0)
5688 		goto out;
5689 
5690 	/* Map the socket to an unused fd that can be returned to the user.  */
5691 	retval = get_unused_fd_flags(flags & SOCK_CLOEXEC);
5692 	if (retval < 0) {
5693 		sock_release(newsock);
5694 		goto out;
5695 	}
5696 
5697 	*newfile = sock_alloc_file(newsock, 0, NULL);
5698 	if (IS_ERR(*newfile)) {
5699 		put_unused_fd(retval);
5700 		retval = PTR_ERR(*newfile);
5701 		*newfile = NULL;
5702 		return retval;
5703 	}
5704 
5705 	pr_debug("%s: sk:%p, newsk:%p, sd:%d\n", __func__, sk, newsock->sk,
5706 		 retval);
5707 
5708 	peeloff->sd = retval;
5709 
5710 	if (flags & SOCK_NONBLOCK)
5711 		(*newfile)->f_flags |= O_NONBLOCK;
5712 out:
5713 	return retval;
5714 }
5715 
sctp_getsockopt_peeloff(struct sock * sk,int len,char __user * optval,int __user * optlen)5716 static int sctp_getsockopt_peeloff(struct sock *sk, int len, char __user *optval, int __user *optlen)
5717 {
5718 	sctp_peeloff_arg_t peeloff;
5719 	struct file *newfile = NULL;
5720 	int retval = 0;
5721 
5722 	if (len < sizeof(sctp_peeloff_arg_t))
5723 		return -EINVAL;
5724 	len = sizeof(sctp_peeloff_arg_t);
5725 	if (copy_from_user(&peeloff, optval, len))
5726 		return -EFAULT;
5727 
5728 	retval = sctp_getsockopt_peeloff_common(sk, &peeloff, &newfile, 0);
5729 	if (retval < 0)
5730 		goto out;
5731 
5732 	/* Return the fd mapped to the new socket.  */
5733 	if (put_user(len, optlen)) {
5734 		fput(newfile);
5735 		put_unused_fd(retval);
5736 		return -EFAULT;
5737 	}
5738 
5739 	if (copy_to_user(optval, &peeloff, len)) {
5740 		fput(newfile);
5741 		put_unused_fd(retval);
5742 		return -EFAULT;
5743 	}
5744 	fd_install(retval, newfile);
5745 out:
5746 	return retval;
5747 }
5748 
sctp_getsockopt_peeloff_flags(struct sock * sk,int len,char __user * optval,int __user * optlen)5749 static int sctp_getsockopt_peeloff_flags(struct sock *sk, int len,
5750 					 char __user *optval, int __user *optlen)
5751 {
5752 	sctp_peeloff_flags_arg_t peeloff;
5753 	struct file *newfile = NULL;
5754 	int retval = 0;
5755 
5756 	if (len < sizeof(sctp_peeloff_flags_arg_t))
5757 		return -EINVAL;
5758 	len = sizeof(sctp_peeloff_flags_arg_t);
5759 	if (copy_from_user(&peeloff, optval, len))
5760 		return -EFAULT;
5761 
5762 	retval = sctp_getsockopt_peeloff_common(sk, &peeloff.p_arg,
5763 						&newfile, peeloff.flags);
5764 	if (retval < 0)
5765 		goto out;
5766 
5767 	/* Return the fd mapped to the new socket.  */
5768 	if (put_user(len, optlen)) {
5769 		fput(newfile);
5770 		put_unused_fd(retval);
5771 		return -EFAULT;
5772 	}
5773 
5774 	if (copy_to_user(optval, &peeloff, len)) {
5775 		fput(newfile);
5776 		put_unused_fd(retval);
5777 		return -EFAULT;
5778 	}
5779 	fd_install(retval, newfile);
5780 out:
5781 	return retval;
5782 }
5783 
5784 /* 7.1.13 Peer Address Parameters (SCTP_PEER_ADDR_PARAMS)
5785  *
5786  * Applications can enable or disable heartbeats for any peer address of
5787  * an association, modify an address's heartbeat interval, force a
5788  * heartbeat to be sent immediately, and adjust the address's maximum
5789  * number of retransmissions sent before an address is considered
5790  * unreachable.  The following structure is used to access and modify an
5791  * address's parameters:
5792  *
5793  *  struct sctp_paddrparams {
5794  *     sctp_assoc_t            spp_assoc_id;
5795  *     struct sockaddr_storage spp_address;
5796  *     uint32_t                spp_hbinterval;
5797  *     uint16_t                spp_pathmaxrxt;
5798  *     uint32_t                spp_pathmtu;
5799  *     uint32_t                spp_sackdelay;
5800  *     uint32_t                spp_flags;
5801  * };
5802  *
5803  *   spp_assoc_id    - (one-to-many style socket) This is filled in the
5804  *                     application, and identifies the association for
5805  *                     this query.
5806  *   spp_address     - This specifies which address is of interest.
5807  *   spp_hbinterval  - This contains the value of the heartbeat interval,
5808  *                     in milliseconds.  If a  value of zero
5809  *                     is present in this field then no changes are to
5810  *                     be made to this parameter.
5811  *   spp_pathmaxrxt  - This contains the maximum number of
5812  *                     retransmissions before this address shall be
5813  *                     considered unreachable. If a  value of zero
5814  *                     is present in this field then no changes are to
5815  *                     be made to this parameter.
5816  *   spp_pathmtu     - When Path MTU discovery is disabled the value
5817  *                     specified here will be the "fixed" path mtu.
5818  *                     Note that if the spp_address field is empty
5819  *                     then all associations on this address will
5820  *                     have this fixed path mtu set upon them.
5821  *
5822  *   spp_sackdelay   - When delayed sack is enabled, this value specifies
5823  *                     the number of milliseconds that sacks will be delayed
5824  *                     for. This value will apply to all addresses of an
5825  *                     association if the spp_address field is empty. Note
5826  *                     also, that if delayed sack is enabled and this
5827  *                     value is set to 0, no change is made to the last
5828  *                     recorded delayed sack timer value.
5829  *
5830  *   spp_flags       - These flags are used to control various features
5831  *                     on an association. The flag field may contain
5832  *                     zero or more of the following options.
5833  *
5834  *                     SPP_HB_ENABLE  - Enable heartbeats on the
5835  *                     specified address. Note that if the address
5836  *                     field is empty all addresses for the association
5837  *                     have heartbeats enabled upon them.
5838  *
5839  *                     SPP_HB_DISABLE - Disable heartbeats on the
5840  *                     speicifed address. Note that if the address
5841  *                     field is empty all addresses for the association
5842  *                     will have their heartbeats disabled. Note also
5843  *                     that SPP_HB_ENABLE and SPP_HB_DISABLE are
5844  *                     mutually exclusive, only one of these two should
5845  *                     be specified. Enabling both fields will have
5846  *                     undetermined results.
5847  *
5848  *                     SPP_HB_DEMAND - Request a user initiated heartbeat
5849  *                     to be made immediately.
5850  *
5851  *                     SPP_PMTUD_ENABLE - This field will enable PMTU
5852  *                     discovery upon the specified address. Note that
5853  *                     if the address feild is empty then all addresses
5854  *                     on the association are effected.
5855  *
5856  *                     SPP_PMTUD_DISABLE - This field will disable PMTU
5857  *                     discovery upon the specified address. Note that
5858  *                     if the address feild is empty then all addresses
5859  *                     on the association are effected. Not also that
5860  *                     SPP_PMTUD_ENABLE and SPP_PMTUD_DISABLE are mutually
5861  *                     exclusive. Enabling both will have undetermined
5862  *                     results.
5863  *
5864  *                     SPP_SACKDELAY_ENABLE - Setting this flag turns
5865  *                     on delayed sack. The time specified in spp_sackdelay
5866  *                     is used to specify the sack delay for this address. Note
5867  *                     that if spp_address is empty then all addresses will
5868  *                     enable delayed sack and take on the sack delay
5869  *                     value specified in spp_sackdelay.
5870  *                     SPP_SACKDELAY_DISABLE - Setting this flag turns
5871  *                     off delayed sack. If the spp_address field is blank then
5872  *                     delayed sack is disabled for the entire association. Note
5873  *                     also that this field is mutually exclusive to
5874  *                     SPP_SACKDELAY_ENABLE, setting both will have undefined
5875  *                     results.
5876  *
5877  *                     SPP_IPV6_FLOWLABEL:  Setting this flag enables the
5878  *                     setting of the IPV6 flow label value.  The value is
5879  *                     contained in the spp_ipv6_flowlabel field.
5880  *                     Upon retrieval, this flag will be set to indicate that
5881  *                     the spp_ipv6_flowlabel field has a valid value returned.
5882  *                     If a specific destination address is set (in the
5883  *                     spp_address field), then the value returned is that of
5884  *                     the address.  If just an association is specified (and
5885  *                     no address), then the association's default flow label
5886  *                     is returned.  If neither an association nor a destination
5887  *                     is specified, then the socket's default flow label is
5888  *                     returned.  For non-IPv6 sockets, this flag will be left
5889  *                     cleared.
5890  *
5891  *                     SPP_DSCP:  Setting this flag enables the setting of the
5892  *                     Differentiated Services Code Point (DSCP) value
5893  *                     associated with either the association or a specific
5894  *                     address.  The value is obtained in the spp_dscp field.
5895  *                     Upon retrieval, this flag will be set to indicate that
5896  *                     the spp_dscp field has a valid value returned.  If a
5897  *                     specific destination address is set when called (in the
5898  *                     spp_address field), then that specific destination
5899  *                     address's DSCP value is returned.  If just an association
5900  *                     is specified, then the association's default DSCP is
5901  *                     returned.  If neither an association nor a destination is
5902  *                     specified, then the socket's default DSCP is returned.
5903  *
5904  *   spp_ipv6_flowlabel
5905  *                   - This field is used in conjunction with the
5906  *                     SPP_IPV6_FLOWLABEL flag and contains the IPv6 flow label.
5907  *                     The 20 least significant bits are used for the flow
5908  *                     label.  This setting has precedence over any IPv6-layer
5909  *                     setting.
5910  *
5911  *   spp_dscp        - This field is used in conjunction with the SPP_DSCP flag
5912  *                     and contains the DSCP.  The 6 most significant bits are
5913  *                     used for the DSCP.  This setting has precedence over any
5914  *                     IPv4- or IPv6- layer setting.
5915  */
sctp_getsockopt_peer_addr_params(struct sock * sk,int len,char __user * optval,int __user * optlen)5916 static int sctp_getsockopt_peer_addr_params(struct sock *sk, int len,
5917 					    char __user *optval, int __user *optlen)
5918 {
5919 	struct sctp_paddrparams  params;
5920 	struct sctp_transport   *trans = NULL;
5921 	struct sctp_association *asoc = NULL;
5922 	struct sctp_sock        *sp = sctp_sk(sk);
5923 
5924 	if (len >= sizeof(params))
5925 		len = sizeof(params);
5926 	else if (len >= ALIGN(offsetof(struct sctp_paddrparams,
5927 				       spp_ipv6_flowlabel), 4))
5928 		len = ALIGN(offsetof(struct sctp_paddrparams,
5929 				     spp_ipv6_flowlabel), 4);
5930 	else
5931 		return -EINVAL;
5932 
5933 	if (copy_from_user(&params, optval, len))
5934 		return -EFAULT;
5935 
5936 	/* If an address other than INADDR_ANY is specified, and
5937 	 * no transport is found, then the request is invalid.
5938 	 */
5939 	if (!sctp_is_any(sk, (union sctp_addr *)&params.spp_address)) {
5940 		trans = sctp_addr_id2transport(sk, &params.spp_address,
5941 					       params.spp_assoc_id);
5942 		if (!trans) {
5943 			pr_debug("%s: failed no transport\n", __func__);
5944 			return -EINVAL;
5945 		}
5946 	}
5947 
5948 	/* Get association, if assoc_id != SCTP_FUTURE_ASSOC and the
5949 	 * socket is a one to many style socket, and an association
5950 	 * was not found, then the id was invalid.
5951 	 */
5952 	asoc = sctp_id2assoc(sk, params.spp_assoc_id);
5953 	if (!asoc && params.spp_assoc_id != SCTP_FUTURE_ASSOC &&
5954 	    sctp_style(sk, UDP)) {
5955 		pr_debug("%s: failed no association\n", __func__);
5956 		return -EINVAL;
5957 	}
5958 
5959 	if (trans) {
5960 		/* Fetch transport values. */
5961 		params.spp_hbinterval = jiffies_to_msecs(trans->hbinterval);
5962 		params.spp_pathmtu    = trans->pathmtu;
5963 		params.spp_pathmaxrxt = trans->pathmaxrxt;
5964 		params.spp_sackdelay  = jiffies_to_msecs(trans->sackdelay);
5965 
5966 		/*draft-11 doesn't say what to return in spp_flags*/
5967 		params.spp_flags      = trans->param_flags;
5968 		if (trans->flowlabel & SCTP_FLOWLABEL_SET_MASK) {
5969 			params.spp_ipv6_flowlabel = trans->flowlabel &
5970 						    SCTP_FLOWLABEL_VAL_MASK;
5971 			params.spp_flags |= SPP_IPV6_FLOWLABEL;
5972 		}
5973 		if (trans->dscp & SCTP_DSCP_SET_MASK) {
5974 			params.spp_dscp	= trans->dscp & SCTP_DSCP_VAL_MASK;
5975 			params.spp_flags |= SPP_DSCP;
5976 		}
5977 	} else if (asoc) {
5978 		/* Fetch association values. */
5979 		params.spp_hbinterval = jiffies_to_msecs(asoc->hbinterval);
5980 		params.spp_pathmtu    = asoc->pathmtu;
5981 		params.spp_pathmaxrxt = asoc->pathmaxrxt;
5982 		params.spp_sackdelay  = jiffies_to_msecs(asoc->sackdelay);
5983 
5984 		/*draft-11 doesn't say what to return in spp_flags*/
5985 		params.spp_flags      = asoc->param_flags;
5986 		if (asoc->flowlabel & SCTP_FLOWLABEL_SET_MASK) {
5987 			params.spp_ipv6_flowlabel = asoc->flowlabel &
5988 						    SCTP_FLOWLABEL_VAL_MASK;
5989 			params.spp_flags |= SPP_IPV6_FLOWLABEL;
5990 		}
5991 		if (asoc->dscp & SCTP_DSCP_SET_MASK) {
5992 			params.spp_dscp	= asoc->dscp & SCTP_DSCP_VAL_MASK;
5993 			params.spp_flags |= SPP_DSCP;
5994 		}
5995 	} else {
5996 		/* Fetch socket values. */
5997 		params.spp_hbinterval = sp->hbinterval;
5998 		params.spp_pathmtu    = sp->pathmtu;
5999 		params.spp_sackdelay  = sp->sackdelay;
6000 		params.spp_pathmaxrxt = sp->pathmaxrxt;
6001 
6002 		/*draft-11 doesn't say what to return in spp_flags*/
6003 		params.spp_flags      = sp->param_flags;
6004 		if (sp->flowlabel & SCTP_FLOWLABEL_SET_MASK) {
6005 			params.spp_ipv6_flowlabel = sp->flowlabel &
6006 						    SCTP_FLOWLABEL_VAL_MASK;
6007 			params.spp_flags |= SPP_IPV6_FLOWLABEL;
6008 		}
6009 		if (sp->dscp & SCTP_DSCP_SET_MASK) {
6010 			params.spp_dscp	= sp->dscp & SCTP_DSCP_VAL_MASK;
6011 			params.spp_flags |= SPP_DSCP;
6012 		}
6013 	}
6014 
6015 	if (copy_to_user(optval, &params, len))
6016 		return -EFAULT;
6017 
6018 	if (put_user(len, optlen))
6019 		return -EFAULT;
6020 
6021 	return 0;
6022 }
6023 
6024 /*
6025  * 7.1.23.  Get or set delayed ack timer (SCTP_DELAYED_SACK)
6026  *
6027  * This option will effect the way delayed acks are performed.  This
6028  * option allows you to get or set the delayed ack time, in
6029  * milliseconds.  It also allows changing the delayed ack frequency.
6030  * Changing the frequency to 1 disables the delayed sack algorithm.  If
6031  * the assoc_id is 0, then this sets or gets the endpoints default
6032  * values.  If the assoc_id field is non-zero, then the set or get
6033  * effects the specified association for the one to many model (the
6034  * assoc_id field is ignored by the one to one model).  Note that if
6035  * sack_delay or sack_freq are 0 when setting this option, then the
6036  * current values will remain unchanged.
6037  *
6038  * struct sctp_sack_info {
6039  *     sctp_assoc_t            sack_assoc_id;
6040  *     uint32_t                sack_delay;
6041  *     uint32_t                sack_freq;
6042  * };
6043  *
6044  * sack_assoc_id -  This parameter, indicates which association the user
6045  *    is performing an action upon.  Note that if this field's value is
6046  *    zero then the endpoints default value is changed (effecting future
6047  *    associations only).
6048  *
6049  * sack_delay -  This parameter contains the number of milliseconds that
6050  *    the user is requesting the delayed ACK timer be set to.  Note that
6051  *    this value is defined in the standard to be between 200 and 500
6052  *    milliseconds.
6053  *
6054  * sack_freq -  This parameter contains the number of packets that must
6055  *    be received before a sack is sent without waiting for the delay
6056  *    timer to expire.  The default value for this is 2, setting this
6057  *    value to 1 will disable the delayed sack algorithm.
6058  */
sctp_getsockopt_delayed_ack(struct sock * sk,int len,char __user * optval,int __user * optlen)6059 static int sctp_getsockopt_delayed_ack(struct sock *sk, int len,
6060 					    char __user *optval,
6061 					    int __user *optlen)
6062 {
6063 	struct sctp_sack_info    params;
6064 	struct sctp_association *asoc = NULL;
6065 	struct sctp_sock        *sp = sctp_sk(sk);
6066 
6067 	if (len >= sizeof(struct sctp_sack_info)) {
6068 		len = sizeof(struct sctp_sack_info);
6069 
6070 		if (copy_from_user(&params, optval, len))
6071 			return -EFAULT;
6072 	} else if (len == sizeof(struct sctp_assoc_value)) {
6073 		pr_warn_ratelimited(DEPRECATED
6074 				    "%s (pid %d) "
6075 				    "Use of struct sctp_assoc_value in delayed_ack socket option.\n"
6076 				    "Use struct sctp_sack_info instead\n",
6077 				    current->comm, task_pid_nr(current));
6078 		if (copy_from_user(&params, optval, len))
6079 			return -EFAULT;
6080 	} else
6081 		return -EINVAL;
6082 
6083 	/* Get association, if sack_assoc_id != SCTP_FUTURE_ASSOC and the
6084 	 * socket is a one to many style socket, and an association
6085 	 * was not found, then the id was invalid.
6086 	 */
6087 	asoc = sctp_id2assoc(sk, params.sack_assoc_id);
6088 	if (!asoc && params.sack_assoc_id != SCTP_FUTURE_ASSOC &&
6089 	    sctp_style(sk, UDP))
6090 		return -EINVAL;
6091 
6092 	if (asoc) {
6093 		/* Fetch association values. */
6094 		if (asoc->param_flags & SPP_SACKDELAY_ENABLE) {
6095 			params.sack_delay = jiffies_to_msecs(asoc->sackdelay);
6096 			params.sack_freq = asoc->sackfreq;
6097 
6098 		} else {
6099 			params.sack_delay = 0;
6100 			params.sack_freq = 1;
6101 		}
6102 	} else {
6103 		/* Fetch socket values. */
6104 		if (sp->param_flags & SPP_SACKDELAY_ENABLE) {
6105 			params.sack_delay  = sp->sackdelay;
6106 			params.sack_freq = sp->sackfreq;
6107 		} else {
6108 			params.sack_delay  = 0;
6109 			params.sack_freq = 1;
6110 		}
6111 	}
6112 
6113 	if (copy_to_user(optval, &params, len))
6114 		return -EFAULT;
6115 
6116 	if (put_user(len, optlen))
6117 		return -EFAULT;
6118 
6119 	return 0;
6120 }
6121 
6122 /* 7.1.3 Initialization Parameters (SCTP_INITMSG)
6123  *
6124  * Applications can specify protocol parameters for the default association
6125  * initialization.  The option name argument to setsockopt() and getsockopt()
6126  * is SCTP_INITMSG.
6127  *
6128  * Setting initialization parameters is effective only on an unconnected
6129  * socket (for UDP-style sockets only future associations are effected
6130  * by the change).  With TCP-style sockets, this option is inherited by
6131  * sockets derived from a listener socket.
6132  */
sctp_getsockopt_initmsg(struct sock * sk,int len,char __user * optval,int __user * optlen)6133 static int sctp_getsockopt_initmsg(struct sock *sk, int len, char __user *optval, int __user *optlen)
6134 {
6135 	if (len < sizeof(struct sctp_initmsg))
6136 		return -EINVAL;
6137 	len = sizeof(struct sctp_initmsg);
6138 	if (put_user(len, optlen))
6139 		return -EFAULT;
6140 	if (copy_to_user(optval, &sctp_sk(sk)->initmsg, len))
6141 		return -EFAULT;
6142 	return 0;
6143 }
6144 
6145 
sctp_getsockopt_peer_addrs(struct sock * sk,int len,char __user * optval,int __user * optlen)6146 static int sctp_getsockopt_peer_addrs(struct sock *sk, int len,
6147 				      char __user *optval, int __user *optlen)
6148 {
6149 	struct sctp_association *asoc;
6150 	int cnt = 0;
6151 	struct sctp_getaddrs getaddrs;
6152 	struct sctp_transport *from;
6153 	void __user *to;
6154 	union sctp_addr temp;
6155 	struct sctp_sock *sp = sctp_sk(sk);
6156 	int addrlen;
6157 	size_t space_left;
6158 	int bytes_copied;
6159 
6160 	if (len < sizeof(struct sctp_getaddrs))
6161 		return -EINVAL;
6162 
6163 	if (copy_from_user(&getaddrs, optval, sizeof(struct sctp_getaddrs)))
6164 		return -EFAULT;
6165 
6166 	/* For UDP-style sockets, id specifies the association to query.  */
6167 	asoc = sctp_id2assoc(sk, getaddrs.assoc_id);
6168 	if (!asoc)
6169 		return -EINVAL;
6170 
6171 	to = optval + offsetof(struct sctp_getaddrs, addrs);
6172 	space_left = len - offsetof(struct sctp_getaddrs, addrs);
6173 
6174 	list_for_each_entry(from, &asoc->peer.transport_addr_list,
6175 				transports) {
6176 		memcpy(&temp, &from->ipaddr, sizeof(temp));
6177 		addrlen = sctp_get_pf_specific(sk->sk_family)
6178 			      ->addr_to_user(sp, &temp);
6179 		if (space_left < addrlen)
6180 			return -ENOMEM;
6181 		if (copy_to_user(to, &temp, addrlen))
6182 			return -EFAULT;
6183 		to += addrlen;
6184 		cnt++;
6185 		space_left -= addrlen;
6186 	}
6187 
6188 	if (put_user(cnt, &((struct sctp_getaddrs __user *)optval)->addr_num))
6189 		return -EFAULT;
6190 	bytes_copied = ((char __user *)to) - optval;
6191 	if (put_user(bytes_copied, optlen))
6192 		return -EFAULT;
6193 
6194 	return 0;
6195 }
6196 
sctp_copy_laddrs(struct sock * sk,__u16 port,void * to,size_t space_left,int * bytes_copied)6197 static int sctp_copy_laddrs(struct sock *sk, __u16 port, void *to,
6198 			    size_t space_left, int *bytes_copied)
6199 {
6200 	struct sctp_sockaddr_entry *addr;
6201 	union sctp_addr temp;
6202 	int cnt = 0;
6203 	int addrlen;
6204 	struct net *net = sock_net(sk);
6205 
6206 	rcu_read_lock();
6207 	list_for_each_entry_rcu(addr, &net->sctp.local_addr_list, list) {
6208 		if (!addr->valid)
6209 			continue;
6210 
6211 		if ((PF_INET == sk->sk_family) &&
6212 		    (AF_INET6 == addr->a.sa.sa_family))
6213 			continue;
6214 		if ((PF_INET6 == sk->sk_family) &&
6215 		    inet_v6_ipv6only(sk) &&
6216 		    (AF_INET == addr->a.sa.sa_family))
6217 			continue;
6218 		memcpy(&temp, &addr->a, sizeof(temp));
6219 		if (!temp.v4.sin_port)
6220 			temp.v4.sin_port = htons(port);
6221 
6222 		addrlen = sctp_get_pf_specific(sk->sk_family)
6223 			      ->addr_to_user(sctp_sk(sk), &temp);
6224 
6225 		if (space_left < addrlen) {
6226 			cnt =  -ENOMEM;
6227 			break;
6228 		}
6229 		memcpy(to, &temp, addrlen);
6230 
6231 		to += addrlen;
6232 		cnt++;
6233 		space_left -= addrlen;
6234 		*bytes_copied += addrlen;
6235 	}
6236 	rcu_read_unlock();
6237 
6238 	return cnt;
6239 }
6240 
6241 
sctp_getsockopt_local_addrs(struct sock * sk,int len,char __user * optval,int __user * optlen)6242 static int sctp_getsockopt_local_addrs(struct sock *sk, int len,
6243 				       char __user *optval, int __user *optlen)
6244 {
6245 	struct sctp_bind_addr *bp;
6246 	struct sctp_association *asoc;
6247 	int cnt = 0;
6248 	struct sctp_getaddrs getaddrs;
6249 	struct sctp_sockaddr_entry *addr;
6250 	void __user *to;
6251 	union sctp_addr temp;
6252 	struct sctp_sock *sp = sctp_sk(sk);
6253 	int addrlen;
6254 	int err = 0;
6255 	size_t space_left;
6256 	int bytes_copied = 0;
6257 	void *addrs;
6258 	void *buf;
6259 
6260 	if (len < sizeof(struct sctp_getaddrs))
6261 		return -EINVAL;
6262 
6263 	if (copy_from_user(&getaddrs, optval, sizeof(struct sctp_getaddrs)))
6264 		return -EFAULT;
6265 
6266 	/*
6267 	 *  For UDP-style sockets, id specifies the association to query.
6268 	 *  If the id field is set to the value '0' then the locally bound
6269 	 *  addresses are returned without regard to any particular
6270 	 *  association.
6271 	 */
6272 	if (0 == getaddrs.assoc_id) {
6273 		bp = &sctp_sk(sk)->ep->base.bind_addr;
6274 	} else {
6275 		asoc = sctp_id2assoc(sk, getaddrs.assoc_id);
6276 		if (!asoc)
6277 			return -EINVAL;
6278 		bp = &asoc->base.bind_addr;
6279 	}
6280 
6281 	to = optval + offsetof(struct sctp_getaddrs, addrs);
6282 	space_left = len - offsetof(struct sctp_getaddrs, addrs);
6283 
6284 	addrs = kmalloc(space_left, GFP_USER | __GFP_NOWARN);
6285 	if (!addrs)
6286 		return -ENOMEM;
6287 
6288 	/* If the endpoint is bound to 0.0.0.0 or ::0, get the valid
6289 	 * addresses from the global local address list.
6290 	 */
6291 	if (sctp_list_single_entry(&bp->address_list)) {
6292 		addr = list_entry(bp->address_list.next,
6293 				  struct sctp_sockaddr_entry, list);
6294 		if (sctp_is_any(sk, &addr->a)) {
6295 			cnt = sctp_copy_laddrs(sk, bp->port, addrs,
6296 						space_left, &bytes_copied);
6297 			if (cnt < 0) {
6298 				err = cnt;
6299 				goto out;
6300 			}
6301 			goto copy_getaddrs;
6302 		}
6303 	}
6304 
6305 	buf = addrs;
6306 	/* Protection on the bound address list is not needed since
6307 	 * in the socket option context we hold a socket lock and
6308 	 * thus the bound address list can't change.
6309 	 */
6310 	list_for_each_entry(addr, &bp->address_list, list) {
6311 		memcpy(&temp, &addr->a, sizeof(temp));
6312 		addrlen = sctp_get_pf_specific(sk->sk_family)
6313 			      ->addr_to_user(sp, &temp);
6314 		if (space_left < addrlen) {
6315 			err =  -ENOMEM; /*fixme: right error?*/
6316 			goto out;
6317 		}
6318 		memcpy(buf, &temp, addrlen);
6319 		buf += addrlen;
6320 		bytes_copied += addrlen;
6321 		cnt++;
6322 		space_left -= addrlen;
6323 	}
6324 
6325 copy_getaddrs:
6326 	if (copy_to_user(to, addrs, bytes_copied)) {
6327 		err = -EFAULT;
6328 		goto out;
6329 	}
6330 	if (put_user(cnt, &((struct sctp_getaddrs __user *)optval)->addr_num)) {
6331 		err = -EFAULT;
6332 		goto out;
6333 	}
6334 	/* XXX: We should have accounted for sizeof(struct sctp_getaddrs) too,
6335 	 * but we can't change it anymore.
6336 	 */
6337 	if (put_user(bytes_copied, optlen))
6338 		err = -EFAULT;
6339 out:
6340 	kfree(addrs);
6341 	return err;
6342 }
6343 
6344 /* 7.1.10 Set Primary Address (SCTP_PRIMARY_ADDR)
6345  *
6346  * Requests that the local SCTP stack use the enclosed peer address as
6347  * the association primary.  The enclosed address must be one of the
6348  * association peer's addresses.
6349  */
sctp_getsockopt_primary_addr(struct sock * sk,int len,char __user * optval,int __user * optlen)6350 static int sctp_getsockopt_primary_addr(struct sock *sk, int len,
6351 					char __user *optval, int __user *optlen)
6352 {
6353 	struct sctp_prim prim;
6354 	struct sctp_association *asoc;
6355 	struct sctp_sock *sp = sctp_sk(sk);
6356 
6357 	if (len < sizeof(struct sctp_prim))
6358 		return -EINVAL;
6359 
6360 	len = sizeof(struct sctp_prim);
6361 
6362 	if (copy_from_user(&prim, optval, len))
6363 		return -EFAULT;
6364 
6365 	asoc = sctp_id2assoc(sk, prim.ssp_assoc_id);
6366 	if (!asoc)
6367 		return -EINVAL;
6368 
6369 	if (!asoc->peer.primary_path)
6370 		return -ENOTCONN;
6371 
6372 	memcpy(&prim.ssp_addr, &asoc->peer.primary_path->ipaddr,
6373 		asoc->peer.primary_path->af_specific->sockaddr_len);
6374 
6375 	sctp_get_pf_specific(sk->sk_family)->addr_to_user(sp,
6376 			(union sctp_addr *)&prim.ssp_addr);
6377 
6378 	if (put_user(len, optlen))
6379 		return -EFAULT;
6380 	if (copy_to_user(optval, &prim, len))
6381 		return -EFAULT;
6382 
6383 	return 0;
6384 }
6385 
6386 /*
6387  * 7.1.11  Set Adaptation Layer Indicator (SCTP_ADAPTATION_LAYER)
6388  *
6389  * Requests that the local endpoint set the specified Adaptation Layer
6390  * Indication parameter for all future INIT and INIT-ACK exchanges.
6391  */
sctp_getsockopt_adaptation_layer(struct sock * sk,int len,char __user * optval,int __user * optlen)6392 static int sctp_getsockopt_adaptation_layer(struct sock *sk, int len,
6393 				  char __user *optval, int __user *optlen)
6394 {
6395 	struct sctp_setadaptation adaptation;
6396 
6397 	if (len < sizeof(struct sctp_setadaptation))
6398 		return -EINVAL;
6399 
6400 	len = sizeof(struct sctp_setadaptation);
6401 
6402 	adaptation.ssb_adaptation_ind = sctp_sk(sk)->adaptation_ind;
6403 
6404 	if (put_user(len, optlen))
6405 		return -EFAULT;
6406 	if (copy_to_user(optval, &adaptation, len))
6407 		return -EFAULT;
6408 
6409 	return 0;
6410 }
6411 
6412 /*
6413  *
6414  * 7.1.14 Set default send parameters (SCTP_DEFAULT_SEND_PARAM)
6415  *
6416  *   Applications that wish to use the sendto() system call may wish to
6417  *   specify a default set of parameters that would normally be supplied
6418  *   through the inclusion of ancillary data.  This socket option allows
6419  *   such an application to set the default sctp_sndrcvinfo structure.
6420 
6421 
6422  *   The application that wishes to use this socket option simply passes
6423  *   in to this call the sctp_sndrcvinfo structure defined in Section
6424  *   5.2.2) The input parameters accepted by this call include
6425  *   sinfo_stream, sinfo_flags, sinfo_ppid, sinfo_context,
6426  *   sinfo_timetolive.  The user must provide the sinfo_assoc_id field in
6427  *   to this call if the caller is using the UDP model.
6428  *
6429  *   For getsockopt, it get the default sctp_sndrcvinfo structure.
6430  */
sctp_getsockopt_default_send_param(struct sock * sk,int len,char __user * optval,int __user * optlen)6431 static int sctp_getsockopt_default_send_param(struct sock *sk,
6432 					int len, char __user *optval,
6433 					int __user *optlen)
6434 {
6435 	struct sctp_sock *sp = sctp_sk(sk);
6436 	struct sctp_association *asoc;
6437 	struct sctp_sndrcvinfo info;
6438 
6439 	if (len < sizeof(info))
6440 		return -EINVAL;
6441 
6442 	len = sizeof(info);
6443 
6444 	if (copy_from_user(&info, optval, len))
6445 		return -EFAULT;
6446 
6447 	asoc = sctp_id2assoc(sk, info.sinfo_assoc_id);
6448 	if (!asoc && info.sinfo_assoc_id != SCTP_FUTURE_ASSOC &&
6449 	    sctp_style(sk, UDP))
6450 		return -EINVAL;
6451 
6452 	if (asoc) {
6453 		info.sinfo_stream = asoc->default_stream;
6454 		info.sinfo_flags = asoc->default_flags;
6455 		info.sinfo_ppid = asoc->default_ppid;
6456 		info.sinfo_context = asoc->default_context;
6457 		info.sinfo_timetolive = asoc->default_timetolive;
6458 	} else {
6459 		info.sinfo_stream = sp->default_stream;
6460 		info.sinfo_flags = sp->default_flags;
6461 		info.sinfo_ppid = sp->default_ppid;
6462 		info.sinfo_context = sp->default_context;
6463 		info.sinfo_timetolive = sp->default_timetolive;
6464 	}
6465 
6466 	if (put_user(len, optlen))
6467 		return -EFAULT;
6468 	if (copy_to_user(optval, &info, len))
6469 		return -EFAULT;
6470 
6471 	return 0;
6472 }
6473 
6474 /* RFC6458, Section 8.1.31. Set/get Default Send Parameters
6475  * (SCTP_DEFAULT_SNDINFO)
6476  */
sctp_getsockopt_default_sndinfo(struct sock * sk,int len,char __user * optval,int __user * optlen)6477 static int sctp_getsockopt_default_sndinfo(struct sock *sk, int len,
6478 					   char __user *optval,
6479 					   int __user *optlen)
6480 {
6481 	struct sctp_sock *sp = sctp_sk(sk);
6482 	struct sctp_association *asoc;
6483 	struct sctp_sndinfo info;
6484 
6485 	if (len < sizeof(info))
6486 		return -EINVAL;
6487 
6488 	len = sizeof(info);
6489 
6490 	if (copy_from_user(&info, optval, len))
6491 		return -EFAULT;
6492 
6493 	asoc = sctp_id2assoc(sk, info.snd_assoc_id);
6494 	if (!asoc && info.snd_assoc_id != SCTP_FUTURE_ASSOC &&
6495 	    sctp_style(sk, UDP))
6496 		return -EINVAL;
6497 
6498 	if (asoc) {
6499 		info.snd_sid = asoc->default_stream;
6500 		info.snd_flags = asoc->default_flags;
6501 		info.snd_ppid = asoc->default_ppid;
6502 		info.snd_context = asoc->default_context;
6503 	} else {
6504 		info.snd_sid = sp->default_stream;
6505 		info.snd_flags = sp->default_flags;
6506 		info.snd_ppid = sp->default_ppid;
6507 		info.snd_context = sp->default_context;
6508 	}
6509 
6510 	if (put_user(len, optlen))
6511 		return -EFAULT;
6512 	if (copy_to_user(optval, &info, len))
6513 		return -EFAULT;
6514 
6515 	return 0;
6516 }
6517 
6518 /*
6519  *
6520  * 7.1.5 SCTP_NODELAY
6521  *
6522  * Turn on/off any Nagle-like algorithm.  This means that packets are
6523  * generally sent as soon as possible and no unnecessary delays are
6524  * introduced, at the cost of more packets in the network.  Expects an
6525  * integer boolean flag.
6526  */
6527 
sctp_getsockopt_nodelay(struct sock * sk,int len,char __user * optval,int __user * optlen)6528 static int sctp_getsockopt_nodelay(struct sock *sk, int len,
6529 				   char __user *optval, int __user *optlen)
6530 {
6531 	int val;
6532 
6533 	if (len < sizeof(int))
6534 		return -EINVAL;
6535 
6536 	len = sizeof(int);
6537 	val = (sctp_sk(sk)->nodelay == 1);
6538 	if (put_user(len, optlen))
6539 		return -EFAULT;
6540 	if (copy_to_user(optval, &val, len))
6541 		return -EFAULT;
6542 	return 0;
6543 }
6544 
6545 /*
6546  *
6547  * 7.1.1 SCTP_RTOINFO
6548  *
6549  * The protocol parameters used to initialize and bound retransmission
6550  * timeout (RTO) are tunable. sctp_rtoinfo structure is used to access
6551  * and modify these parameters.
6552  * All parameters are time values, in milliseconds.  A value of 0, when
6553  * modifying the parameters, indicates that the current value should not
6554  * be changed.
6555  *
6556  */
sctp_getsockopt_rtoinfo(struct sock * sk,int len,char __user * optval,int __user * optlen)6557 static int sctp_getsockopt_rtoinfo(struct sock *sk, int len,
6558 				char __user *optval,
6559 				int __user *optlen) {
6560 	struct sctp_rtoinfo rtoinfo;
6561 	struct sctp_association *asoc;
6562 
6563 	if (len < sizeof (struct sctp_rtoinfo))
6564 		return -EINVAL;
6565 
6566 	len = sizeof(struct sctp_rtoinfo);
6567 
6568 	if (copy_from_user(&rtoinfo, optval, len))
6569 		return -EFAULT;
6570 
6571 	asoc = sctp_id2assoc(sk, rtoinfo.srto_assoc_id);
6572 
6573 	if (!asoc && rtoinfo.srto_assoc_id != SCTP_FUTURE_ASSOC &&
6574 	    sctp_style(sk, UDP))
6575 		return -EINVAL;
6576 
6577 	/* Values corresponding to the specific association. */
6578 	if (asoc) {
6579 		rtoinfo.srto_initial = jiffies_to_msecs(asoc->rto_initial);
6580 		rtoinfo.srto_max = jiffies_to_msecs(asoc->rto_max);
6581 		rtoinfo.srto_min = jiffies_to_msecs(asoc->rto_min);
6582 	} else {
6583 		/* Values corresponding to the endpoint. */
6584 		struct sctp_sock *sp = sctp_sk(sk);
6585 
6586 		rtoinfo.srto_initial = sp->rtoinfo.srto_initial;
6587 		rtoinfo.srto_max = sp->rtoinfo.srto_max;
6588 		rtoinfo.srto_min = sp->rtoinfo.srto_min;
6589 	}
6590 
6591 	if (put_user(len, optlen))
6592 		return -EFAULT;
6593 
6594 	if (copy_to_user(optval, &rtoinfo, len))
6595 		return -EFAULT;
6596 
6597 	return 0;
6598 }
6599 
6600 /*
6601  *
6602  * 7.1.2 SCTP_ASSOCINFO
6603  *
6604  * This option is used to tune the maximum retransmission attempts
6605  * of the association.
6606  * Returns an error if the new association retransmission value is
6607  * greater than the sum of the retransmission value  of the peer.
6608  * See [SCTP] for more information.
6609  *
6610  */
sctp_getsockopt_associnfo(struct sock * sk,int len,char __user * optval,int __user * optlen)6611 static int sctp_getsockopt_associnfo(struct sock *sk, int len,
6612 				     char __user *optval,
6613 				     int __user *optlen)
6614 {
6615 
6616 	struct sctp_assocparams assocparams;
6617 	struct sctp_association *asoc;
6618 	struct list_head *pos;
6619 	int cnt = 0;
6620 
6621 	if (len < sizeof (struct sctp_assocparams))
6622 		return -EINVAL;
6623 
6624 	len = sizeof(struct sctp_assocparams);
6625 
6626 	if (copy_from_user(&assocparams, optval, len))
6627 		return -EFAULT;
6628 
6629 	asoc = sctp_id2assoc(sk, assocparams.sasoc_assoc_id);
6630 
6631 	if (!asoc && assocparams.sasoc_assoc_id != SCTP_FUTURE_ASSOC &&
6632 	    sctp_style(sk, UDP))
6633 		return -EINVAL;
6634 
6635 	/* Values correspoinding to the specific association */
6636 	if (asoc) {
6637 		assocparams.sasoc_asocmaxrxt = asoc->max_retrans;
6638 		assocparams.sasoc_peer_rwnd = asoc->peer.rwnd;
6639 		assocparams.sasoc_local_rwnd = asoc->a_rwnd;
6640 		assocparams.sasoc_cookie_life = ktime_to_ms(asoc->cookie_life);
6641 
6642 		list_for_each(pos, &asoc->peer.transport_addr_list) {
6643 			cnt++;
6644 		}
6645 
6646 		assocparams.sasoc_number_peer_destinations = cnt;
6647 	} else {
6648 		/* Values corresponding to the endpoint */
6649 		struct sctp_sock *sp = sctp_sk(sk);
6650 
6651 		assocparams.sasoc_asocmaxrxt = sp->assocparams.sasoc_asocmaxrxt;
6652 		assocparams.sasoc_peer_rwnd = sp->assocparams.sasoc_peer_rwnd;
6653 		assocparams.sasoc_local_rwnd = sp->assocparams.sasoc_local_rwnd;
6654 		assocparams.sasoc_cookie_life =
6655 					sp->assocparams.sasoc_cookie_life;
6656 		assocparams.sasoc_number_peer_destinations =
6657 					sp->assocparams.
6658 					sasoc_number_peer_destinations;
6659 	}
6660 
6661 	if (put_user(len, optlen))
6662 		return -EFAULT;
6663 
6664 	if (copy_to_user(optval, &assocparams, len))
6665 		return -EFAULT;
6666 
6667 	return 0;
6668 }
6669 
6670 /*
6671  * 7.1.16 Set/clear IPv4 mapped addresses (SCTP_I_WANT_MAPPED_V4_ADDR)
6672  *
6673  * This socket option is a boolean flag which turns on or off mapped V4
6674  * addresses.  If this option is turned on and the socket is type
6675  * PF_INET6, then IPv4 addresses will be mapped to V6 representation.
6676  * If this option is turned off, then no mapping will be done of V4
6677  * addresses and a user will receive both PF_INET6 and PF_INET type
6678  * addresses on the socket.
6679  */
sctp_getsockopt_mappedv4(struct sock * sk,int len,char __user * optval,int __user * optlen)6680 static int sctp_getsockopt_mappedv4(struct sock *sk, int len,
6681 				    char __user *optval, int __user *optlen)
6682 {
6683 	int val;
6684 	struct sctp_sock *sp = sctp_sk(sk);
6685 
6686 	if (len < sizeof(int))
6687 		return -EINVAL;
6688 
6689 	len = sizeof(int);
6690 	val = sp->v4mapped;
6691 	if (put_user(len, optlen))
6692 		return -EFAULT;
6693 	if (copy_to_user(optval, &val, len))
6694 		return -EFAULT;
6695 
6696 	return 0;
6697 }
6698 
6699 /*
6700  * 7.1.29.  Set or Get the default context (SCTP_CONTEXT)
6701  * (chapter and verse is quoted at sctp_setsockopt_context())
6702  */
sctp_getsockopt_context(struct sock * sk,int len,char __user * optval,int __user * optlen)6703 static int sctp_getsockopt_context(struct sock *sk, int len,
6704 				   char __user *optval, int __user *optlen)
6705 {
6706 	struct sctp_assoc_value params;
6707 	struct sctp_association *asoc;
6708 
6709 	if (len < sizeof(struct sctp_assoc_value))
6710 		return -EINVAL;
6711 
6712 	len = sizeof(struct sctp_assoc_value);
6713 
6714 	if (copy_from_user(&params, optval, len))
6715 		return -EFAULT;
6716 
6717 	asoc = sctp_id2assoc(sk, params.assoc_id);
6718 	if (!asoc && params.assoc_id != SCTP_FUTURE_ASSOC &&
6719 	    sctp_style(sk, UDP))
6720 		return -EINVAL;
6721 
6722 	params.assoc_value = asoc ? asoc->default_rcv_context
6723 				  : sctp_sk(sk)->default_rcv_context;
6724 
6725 	if (put_user(len, optlen))
6726 		return -EFAULT;
6727 	if (copy_to_user(optval, &params, len))
6728 		return -EFAULT;
6729 
6730 	return 0;
6731 }
6732 
6733 /*
6734  * 8.1.16.  Get or Set the Maximum Fragmentation Size (SCTP_MAXSEG)
6735  * This option will get or set the maximum size to put in any outgoing
6736  * SCTP DATA chunk.  If a message is larger than this size it will be
6737  * fragmented by SCTP into the specified size.  Note that the underlying
6738  * SCTP implementation may fragment into smaller sized chunks when the
6739  * PMTU of the underlying association is smaller than the value set by
6740  * the user.  The default value for this option is '0' which indicates
6741  * the user is NOT limiting fragmentation and only the PMTU will effect
6742  * SCTP's choice of DATA chunk size.  Note also that values set larger
6743  * than the maximum size of an IP datagram will effectively let SCTP
6744  * control fragmentation (i.e. the same as setting this option to 0).
6745  *
6746  * The following structure is used to access and modify this parameter:
6747  *
6748  * struct sctp_assoc_value {
6749  *   sctp_assoc_t assoc_id;
6750  *   uint32_t assoc_value;
6751  * };
6752  *
6753  * assoc_id:  This parameter is ignored for one-to-one style sockets.
6754  *    For one-to-many style sockets this parameter indicates which
6755  *    association the user is performing an action upon.  Note that if
6756  *    this field's value is zero then the endpoints default value is
6757  *    changed (effecting future associations only).
6758  * assoc_value:  This parameter specifies the maximum size in bytes.
6759  */
sctp_getsockopt_maxseg(struct sock * sk,int len,char __user * optval,int __user * optlen)6760 static int sctp_getsockopt_maxseg(struct sock *sk, int len,
6761 				  char __user *optval, int __user *optlen)
6762 {
6763 	struct sctp_assoc_value params;
6764 	struct sctp_association *asoc;
6765 
6766 	if (len == sizeof(int)) {
6767 		pr_warn_ratelimited(DEPRECATED
6768 				    "%s (pid %d) "
6769 				    "Use of int in maxseg socket option.\n"
6770 				    "Use struct sctp_assoc_value instead\n",
6771 				    current->comm, task_pid_nr(current));
6772 		params.assoc_id = SCTP_FUTURE_ASSOC;
6773 	} else if (len >= sizeof(struct sctp_assoc_value)) {
6774 		len = sizeof(struct sctp_assoc_value);
6775 		if (copy_from_user(&params, optval, len))
6776 			return -EFAULT;
6777 	} else
6778 		return -EINVAL;
6779 
6780 	asoc = sctp_id2assoc(sk, params.assoc_id);
6781 	if (!asoc && params.assoc_id != SCTP_FUTURE_ASSOC &&
6782 	    sctp_style(sk, UDP))
6783 		return -EINVAL;
6784 
6785 	if (asoc)
6786 		params.assoc_value = asoc->frag_point;
6787 	else
6788 		params.assoc_value = sctp_sk(sk)->user_frag;
6789 
6790 	if (put_user(len, optlen))
6791 		return -EFAULT;
6792 	if (len == sizeof(int)) {
6793 		if (copy_to_user(optval, &params.assoc_value, len))
6794 			return -EFAULT;
6795 	} else {
6796 		if (copy_to_user(optval, &params, len))
6797 			return -EFAULT;
6798 	}
6799 
6800 	return 0;
6801 }
6802 
6803 /*
6804  * 7.1.24.  Get or set fragmented interleave (SCTP_FRAGMENT_INTERLEAVE)
6805  * (chapter and verse is quoted at sctp_setsockopt_fragment_interleave())
6806  */
sctp_getsockopt_fragment_interleave(struct sock * sk,int len,char __user * optval,int __user * optlen)6807 static int sctp_getsockopt_fragment_interleave(struct sock *sk, int len,
6808 					       char __user *optval, int __user *optlen)
6809 {
6810 	int val;
6811 
6812 	if (len < sizeof(int))
6813 		return -EINVAL;
6814 
6815 	len = sizeof(int);
6816 
6817 	val = sctp_sk(sk)->frag_interleave;
6818 	if (put_user(len, optlen))
6819 		return -EFAULT;
6820 	if (copy_to_user(optval, &val, len))
6821 		return -EFAULT;
6822 
6823 	return 0;
6824 }
6825 
6826 /*
6827  * 7.1.25.  Set or Get the sctp partial delivery point
6828  * (chapter and verse is quoted at sctp_setsockopt_partial_delivery_point())
6829  */
sctp_getsockopt_partial_delivery_point(struct sock * sk,int len,char __user * optval,int __user * optlen)6830 static int sctp_getsockopt_partial_delivery_point(struct sock *sk, int len,
6831 						  char __user *optval,
6832 						  int __user *optlen)
6833 {
6834 	u32 val;
6835 
6836 	if (len < sizeof(u32))
6837 		return -EINVAL;
6838 
6839 	len = sizeof(u32);
6840 
6841 	val = sctp_sk(sk)->pd_point;
6842 	if (put_user(len, optlen))
6843 		return -EFAULT;
6844 	if (copy_to_user(optval, &val, len))
6845 		return -EFAULT;
6846 
6847 	return 0;
6848 }
6849 
6850 /*
6851  * 7.1.28.  Set or Get the maximum burst (SCTP_MAX_BURST)
6852  * (chapter and verse is quoted at sctp_setsockopt_maxburst())
6853  */
sctp_getsockopt_maxburst(struct sock * sk,int len,char __user * optval,int __user * optlen)6854 static int sctp_getsockopt_maxburst(struct sock *sk, int len,
6855 				    char __user *optval,
6856 				    int __user *optlen)
6857 {
6858 	struct sctp_assoc_value params;
6859 	struct sctp_association *asoc;
6860 
6861 	if (len == sizeof(int)) {
6862 		pr_warn_ratelimited(DEPRECATED
6863 				    "%s (pid %d) "
6864 				    "Use of int in max_burst socket option.\n"
6865 				    "Use struct sctp_assoc_value instead\n",
6866 				    current->comm, task_pid_nr(current));
6867 		params.assoc_id = SCTP_FUTURE_ASSOC;
6868 	} else if (len >= sizeof(struct sctp_assoc_value)) {
6869 		len = sizeof(struct sctp_assoc_value);
6870 		if (copy_from_user(&params, optval, len))
6871 			return -EFAULT;
6872 	} else
6873 		return -EINVAL;
6874 
6875 	asoc = sctp_id2assoc(sk, params.assoc_id);
6876 	if (!asoc && params.assoc_id != SCTP_FUTURE_ASSOC &&
6877 	    sctp_style(sk, UDP))
6878 		return -EINVAL;
6879 
6880 	params.assoc_value = asoc ? asoc->max_burst : sctp_sk(sk)->max_burst;
6881 
6882 	if (len == sizeof(int)) {
6883 		if (copy_to_user(optval, &params.assoc_value, len))
6884 			return -EFAULT;
6885 	} else {
6886 		if (copy_to_user(optval, &params, len))
6887 			return -EFAULT;
6888 	}
6889 
6890 	return 0;
6891 
6892 }
6893 
sctp_getsockopt_hmac_ident(struct sock * sk,int len,char __user * optval,int __user * optlen)6894 static int sctp_getsockopt_hmac_ident(struct sock *sk, int len,
6895 				    char __user *optval, int __user *optlen)
6896 {
6897 	struct sctp_endpoint *ep = sctp_sk(sk)->ep;
6898 	struct sctp_hmacalgo  __user *p = (void __user *)optval;
6899 	struct sctp_hmac_algo_param *hmacs;
6900 	__u16 data_len = 0;
6901 	u32 num_idents;
6902 	int i;
6903 
6904 	if (!ep->auth_enable)
6905 		return -EACCES;
6906 
6907 	hmacs = ep->auth_hmacs_list;
6908 	data_len = ntohs(hmacs->param_hdr.length) -
6909 		   sizeof(struct sctp_paramhdr);
6910 
6911 	if (len < sizeof(struct sctp_hmacalgo) + data_len)
6912 		return -EINVAL;
6913 
6914 	len = sizeof(struct sctp_hmacalgo) + data_len;
6915 	num_idents = data_len / sizeof(u16);
6916 
6917 	if (put_user(len, optlen))
6918 		return -EFAULT;
6919 	if (put_user(num_idents, &p->shmac_num_idents))
6920 		return -EFAULT;
6921 	for (i = 0; i < num_idents; i++) {
6922 		__u16 hmacid = ntohs(hmacs->hmac_ids[i]);
6923 
6924 		if (copy_to_user(&p->shmac_idents[i], &hmacid, sizeof(__u16)))
6925 			return -EFAULT;
6926 	}
6927 	return 0;
6928 }
6929 
sctp_getsockopt_active_key(struct sock * sk,int len,char __user * optval,int __user * optlen)6930 static int sctp_getsockopt_active_key(struct sock *sk, int len,
6931 				    char __user *optval, int __user *optlen)
6932 {
6933 	struct sctp_endpoint *ep = sctp_sk(sk)->ep;
6934 	struct sctp_authkeyid val;
6935 	struct sctp_association *asoc;
6936 
6937 	if (len < sizeof(struct sctp_authkeyid))
6938 		return -EINVAL;
6939 
6940 	len = sizeof(struct sctp_authkeyid);
6941 	if (copy_from_user(&val, optval, len))
6942 		return -EFAULT;
6943 
6944 	asoc = sctp_id2assoc(sk, val.scact_assoc_id);
6945 	if (!asoc && val.scact_assoc_id && sctp_style(sk, UDP))
6946 		return -EINVAL;
6947 
6948 	if (asoc) {
6949 		if (!asoc->peer.auth_capable)
6950 			return -EACCES;
6951 		val.scact_keynumber = asoc->active_key_id;
6952 	} else {
6953 		if (!ep->auth_enable)
6954 			return -EACCES;
6955 		val.scact_keynumber = ep->active_key_id;
6956 	}
6957 
6958 	if (put_user(len, optlen))
6959 		return -EFAULT;
6960 	if (copy_to_user(optval, &val, len))
6961 		return -EFAULT;
6962 
6963 	return 0;
6964 }
6965 
sctp_getsockopt_peer_auth_chunks(struct sock * sk,int len,char __user * optval,int __user * optlen)6966 static int sctp_getsockopt_peer_auth_chunks(struct sock *sk, int len,
6967 				    char __user *optval, int __user *optlen)
6968 {
6969 	struct sctp_authchunks __user *p = (void __user *)optval;
6970 	struct sctp_authchunks val;
6971 	struct sctp_association *asoc;
6972 	struct sctp_chunks_param *ch;
6973 	u32    num_chunks = 0;
6974 	char __user *to;
6975 
6976 	if (len < sizeof(struct sctp_authchunks))
6977 		return -EINVAL;
6978 
6979 	if (copy_from_user(&val, optval, sizeof(val)))
6980 		return -EFAULT;
6981 
6982 	to = p->gauth_chunks;
6983 	asoc = sctp_id2assoc(sk, val.gauth_assoc_id);
6984 	if (!asoc)
6985 		return -EINVAL;
6986 
6987 	if (!asoc->peer.auth_capable)
6988 		return -EACCES;
6989 
6990 	ch = asoc->peer.peer_chunks;
6991 	if (!ch)
6992 		goto num;
6993 
6994 	/* See if the user provided enough room for all the data */
6995 	num_chunks = ntohs(ch->param_hdr.length) - sizeof(struct sctp_paramhdr);
6996 	if (len < num_chunks)
6997 		return -EINVAL;
6998 
6999 	if (copy_to_user(to, ch->chunks, num_chunks))
7000 		return -EFAULT;
7001 num:
7002 	len = sizeof(struct sctp_authchunks) + num_chunks;
7003 	if (put_user(len, optlen))
7004 		return -EFAULT;
7005 	if (put_user(num_chunks, &p->gauth_number_of_chunks))
7006 		return -EFAULT;
7007 	return 0;
7008 }
7009 
sctp_getsockopt_local_auth_chunks(struct sock * sk,int len,char __user * optval,int __user * optlen)7010 static int sctp_getsockopt_local_auth_chunks(struct sock *sk, int len,
7011 				    char __user *optval, int __user *optlen)
7012 {
7013 	struct sctp_endpoint *ep = sctp_sk(sk)->ep;
7014 	struct sctp_authchunks __user *p = (void __user *)optval;
7015 	struct sctp_authchunks val;
7016 	struct sctp_association *asoc;
7017 	struct sctp_chunks_param *ch;
7018 	u32    num_chunks = 0;
7019 	char __user *to;
7020 
7021 	if (len < sizeof(struct sctp_authchunks))
7022 		return -EINVAL;
7023 
7024 	if (copy_from_user(&val, optval, sizeof(val)))
7025 		return -EFAULT;
7026 
7027 	to = p->gauth_chunks;
7028 	asoc = sctp_id2assoc(sk, val.gauth_assoc_id);
7029 	if (!asoc && val.gauth_assoc_id != SCTP_FUTURE_ASSOC &&
7030 	    sctp_style(sk, UDP))
7031 		return -EINVAL;
7032 
7033 	if (asoc) {
7034 		if (!asoc->peer.auth_capable)
7035 			return -EACCES;
7036 		ch = (struct sctp_chunks_param *)asoc->c.auth_chunks;
7037 	} else {
7038 		if (!ep->auth_enable)
7039 			return -EACCES;
7040 		ch = ep->auth_chunk_list;
7041 	}
7042 	if (!ch)
7043 		goto num;
7044 
7045 	num_chunks = ntohs(ch->param_hdr.length) - sizeof(struct sctp_paramhdr);
7046 	if (len < sizeof(struct sctp_authchunks) + num_chunks)
7047 		return -EINVAL;
7048 
7049 	if (copy_to_user(to, ch->chunks, num_chunks))
7050 		return -EFAULT;
7051 num:
7052 	len = sizeof(struct sctp_authchunks) + num_chunks;
7053 	if (put_user(len, optlen))
7054 		return -EFAULT;
7055 	if (put_user(num_chunks, &p->gauth_number_of_chunks))
7056 		return -EFAULT;
7057 
7058 	return 0;
7059 }
7060 
7061 /*
7062  * 8.2.5.  Get the Current Number of Associations (SCTP_GET_ASSOC_NUMBER)
7063  * This option gets the current number of associations that are attached
7064  * to a one-to-many style socket.  The option value is an uint32_t.
7065  */
sctp_getsockopt_assoc_number(struct sock * sk,int len,char __user * optval,int __user * optlen)7066 static int sctp_getsockopt_assoc_number(struct sock *sk, int len,
7067 				    char __user *optval, int __user *optlen)
7068 {
7069 	struct sctp_sock *sp = sctp_sk(sk);
7070 	struct sctp_association *asoc;
7071 	u32 val = 0;
7072 
7073 	if (sctp_style(sk, TCP))
7074 		return -EOPNOTSUPP;
7075 
7076 	if (len < sizeof(u32))
7077 		return -EINVAL;
7078 
7079 	len = sizeof(u32);
7080 
7081 	list_for_each_entry(asoc, &(sp->ep->asocs), asocs) {
7082 		val++;
7083 	}
7084 
7085 	if (put_user(len, optlen))
7086 		return -EFAULT;
7087 	if (copy_to_user(optval, &val, len))
7088 		return -EFAULT;
7089 
7090 	return 0;
7091 }
7092 
7093 /*
7094  * 8.1.23 SCTP_AUTO_ASCONF
7095  * See the corresponding setsockopt entry as description
7096  */
sctp_getsockopt_auto_asconf(struct sock * sk,int len,char __user * optval,int __user * optlen)7097 static int sctp_getsockopt_auto_asconf(struct sock *sk, int len,
7098 				   char __user *optval, int __user *optlen)
7099 {
7100 	int val = 0;
7101 
7102 	if (len < sizeof(int))
7103 		return -EINVAL;
7104 
7105 	len = sizeof(int);
7106 	if (sctp_sk(sk)->do_auto_asconf && sctp_is_ep_boundall(sk))
7107 		val = 1;
7108 	if (put_user(len, optlen))
7109 		return -EFAULT;
7110 	if (copy_to_user(optval, &val, len))
7111 		return -EFAULT;
7112 	return 0;
7113 }
7114 
7115 /*
7116  * 8.2.6. Get the Current Identifiers of Associations
7117  *        (SCTP_GET_ASSOC_ID_LIST)
7118  *
7119  * This option gets the current list of SCTP association identifiers of
7120  * the SCTP associations handled by a one-to-many style socket.
7121  */
sctp_getsockopt_assoc_ids(struct sock * sk,int len,char __user * optval,int __user * optlen)7122 static int sctp_getsockopt_assoc_ids(struct sock *sk, int len,
7123 				    char __user *optval, int __user *optlen)
7124 {
7125 	struct sctp_sock *sp = sctp_sk(sk);
7126 	struct sctp_association *asoc;
7127 	struct sctp_assoc_ids *ids;
7128 	size_t ids_size;
7129 	u32 num = 0;
7130 
7131 	if (sctp_style(sk, TCP))
7132 		return -EOPNOTSUPP;
7133 
7134 	if (len < sizeof(struct sctp_assoc_ids))
7135 		return -EINVAL;
7136 
7137 	list_for_each_entry(asoc, &(sp->ep->asocs), asocs) {
7138 		num++;
7139 	}
7140 
7141 	ids_size = struct_size(ids, gaids_assoc_id, num);
7142 	if (len < ids_size)
7143 		return -EINVAL;
7144 
7145 	len = ids_size;
7146 	ids = kmalloc(len, GFP_USER | __GFP_NOWARN);
7147 	if (unlikely(!ids))
7148 		return -ENOMEM;
7149 
7150 	ids->gaids_number_of_ids = num;
7151 	num = 0;
7152 	list_for_each_entry(asoc, &(sp->ep->asocs), asocs) {
7153 		ids->gaids_assoc_id[num++] = asoc->assoc_id;
7154 	}
7155 
7156 	if (put_user(len, optlen) || copy_to_user(optval, ids, len)) {
7157 		kfree(ids);
7158 		return -EFAULT;
7159 	}
7160 
7161 	kfree(ids);
7162 	return 0;
7163 }
7164 
7165 /*
7166  * SCTP_PEER_ADDR_THLDS
7167  *
7168  * This option allows us to fetch the partially failed threshold for one or all
7169  * transports in an association.  See Section 6.1 of:
7170  * http://www.ietf.org/id/draft-nishida-tsvwg-sctp-failover-05.txt
7171  */
sctp_getsockopt_paddr_thresholds(struct sock * sk,char __user * optval,int len,int __user * optlen,bool v2)7172 static int sctp_getsockopt_paddr_thresholds(struct sock *sk,
7173 					    char __user *optval, int len,
7174 					    int __user *optlen, bool v2)
7175 {
7176 	struct sctp_paddrthlds_v2 val;
7177 	struct sctp_transport *trans;
7178 	struct sctp_association *asoc;
7179 	int min;
7180 
7181 	min = v2 ? sizeof(val) : sizeof(struct sctp_paddrthlds);
7182 	if (len < min)
7183 		return -EINVAL;
7184 	len = min;
7185 	if (copy_from_user(&val, optval, len))
7186 		return -EFAULT;
7187 
7188 	if (!sctp_is_any(sk, (const union sctp_addr *)&val.spt_address)) {
7189 		trans = sctp_addr_id2transport(sk, &val.spt_address,
7190 					       val.spt_assoc_id);
7191 		if (!trans)
7192 			return -ENOENT;
7193 
7194 		val.spt_pathmaxrxt = trans->pathmaxrxt;
7195 		val.spt_pathpfthld = trans->pf_retrans;
7196 		val.spt_pathcpthld = trans->ps_retrans;
7197 
7198 		goto out;
7199 	}
7200 
7201 	asoc = sctp_id2assoc(sk, val.spt_assoc_id);
7202 	if (!asoc && val.spt_assoc_id != SCTP_FUTURE_ASSOC &&
7203 	    sctp_style(sk, UDP))
7204 		return -EINVAL;
7205 
7206 	if (asoc) {
7207 		val.spt_pathpfthld = asoc->pf_retrans;
7208 		val.spt_pathmaxrxt = asoc->pathmaxrxt;
7209 		val.spt_pathcpthld = asoc->ps_retrans;
7210 	} else {
7211 		struct sctp_sock *sp = sctp_sk(sk);
7212 
7213 		val.spt_pathpfthld = sp->pf_retrans;
7214 		val.spt_pathmaxrxt = sp->pathmaxrxt;
7215 		val.spt_pathcpthld = sp->ps_retrans;
7216 	}
7217 
7218 out:
7219 	if (put_user(len, optlen) || copy_to_user(optval, &val, len))
7220 		return -EFAULT;
7221 
7222 	return 0;
7223 }
7224 
7225 /*
7226  * SCTP_GET_ASSOC_STATS
7227  *
7228  * This option retrieves local per endpoint statistics. It is modeled
7229  * after OpenSolaris' implementation
7230  */
sctp_getsockopt_assoc_stats(struct sock * sk,int len,char __user * optval,int __user * optlen)7231 static int sctp_getsockopt_assoc_stats(struct sock *sk, int len,
7232 				       char __user *optval,
7233 				       int __user *optlen)
7234 {
7235 	struct sctp_assoc_stats sas;
7236 	struct sctp_association *asoc = NULL;
7237 
7238 	/* User must provide at least the assoc id */
7239 	if (len < sizeof(sctp_assoc_t))
7240 		return -EINVAL;
7241 
7242 	/* Allow the struct to grow and fill in as much as possible */
7243 	len = min_t(size_t, len, sizeof(sas));
7244 
7245 	if (copy_from_user(&sas, optval, len))
7246 		return -EFAULT;
7247 
7248 	asoc = sctp_id2assoc(sk, sas.sas_assoc_id);
7249 	if (!asoc)
7250 		return -EINVAL;
7251 
7252 	sas.sas_rtxchunks = asoc->stats.rtxchunks;
7253 	sas.sas_gapcnt = asoc->stats.gapcnt;
7254 	sas.sas_outofseqtsns = asoc->stats.outofseqtsns;
7255 	sas.sas_osacks = asoc->stats.osacks;
7256 	sas.sas_isacks = asoc->stats.isacks;
7257 	sas.sas_octrlchunks = asoc->stats.octrlchunks;
7258 	sas.sas_ictrlchunks = asoc->stats.ictrlchunks;
7259 	sas.sas_oodchunks = asoc->stats.oodchunks;
7260 	sas.sas_iodchunks = asoc->stats.iodchunks;
7261 	sas.sas_ouodchunks = asoc->stats.ouodchunks;
7262 	sas.sas_iuodchunks = asoc->stats.iuodchunks;
7263 	sas.sas_idupchunks = asoc->stats.idupchunks;
7264 	sas.sas_opackets = asoc->stats.opackets;
7265 	sas.sas_ipackets = asoc->stats.ipackets;
7266 
7267 	/* New high max rto observed, will return 0 if not a single
7268 	 * RTO update took place. obs_rto_ipaddr will be bogus
7269 	 * in such a case
7270 	 */
7271 	sas.sas_maxrto = asoc->stats.max_obs_rto;
7272 	memcpy(&sas.sas_obs_rto_ipaddr, &asoc->stats.obs_rto_ipaddr,
7273 		sizeof(struct sockaddr_storage));
7274 
7275 	/* Mark beginning of a new observation period */
7276 	asoc->stats.max_obs_rto = asoc->rto_min;
7277 
7278 	if (put_user(len, optlen))
7279 		return -EFAULT;
7280 
7281 	pr_debug("%s: len:%d, assoc_id:%d\n", __func__, len, sas.sas_assoc_id);
7282 
7283 	if (copy_to_user(optval, &sas, len))
7284 		return -EFAULT;
7285 
7286 	return 0;
7287 }
7288 
sctp_getsockopt_recvrcvinfo(struct sock * sk,int len,char __user * optval,int __user * optlen)7289 static int sctp_getsockopt_recvrcvinfo(struct sock *sk,	int len,
7290 				       char __user *optval,
7291 				       int __user *optlen)
7292 {
7293 	int val = 0;
7294 
7295 	if (len < sizeof(int))
7296 		return -EINVAL;
7297 
7298 	len = sizeof(int);
7299 	if (sctp_sk(sk)->recvrcvinfo)
7300 		val = 1;
7301 	if (put_user(len, optlen))
7302 		return -EFAULT;
7303 	if (copy_to_user(optval, &val, len))
7304 		return -EFAULT;
7305 
7306 	return 0;
7307 }
7308 
sctp_getsockopt_recvnxtinfo(struct sock * sk,int len,char __user * optval,int __user * optlen)7309 static int sctp_getsockopt_recvnxtinfo(struct sock *sk,	int len,
7310 				       char __user *optval,
7311 				       int __user *optlen)
7312 {
7313 	int val = 0;
7314 
7315 	if (len < sizeof(int))
7316 		return -EINVAL;
7317 
7318 	len = sizeof(int);
7319 	if (sctp_sk(sk)->recvnxtinfo)
7320 		val = 1;
7321 	if (put_user(len, optlen))
7322 		return -EFAULT;
7323 	if (copy_to_user(optval, &val, len))
7324 		return -EFAULT;
7325 
7326 	return 0;
7327 }
7328 
sctp_getsockopt_pr_supported(struct sock * sk,int len,char __user * optval,int __user * optlen)7329 static int sctp_getsockopt_pr_supported(struct sock *sk, int len,
7330 					char __user *optval,
7331 					int __user *optlen)
7332 {
7333 	struct sctp_assoc_value params;
7334 	struct sctp_association *asoc;
7335 	int retval = -EFAULT;
7336 
7337 	if (len < sizeof(params)) {
7338 		retval = -EINVAL;
7339 		goto out;
7340 	}
7341 
7342 	len = sizeof(params);
7343 	if (copy_from_user(&params, optval, len))
7344 		goto out;
7345 
7346 	asoc = sctp_id2assoc(sk, params.assoc_id);
7347 	if (!asoc && params.assoc_id != SCTP_FUTURE_ASSOC &&
7348 	    sctp_style(sk, UDP)) {
7349 		retval = -EINVAL;
7350 		goto out;
7351 	}
7352 
7353 	params.assoc_value = asoc ? asoc->peer.prsctp_capable
7354 				  : sctp_sk(sk)->ep->prsctp_enable;
7355 
7356 	if (put_user(len, optlen))
7357 		goto out;
7358 
7359 	if (copy_to_user(optval, &params, len))
7360 		goto out;
7361 
7362 	retval = 0;
7363 
7364 out:
7365 	return retval;
7366 }
7367 
sctp_getsockopt_default_prinfo(struct sock * sk,int len,char __user * optval,int __user * optlen)7368 static int sctp_getsockopt_default_prinfo(struct sock *sk, int len,
7369 					  char __user *optval,
7370 					  int __user *optlen)
7371 {
7372 	struct sctp_default_prinfo info;
7373 	struct sctp_association *asoc;
7374 	int retval = -EFAULT;
7375 
7376 	if (len < sizeof(info)) {
7377 		retval = -EINVAL;
7378 		goto out;
7379 	}
7380 
7381 	len = sizeof(info);
7382 	if (copy_from_user(&info, optval, len))
7383 		goto out;
7384 
7385 	asoc = sctp_id2assoc(sk, info.pr_assoc_id);
7386 	if (!asoc && info.pr_assoc_id != SCTP_FUTURE_ASSOC &&
7387 	    sctp_style(sk, UDP)) {
7388 		retval = -EINVAL;
7389 		goto out;
7390 	}
7391 
7392 	if (asoc) {
7393 		info.pr_policy = SCTP_PR_POLICY(asoc->default_flags);
7394 		info.pr_value = asoc->default_timetolive;
7395 	} else {
7396 		struct sctp_sock *sp = sctp_sk(sk);
7397 
7398 		info.pr_policy = SCTP_PR_POLICY(sp->default_flags);
7399 		info.pr_value = sp->default_timetolive;
7400 	}
7401 
7402 	if (put_user(len, optlen))
7403 		goto out;
7404 
7405 	if (copy_to_user(optval, &info, len))
7406 		goto out;
7407 
7408 	retval = 0;
7409 
7410 out:
7411 	return retval;
7412 }
7413 
sctp_getsockopt_pr_assocstatus(struct sock * sk,int len,char __user * optval,int __user * optlen)7414 static int sctp_getsockopt_pr_assocstatus(struct sock *sk, int len,
7415 					  char __user *optval,
7416 					  int __user *optlen)
7417 {
7418 	struct sctp_prstatus params;
7419 	struct sctp_association *asoc;
7420 	int policy;
7421 	int retval = -EINVAL;
7422 
7423 	if (len < sizeof(params))
7424 		goto out;
7425 
7426 	len = sizeof(params);
7427 	if (copy_from_user(&params, optval, len)) {
7428 		retval = -EFAULT;
7429 		goto out;
7430 	}
7431 
7432 	policy = params.sprstat_policy;
7433 	if (!policy || (policy & ~(SCTP_PR_SCTP_MASK | SCTP_PR_SCTP_ALL)) ||
7434 	    ((policy & SCTP_PR_SCTP_ALL) && (policy & SCTP_PR_SCTP_MASK)))
7435 		goto out;
7436 
7437 	asoc = sctp_id2assoc(sk, params.sprstat_assoc_id);
7438 	if (!asoc)
7439 		goto out;
7440 
7441 	if (policy == SCTP_PR_SCTP_ALL) {
7442 		params.sprstat_abandoned_unsent = 0;
7443 		params.sprstat_abandoned_sent = 0;
7444 		for (policy = 0; policy <= SCTP_PR_INDEX(MAX); policy++) {
7445 			params.sprstat_abandoned_unsent +=
7446 				asoc->abandoned_unsent[policy];
7447 			params.sprstat_abandoned_sent +=
7448 				asoc->abandoned_sent[policy];
7449 		}
7450 	} else {
7451 		params.sprstat_abandoned_unsent =
7452 			asoc->abandoned_unsent[__SCTP_PR_INDEX(policy)];
7453 		params.sprstat_abandoned_sent =
7454 			asoc->abandoned_sent[__SCTP_PR_INDEX(policy)];
7455 	}
7456 
7457 	if (put_user(len, optlen)) {
7458 		retval = -EFAULT;
7459 		goto out;
7460 	}
7461 
7462 	if (copy_to_user(optval, &params, len)) {
7463 		retval = -EFAULT;
7464 		goto out;
7465 	}
7466 
7467 	retval = 0;
7468 
7469 out:
7470 	return retval;
7471 }
7472 
sctp_getsockopt_pr_streamstatus(struct sock * sk,int len,char __user * optval,int __user * optlen)7473 static int sctp_getsockopt_pr_streamstatus(struct sock *sk, int len,
7474 					   char __user *optval,
7475 					   int __user *optlen)
7476 {
7477 	struct sctp_stream_out_ext *streamoute;
7478 	struct sctp_association *asoc;
7479 	struct sctp_prstatus params;
7480 	int retval = -EINVAL;
7481 	int policy;
7482 
7483 	if (len < sizeof(params))
7484 		goto out;
7485 
7486 	len = sizeof(params);
7487 	if (copy_from_user(&params, optval, len)) {
7488 		retval = -EFAULT;
7489 		goto out;
7490 	}
7491 
7492 	policy = params.sprstat_policy;
7493 	if (!policy || (policy & ~(SCTP_PR_SCTP_MASK | SCTP_PR_SCTP_ALL)) ||
7494 	    ((policy & SCTP_PR_SCTP_ALL) && (policy & SCTP_PR_SCTP_MASK)))
7495 		goto out;
7496 
7497 	asoc = sctp_id2assoc(sk, params.sprstat_assoc_id);
7498 	if (!asoc || params.sprstat_sid >= asoc->stream.outcnt)
7499 		goto out;
7500 
7501 	streamoute = SCTP_SO(&asoc->stream, params.sprstat_sid)->ext;
7502 	if (!streamoute) {
7503 		/* Not allocated yet, means all stats are 0 */
7504 		params.sprstat_abandoned_unsent = 0;
7505 		params.sprstat_abandoned_sent = 0;
7506 		retval = 0;
7507 		goto out;
7508 	}
7509 
7510 	if (policy == SCTP_PR_SCTP_ALL) {
7511 		params.sprstat_abandoned_unsent = 0;
7512 		params.sprstat_abandoned_sent = 0;
7513 		for (policy = 0; policy <= SCTP_PR_INDEX(MAX); policy++) {
7514 			params.sprstat_abandoned_unsent +=
7515 				streamoute->abandoned_unsent[policy];
7516 			params.sprstat_abandoned_sent +=
7517 				streamoute->abandoned_sent[policy];
7518 		}
7519 	} else {
7520 		params.sprstat_abandoned_unsent =
7521 			streamoute->abandoned_unsent[__SCTP_PR_INDEX(policy)];
7522 		params.sprstat_abandoned_sent =
7523 			streamoute->abandoned_sent[__SCTP_PR_INDEX(policy)];
7524 	}
7525 
7526 	if (put_user(len, optlen) || copy_to_user(optval, &params, len)) {
7527 		retval = -EFAULT;
7528 		goto out;
7529 	}
7530 
7531 	retval = 0;
7532 
7533 out:
7534 	return retval;
7535 }
7536 
sctp_getsockopt_reconfig_supported(struct sock * sk,int len,char __user * optval,int __user * optlen)7537 static int sctp_getsockopt_reconfig_supported(struct sock *sk, int len,
7538 					      char __user *optval,
7539 					      int __user *optlen)
7540 {
7541 	struct sctp_assoc_value params;
7542 	struct sctp_association *asoc;
7543 	int retval = -EFAULT;
7544 
7545 	if (len < sizeof(params)) {
7546 		retval = -EINVAL;
7547 		goto out;
7548 	}
7549 
7550 	len = sizeof(params);
7551 	if (copy_from_user(&params, optval, len))
7552 		goto out;
7553 
7554 	asoc = sctp_id2assoc(sk, params.assoc_id);
7555 	if (!asoc && params.assoc_id != SCTP_FUTURE_ASSOC &&
7556 	    sctp_style(sk, UDP)) {
7557 		retval = -EINVAL;
7558 		goto out;
7559 	}
7560 
7561 	params.assoc_value = asoc ? asoc->peer.reconf_capable
7562 				  : sctp_sk(sk)->ep->reconf_enable;
7563 
7564 	if (put_user(len, optlen))
7565 		goto out;
7566 
7567 	if (copy_to_user(optval, &params, len))
7568 		goto out;
7569 
7570 	retval = 0;
7571 
7572 out:
7573 	return retval;
7574 }
7575 
sctp_getsockopt_enable_strreset(struct sock * sk,int len,char __user * optval,int __user * optlen)7576 static int sctp_getsockopt_enable_strreset(struct sock *sk, int len,
7577 					   char __user *optval,
7578 					   int __user *optlen)
7579 {
7580 	struct sctp_assoc_value params;
7581 	struct sctp_association *asoc;
7582 	int retval = -EFAULT;
7583 
7584 	if (len < sizeof(params)) {
7585 		retval = -EINVAL;
7586 		goto out;
7587 	}
7588 
7589 	len = sizeof(params);
7590 	if (copy_from_user(&params, optval, len))
7591 		goto out;
7592 
7593 	asoc = sctp_id2assoc(sk, params.assoc_id);
7594 	if (!asoc && params.assoc_id != SCTP_FUTURE_ASSOC &&
7595 	    sctp_style(sk, UDP)) {
7596 		retval = -EINVAL;
7597 		goto out;
7598 	}
7599 
7600 	params.assoc_value = asoc ? asoc->strreset_enable
7601 				  : sctp_sk(sk)->ep->strreset_enable;
7602 
7603 	if (put_user(len, optlen))
7604 		goto out;
7605 
7606 	if (copy_to_user(optval, &params, len))
7607 		goto out;
7608 
7609 	retval = 0;
7610 
7611 out:
7612 	return retval;
7613 }
7614 
sctp_getsockopt_scheduler(struct sock * sk,int len,char __user * optval,int __user * optlen)7615 static int sctp_getsockopt_scheduler(struct sock *sk, int len,
7616 				     char __user *optval,
7617 				     int __user *optlen)
7618 {
7619 	struct sctp_assoc_value params;
7620 	struct sctp_association *asoc;
7621 	int retval = -EFAULT;
7622 
7623 	if (len < sizeof(params)) {
7624 		retval = -EINVAL;
7625 		goto out;
7626 	}
7627 
7628 	len = sizeof(params);
7629 	if (copy_from_user(&params, optval, len))
7630 		goto out;
7631 
7632 	asoc = sctp_id2assoc(sk, params.assoc_id);
7633 	if (!asoc && params.assoc_id != SCTP_FUTURE_ASSOC &&
7634 	    sctp_style(sk, UDP)) {
7635 		retval = -EINVAL;
7636 		goto out;
7637 	}
7638 
7639 	params.assoc_value = asoc ? sctp_sched_get_sched(asoc)
7640 				  : sctp_sk(sk)->default_ss;
7641 
7642 	if (put_user(len, optlen))
7643 		goto out;
7644 
7645 	if (copy_to_user(optval, &params, len))
7646 		goto out;
7647 
7648 	retval = 0;
7649 
7650 out:
7651 	return retval;
7652 }
7653 
sctp_getsockopt_scheduler_value(struct sock * sk,int len,char __user * optval,int __user * optlen)7654 static int sctp_getsockopt_scheduler_value(struct sock *sk, int len,
7655 					   char __user *optval,
7656 					   int __user *optlen)
7657 {
7658 	struct sctp_stream_value params;
7659 	struct sctp_association *asoc;
7660 	int retval = -EFAULT;
7661 
7662 	if (len < sizeof(params)) {
7663 		retval = -EINVAL;
7664 		goto out;
7665 	}
7666 
7667 	len = sizeof(params);
7668 	if (copy_from_user(&params, optval, len))
7669 		goto out;
7670 
7671 	asoc = sctp_id2assoc(sk, params.assoc_id);
7672 	if (!asoc) {
7673 		retval = -EINVAL;
7674 		goto out;
7675 	}
7676 
7677 	retval = sctp_sched_get_value(asoc, params.stream_id,
7678 				      &params.stream_value);
7679 	if (retval)
7680 		goto out;
7681 
7682 	if (put_user(len, optlen)) {
7683 		retval = -EFAULT;
7684 		goto out;
7685 	}
7686 
7687 	if (copy_to_user(optval, &params, len)) {
7688 		retval = -EFAULT;
7689 		goto out;
7690 	}
7691 
7692 out:
7693 	return retval;
7694 }
7695 
sctp_getsockopt_interleaving_supported(struct sock * sk,int len,char __user * optval,int __user * optlen)7696 static int sctp_getsockopt_interleaving_supported(struct sock *sk, int len,
7697 						  char __user *optval,
7698 						  int __user *optlen)
7699 {
7700 	struct sctp_assoc_value params;
7701 	struct sctp_association *asoc;
7702 	int retval = -EFAULT;
7703 
7704 	if (len < sizeof(params)) {
7705 		retval = -EINVAL;
7706 		goto out;
7707 	}
7708 
7709 	len = sizeof(params);
7710 	if (copy_from_user(&params, optval, len))
7711 		goto out;
7712 
7713 	asoc = sctp_id2assoc(sk, params.assoc_id);
7714 	if (!asoc && params.assoc_id != SCTP_FUTURE_ASSOC &&
7715 	    sctp_style(sk, UDP)) {
7716 		retval = -EINVAL;
7717 		goto out;
7718 	}
7719 
7720 	params.assoc_value = asoc ? asoc->peer.intl_capable
7721 				  : sctp_sk(sk)->ep->intl_enable;
7722 
7723 	if (put_user(len, optlen))
7724 		goto out;
7725 
7726 	if (copy_to_user(optval, &params, len))
7727 		goto out;
7728 
7729 	retval = 0;
7730 
7731 out:
7732 	return retval;
7733 }
7734 
sctp_getsockopt_reuse_port(struct sock * sk,int len,char __user * optval,int __user * optlen)7735 static int sctp_getsockopt_reuse_port(struct sock *sk, int len,
7736 				      char __user *optval,
7737 				      int __user *optlen)
7738 {
7739 	int val;
7740 
7741 	if (len < sizeof(int))
7742 		return -EINVAL;
7743 
7744 	len = sizeof(int);
7745 	val = sctp_sk(sk)->reuse;
7746 	if (put_user(len, optlen))
7747 		return -EFAULT;
7748 
7749 	if (copy_to_user(optval, &val, len))
7750 		return -EFAULT;
7751 
7752 	return 0;
7753 }
7754 
sctp_getsockopt_event(struct sock * sk,int len,char __user * optval,int __user * optlen)7755 static int sctp_getsockopt_event(struct sock *sk, int len, char __user *optval,
7756 				 int __user *optlen)
7757 {
7758 	struct sctp_association *asoc;
7759 	struct sctp_event param;
7760 	__u16 subscribe;
7761 
7762 	if (len < sizeof(param))
7763 		return -EINVAL;
7764 
7765 	len = sizeof(param);
7766 	if (copy_from_user(&param, optval, len))
7767 		return -EFAULT;
7768 
7769 	if (param.se_type < SCTP_SN_TYPE_BASE ||
7770 	    param.se_type > SCTP_SN_TYPE_MAX)
7771 		return -EINVAL;
7772 
7773 	asoc = sctp_id2assoc(sk, param.se_assoc_id);
7774 	if (!asoc && param.se_assoc_id != SCTP_FUTURE_ASSOC &&
7775 	    sctp_style(sk, UDP))
7776 		return -EINVAL;
7777 
7778 	subscribe = asoc ? asoc->subscribe : sctp_sk(sk)->subscribe;
7779 	param.se_on = sctp_ulpevent_type_enabled(subscribe, param.se_type);
7780 
7781 	if (put_user(len, optlen))
7782 		return -EFAULT;
7783 
7784 	if (copy_to_user(optval, &param, len))
7785 		return -EFAULT;
7786 
7787 	return 0;
7788 }
7789 
sctp_getsockopt_asconf_supported(struct sock * sk,int len,char __user * optval,int __user * optlen)7790 static int sctp_getsockopt_asconf_supported(struct sock *sk, int len,
7791 					    char __user *optval,
7792 					    int __user *optlen)
7793 {
7794 	struct sctp_assoc_value params;
7795 	struct sctp_association *asoc;
7796 	int retval = -EFAULT;
7797 
7798 	if (len < sizeof(params)) {
7799 		retval = -EINVAL;
7800 		goto out;
7801 	}
7802 
7803 	len = sizeof(params);
7804 	if (copy_from_user(&params, optval, len))
7805 		goto out;
7806 
7807 	asoc = sctp_id2assoc(sk, params.assoc_id);
7808 	if (!asoc && params.assoc_id != SCTP_FUTURE_ASSOC &&
7809 	    sctp_style(sk, UDP)) {
7810 		retval = -EINVAL;
7811 		goto out;
7812 	}
7813 
7814 	params.assoc_value = asoc ? asoc->peer.asconf_capable
7815 				  : sctp_sk(sk)->ep->asconf_enable;
7816 
7817 	if (put_user(len, optlen))
7818 		goto out;
7819 
7820 	if (copy_to_user(optval, &params, len))
7821 		goto out;
7822 
7823 	retval = 0;
7824 
7825 out:
7826 	return retval;
7827 }
7828 
sctp_getsockopt_auth_supported(struct sock * sk,int len,char __user * optval,int __user * optlen)7829 static int sctp_getsockopt_auth_supported(struct sock *sk, int len,
7830 					  char __user *optval,
7831 					  int __user *optlen)
7832 {
7833 	struct sctp_assoc_value params;
7834 	struct sctp_association *asoc;
7835 	int retval = -EFAULT;
7836 
7837 	if (len < sizeof(params)) {
7838 		retval = -EINVAL;
7839 		goto out;
7840 	}
7841 
7842 	len = sizeof(params);
7843 	if (copy_from_user(&params, optval, len))
7844 		goto out;
7845 
7846 	asoc = sctp_id2assoc(sk, params.assoc_id);
7847 	if (!asoc && params.assoc_id != SCTP_FUTURE_ASSOC &&
7848 	    sctp_style(sk, UDP)) {
7849 		retval = -EINVAL;
7850 		goto out;
7851 	}
7852 
7853 	params.assoc_value = asoc ? asoc->peer.auth_capable
7854 				  : sctp_sk(sk)->ep->auth_enable;
7855 
7856 	if (put_user(len, optlen))
7857 		goto out;
7858 
7859 	if (copy_to_user(optval, &params, len))
7860 		goto out;
7861 
7862 	retval = 0;
7863 
7864 out:
7865 	return retval;
7866 }
7867 
sctp_getsockopt_ecn_supported(struct sock * sk,int len,char __user * optval,int __user * optlen)7868 static int sctp_getsockopt_ecn_supported(struct sock *sk, int len,
7869 					 char __user *optval,
7870 					 int __user *optlen)
7871 {
7872 	struct sctp_assoc_value params;
7873 	struct sctp_association *asoc;
7874 	int retval = -EFAULT;
7875 
7876 	if (len < sizeof(params)) {
7877 		retval = -EINVAL;
7878 		goto out;
7879 	}
7880 
7881 	len = sizeof(params);
7882 	if (copy_from_user(&params, optval, len))
7883 		goto out;
7884 
7885 	asoc = sctp_id2assoc(sk, params.assoc_id);
7886 	if (!asoc && params.assoc_id != SCTP_FUTURE_ASSOC &&
7887 	    sctp_style(sk, UDP)) {
7888 		retval = -EINVAL;
7889 		goto out;
7890 	}
7891 
7892 	params.assoc_value = asoc ? asoc->peer.ecn_capable
7893 				  : sctp_sk(sk)->ep->ecn_enable;
7894 
7895 	if (put_user(len, optlen))
7896 		goto out;
7897 
7898 	if (copy_to_user(optval, &params, len))
7899 		goto out;
7900 
7901 	retval = 0;
7902 
7903 out:
7904 	return retval;
7905 }
7906 
sctp_getsockopt_pf_expose(struct sock * sk,int len,char __user * optval,int __user * optlen)7907 static int sctp_getsockopt_pf_expose(struct sock *sk, int len,
7908 				     char __user *optval,
7909 				     int __user *optlen)
7910 {
7911 	struct sctp_assoc_value params;
7912 	struct sctp_association *asoc;
7913 	int retval = -EFAULT;
7914 
7915 	if (len < sizeof(params)) {
7916 		retval = -EINVAL;
7917 		goto out;
7918 	}
7919 
7920 	len = sizeof(params);
7921 	if (copy_from_user(&params, optval, len))
7922 		goto out;
7923 
7924 	asoc = sctp_id2assoc(sk, params.assoc_id);
7925 	if (!asoc && params.assoc_id != SCTP_FUTURE_ASSOC &&
7926 	    sctp_style(sk, UDP)) {
7927 		retval = -EINVAL;
7928 		goto out;
7929 	}
7930 
7931 	params.assoc_value = asoc ? asoc->pf_expose
7932 				  : sctp_sk(sk)->pf_expose;
7933 
7934 	if (put_user(len, optlen))
7935 		goto out;
7936 
7937 	if (copy_to_user(optval, &params, len))
7938 		goto out;
7939 
7940 	retval = 0;
7941 
7942 out:
7943 	return retval;
7944 }
7945 
sctp_getsockopt_encap_port(struct sock * sk,int len,char __user * optval,int __user * optlen)7946 static int sctp_getsockopt_encap_port(struct sock *sk, int len,
7947 				      char __user *optval, int __user *optlen)
7948 {
7949 	struct sctp_association *asoc;
7950 	struct sctp_udpencaps encap;
7951 	struct sctp_transport *t;
7952 	__be16 encap_port;
7953 
7954 	if (len < sizeof(encap))
7955 		return -EINVAL;
7956 
7957 	len = sizeof(encap);
7958 	if (copy_from_user(&encap, optval, len))
7959 		return -EFAULT;
7960 
7961 	/* If an address other than INADDR_ANY is specified, and
7962 	 * no transport is found, then the request is invalid.
7963 	 */
7964 	if (!sctp_is_any(sk, (union sctp_addr *)&encap.sue_address)) {
7965 		t = sctp_addr_id2transport(sk, &encap.sue_address,
7966 					   encap.sue_assoc_id);
7967 		if (!t) {
7968 			pr_debug("%s: failed no transport\n", __func__);
7969 			return -EINVAL;
7970 		}
7971 
7972 		encap_port = t->encap_port;
7973 		goto out;
7974 	}
7975 
7976 	/* Get association, if assoc_id != SCTP_FUTURE_ASSOC and the
7977 	 * socket is a one to many style socket, and an association
7978 	 * was not found, then the id was invalid.
7979 	 */
7980 	asoc = sctp_id2assoc(sk, encap.sue_assoc_id);
7981 	if (!asoc && encap.sue_assoc_id != SCTP_FUTURE_ASSOC &&
7982 	    sctp_style(sk, UDP)) {
7983 		pr_debug("%s: failed no association\n", __func__);
7984 		return -EINVAL;
7985 	}
7986 
7987 	if (asoc) {
7988 		encap_port = asoc->encap_port;
7989 		goto out;
7990 	}
7991 
7992 	encap_port = sctp_sk(sk)->encap_port;
7993 
7994 out:
7995 	encap.sue_port = (__force uint16_t)encap_port;
7996 	if (copy_to_user(optval, &encap, len))
7997 		return -EFAULT;
7998 
7999 	if (put_user(len, optlen))
8000 		return -EFAULT;
8001 
8002 	return 0;
8003 }
8004 
sctp_getsockopt_probe_interval(struct sock * sk,int len,char __user * optval,int __user * optlen)8005 static int sctp_getsockopt_probe_interval(struct sock *sk, int len,
8006 					  char __user *optval,
8007 					  int __user *optlen)
8008 {
8009 	struct sctp_probeinterval params;
8010 	struct sctp_association *asoc;
8011 	struct sctp_transport *t;
8012 	__u32 probe_interval;
8013 
8014 	if (len < sizeof(params))
8015 		return -EINVAL;
8016 
8017 	len = sizeof(params);
8018 	if (copy_from_user(&params, optval, len))
8019 		return -EFAULT;
8020 
8021 	/* If an address other than INADDR_ANY is specified, and
8022 	 * no transport is found, then the request is invalid.
8023 	 */
8024 	if (!sctp_is_any(sk, (union sctp_addr *)&params.spi_address)) {
8025 		t = sctp_addr_id2transport(sk, &params.spi_address,
8026 					   params.spi_assoc_id);
8027 		if (!t) {
8028 			pr_debug("%s: failed no transport\n", __func__);
8029 			return -EINVAL;
8030 		}
8031 
8032 		probe_interval = jiffies_to_msecs(t->probe_interval);
8033 		goto out;
8034 	}
8035 
8036 	/* Get association, if assoc_id != SCTP_FUTURE_ASSOC and the
8037 	 * socket is a one to many style socket, and an association
8038 	 * was not found, then the id was invalid.
8039 	 */
8040 	asoc = sctp_id2assoc(sk, params.spi_assoc_id);
8041 	if (!asoc && params.spi_assoc_id != SCTP_FUTURE_ASSOC &&
8042 	    sctp_style(sk, UDP)) {
8043 		pr_debug("%s: failed no association\n", __func__);
8044 		return -EINVAL;
8045 	}
8046 
8047 	if (asoc) {
8048 		probe_interval = jiffies_to_msecs(asoc->probe_interval);
8049 		goto out;
8050 	}
8051 
8052 	probe_interval = sctp_sk(sk)->probe_interval;
8053 
8054 out:
8055 	params.spi_interval = probe_interval;
8056 	if (copy_to_user(optval, &params, len))
8057 		return -EFAULT;
8058 
8059 	if (put_user(len, optlen))
8060 		return -EFAULT;
8061 
8062 	return 0;
8063 }
8064 
sctp_getsockopt(struct sock * sk,int level,int optname,char __user * optval,int __user * optlen)8065 static int sctp_getsockopt(struct sock *sk, int level, int optname,
8066 			   char __user *optval, int __user *optlen)
8067 {
8068 	int retval = 0;
8069 	int len;
8070 
8071 	pr_debug("%s: sk:%p, optname:%d\n", __func__, sk, optname);
8072 
8073 	/* I can hardly begin to describe how wrong this is.  This is
8074 	 * so broken as to be worse than useless.  The API draft
8075 	 * REALLY is NOT helpful here...  I am not convinced that the
8076 	 * semantics of getsockopt() with a level OTHER THAN SOL_SCTP
8077 	 * are at all well-founded.
8078 	 */
8079 	if (level != SOL_SCTP) {
8080 		struct sctp_af *af = sctp_sk(sk)->pf->af;
8081 
8082 		retval = af->getsockopt(sk, level, optname, optval, optlen);
8083 		return retval;
8084 	}
8085 
8086 	if (get_user(len, optlen))
8087 		return -EFAULT;
8088 
8089 	if (len < 0)
8090 		return -EINVAL;
8091 
8092 	lock_sock(sk);
8093 
8094 	switch (optname) {
8095 	case SCTP_STATUS:
8096 		retval = sctp_getsockopt_sctp_status(sk, len, optval, optlen);
8097 		break;
8098 	case SCTP_DISABLE_FRAGMENTS:
8099 		retval = sctp_getsockopt_disable_fragments(sk, len, optval,
8100 							   optlen);
8101 		break;
8102 	case SCTP_EVENTS:
8103 		retval = sctp_getsockopt_events(sk, len, optval, optlen);
8104 		break;
8105 	case SCTP_AUTOCLOSE:
8106 		retval = sctp_getsockopt_autoclose(sk, len, optval, optlen);
8107 		break;
8108 	case SCTP_SOCKOPT_PEELOFF:
8109 		retval = sctp_getsockopt_peeloff(sk, len, optval, optlen);
8110 		break;
8111 	case SCTP_SOCKOPT_PEELOFF_FLAGS:
8112 		retval = sctp_getsockopt_peeloff_flags(sk, len, optval, optlen);
8113 		break;
8114 	case SCTP_PEER_ADDR_PARAMS:
8115 		retval = sctp_getsockopt_peer_addr_params(sk, len, optval,
8116 							  optlen);
8117 		break;
8118 	case SCTP_DELAYED_SACK:
8119 		retval = sctp_getsockopt_delayed_ack(sk, len, optval,
8120 							  optlen);
8121 		break;
8122 	case SCTP_INITMSG:
8123 		retval = sctp_getsockopt_initmsg(sk, len, optval, optlen);
8124 		break;
8125 	case SCTP_GET_PEER_ADDRS:
8126 		retval = sctp_getsockopt_peer_addrs(sk, len, optval,
8127 						    optlen);
8128 		break;
8129 	case SCTP_GET_LOCAL_ADDRS:
8130 		retval = sctp_getsockopt_local_addrs(sk, len, optval,
8131 						     optlen);
8132 		break;
8133 	case SCTP_SOCKOPT_CONNECTX3:
8134 		retval = sctp_getsockopt_connectx3(sk, len, optval, optlen);
8135 		break;
8136 	case SCTP_DEFAULT_SEND_PARAM:
8137 		retval = sctp_getsockopt_default_send_param(sk, len,
8138 							    optval, optlen);
8139 		break;
8140 	case SCTP_DEFAULT_SNDINFO:
8141 		retval = sctp_getsockopt_default_sndinfo(sk, len,
8142 							 optval, optlen);
8143 		break;
8144 	case SCTP_PRIMARY_ADDR:
8145 		retval = sctp_getsockopt_primary_addr(sk, len, optval, optlen);
8146 		break;
8147 	case SCTP_NODELAY:
8148 		retval = sctp_getsockopt_nodelay(sk, len, optval, optlen);
8149 		break;
8150 	case SCTP_RTOINFO:
8151 		retval = sctp_getsockopt_rtoinfo(sk, len, optval, optlen);
8152 		break;
8153 	case SCTP_ASSOCINFO:
8154 		retval = sctp_getsockopt_associnfo(sk, len, optval, optlen);
8155 		break;
8156 	case SCTP_I_WANT_MAPPED_V4_ADDR:
8157 		retval = sctp_getsockopt_mappedv4(sk, len, optval, optlen);
8158 		break;
8159 	case SCTP_MAXSEG:
8160 		retval = sctp_getsockopt_maxseg(sk, len, optval, optlen);
8161 		break;
8162 	case SCTP_GET_PEER_ADDR_INFO:
8163 		retval = sctp_getsockopt_peer_addr_info(sk, len, optval,
8164 							optlen);
8165 		break;
8166 	case SCTP_ADAPTATION_LAYER:
8167 		retval = sctp_getsockopt_adaptation_layer(sk, len, optval,
8168 							optlen);
8169 		break;
8170 	case SCTP_CONTEXT:
8171 		retval = sctp_getsockopt_context(sk, len, optval, optlen);
8172 		break;
8173 	case SCTP_FRAGMENT_INTERLEAVE:
8174 		retval = sctp_getsockopt_fragment_interleave(sk, len, optval,
8175 							     optlen);
8176 		break;
8177 	case SCTP_PARTIAL_DELIVERY_POINT:
8178 		retval = sctp_getsockopt_partial_delivery_point(sk, len, optval,
8179 								optlen);
8180 		break;
8181 	case SCTP_MAX_BURST:
8182 		retval = sctp_getsockopt_maxburst(sk, len, optval, optlen);
8183 		break;
8184 	case SCTP_AUTH_KEY:
8185 	case SCTP_AUTH_CHUNK:
8186 	case SCTP_AUTH_DELETE_KEY:
8187 	case SCTP_AUTH_DEACTIVATE_KEY:
8188 		retval = -EOPNOTSUPP;
8189 		break;
8190 	case SCTP_HMAC_IDENT:
8191 		retval = sctp_getsockopt_hmac_ident(sk, len, optval, optlen);
8192 		break;
8193 	case SCTP_AUTH_ACTIVE_KEY:
8194 		retval = sctp_getsockopt_active_key(sk, len, optval, optlen);
8195 		break;
8196 	case SCTP_PEER_AUTH_CHUNKS:
8197 		retval = sctp_getsockopt_peer_auth_chunks(sk, len, optval,
8198 							optlen);
8199 		break;
8200 	case SCTP_LOCAL_AUTH_CHUNKS:
8201 		retval = sctp_getsockopt_local_auth_chunks(sk, len, optval,
8202 							optlen);
8203 		break;
8204 	case SCTP_GET_ASSOC_NUMBER:
8205 		retval = sctp_getsockopt_assoc_number(sk, len, optval, optlen);
8206 		break;
8207 	case SCTP_GET_ASSOC_ID_LIST:
8208 		retval = sctp_getsockopt_assoc_ids(sk, len, optval, optlen);
8209 		break;
8210 	case SCTP_AUTO_ASCONF:
8211 		retval = sctp_getsockopt_auto_asconf(sk, len, optval, optlen);
8212 		break;
8213 	case SCTP_PEER_ADDR_THLDS:
8214 		retval = sctp_getsockopt_paddr_thresholds(sk, optval, len,
8215 							  optlen, false);
8216 		break;
8217 	case SCTP_PEER_ADDR_THLDS_V2:
8218 		retval = sctp_getsockopt_paddr_thresholds(sk, optval, len,
8219 							  optlen, true);
8220 		break;
8221 	case SCTP_GET_ASSOC_STATS:
8222 		retval = sctp_getsockopt_assoc_stats(sk, len, optval, optlen);
8223 		break;
8224 	case SCTP_RECVRCVINFO:
8225 		retval = sctp_getsockopt_recvrcvinfo(sk, len, optval, optlen);
8226 		break;
8227 	case SCTP_RECVNXTINFO:
8228 		retval = sctp_getsockopt_recvnxtinfo(sk, len, optval, optlen);
8229 		break;
8230 	case SCTP_PR_SUPPORTED:
8231 		retval = sctp_getsockopt_pr_supported(sk, len, optval, optlen);
8232 		break;
8233 	case SCTP_DEFAULT_PRINFO:
8234 		retval = sctp_getsockopt_default_prinfo(sk, len, optval,
8235 							optlen);
8236 		break;
8237 	case SCTP_PR_ASSOC_STATUS:
8238 		retval = sctp_getsockopt_pr_assocstatus(sk, len, optval,
8239 							optlen);
8240 		break;
8241 	case SCTP_PR_STREAM_STATUS:
8242 		retval = sctp_getsockopt_pr_streamstatus(sk, len, optval,
8243 							 optlen);
8244 		break;
8245 	case SCTP_RECONFIG_SUPPORTED:
8246 		retval = sctp_getsockopt_reconfig_supported(sk, len, optval,
8247 							    optlen);
8248 		break;
8249 	case SCTP_ENABLE_STREAM_RESET:
8250 		retval = sctp_getsockopt_enable_strreset(sk, len, optval,
8251 							 optlen);
8252 		break;
8253 	case SCTP_STREAM_SCHEDULER:
8254 		retval = sctp_getsockopt_scheduler(sk, len, optval,
8255 						   optlen);
8256 		break;
8257 	case SCTP_STREAM_SCHEDULER_VALUE:
8258 		retval = sctp_getsockopt_scheduler_value(sk, len, optval,
8259 							 optlen);
8260 		break;
8261 	case SCTP_INTERLEAVING_SUPPORTED:
8262 		retval = sctp_getsockopt_interleaving_supported(sk, len, optval,
8263 								optlen);
8264 		break;
8265 	case SCTP_REUSE_PORT:
8266 		retval = sctp_getsockopt_reuse_port(sk, len, optval, optlen);
8267 		break;
8268 	case SCTP_EVENT:
8269 		retval = sctp_getsockopt_event(sk, len, optval, optlen);
8270 		break;
8271 	case SCTP_ASCONF_SUPPORTED:
8272 		retval = sctp_getsockopt_asconf_supported(sk, len, optval,
8273 							  optlen);
8274 		break;
8275 	case SCTP_AUTH_SUPPORTED:
8276 		retval = sctp_getsockopt_auth_supported(sk, len, optval,
8277 							optlen);
8278 		break;
8279 	case SCTP_ECN_SUPPORTED:
8280 		retval = sctp_getsockopt_ecn_supported(sk, len, optval, optlen);
8281 		break;
8282 	case SCTP_EXPOSE_POTENTIALLY_FAILED_STATE:
8283 		retval = sctp_getsockopt_pf_expose(sk, len, optval, optlen);
8284 		break;
8285 	case SCTP_REMOTE_UDP_ENCAPS_PORT:
8286 		retval = sctp_getsockopt_encap_port(sk, len, optval, optlen);
8287 		break;
8288 	case SCTP_PLPMTUD_PROBE_INTERVAL:
8289 		retval = sctp_getsockopt_probe_interval(sk, len, optval, optlen);
8290 		break;
8291 	default:
8292 		retval = -ENOPROTOOPT;
8293 		break;
8294 	}
8295 
8296 	release_sock(sk);
8297 	return retval;
8298 }
8299 
sctp_bpf_bypass_getsockopt(int level,int optname)8300 static bool sctp_bpf_bypass_getsockopt(int level, int optname)
8301 {
8302 	if (level == SOL_SCTP) {
8303 		switch (optname) {
8304 		case SCTP_SOCKOPT_PEELOFF:
8305 		case SCTP_SOCKOPT_PEELOFF_FLAGS:
8306 		case SCTP_SOCKOPT_CONNECTX3:
8307 			return true;
8308 		default:
8309 			return false;
8310 		}
8311 	}
8312 
8313 	return false;
8314 }
8315 
sctp_hash(struct sock * sk)8316 static int sctp_hash(struct sock *sk)
8317 {
8318 	/* STUB */
8319 	return 0;
8320 }
8321 
sctp_unhash(struct sock * sk)8322 static void sctp_unhash(struct sock *sk)
8323 {
8324 	/* STUB */
8325 }
8326 
8327 /* Check if port is acceptable.  Possibly find first available port.
8328  *
8329  * The port hash table (contained in the 'global' SCTP protocol storage
8330  * returned by struct sctp_protocol *sctp_get_protocol()). The hash
8331  * table is an array of 4096 lists (sctp_bind_hashbucket). Each
8332  * list (the list number is the port number hashed out, so as you
8333  * would expect from a hash function, all the ports in a given list have
8334  * such a number that hashes out to the same list number; you were
8335  * expecting that, right?); so each list has a set of ports, with a
8336  * link to the socket (struct sock) that uses it, the port number and
8337  * a fastreuse flag (FIXME: NPI ipg).
8338  */
8339 static struct sctp_bind_bucket *sctp_bucket_create(
8340 	struct sctp_bind_hashbucket *head, struct net *, unsigned short snum);
8341 
sctp_get_port_local(struct sock * sk,union sctp_addr * addr)8342 static int sctp_get_port_local(struct sock *sk, union sctp_addr *addr)
8343 {
8344 	struct sctp_sock *sp = sctp_sk(sk);
8345 	bool reuse = (sk->sk_reuse || sp->reuse);
8346 	struct sctp_bind_hashbucket *head; /* hash list */
8347 	struct net *net = sock_net(sk);
8348 	kuid_t uid = sock_i_uid(sk);
8349 	struct sctp_bind_bucket *pp;
8350 	unsigned short snum;
8351 	int ret;
8352 
8353 	snum = ntohs(addr->v4.sin_port);
8354 
8355 	pr_debug("%s: begins, snum:%d\n", __func__, snum);
8356 
8357 	if (snum == 0) {
8358 		/* Search for an available port. */
8359 		int low, high, remaining, index;
8360 		unsigned int rover;
8361 
8362 		inet_sk_get_local_port_range(sk, &low, &high);
8363 		remaining = (high - low) + 1;
8364 		rover = get_random_u32_below(remaining) + low;
8365 
8366 		do {
8367 			rover++;
8368 			if ((rover < low) || (rover > high))
8369 				rover = low;
8370 			if (inet_is_local_reserved_port(net, rover))
8371 				continue;
8372 			index = sctp_phashfn(net, rover);
8373 			head = &sctp_port_hashtable[index];
8374 			spin_lock_bh(&head->lock);
8375 			sctp_for_each_hentry(pp, &head->chain)
8376 				if ((pp->port == rover) &&
8377 				    net_eq(net, pp->net))
8378 					goto next;
8379 			break;
8380 		next:
8381 			spin_unlock_bh(&head->lock);
8382 			cond_resched();
8383 		} while (--remaining > 0);
8384 
8385 		/* Exhausted local port range during search? */
8386 		ret = 1;
8387 		if (remaining <= 0)
8388 			return ret;
8389 
8390 		/* OK, here is the one we will use.  HEAD (the port
8391 		 * hash table list entry) is non-NULL and we hold it's
8392 		 * mutex.
8393 		 */
8394 		snum = rover;
8395 	} else {
8396 		/* We are given an specific port number; we verify
8397 		 * that it is not being used. If it is used, we will
8398 		 * exahust the search in the hash list corresponding
8399 		 * to the port number (snum) - we detect that with the
8400 		 * port iterator, pp being NULL.
8401 		 */
8402 		head = &sctp_port_hashtable[sctp_phashfn(net, snum)];
8403 		spin_lock_bh(&head->lock);
8404 		sctp_for_each_hentry(pp, &head->chain) {
8405 			if ((pp->port == snum) && net_eq(pp->net, net))
8406 				goto pp_found;
8407 		}
8408 	}
8409 	pp = NULL;
8410 	goto pp_not_found;
8411 pp_found:
8412 	if (!hlist_empty(&pp->owner)) {
8413 		/* We had a port hash table hit - there is an
8414 		 * available port (pp != NULL) and it is being
8415 		 * used by other socket (pp->owner not empty); that other
8416 		 * socket is going to be sk2.
8417 		 */
8418 		struct sock *sk2;
8419 
8420 		pr_debug("%s: found a possible match\n", __func__);
8421 
8422 		if ((pp->fastreuse && reuse &&
8423 		     sk->sk_state != SCTP_SS_LISTENING) ||
8424 		    (pp->fastreuseport && sk->sk_reuseport &&
8425 		     uid_eq(pp->fastuid, uid)))
8426 			goto success;
8427 
8428 		/* Run through the list of sockets bound to the port
8429 		 * (pp->port) [via the pointers bind_next and
8430 		 * bind_pprev in the struct sock *sk2 (pp->sk)]. On each one,
8431 		 * we get the endpoint they describe and run through
8432 		 * the endpoint's list of IP (v4 or v6) addresses,
8433 		 * comparing each of the addresses with the address of
8434 		 * the socket sk. If we find a match, then that means
8435 		 * that this port/socket (sk) combination are already
8436 		 * in an endpoint.
8437 		 */
8438 		sk_for_each_bound(sk2, &pp->owner) {
8439 			int bound_dev_if2 = READ_ONCE(sk2->sk_bound_dev_if);
8440 			struct sctp_sock *sp2 = sctp_sk(sk2);
8441 			struct sctp_endpoint *ep2 = sp2->ep;
8442 
8443 			if (sk == sk2 ||
8444 			    (reuse && (sk2->sk_reuse || sp2->reuse) &&
8445 			     sk2->sk_state != SCTP_SS_LISTENING) ||
8446 			    (sk->sk_reuseport && sk2->sk_reuseport &&
8447 			     uid_eq(uid, sock_i_uid(sk2))))
8448 				continue;
8449 
8450 			if ((!sk->sk_bound_dev_if || !bound_dev_if2 ||
8451 			     sk->sk_bound_dev_if == bound_dev_if2) &&
8452 			    sctp_bind_addr_conflict(&ep2->base.bind_addr,
8453 						    addr, sp2, sp)) {
8454 				ret = 1;
8455 				goto fail_unlock;
8456 			}
8457 		}
8458 
8459 		pr_debug("%s: found a match\n", __func__);
8460 	}
8461 pp_not_found:
8462 	/* If there was a hash table miss, create a new port.  */
8463 	ret = 1;
8464 	if (!pp && !(pp = sctp_bucket_create(head, net, snum)))
8465 		goto fail_unlock;
8466 
8467 	/* In either case (hit or miss), make sure fastreuse is 1 only
8468 	 * if sk->sk_reuse is too (that is, if the caller requested
8469 	 * SO_REUSEADDR on this socket -sk-).
8470 	 */
8471 	if (hlist_empty(&pp->owner)) {
8472 		if (reuse && sk->sk_state != SCTP_SS_LISTENING)
8473 			pp->fastreuse = 1;
8474 		else
8475 			pp->fastreuse = 0;
8476 
8477 		if (sk->sk_reuseport) {
8478 			pp->fastreuseport = 1;
8479 			pp->fastuid = uid;
8480 		} else {
8481 			pp->fastreuseport = 0;
8482 		}
8483 	} else {
8484 		if (pp->fastreuse &&
8485 		    (!reuse || sk->sk_state == SCTP_SS_LISTENING))
8486 			pp->fastreuse = 0;
8487 
8488 		if (pp->fastreuseport &&
8489 		    (!sk->sk_reuseport || !uid_eq(pp->fastuid, uid)))
8490 			pp->fastreuseport = 0;
8491 	}
8492 
8493 	/* We are set, so fill up all the data in the hash table
8494 	 * entry, tie the socket list information with the rest of the
8495 	 * sockets FIXME: Blurry, NPI (ipg).
8496 	 */
8497 success:
8498 	if (!sp->bind_hash) {
8499 		inet_sk(sk)->inet_num = snum;
8500 		sk_add_bind_node(sk, &pp->owner);
8501 		sp->bind_hash = pp;
8502 	}
8503 	ret = 0;
8504 
8505 fail_unlock:
8506 	spin_unlock_bh(&head->lock);
8507 	return ret;
8508 }
8509 
8510 /* Assign a 'snum' port to the socket.  If snum == 0, an ephemeral
8511  * port is requested.
8512  */
sctp_get_port(struct sock * sk,unsigned short snum)8513 static int sctp_get_port(struct sock *sk, unsigned short snum)
8514 {
8515 	union sctp_addr addr;
8516 	struct sctp_af *af = sctp_sk(sk)->pf->af;
8517 
8518 	/* Set up a dummy address struct from the sk. */
8519 	af->from_sk(&addr, sk);
8520 	addr.v4.sin_port = htons(snum);
8521 
8522 	/* Note: sk->sk_num gets filled in if ephemeral port request. */
8523 	return sctp_get_port_local(sk, &addr);
8524 }
8525 
8526 /*
8527  *  Move a socket to LISTENING state.
8528  */
sctp_listen_start(struct sock * sk,int backlog)8529 static int sctp_listen_start(struct sock *sk, int backlog)
8530 {
8531 	struct sctp_sock *sp = sctp_sk(sk);
8532 	struct sctp_endpoint *ep = sp->ep;
8533 	struct crypto_shash *tfm = NULL;
8534 	char alg[32];
8535 	int err;
8536 
8537 	/* Allocate HMAC for generating cookie. */
8538 	if (!sp->hmac && sp->sctp_hmac_alg) {
8539 		sprintf(alg, "hmac(%s)", sp->sctp_hmac_alg);
8540 		tfm = crypto_alloc_shash(alg, 0, 0);
8541 		if (IS_ERR(tfm)) {
8542 			net_info_ratelimited("failed to load transform for %s: %ld\n",
8543 					     sp->sctp_hmac_alg, PTR_ERR(tfm));
8544 			return -ENOSYS;
8545 		}
8546 		sctp_sk(sk)->hmac = tfm;
8547 	}
8548 
8549 	/*
8550 	 * If a bind() or sctp_bindx() is not called prior to a listen()
8551 	 * call that allows new associations to be accepted, the system
8552 	 * picks an ephemeral port and will choose an address set equivalent
8553 	 * to binding with a wildcard address.
8554 	 *
8555 	 * This is not currently spelled out in the SCTP sockets
8556 	 * extensions draft, but follows the practice as seen in TCP
8557 	 * sockets.
8558 	 *
8559 	 */
8560 	inet_sk_set_state(sk, SCTP_SS_LISTENING);
8561 	if (!ep->base.bind_addr.port) {
8562 		if (sctp_autobind(sk)) {
8563 			err = -EAGAIN;
8564 			goto err;
8565 		}
8566 	} else {
8567 		if (sctp_get_port(sk, inet_sk(sk)->inet_num)) {
8568 			err = -EADDRINUSE;
8569 			goto err;
8570 		}
8571 	}
8572 
8573 	WRITE_ONCE(sk->sk_max_ack_backlog, backlog);
8574 	err = sctp_hash_endpoint(ep);
8575 	if (err)
8576 		goto err;
8577 
8578 	return 0;
8579 err:
8580 	inet_sk_set_state(sk, SCTP_SS_CLOSED);
8581 	return err;
8582 }
8583 
8584 /*
8585  * 4.1.3 / 5.1.3 listen()
8586  *
8587  *   By default, new associations are not accepted for UDP style sockets.
8588  *   An application uses listen() to mark a socket as being able to
8589  *   accept new associations.
8590  *
8591  *   On TCP style sockets, applications use listen() to ready the SCTP
8592  *   endpoint for accepting inbound associations.
8593  *
8594  *   On both types of endpoints a backlog of '0' disables listening.
8595  *
8596  *  Move a socket to LISTENING state.
8597  */
sctp_inet_listen(struct socket * sock,int backlog)8598 int sctp_inet_listen(struct socket *sock, int backlog)
8599 {
8600 	struct sock *sk = sock->sk;
8601 	struct sctp_endpoint *ep = sctp_sk(sk)->ep;
8602 	int err = -EINVAL;
8603 
8604 	if (unlikely(backlog < 0))
8605 		return err;
8606 
8607 	lock_sock(sk);
8608 
8609 	/* Peeled-off sockets are not allowed to listen().  */
8610 	if (sctp_style(sk, UDP_HIGH_BANDWIDTH))
8611 		goto out;
8612 
8613 	if (sock->state != SS_UNCONNECTED)
8614 		goto out;
8615 
8616 	if (!sctp_sstate(sk, LISTENING) && !sctp_sstate(sk, CLOSED))
8617 		goto out;
8618 
8619 	/* If backlog is zero, disable listening. */
8620 	if (!backlog) {
8621 		if (sctp_sstate(sk, CLOSED))
8622 			goto out;
8623 
8624 		err = 0;
8625 		sctp_unhash_endpoint(ep);
8626 		sk->sk_state = SCTP_SS_CLOSED;
8627 		if (sk->sk_reuse || sctp_sk(sk)->reuse)
8628 			sctp_sk(sk)->bind_hash->fastreuse = 1;
8629 		goto out;
8630 	}
8631 
8632 	/* If we are already listening, just update the backlog */
8633 	if (sctp_sstate(sk, LISTENING))
8634 		WRITE_ONCE(sk->sk_max_ack_backlog, backlog);
8635 	else {
8636 		err = sctp_listen_start(sk, backlog);
8637 		if (err)
8638 			goto out;
8639 	}
8640 
8641 	err = 0;
8642 out:
8643 	release_sock(sk);
8644 	return err;
8645 }
8646 
8647 /*
8648  * This function is done by modeling the current datagram_poll() and the
8649  * tcp_poll().  Note that, based on these implementations, we don't
8650  * lock the socket in this function, even though it seems that,
8651  * ideally, locking or some other mechanisms can be used to ensure
8652  * the integrity of the counters (sndbuf and wmem_alloc) used
8653  * in this place.  We assume that we don't need locks either until proven
8654  * otherwise.
8655  *
8656  * Another thing to note is that we include the Async I/O support
8657  * here, again, by modeling the current TCP/UDP code.  We don't have
8658  * a good way to test with it yet.
8659  */
sctp_poll(struct file * file,struct socket * sock,poll_table * wait)8660 __poll_t sctp_poll(struct file *file, struct socket *sock, poll_table *wait)
8661 {
8662 	struct sock *sk = sock->sk;
8663 	struct sctp_sock *sp = sctp_sk(sk);
8664 	__poll_t mask;
8665 
8666 	poll_wait(file, sk_sleep(sk), wait);
8667 
8668 	sock_rps_record_flow(sk);
8669 
8670 	/* A TCP-style listening socket becomes readable when the accept queue
8671 	 * is not empty.
8672 	 */
8673 	if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING))
8674 		return (!list_empty(&sp->ep->asocs)) ?
8675 			(EPOLLIN | EPOLLRDNORM) : 0;
8676 
8677 	mask = 0;
8678 
8679 	/* Is there any exceptional events?  */
8680 	if (sk->sk_err || !skb_queue_empty_lockless(&sk->sk_error_queue))
8681 		mask |= EPOLLERR |
8682 			(sock_flag(sk, SOCK_SELECT_ERR_QUEUE) ? EPOLLPRI : 0);
8683 	if (sk->sk_shutdown & RCV_SHUTDOWN)
8684 		mask |= EPOLLRDHUP | EPOLLIN | EPOLLRDNORM;
8685 	if (sk->sk_shutdown == SHUTDOWN_MASK)
8686 		mask |= EPOLLHUP;
8687 
8688 	/* Is it readable?  Reconsider this code with TCP-style support.  */
8689 	if (!skb_queue_empty_lockless(&sk->sk_receive_queue))
8690 		mask |= EPOLLIN | EPOLLRDNORM;
8691 
8692 	/* The association is either gone or not ready.  */
8693 	if (!sctp_style(sk, UDP) && sctp_sstate(sk, CLOSED))
8694 		return mask;
8695 
8696 	/* Is it writable?  */
8697 	if (sctp_writeable(sk)) {
8698 		mask |= EPOLLOUT | EPOLLWRNORM;
8699 	} else {
8700 		sk_set_bit(SOCKWQ_ASYNC_NOSPACE, sk);
8701 		/*
8702 		 * Since the socket is not locked, the buffer
8703 		 * might be made available after the writeable check and
8704 		 * before the bit is set.  This could cause a lost I/O
8705 		 * signal.  tcp_poll() has a race breaker for this race
8706 		 * condition.  Based on their implementation, we put
8707 		 * in the following code to cover it as well.
8708 		 */
8709 		if (sctp_writeable(sk))
8710 			mask |= EPOLLOUT | EPOLLWRNORM;
8711 	}
8712 	return mask;
8713 }
8714 
8715 /********************************************************************
8716  * 2nd Level Abstractions
8717  ********************************************************************/
8718 
sctp_bucket_create(struct sctp_bind_hashbucket * head,struct net * net,unsigned short snum)8719 static struct sctp_bind_bucket *sctp_bucket_create(
8720 	struct sctp_bind_hashbucket *head, struct net *net, unsigned short snum)
8721 {
8722 	struct sctp_bind_bucket *pp;
8723 
8724 	pp = kmem_cache_alloc(sctp_bucket_cachep, GFP_ATOMIC);
8725 	if (pp) {
8726 		SCTP_DBG_OBJCNT_INC(bind_bucket);
8727 		pp->port = snum;
8728 		pp->fastreuse = 0;
8729 		INIT_HLIST_HEAD(&pp->owner);
8730 		pp->net = net;
8731 		hlist_add_head(&pp->node, &head->chain);
8732 	}
8733 	return pp;
8734 }
8735 
8736 /* Caller must hold hashbucket lock for this tb with local BH disabled */
sctp_bucket_destroy(struct sctp_bind_bucket * pp)8737 static void sctp_bucket_destroy(struct sctp_bind_bucket *pp)
8738 {
8739 	if (pp && hlist_empty(&pp->owner)) {
8740 		__hlist_del(&pp->node);
8741 		kmem_cache_free(sctp_bucket_cachep, pp);
8742 		SCTP_DBG_OBJCNT_DEC(bind_bucket);
8743 	}
8744 }
8745 
8746 /* Release this socket's reference to a local port.  */
__sctp_put_port(struct sock * sk)8747 static inline void __sctp_put_port(struct sock *sk)
8748 {
8749 	struct sctp_bind_hashbucket *head =
8750 		&sctp_port_hashtable[sctp_phashfn(sock_net(sk),
8751 						  inet_sk(sk)->inet_num)];
8752 	struct sctp_bind_bucket *pp;
8753 
8754 	spin_lock(&head->lock);
8755 	pp = sctp_sk(sk)->bind_hash;
8756 	__sk_del_bind_node(sk);
8757 	sctp_sk(sk)->bind_hash = NULL;
8758 	inet_sk(sk)->inet_num = 0;
8759 	sctp_bucket_destroy(pp);
8760 	spin_unlock(&head->lock);
8761 }
8762 
sctp_put_port(struct sock * sk)8763 void sctp_put_port(struct sock *sk)
8764 {
8765 	local_bh_disable();
8766 	__sctp_put_port(sk);
8767 	local_bh_enable();
8768 }
8769 
8770 /*
8771  * The system picks an ephemeral port and choose an address set equivalent
8772  * to binding with a wildcard address.
8773  * One of those addresses will be the primary address for the association.
8774  * This automatically enables the multihoming capability of SCTP.
8775  */
sctp_autobind(struct sock * sk)8776 static int sctp_autobind(struct sock *sk)
8777 {
8778 	union sctp_addr autoaddr;
8779 	struct sctp_af *af;
8780 	__be16 port;
8781 
8782 	/* Initialize a local sockaddr structure to INADDR_ANY. */
8783 	af = sctp_sk(sk)->pf->af;
8784 
8785 	port = htons(inet_sk(sk)->inet_num);
8786 	af->inaddr_any(&autoaddr, port);
8787 
8788 	return sctp_do_bind(sk, &autoaddr, af->sockaddr_len);
8789 }
8790 
8791 /* Parse out IPPROTO_SCTP CMSG headers.  Perform only minimal validation.
8792  *
8793  * From RFC 2292
8794  * 4.2 The cmsghdr Structure *
8795  *
8796  * When ancillary data is sent or received, any number of ancillary data
8797  * objects can be specified by the msg_control and msg_controllen members of
8798  * the msghdr structure, because each object is preceded by
8799  * a cmsghdr structure defining the object's length (the cmsg_len member).
8800  * Historically Berkeley-derived implementations have passed only one object
8801  * at a time, but this API allows multiple objects to be
8802  * passed in a single call to sendmsg() or recvmsg(). The following example
8803  * shows two ancillary data objects in a control buffer.
8804  *
8805  *   |<--------------------------- msg_controllen -------------------------->|
8806  *   |                                                                       |
8807  *
8808  *   |<----- ancillary data object ----->|<----- ancillary data object ----->|
8809  *
8810  *   |<---------- CMSG_SPACE() --------->|<---------- CMSG_SPACE() --------->|
8811  *   |                                   |                                   |
8812  *
8813  *   |<---------- cmsg_len ---------->|  |<--------- cmsg_len ----------->|  |
8814  *
8815  *   |<--------- CMSG_LEN() --------->|  |<-------- CMSG_LEN() ---------->|  |
8816  *   |                                |  |                                |  |
8817  *
8818  *   +-----+-----+-----+--+-----------+--+-----+-----+-----+--+-----------+--+
8819  *   |cmsg_|cmsg_|cmsg_|XX|           |XX|cmsg_|cmsg_|cmsg_|XX|           |XX|
8820  *
8821  *   |len  |level|type |XX|cmsg_data[]|XX|len  |level|type |XX|cmsg_data[]|XX|
8822  *
8823  *   +-----+-----+-----+--+-----------+--+-----+-----+-----+--+-----------+--+
8824  *    ^
8825  *    |
8826  *
8827  * msg_control
8828  * points here
8829  */
sctp_msghdr_parse(const struct msghdr * msg,struct sctp_cmsgs * cmsgs)8830 static int sctp_msghdr_parse(const struct msghdr *msg, struct sctp_cmsgs *cmsgs)
8831 {
8832 	struct msghdr *my_msg = (struct msghdr *)msg;
8833 	struct cmsghdr *cmsg;
8834 
8835 	for_each_cmsghdr(cmsg, my_msg) {
8836 		if (!CMSG_OK(my_msg, cmsg))
8837 			return -EINVAL;
8838 
8839 		/* Should we parse this header or ignore?  */
8840 		if (cmsg->cmsg_level != IPPROTO_SCTP)
8841 			continue;
8842 
8843 		/* Strictly check lengths following example in SCM code.  */
8844 		switch (cmsg->cmsg_type) {
8845 		case SCTP_INIT:
8846 			/* SCTP Socket API Extension
8847 			 * 5.3.1 SCTP Initiation Structure (SCTP_INIT)
8848 			 *
8849 			 * This cmsghdr structure provides information for
8850 			 * initializing new SCTP associations with sendmsg().
8851 			 * The SCTP_INITMSG socket option uses this same data
8852 			 * structure.  This structure is not used for
8853 			 * recvmsg().
8854 			 *
8855 			 * cmsg_level    cmsg_type      cmsg_data[]
8856 			 * ------------  ------------   ----------------------
8857 			 * IPPROTO_SCTP  SCTP_INIT      struct sctp_initmsg
8858 			 */
8859 			if (cmsg->cmsg_len != CMSG_LEN(sizeof(struct sctp_initmsg)))
8860 				return -EINVAL;
8861 
8862 			cmsgs->init = CMSG_DATA(cmsg);
8863 			break;
8864 
8865 		case SCTP_SNDRCV:
8866 			/* SCTP Socket API Extension
8867 			 * 5.3.2 SCTP Header Information Structure(SCTP_SNDRCV)
8868 			 *
8869 			 * This cmsghdr structure specifies SCTP options for
8870 			 * sendmsg() and describes SCTP header information
8871 			 * about a received message through recvmsg().
8872 			 *
8873 			 * cmsg_level    cmsg_type      cmsg_data[]
8874 			 * ------------  ------------   ----------------------
8875 			 * IPPROTO_SCTP  SCTP_SNDRCV    struct sctp_sndrcvinfo
8876 			 */
8877 			if (cmsg->cmsg_len != CMSG_LEN(sizeof(struct sctp_sndrcvinfo)))
8878 				return -EINVAL;
8879 
8880 			cmsgs->srinfo = CMSG_DATA(cmsg);
8881 
8882 			if (cmsgs->srinfo->sinfo_flags &
8883 			    ~(SCTP_UNORDERED | SCTP_ADDR_OVER |
8884 			      SCTP_SACK_IMMEDIATELY | SCTP_SENDALL |
8885 			      SCTP_PR_SCTP_MASK | SCTP_ABORT | SCTP_EOF))
8886 				return -EINVAL;
8887 			break;
8888 
8889 		case SCTP_SNDINFO:
8890 			/* SCTP Socket API Extension
8891 			 * 5.3.4 SCTP Send Information Structure (SCTP_SNDINFO)
8892 			 *
8893 			 * This cmsghdr structure specifies SCTP options for
8894 			 * sendmsg(). This structure and SCTP_RCVINFO replaces
8895 			 * SCTP_SNDRCV which has been deprecated.
8896 			 *
8897 			 * cmsg_level    cmsg_type      cmsg_data[]
8898 			 * ------------  ------------   ---------------------
8899 			 * IPPROTO_SCTP  SCTP_SNDINFO    struct sctp_sndinfo
8900 			 */
8901 			if (cmsg->cmsg_len != CMSG_LEN(sizeof(struct sctp_sndinfo)))
8902 				return -EINVAL;
8903 
8904 			cmsgs->sinfo = CMSG_DATA(cmsg);
8905 
8906 			if (cmsgs->sinfo->snd_flags &
8907 			    ~(SCTP_UNORDERED | SCTP_ADDR_OVER |
8908 			      SCTP_SACK_IMMEDIATELY | SCTP_SENDALL |
8909 			      SCTP_PR_SCTP_MASK | SCTP_ABORT | SCTP_EOF))
8910 				return -EINVAL;
8911 			break;
8912 		case SCTP_PRINFO:
8913 			/* SCTP Socket API Extension
8914 			 * 5.3.7 SCTP PR-SCTP Information Structure (SCTP_PRINFO)
8915 			 *
8916 			 * This cmsghdr structure specifies SCTP options for sendmsg().
8917 			 *
8918 			 * cmsg_level    cmsg_type      cmsg_data[]
8919 			 * ------------  ------------   ---------------------
8920 			 * IPPROTO_SCTP  SCTP_PRINFO    struct sctp_prinfo
8921 			 */
8922 			if (cmsg->cmsg_len != CMSG_LEN(sizeof(struct sctp_prinfo)))
8923 				return -EINVAL;
8924 
8925 			cmsgs->prinfo = CMSG_DATA(cmsg);
8926 			if (cmsgs->prinfo->pr_policy & ~SCTP_PR_SCTP_MASK)
8927 				return -EINVAL;
8928 
8929 			if (cmsgs->prinfo->pr_policy == SCTP_PR_SCTP_NONE)
8930 				cmsgs->prinfo->pr_value = 0;
8931 			break;
8932 		case SCTP_AUTHINFO:
8933 			/* SCTP Socket API Extension
8934 			 * 5.3.8 SCTP AUTH Information Structure (SCTP_AUTHINFO)
8935 			 *
8936 			 * This cmsghdr structure specifies SCTP options for sendmsg().
8937 			 *
8938 			 * cmsg_level    cmsg_type      cmsg_data[]
8939 			 * ------------  ------------   ---------------------
8940 			 * IPPROTO_SCTP  SCTP_AUTHINFO  struct sctp_authinfo
8941 			 */
8942 			if (cmsg->cmsg_len != CMSG_LEN(sizeof(struct sctp_authinfo)))
8943 				return -EINVAL;
8944 
8945 			cmsgs->authinfo = CMSG_DATA(cmsg);
8946 			break;
8947 		case SCTP_DSTADDRV4:
8948 		case SCTP_DSTADDRV6:
8949 			/* SCTP Socket API Extension
8950 			 * 5.3.9/10 SCTP Destination IPv4/6 Address Structure (SCTP_DSTADDRV4/6)
8951 			 *
8952 			 * This cmsghdr structure specifies SCTP options for sendmsg().
8953 			 *
8954 			 * cmsg_level    cmsg_type         cmsg_data[]
8955 			 * ------------  ------------   ---------------------
8956 			 * IPPROTO_SCTP  SCTP_DSTADDRV4 struct in_addr
8957 			 * ------------  ------------   ---------------------
8958 			 * IPPROTO_SCTP  SCTP_DSTADDRV6 struct in6_addr
8959 			 */
8960 			cmsgs->addrs_msg = my_msg;
8961 			break;
8962 		default:
8963 			return -EINVAL;
8964 		}
8965 	}
8966 
8967 	return 0;
8968 }
8969 
8970 /*
8971  * Wait for a packet..
8972  * Note: This function is the same function as in core/datagram.c
8973  * with a few modifications to make lksctp work.
8974  */
sctp_wait_for_packet(struct sock * sk,int * err,long * timeo_p)8975 static int sctp_wait_for_packet(struct sock *sk, int *err, long *timeo_p)
8976 {
8977 	int error;
8978 	DEFINE_WAIT(wait);
8979 
8980 	prepare_to_wait_exclusive(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
8981 
8982 	/* Socket errors? */
8983 	error = sock_error(sk);
8984 	if (error)
8985 		goto out;
8986 
8987 	if (!skb_queue_empty(&sk->sk_receive_queue))
8988 		goto ready;
8989 
8990 	/* Socket shut down?  */
8991 	if (sk->sk_shutdown & RCV_SHUTDOWN)
8992 		goto out;
8993 
8994 	/* Sequenced packets can come disconnected.  If so we report the
8995 	 * problem.
8996 	 */
8997 	error = -ENOTCONN;
8998 
8999 	/* Is there a good reason to think that we may receive some data?  */
9000 	if (list_empty(&sctp_sk(sk)->ep->asocs) && !sctp_sstate(sk, LISTENING))
9001 		goto out;
9002 
9003 	/* Handle signals.  */
9004 	if (signal_pending(current))
9005 		goto interrupted;
9006 
9007 	/* Let another process have a go.  Since we are going to sleep
9008 	 * anyway.  Note: This may cause odd behaviors if the message
9009 	 * does not fit in the user's buffer, but this seems to be the
9010 	 * only way to honor MSG_DONTWAIT realistically.
9011 	 */
9012 	release_sock(sk);
9013 	*timeo_p = schedule_timeout(*timeo_p);
9014 	lock_sock(sk);
9015 
9016 ready:
9017 	finish_wait(sk_sleep(sk), &wait);
9018 	return 0;
9019 
9020 interrupted:
9021 	error = sock_intr_errno(*timeo_p);
9022 
9023 out:
9024 	finish_wait(sk_sleep(sk), &wait);
9025 	*err = error;
9026 	return error;
9027 }
9028 
9029 /* Receive a datagram.
9030  * Note: This is pretty much the same routine as in core/datagram.c
9031  * with a few changes to make lksctp work.
9032  */
sctp_skb_recv_datagram(struct sock * sk,int flags,int * err)9033 struct sk_buff *sctp_skb_recv_datagram(struct sock *sk, int flags, int *err)
9034 {
9035 	int error;
9036 	struct sk_buff *skb;
9037 	long timeo;
9038 
9039 	timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
9040 
9041 	pr_debug("%s: timeo:%ld, max:%ld\n", __func__, timeo,
9042 		 MAX_SCHEDULE_TIMEOUT);
9043 
9044 	do {
9045 		/* Again only user level code calls this function,
9046 		 * so nothing interrupt level
9047 		 * will suddenly eat the receive_queue.
9048 		 *
9049 		 *  Look at current nfs client by the way...
9050 		 *  However, this function was correct in any case. 8)
9051 		 */
9052 		if (flags & MSG_PEEK) {
9053 			skb = skb_peek(&sk->sk_receive_queue);
9054 			if (skb)
9055 				refcount_inc(&skb->users);
9056 		} else {
9057 			skb = __skb_dequeue(&sk->sk_receive_queue);
9058 		}
9059 
9060 		if (skb)
9061 			return skb;
9062 
9063 		/* Caller is allowed not to check sk->sk_err before calling. */
9064 		error = sock_error(sk);
9065 		if (error)
9066 			goto no_packet;
9067 
9068 		if (sk->sk_shutdown & RCV_SHUTDOWN)
9069 			break;
9070 
9071 
9072 		/* User doesn't want to wait.  */
9073 		error = -EAGAIN;
9074 		if (!timeo)
9075 			goto no_packet;
9076 	} while (sctp_wait_for_packet(sk, err, &timeo) == 0);
9077 
9078 	return NULL;
9079 
9080 no_packet:
9081 	*err = error;
9082 	return NULL;
9083 }
9084 
9085 /* If sndbuf has changed, wake up per association sndbuf waiters.  */
__sctp_write_space(struct sctp_association * asoc)9086 static void __sctp_write_space(struct sctp_association *asoc)
9087 {
9088 	struct sock *sk = asoc->base.sk;
9089 
9090 	if (sctp_wspace(asoc) <= 0)
9091 		return;
9092 
9093 	if (waitqueue_active(&asoc->wait))
9094 		wake_up_interruptible(&asoc->wait);
9095 
9096 	if (sctp_writeable(sk)) {
9097 		struct socket_wq *wq;
9098 
9099 		rcu_read_lock();
9100 		wq = rcu_dereference(sk->sk_wq);
9101 		if (wq) {
9102 			if (waitqueue_active(&wq->wait))
9103 				wake_up_interruptible(&wq->wait);
9104 
9105 			/* Note that we try to include the Async I/O support
9106 			 * here by modeling from the current TCP/UDP code.
9107 			 * We have not tested with it yet.
9108 			 */
9109 			if (!(sk->sk_shutdown & SEND_SHUTDOWN))
9110 				sock_wake_async(wq, SOCK_WAKE_SPACE, POLL_OUT);
9111 		}
9112 		rcu_read_unlock();
9113 	}
9114 }
9115 
sctp_wake_up_waiters(struct sock * sk,struct sctp_association * asoc)9116 static void sctp_wake_up_waiters(struct sock *sk,
9117 				 struct sctp_association *asoc)
9118 {
9119 	struct sctp_association *tmp = asoc;
9120 
9121 	/* We do accounting for the sndbuf space per association,
9122 	 * so we only need to wake our own association.
9123 	 */
9124 	if (asoc->ep->sndbuf_policy)
9125 		return __sctp_write_space(asoc);
9126 
9127 	/* If association goes down and is just flushing its
9128 	 * outq, then just normally notify others.
9129 	 */
9130 	if (asoc->base.dead)
9131 		return sctp_write_space(sk);
9132 
9133 	/* Accounting for the sndbuf space is per socket, so we
9134 	 * need to wake up others, try to be fair and in case of
9135 	 * other associations, let them have a go first instead
9136 	 * of just doing a sctp_write_space() call.
9137 	 *
9138 	 * Note that we reach sctp_wake_up_waiters() only when
9139 	 * associations free up queued chunks, thus we are under
9140 	 * lock and the list of associations on a socket is
9141 	 * guaranteed not to change.
9142 	 */
9143 	for (tmp = list_next_entry(tmp, asocs); 1;
9144 	     tmp = list_next_entry(tmp, asocs)) {
9145 		/* Manually skip the head element. */
9146 		if (&tmp->asocs == &((sctp_sk(sk))->ep->asocs))
9147 			continue;
9148 		/* Wake up association. */
9149 		__sctp_write_space(tmp);
9150 		/* We've reached the end. */
9151 		if (tmp == asoc)
9152 			break;
9153 	}
9154 }
9155 
9156 /* Do accounting for the sndbuf space.
9157  * Decrement the used sndbuf space of the corresponding association by the
9158  * data size which was just transmitted(freed).
9159  */
sctp_wfree(struct sk_buff * skb)9160 static void sctp_wfree(struct sk_buff *skb)
9161 {
9162 	struct sctp_chunk *chunk = skb_shinfo(skb)->destructor_arg;
9163 	struct sctp_association *asoc = chunk->asoc;
9164 	struct sock *sk = asoc->base.sk;
9165 
9166 	sk_mem_uncharge(sk, skb->truesize);
9167 	sk_wmem_queued_add(sk, -(skb->truesize + sizeof(struct sctp_chunk)));
9168 	asoc->sndbuf_used -= skb->truesize + sizeof(struct sctp_chunk);
9169 	WARN_ON(refcount_sub_and_test(sizeof(struct sctp_chunk),
9170 				      &sk->sk_wmem_alloc));
9171 
9172 	if (chunk->shkey) {
9173 		struct sctp_shared_key *shkey = chunk->shkey;
9174 
9175 		/* refcnt == 2 and !list_empty mean after this release, it's
9176 		 * not being used anywhere, and it's time to notify userland
9177 		 * that this shkey can be freed if it's been deactivated.
9178 		 */
9179 		if (shkey->deactivated && !list_empty(&shkey->key_list) &&
9180 		    refcount_read(&shkey->refcnt) == 2) {
9181 			struct sctp_ulpevent *ev;
9182 
9183 			ev = sctp_ulpevent_make_authkey(asoc, shkey->key_id,
9184 							SCTP_AUTH_FREE_KEY,
9185 							GFP_KERNEL);
9186 			if (ev)
9187 				asoc->stream.si->enqueue_event(&asoc->ulpq, ev);
9188 		}
9189 		sctp_auth_shkey_release(chunk->shkey);
9190 	}
9191 
9192 	sock_wfree(skb);
9193 	sctp_wake_up_waiters(sk, asoc);
9194 
9195 	sctp_association_put(asoc);
9196 }
9197 
9198 /* Do accounting for the receive space on the socket.
9199  * Accounting for the association is done in ulpevent.c
9200  * We set this as a destructor for the cloned data skbs so that
9201  * accounting is done at the correct time.
9202  */
sctp_sock_rfree(struct sk_buff * skb)9203 void sctp_sock_rfree(struct sk_buff *skb)
9204 {
9205 	struct sock *sk = skb->sk;
9206 	struct sctp_ulpevent *event = sctp_skb2event(skb);
9207 
9208 	atomic_sub(event->rmem_len, &sk->sk_rmem_alloc);
9209 
9210 	/*
9211 	 * Mimic the behavior of sock_rfree
9212 	 */
9213 	sk_mem_uncharge(sk, event->rmem_len);
9214 }
9215 
9216 
9217 /* Helper function to wait for space in the sndbuf.  */
sctp_wait_for_sndbuf(struct sctp_association * asoc,struct sctp_transport * transport,long * timeo_p,size_t msg_len)9218 static int sctp_wait_for_sndbuf(struct sctp_association *asoc,
9219 				struct sctp_transport *transport,
9220 				long *timeo_p, size_t msg_len)
9221 {
9222 	struct sock *sk = asoc->base.sk;
9223 	long current_timeo = *timeo_p;
9224 	DEFINE_WAIT(wait);
9225 	int err = 0;
9226 
9227 	pr_debug("%s: asoc:%p, timeo:%ld, msg_len:%zu\n", __func__, asoc,
9228 		 *timeo_p, msg_len);
9229 
9230 	/* Increment the transport and association's refcnt. */
9231 	if (transport)
9232 		sctp_transport_hold(transport);
9233 	sctp_association_hold(asoc);
9234 
9235 	/* Wait on the association specific sndbuf space. */
9236 	for (;;) {
9237 		prepare_to_wait_exclusive(&asoc->wait, &wait,
9238 					  TASK_INTERRUPTIBLE);
9239 		if (asoc->base.dead)
9240 			goto do_dead;
9241 		if ((!*timeo_p) || (transport && transport->dead))
9242 			goto do_nonblock;
9243 		if (sk->sk_err || asoc->state >= SCTP_STATE_SHUTDOWN_PENDING)
9244 			goto do_error;
9245 		if (signal_pending(current))
9246 			goto do_interrupted;
9247 		if ((int)msg_len <= sctp_wspace(asoc) &&
9248 		    sk_wmem_schedule(sk, msg_len))
9249 			break;
9250 
9251 		/* Let another process have a go.  Since we are going
9252 		 * to sleep anyway.
9253 		 */
9254 		release_sock(sk);
9255 		current_timeo = schedule_timeout(current_timeo);
9256 		lock_sock(sk);
9257 		if (sk != asoc->base.sk)
9258 			goto do_error;
9259 
9260 		*timeo_p = current_timeo;
9261 	}
9262 
9263 out:
9264 	finish_wait(&asoc->wait, &wait);
9265 
9266 	/* Release the transport and association's refcnt. */
9267 	if (transport)
9268 		sctp_transport_put(transport);
9269 	sctp_association_put(asoc);
9270 
9271 	return err;
9272 
9273 do_dead:
9274 	err = -ESRCH;
9275 	goto out;
9276 
9277 do_error:
9278 	err = -EPIPE;
9279 	goto out;
9280 
9281 do_interrupted:
9282 	err = sock_intr_errno(*timeo_p);
9283 	goto out;
9284 
9285 do_nonblock:
9286 	err = -EAGAIN;
9287 	goto out;
9288 }
9289 
sctp_data_ready(struct sock * sk)9290 void sctp_data_ready(struct sock *sk)
9291 {
9292 	struct socket_wq *wq;
9293 
9294 	trace_sk_data_ready(sk);
9295 
9296 	rcu_read_lock();
9297 	wq = rcu_dereference(sk->sk_wq);
9298 	if (skwq_has_sleeper(wq))
9299 		wake_up_interruptible_sync_poll(&wq->wait, EPOLLIN |
9300 						EPOLLRDNORM | EPOLLRDBAND);
9301 	sk_wake_async_rcu(sk, SOCK_WAKE_WAITD, POLL_IN);
9302 	rcu_read_unlock();
9303 }
9304 
9305 /* If socket sndbuf has changed, wake up all per association waiters.  */
sctp_write_space(struct sock * sk)9306 void sctp_write_space(struct sock *sk)
9307 {
9308 	struct sctp_association *asoc;
9309 
9310 	/* Wake up the tasks in each wait queue.  */
9311 	list_for_each_entry(asoc, &((sctp_sk(sk))->ep->asocs), asocs) {
9312 		__sctp_write_space(asoc);
9313 	}
9314 }
9315 
9316 /* Is there any sndbuf space available on the socket?
9317  *
9318  * Note that sk_wmem_alloc is the sum of the send buffers on all of the
9319  * associations on the same socket.  For a UDP-style socket with
9320  * multiple associations, it is possible for it to be "unwriteable"
9321  * prematurely.  I assume that this is acceptable because
9322  * a premature "unwriteable" is better than an accidental "writeable" which
9323  * would cause an unwanted block under certain circumstances.  For the 1-1
9324  * UDP-style sockets or TCP-style sockets, this code should work.
9325  *  - Daisy
9326  */
sctp_writeable(const struct sock * sk)9327 static bool sctp_writeable(const struct sock *sk)
9328 {
9329 	return READ_ONCE(sk->sk_sndbuf) > READ_ONCE(sk->sk_wmem_queued);
9330 }
9331 
9332 /* Wait for an association to go into ESTABLISHED state. If timeout is 0,
9333  * returns immediately with EINPROGRESS.
9334  */
sctp_wait_for_connect(struct sctp_association * asoc,long * timeo_p)9335 static int sctp_wait_for_connect(struct sctp_association *asoc, long *timeo_p)
9336 {
9337 	struct sock *sk = asoc->base.sk;
9338 	int err = 0;
9339 	long current_timeo = *timeo_p;
9340 	DEFINE_WAIT(wait);
9341 
9342 	pr_debug("%s: asoc:%p, timeo:%ld\n", __func__, asoc, *timeo_p);
9343 
9344 	/* Increment the association's refcnt.  */
9345 	sctp_association_hold(asoc);
9346 
9347 	for (;;) {
9348 		prepare_to_wait_exclusive(&asoc->wait, &wait,
9349 					  TASK_INTERRUPTIBLE);
9350 		if (!*timeo_p)
9351 			goto do_nonblock;
9352 		if (sk->sk_shutdown & RCV_SHUTDOWN)
9353 			break;
9354 		if (sk->sk_err || asoc->state >= SCTP_STATE_SHUTDOWN_PENDING ||
9355 		    asoc->base.dead)
9356 			goto do_error;
9357 		if (signal_pending(current))
9358 			goto do_interrupted;
9359 
9360 		if (sctp_state(asoc, ESTABLISHED))
9361 			break;
9362 
9363 		/* Let another process have a go.  Since we are going
9364 		 * to sleep anyway.
9365 		 */
9366 		release_sock(sk);
9367 		current_timeo = schedule_timeout(current_timeo);
9368 		lock_sock(sk);
9369 
9370 		*timeo_p = current_timeo;
9371 	}
9372 
9373 out:
9374 	finish_wait(&asoc->wait, &wait);
9375 
9376 	/* Release the association's refcnt.  */
9377 	sctp_association_put(asoc);
9378 
9379 	return err;
9380 
9381 do_error:
9382 	if (asoc->init_err_counter + 1 > asoc->max_init_attempts)
9383 		err = -ETIMEDOUT;
9384 	else
9385 		err = -ECONNREFUSED;
9386 	goto out;
9387 
9388 do_interrupted:
9389 	err = sock_intr_errno(*timeo_p);
9390 	goto out;
9391 
9392 do_nonblock:
9393 	err = -EINPROGRESS;
9394 	goto out;
9395 }
9396 
sctp_wait_for_accept(struct sock * sk,long timeo)9397 static int sctp_wait_for_accept(struct sock *sk, long timeo)
9398 {
9399 	struct sctp_endpoint *ep;
9400 	int err = 0;
9401 	DEFINE_WAIT(wait);
9402 
9403 	ep = sctp_sk(sk)->ep;
9404 
9405 
9406 	for (;;) {
9407 		prepare_to_wait_exclusive(sk_sleep(sk), &wait,
9408 					  TASK_INTERRUPTIBLE);
9409 
9410 		if (list_empty(&ep->asocs)) {
9411 			release_sock(sk);
9412 			timeo = schedule_timeout(timeo);
9413 			lock_sock(sk);
9414 		}
9415 
9416 		err = -EINVAL;
9417 		if (!sctp_sstate(sk, LISTENING) ||
9418 		    (sk->sk_shutdown & RCV_SHUTDOWN))
9419 			break;
9420 
9421 		err = 0;
9422 		if (!list_empty(&ep->asocs))
9423 			break;
9424 
9425 		err = sock_intr_errno(timeo);
9426 		if (signal_pending(current))
9427 			break;
9428 
9429 		err = -EAGAIN;
9430 		if (!timeo)
9431 			break;
9432 	}
9433 
9434 	finish_wait(sk_sleep(sk), &wait);
9435 
9436 	return err;
9437 }
9438 
sctp_wait_for_close(struct sock * sk,long timeout)9439 static void sctp_wait_for_close(struct sock *sk, long timeout)
9440 {
9441 	DEFINE_WAIT(wait);
9442 
9443 	do {
9444 		prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
9445 		if (list_empty(&sctp_sk(sk)->ep->asocs))
9446 			break;
9447 		release_sock(sk);
9448 		timeout = schedule_timeout(timeout);
9449 		lock_sock(sk);
9450 	} while (!signal_pending(current) && timeout);
9451 
9452 	finish_wait(sk_sleep(sk), &wait);
9453 }
9454 
sctp_skb_set_owner_r_frag(struct sk_buff * skb,struct sock * sk)9455 static void sctp_skb_set_owner_r_frag(struct sk_buff *skb, struct sock *sk)
9456 {
9457 	struct sk_buff *frag;
9458 
9459 	if (!skb->data_len)
9460 		goto done;
9461 
9462 	/* Don't forget the fragments. */
9463 	skb_walk_frags(skb, frag)
9464 		sctp_skb_set_owner_r_frag(frag, sk);
9465 
9466 done:
9467 	sctp_skb_set_owner_r(skb, sk);
9468 }
9469 
sctp_copy_sock(struct sock * newsk,struct sock * sk,struct sctp_association * asoc)9470 void sctp_copy_sock(struct sock *newsk, struct sock *sk,
9471 		    struct sctp_association *asoc)
9472 {
9473 	struct inet_sock *inet = inet_sk(sk);
9474 	struct inet_sock *newinet;
9475 	struct sctp_sock *sp = sctp_sk(sk);
9476 
9477 	newsk->sk_type = sk->sk_type;
9478 	newsk->sk_bound_dev_if = sk->sk_bound_dev_if;
9479 	newsk->sk_flags = sk->sk_flags;
9480 	newsk->sk_tsflags = sk->sk_tsflags;
9481 	newsk->sk_no_check_tx = sk->sk_no_check_tx;
9482 	newsk->sk_no_check_rx = sk->sk_no_check_rx;
9483 	newsk->sk_reuse = sk->sk_reuse;
9484 	sctp_sk(newsk)->reuse = sp->reuse;
9485 
9486 	newsk->sk_shutdown = sk->sk_shutdown;
9487 	newsk->sk_destruct = sk->sk_destruct;
9488 	newsk->sk_family = sk->sk_family;
9489 	newsk->sk_protocol = IPPROTO_SCTP;
9490 	newsk->sk_backlog_rcv = sk->sk_prot->backlog_rcv;
9491 	newsk->sk_sndbuf = sk->sk_sndbuf;
9492 	newsk->sk_rcvbuf = sk->sk_rcvbuf;
9493 	newsk->sk_lingertime = sk->sk_lingertime;
9494 	newsk->sk_rcvtimeo = sk->sk_rcvtimeo;
9495 	newsk->sk_sndtimeo = sk->sk_sndtimeo;
9496 	newsk->sk_rxhash = sk->sk_rxhash;
9497 
9498 	newinet = inet_sk(newsk);
9499 
9500 	/* Initialize sk's sport, dport, rcv_saddr and daddr for
9501 	 * getsockname() and getpeername()
9502 	 */
9503 	newinet->inet_sport = inet->inet_sport;
9504 	newinet->inet_saddr = inet->inet_saddr;
9505 	newinet->inet_rcv_saddr = inet->inet_rcv_saddr;
9506 	newinet->inet_dport = htons(asoc->peer.port);
9507 	newinet->pmtudisc = inet->pmtudisc;
9508 	atomic_set(&newinet->inet_id, get_random_u16());
9509 
9510 	newinet->uc_ttl = inet->uc_ttl;
9511 	inet_set_bit(MC_LOOP, newsk);
9512 	newinet->mc_ttl = 1;
9513 	newinet->mc_index = 0;
9514 	newinet->mc_list = NULL;
9515 
9516 	if (newsk->sk_flags & SK_FLAGS_TIMESTAMP)
9517 		net_enable_timestamp();
9518 
9519 	/* Set newsk security attributes from original sk and connection
9520 	 * security attribute from asoc.
9521 	 */
9522 	security_sctp_sk_clone(asoc, sk, newsk);
9523 }
9524 
sctp_copy_descendant(struct sock * sk_to,const struct sock * sk_from)9525 static inline void sctp_copy_descendant(struct sock *sk_to,
9526 					const struct sock *sk_from)
9527 {
9528 	size_t ancestor_size = sizeof(struct inet_sock);
9529 
9530 	ancestor_size += sk_from->sk_prot->obj_size;
9531 	ancestor_size -= offsetof(struct sctp_sock, pd_lobby);
9532 	__inet_sk_copy_descendant(sk_to, sk_from, ancestor_size);
9533 }
9534 
9535 /* Populate the fields of the newsk from the oldsk and migrate the assoc
9536  * and its messages to the newsk.
9537  */
sctp_sock_migrate(struct sock * oldsk,struct sock * newsk,struct sctp_association * assoc,enum sctp_socket_type type)9538 static int sctp_sock_migrate(struct sock *oldsk, struct sock *newsk,
9539 			     struct sctp_association *assoc,
9540 			     enum sctp_socket_type type)
9541 {
9542 	struct sctp_sock *oldsp = sctp_sk(oldsk);
9543 	struct sctp_sock *newsp = sctp_sk(newsk);
9544 	struct sctp_bind_bucket *pp; /* hash list port iterator */
9545 	struct sctp_endpoint *newep = newsp->ep;
9546 	struct sk_buff *skb, *tmp;
9547 	struct sctp_ulpevent *event;
9548 	struct sctp_bind_hashbucket *head;
9549 	int err;
9550 
9551 	/* Migrate socket buffer sizes and all the socket level options to the
9552 	 * new socket.
9553 	 */
9554 	newsk->sk_sndbuf = oldsk->sk_sndbuf;
9555 	newsk->sk_rcvbuf = oldsk->sk_rcvbuf;
9556 	/* Brute force copy old sctp opt. */
9557 	sctp_copy_descendant(newsk, oldsk);
9558 
9559 	/* Restore the ep value that was overwritten with the above structure
9560 	 * copy.
9561 	 */
9562 	newsp->ep = newep;
9563 	newsp->hmac = NULL;
9564 
9565 	/* Hook this new socket in to the bind_hash list. */
9566 	head = &sctp_port_hashtable[sctp_phashfn(sock_net(oldsk),
9567 						 inet_sk(oldsk)->inet_num)];
9568 	spin_lock_bh(&head->lock);
9569 	pp = sctp_sk(oldsk)->bind_hash;
9570 	sk_add_bind_node(newsk, &pp->owner);
9571 	sctp_sk(newsk)->bind_hash = pp;
9572 	inet_sk(newsk)->inet_num = inet_sk(oldsk)->inet_num;
9573 	spin_unlock_bh(&head->lock);
9574 
9575 	/* Copy the bind_addr list from the original endpoint to the new
9576 	 * endpoint so that we can handle restarts properly
9577 	 */
9578 	err = sctp_bind_addr_dup(&newsp->ep->base.bind_addr,
9579 				 &oldsp->ep->base.bind_addr, GFP_KERNEL);
9580 	if (err)
9581 		return err;
9582 
9583 	/* New ep's auth_hmacs should be set if old ep's is set, in case
9584 	 * that net->sctp.auth_enable has been changed to 0 by users and
9585 	 * new ep's auth_hmacs couldn't be set in sctp_endpoint_init().
9586 	 */
9587 	if (oldsp->ep->auth_hmacs) {
9588 		err = sctp_auth_init_hmacs(newsp->ep, GFP_KERNEL);
9589 		if (err)
9590 			return err;
9591 	}
9592 
9593 	sctp_auto_asconf_init(newsp);
9594 
9595 	/* Move any messages in the old socket's receive queue that are for the
9596 	 * peeled off association to the new socket's receive queue.
9597 	 */
9598 	sctp_skb_for_each(skb, &oldsk->sk_receive_queue, tmp) {
9599 		event = sctp_skb2event(skb);
9600 		if (event->asoc == assoc) {
9601 			__skb_unlink(skb, &oldsk->sk_receive_queue);
9602 			__skb_queue_tail(&newsk->sk_receive_queue, skb);
9603 			sctp_skb_set_owner_r_frag(skb, newsk);
9604 		}
9605 	}
9606 
9607 	/* Clean up any messages pending delivery due to partial
9608 	 * delivery.   Three cases:
9609 	 * 1) No partial deliver;  no work.
9610 	 * 2) Peeling off partial delivery; keep pd_lobby in new pd_lobby.
9611 	 * 3) Peeling off non-partial delivery; move pd_lobby to receive_queue.
9612 	 */
9613 	atomic_set(&sctp_sk(newsk)->pd_mode, assoc->ulpq.pd_mode);
9614 
9615 	if (atomic_read(&sctp_sk(oldsk)->pd_mode)) {
9616 		struct sk_buff_head *queue;
9617 
9618 		/* Decide which queue to move pd_lobby skbs to. */
9619 		if (assoc->ulpq.pd_mode) {
9620 			queue = &newsp->pd_lobby;
9621 		} else
9622 			queue = &newsk->sk_receive_queue;
9623 
9624 		/* Walk through the pd_lobby, looking for skbs that
9625 		 * need moved to the new socket.
9626 		 */
9627 		sctp_skb_for_each(skb, &oldsp->pd_lobby, tmp) {
9628 			event = sctp_skb2event(skb);
9629 			if (event->asoc == assoc) {
9630 				__skb_unlink(skb, &oldsp->pd_lobby);
9631 				__skb_queue_tail(queue, skb);
9632 				sctp_skb_set_owner_r_frag(skb, newsk);
9633 			}
9634 		}
9635 
9636 		/* Clear up any skbs waiting for the partial
9637 		 * delivery to finish.
9638 		 */
9639 		if (assoc->ulpq.pd_mode)
9640 			sctp_clear_pd(oldsk, NULL);
9641 
9642 	}
9643 
9644 	sctp_for_each_rx_skb(assoc, newsk, sctp_skb_set_owner_r_frag);
9645 
9646 	/* Set the type of socket to indicate that it is peeled off from the
9647 	 * original UDP-style socket or created with the accept() call on a
9648 	 * TCP-style socket..
9649 	 */
9650 	newsp->type = type;
9651 
9652 	/* Mark the new socket "in-use" by the user so that any packets
9653 	 * that may arrive on the association after we've moved it are
9654 	 * queued to the backlog.  This prevents a potential race between
9655 	 * backlog processing on the old socket and new-packet processing
9656 	 * on the new socket.
9657 	 *
9658 	 * The caller has just allocated newsk so we can guarantee that other
9659 	 * paths won't try to lock it and then oldsk.
9660 	 */
9661 	lock_sock_nested(newsk, SINGLE_DEPTH_NESTING);
9662 	sctp_for_each_tx_datachunk(assoc, true, sctp_clear_owner_w);
9663 	sctp_assoc_migrate(assoc, newsk);
9664 	sctp_for_each_tx_datachunk(assoc, false, sctp_set_owner_w);
9665 
9666 	/* If the association on the newsk is already closed before accept()
9667 	 * is called, set RCV_SHUTDOWN flag.
9668 	 */
9669 	if (sctp_state(assoc, CLOSED) && sctp_style(newsk, TCP)) {
9670 		inet_sk_set_state(newsk, SCTP_SS_CLOSED);
9671 		newsk->sk_shutdown |= RCV_SHUTDOWN;
9672 	} else {
9673 		inet_sk_set_state(newsk, SCTP_SS_ESTABLISHED);
9674 	}
9675 
9676 	release_sock(newsk);
9677 
9678 	return 0;
9679 }
9680 
9681 
9682 /* This proto struct describes the ULP interface for SCTP.  */
9683 struct proto sctp_prot = {
9684 	.name        =	"SCTP",
9685 	.owner       =	THIS_MODULE,
9686 	.close       =	sctp_close,
9687 	.disconnect  =	sctp_disconnect,
9688 	.accept      =	sctp_accept,
9689 	.ioctl       =	sctp_ioctl,
9690 	.init        =	sctp_init_sock,
9691 	.destroy     =	sctp_destroy_sock,
9692 	.shutdown    =	sctp_shutdown,
9693 	.setsockopt  =	sctp_setsockopt,
9694 	.getsockopt  =	sctp_getsockopt,
9695 	.bpf_bypass_getsockopt	= sctp_bpf_bypass_getsockopt,
9696 	.sendmsg     =	sctp_sendmsg,
9697 	.recvmsg     =	sctp_recvmsg,
9698 	.bind        =	sctp_bind,
9699 	.bind_add    =  sctp_bind_add,
9700 	.backlog_rcv =	sctp_backlog_rcv,
9701 	.hash        =	sctp_hash,
9702 	.unhash      =	sctp_unhash,
9703 	.no_autobind =	true,
9704 	.obj_size    =  sizeof(struct sctp_sock),
9705 	.useroffset  =  offsetof(struct sctp_sock, subscribe),
9706 	.usersize    =  offsetof(struct sctp_sock, initmsg) -
9707 				offsetof(struct sctp_sock, subscribe) +
9708 				sizeof_field(struct sctp_sock, initmsg),
9709 	.sysctl_mem  =  sysctl_sctp_mem,
9710 	.sysctl_rmem =  sysctl_sctp_rmem,
9711 	.sysctl_wmem =  sysctl_sctp_wmem,
9712 	.memory_pressure = &sctp_memory_pressure,
9713 	.enter_memory_pressure = sctp_enter_memory_pressure,
9714 
9715 	.memory_allocated = &sctp_memory_allocated,
9716 	.per_cpu_fw_alloc = &sctp_memory_per_cpu_fw_alloc,
9717 
9718 	.sockets_allocated = &sctp_sockets_allocated,
9719 };
9720 
9721 #if IS_ENABLED(CONFIG_IPV6)
9722 
sctp_v6_destruct_sock(struct sock * sk)9723 static void sctp_v6_destruct_sock(struct sock *sk)
9724 {
9725 	sctp_destruct_common(sk);
9726 	inet6_sock_destruct(sk);
9727 }
9728 
sctp_v6_init_sock(struct sock * sk)9729 static int sctp_v6_init_sock(struct sock *sk)
9730 {
9731 	int ret = sctp_init_sock(sk);
9732 
9733 	if (!ret)
9734 		sk->sk_destruct = sctp_v6_destruct_sock;
9735 
9736 	return ret;
9737 }
9738 
9739 struct proto sctpv6_prot = {
9740 	.name		= "SCTPv6",
9741 	.owner		= THIS_MODULE,
9742 	.close		= sctp_close,
9743 	.disconnect	= sctp_disconnect,
9744 	.accept		= sctp_accept,
9745 	.ioctl		= sctp_ioctl,
9746 	.init		= sctp_v6_init_sock,
9747 	.destroy	= sctp_destroy_sock,
9748 	.shutdown	= sctp_shutdown,
9749 	.setsockopt	= sctp_setsockopt,
9750 	.getsockopt	= sctp_getsockopt,
9751 	.bpf_bypass_getsockopt	= sctp_bpf_bypass_getsockopt,
9752 	.sendmsg	= sctp_sendmsg,
9753 	.recvmsg	= sctp_recvmsg,
9754 	.bind		= sctp_bind,
9755 	.bind_add	= sctp_bind_add,
9756 	.backlog_rcv	= sctp_backlog_rcv,
9757 	.hash		= sctp_hash,
9758 	.unhash		= sctp_unhash,
9759 	.no_autobind	= true,
9760 	.obj_size	= sizeof(struct sctp6_sock),
9761 	.ipv6_pinfo_offset = offsetof(struct sctp6_sock, inet6),
9762 	.useroffset	= offsetof(struct sctp6_sock, sctp.subscribe),
9763 	.usersize	= offsetof(struct sctp6_sock, sctp.initmsg) -
9764 				offsetof(struct sctp6_sock, sctp.subscribe) +
9765 				sizeof_field(struct sctp6_sock, sctp.initmsg),
9766 	.sysctl_mem	= sysctl_sctp_mem,
9767 	.sysctl_rmem	= sysctl_sctp_rmem,
9768 	.sysctl_wmem	= sysctl_sctp_wmem,
9769 	.memory_pressure = &sctp_memory_pressure,
9770 	.enter_memory_pressure = sctp_enter_memory_pressure,
9771 
9772 	.memory_allocated = &sctp_memory_allocated,
9773 	.per_cpu_fw_alloc = &sctp_memory_per_cpu_fw_alloc,
9774 
9775 	.sockets_allocated = &sctp_sockets_allocated,
9776 };
9777 #endif /* IS_ENABLED(CONFIG_IPV6) */
9778