datagram.c 1.91 KB
Newer Older
Linus Torvalds's avatar
Linus Torvalds committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/*
 *	common UDP/RAW code
 *	Linux INET implementation
 *
 * Authors:
 * 	Hideaki YOSHIFUJI <yoshfuji@linux-ipv6.org>
 *
 * 	This program is free software; you can redistribute it and/or
 * 	modify it under the terms of the GNU General Public License
 * 	as published by the Free Software Foundation; either version
 * 	2 of the License, or (at your option) any later version.
 */

#include <linux/types.h>
#include <linux/module.h>
#include <linux/ip.h>
#include <linux/in.h>
18
#include <net/ip.h>
Linus Torvalds's avatar
Linus Torvalds committed
19
20
#include <net/sock.h>
#include <net/route.h>
21
#include <net/tcp_states.h>
Linus Torvalds's avatar
Linus Torvalds committed
22
23
24
25
26
27

int ip4_datagram_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)
{
	struct inet_sock *inet = inet_sk(sk);
	struct sockaddr_in *usin = (struct sockaddr_in *) uaddr;
	struct rtable *rt;
28
	__be32 saddr;
Linus Torvalds's avatar
Linus Torvalds committed
29
30
31
32
	int oif;
	int err;


33
34
35
36
37
	if (addr_len < sizeof(*usin))
		return -EINVAL;

	if (usin->sin_family != AF_INET)
		return -EAFNOSUPPORT;
Linus Torvalds's avatar
Linus Torvalds committed
38
39
40
41

	sk_dst_reset(sk);

	oif = sk->sk_bound_dev_if;
42
	saddr = inet->inet_saddr;
43
	if (ipv4_is_multicast(usin->sin_addr.s_addr)) {
Linus Torvalds's avatar
Linus Torvalds committed
44
45
46
47
48
		if (!oif)
			oif = inet->mc_index;
		if (!saddr)
			saddr = inet->mc_addr;
	}
49
50
51
52
53
54
	rt = ip_route_connect(usin->sin_addr.s_addr, saddr,
			      RT_CONN_FLAGS(sk), oif,
			      sk->sk_protocol,
			      inet->inet_sport, usin->sin_port, sk, true);
	if (IS_ERR(rt)) {
		err = PTR_ERR(rt);
55
		if (err == -ENETUNREACH)
56
			IP_INC_STATS_BH(sock_net(sk), IPSTATS_MIB_OUTNOROUTES);
Linus Torvalds's avatar
Linus Torvalds committed
57
		return err;
58
59
	}

Linus Torvalds's avatar
Linus Torvalds committed
60
61
62
63
	if ((rt->rt_flags & RTCF_BROADCAST) && !sock_flag(sk, SOCK_BROADCAST)) {
		ip_rt_put(rt);
		return -EACCES;
	}
64
65
	if (!inet->inet_saddr)
		inet->inet_saddr = rt->rt_src;	/* Update source address */
Eric Dumazet's avatar
Eric Dumazet committed
66
	if (!inet->inet_rcv_saddr) {
67
		inet->inet_rcv_saddr = rt->rt_src;
Eric Dumazet's avatar
Eric Dumazet committed
68
69
70
		if (sk->sk_prot->rehash)
			sk->sk_prot->rehash(sk);
	}
71
72
	inet->inet_daddr = rt->rt_dst;
	inet->inet_dport = usin->sin_port;
Linus Torvalds's avatar
Linus Torvalds committed
73
	sk->sk_state = TCP_ESTABLISHED;
74
	inet->inet_id = jiffies;
Linus Torvalds's avatar
Linus Torvalds committed
75

76
	sk_dst_set(sk, &rt->dst);
Eric Dumazet's avatar
Eric Dumazet committed
77
	return 0;
Linus Torvalds's avatar
Linus Torvalds committed
78
79
}
EXPORT_SYMBOL(ip4_datagram_connect);