udp_proto.h 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /**
  2. * @file udp_proto.h
  3. * @author Ambroz Bizjak <ambrop7@gmail.com>
  4. *
  5. * @section LICENSE
  6. *
  7. * This file is part of BadVPN.
  8. *
  9. * BadVPN is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License version 2
  11. * as published by the Free Software Foundation.
  12. *
  13. * BadVPN is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License along
  19. * with this program; if not, write to the Free Software Foundation, Inc.,
  20. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  21. *
  22. * @section DESCRIPTION
  23. *
  24. * Definitions for the UDP protocol.
  25. */
  26. #ifndef BADVPN_MISC_UDP_PROTO_H
  27. #define BADVPN_MISC_UDP_PROTO_H
  28. #include <stdint.h>
  29. #include <misc/debug.h>
  30. #include <misc/byteorder.h>
  31. #include <misc/ipv4_proto.h>
  32. struct udp_header {
  33. uint16_t source_port;
  34. uint16_t dest_port;
  35. uint16_t length;
  36. uint16_t checksum;
  37. } __attribute__((packed));
  38. static uint32_t udp_checksum_summer (uint8_t *data, uint16_t len)
  39. {
  40. ASSERT(len % 2 == 0)
  41. struct ipv4_short *s = (void *)data;
  42. uint32_t t = 0;
  43. for (uint16_t i = 0; i < len / 2; i++) {
  44. t += ntoh16(s[i].v);
  45. }
  46. return t;
  47. }
  48. static uint16_t udp_checksum (uint8_t *udp, uint16_t len, uint32_t source_addr, uint32_t dest_addr)
  49. {
  50. uint32_t t = 0;
  51. t += udp_checksum_summer((uint8_t *)&source_addr, sizeof(source_addr));
  52. t += udp_checksum_summer((uint8_t *)&dest_addr, sizeof(dest_addr));
  53. uint16_t x;
  54. x = hton16(IPV4_PROTOCOL_UDP);
  55. t += udp_checksum_summer((uint8_t *)&x, sizeof(x));
  56. x = hton16(len);
  57. t += udp_checksum_summer((uint8_t *)&x, sizeof(x));
  58. if (len % 2 == 0) {
  59. t += udp_checksum_summer(udp, len);
  60. } else {
  61. t += udp_checksum_summer(udp, len - 1);
  62. x = hton16(((uint16_t)udp[len - 1]) << 8);
  63. t += udp_checksum_summer((uint8_t *)&x, sizeof(x));
  64. }
  65. while (t >> 16) {
  66. t = (t & 0xFFFF) + (t >> 16);
  67. }
  68. if (t == 0) {
  69. t = UINT16_MAX;
  70. }
  71. return hton16(~t);
  72. }
  73. #endif