wol.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // SPDX-License-Identifier: GPL-2.0+
  2. /*
  3. * Copyright 2018 Lothar Felten, lothar.felten@gmail.com
  4. */
  5. #include <common.h>
  6. #include <command.h>
  7. #include <env.h>
  8. #include <net.h>
  9. #include "wol.h"
  10. static ulong wol_timeout = WOL_DEFAULT_TIMEOUT;
  11. /*
  12. * Check incoming Wake-on-LAN packet for:
  13. * - sync bytes
  14. * - sixteen copies of the target MAC address
  15. *
  16. * @param wol Wake-on-LAN packet
  17. * @param len Packet length
  18. */
  19. static int wol_check_magic(struct wol_hdr *wol, unsigned int len)
  20. {
  21. int i;
  22. if (len < sizeof(struct wol_hdr))
  23. return 0;
  24. for (i = 0; i < WOL_SYNC_COUNT; i++)
  25. if (wol->wol_sync[i] != WOL_SYNC_BYTE)
  26. return 0;
  27. for (i = 0; i < WOL_MAC_REPETITIONS; i++)
  28. if (memcmp(&wol->wol_dest[i * ARP_HLEN],
  29. net_ethaddr, ARP_HLEN) != 0)
  30. return 0;
  31. return 1;
  32. }
  33. void wol_receive(struct ip_udp_hdr *ip, unsigned int len)
  34. {
  35. struct wol_hdr *wol;
  36. wol = (struct wol_hdr *)ip;
  37. if (!wol_check_magic(wol, len))
  38. return;
  39. /* save the optional password using the ether-wake formats */
  40. /* don't check for exact length, the packet might have padding */
  41. if (len >= (sizeof(struct wol_hdr) + WOL_PASSWORD_6B)) {
  42. eth_env_set_enetaddr("wolpassword", wol->wol_passwd);
  43. } else if (len >= (sizeof(struct wol_hdr) + WOL_PASSWORD_4B)) {
  44. char buffer[16];
  45. struct in_addr *ip = (struct in_addr *)(wol->wol_passwd);
  46. ip_to_string(*ip, buffer);
  47. env_set("wolpassword", buffer);
  48. }
  49. net_set_state(NETLOOP_SUCCESS);
  50. }
  51. static void wol_udp_handler(uchar *pkt, unsigned int dest, struct in_addr sip,
  52. unsigned int src, unsigned int len)
  53. {
  54. struct wol_hdr *wol;
  55. wol = (struct wol_hdr *)pkt;
  56. /* UDP destination port must be 0, 7 or 9 */
  57. if (dest != 0 && dest != 7 && dest != 9)
  58. return;
  59. if (!wol_check_magic(wol, len))
  60. return;
  61. net_set_state(NETLOOP_SUCCESS);
  62. }
  63. void wol_set_timeout(ulong timeout)
  64. {
  65. wol_timeout = timeout;
  66. }
  67. static void wol_timeout_handler(void)
  68. {
  69. eth_halt();
  70. net_set_state(NETLOOP_FAIL);
  71. }
  72. void wol_start(void)
  73. {
  74. net_set_timeout_handler(wol_timeout, wol_timeout_handler);
  75. net_set_udp_handler(wol_udp_handler);
  76. }