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