datagram.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*
  2. * common UDP/RAW code
  3. * Linux INET implementation
  4. *
  5. * Authors:
  6. * Hideaki YOSHIFUJI <yoshfuji@linux-ipv6.org>
  7. *
  8. * This program is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU General Public License
  10. * as published by the Free Software Foundation; either version
  11. * 2 of the License, or (at your option) any later version.
  12. */
  13. #include <linux/types.h>
  14. #include <linux/module.h>
  15. #include <linux/ip.h>
  16. #include <linux/in.h>
  17. #include <net/ip.h>
  18. #include <net/sock.h>
  19. #include <net/route.h>
  20. #include <net/tcp_states.h>
  21. int ip4_datagram_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)
  22. {
  23. struct inet_sock *inet = inet_sk(sk);
  24. struct sockaddr_in *usin = (struct sockaddr_in *) uaddr;
  25. struct flowi4 *fl4;
  26. struct rtable *rt;
  27. __be32 saddr;
  28. int oif;
  29. int err;
  30. if (addr_len < sizeof(*usin))
  31. return -EINVAL;
  32. if (usin->sin_family != AF_INET)
  33. return -EAFNOSUPPORT;
  34. sk_dst_reset(sk);
  35. lock_sock(sk);
  36. oif = sk->sk_bound_dev_if;
  37. saddr = inet->inet_saddr;
  38. if (ipv4_is_multicast(usin->sin_addr.s_addr)) {
  39. if (!oif)
  40. oif = inet->mc_index;
  41. if (!saddr)
  42. saddr = inet->mc_addr;
  43. }
  44. fl4 = &inet->cork.fl.u.ip4;
  45. rt = ip_route_connect(fl4, usin->sin_addr.s_addr, saddr,
  46. RT_CONN_FLAGS(sk), oif,
  47. sk->sk_protocol,
  48. inet->inet_sport, usin->sin_port, sk, true);
  49. if (IS_ERR(rt)) {
  50. err = PTR_ERR(rt);
  51. if (err == -ENETUNREACH)
  52. IP_INC_STATS_BH(sock_net(sk), IPSTATS_MIB_OUTNOROUTES);
  53. goto out;
  54. }
  55. if ((rt->rt_flags & RTCF_BROADCAST) && !sock_flag(sk, SOCK_BROADCAST)) {
  56. ip_rt_put(rt);
  57. err = -EACCES;
  58. goto out;
  59. }
  60. if (!inet->inet_saddr)
  61. inet->inet_saddr = fl4->saddr; /* Update source address */
  62. if (!inet->inet_rcv_saddr) {
  63. inet->inet_rcv_saddr = fl4->saddr;
  64. if (sk->sk_prot->rehash)
  65. sk->sk_prot->rehash(sk);
  66. }
  67. inet->inet_daddr = fl4->daddr;
  68. inet->inet_dport = usin->sin_port;
  69. sk->sk_state = TCP_ESTABLISHED;
  70. inet->inet_id = jiffies;
  71. sk_dst_set(sk, &rt->dst);
  72. err = 0;
  73. out:
  74. release_sock(sk);
  75. return err;
  76. }
  77. EXPORT_SYMBOL(ip4_datagram_connect);