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