ping_sock.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. /*
  2. * SPDX-FileCopyrightText: 2019-2021 Espressif Systems (Shanghai) CO LTD
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. #include <stdlib.h>
  7. #include <stdbool.h>
  8. #include "freertos/FreeRTOS.h"
  9. #include "freertos/task.h"
  10. #include "lwip/opt.h"
  11. #include "lwip/init.h"
  12. #include "lwip/mem.h"
  13. #include "lwip/icmp.h"
  14. #include "lwip/netif.h"
  15. #include "lwip/sys.h"
  16. #include "lwip/timeouts.h"
  17. #include "lwip/inet.h"
  18. #include "lwip/inet_chksum.h"
  19. #include "lwip/ip.h"
  20. #include "lwip/netdb.h"
  21. #include "lwip/sockets.h"
  22. #include "esp_log.h"
  23. #include "ping/ping_sock.h"
  24. #include "esp_check.h"
  25. const static char *TAG = "ping_sock";
  26. #define PING_TIME_DIFF_MS(_end, _start) ((uint32_t)(((_end).tv_sec - (_start).tv_sec) * 1000 + \
  27. ((_end).tv_usec - (_start).tv_usec) / 1000))
  28. #define PING_CHECK_START_TIMEOUT_MS (1000)
  29. #define PING_FLAGS_INIT (1 << 0)
  30. #define PING_FLAGS_START (1 << 1)
  31. typedef struct {
  32. int sock;
  33. struct sockaddr_storage target_addr;
  34. TaskHandle_t ping_task_hdl;
  35. struct icmp_echo_hdr *packet_hdr;
  36. ip_addr_t recv_addr;
  37. uint32_t recv_len;
  38. uint32_t icmp_pkt_size;
  39. uint32_t count;
  40. uint32_t transmitted;
  41. uint32_t received;
  42. uint32_t interval_ms;
  43. uint32_t elapsed_time_ms;
  44. uint32_t total_time_ms;
  45. uint8_t ttl;
  46. uint8_t tos;
  47. uint32_t flags;
  48. void (*on_ping_success)(esp_ping_handle_t hdl, void *args);
  49. void (*on_ping_timeout)(esp_ping_handle_t hdl, void *args);
  50. void (*on_ping_end)(esp_ping_handle_t hdl, void *args);
  51. void *cb_args;
  52. } esp_ping_t;
  53. static esp_err_t esp_ping_send(esp_ping_t *ep)
  54. {
  55. esp_err_t ret = ESP_OK;
  56. ep->packet_hdr->seqno++;
  57. /* generate checksum since "seqno" has changed */
  58. ep->packet_hdr->chksum = 0;
  59. if (ep->packet_hdr->type == ICMP_ECHO) {
  60. ep->packet_hdr->chksum = inet_chksum(ep->packet_hdr, ep->icmp_pkt_size);
  61. }
  62. ssize_t sent = sendto(ep->sock, ep->packet_hdr, ep->icmp_pkt_size, 0,
  63. (struct sockaddr *)&ep->target_addr, sizeof(ep->target_addr));
  64. if (sent != (ssize_t)ep->icmp_pkt_size) {
  65. int opt_val;
  66. socklen_t opt_len = sizeof(opt_val);
  67. getsockopt(ep->sock, SOL_SOCKET, SO_ERROR, &opt_val, &opt_len);
  68. ESP_LOGE(TAG, "send error=%d", opt_val);
  69. ret = ESP_FAIL;
  70. } else {
  71. ep->transmitted++;
  72. }
  73. return ret;
  74. }
  75. static int esp_ping_receive(esp_ping_t *ep)
  76. {
  77. char buf[64]; // 64 bytes are enough to cover IP header and ICMP header
  78. int len = 0;
  79. struct sockaddr_storage from;
  80. int fromlen = sizeof(from);
  81. uint16_t data_head = 0;
  82. while ((len = recvfrom(ep->sock, buf, sizeof(buf), 0, (struct sockaddr *)&from, (socklen_t *)&fromlen)) > 0) {
  83. if (from.ss_family == AF_INET) {
  84. // IPv4
  85. struct sockaddr_in *from4 = (struct sockaddr_in *)&from;
  86. inet_addr_to_ip4addr(ip_2_ip4(&ep->recv_addr), &from4->sin_addr);
  87. IP_SET_TYPE_VAL(ep->recv_addr, IPADDR_TYPE_V4);
  88. data_head = (uint16_t)(sizeof(struct ip_hdr) + sizeof(struct icmp_echo_hdr));
  89. }
  90. #if CONFIG_LWIP_IPV6
  91. else {
  92. // IPv6
  93. struct sockaddr_in6 *from6 = (struct sockaddr_in6 *)&from;
  94. inet6_addr_to_ip6addr(ip_2_ip6(&ep->recv_addr), &from6->sin6_addr);
  95. IP_SET_TYPE_VAL(ep->recv_addr, IPADDR_TYPE_V6);
  96. data_head = (uint16_t)(sizeof(struct ip6_hdr) + sizeof(struct icmp6_echo_hdr));
  97. }
  98. #endif
  99. if (len >= data_head) {
  100. if (IP_IS_V4_VAL(ep->recv_addr)) { // Currently we process IPv4
  101. struct ip_hdr *iphdr = (struct ip_hdr *)buf;
  102. struct icmp_echo_hdr *iecho = (struct icmp_echo_hdr *)(buf + (IPH_HL(iphdr) * 4));
  103. if ((iecho->id == ep->packet_hdr->id) && (iecho->seqno == ep->packet_hdr->seqno)) {
  104. ep->received++;
  105. ep->ttl = iphdr->_ttl;
  106. ep->tos = iphdr->_tos;
  107. ep->recv_len = lwip_ntohs(IPH_LEN(iphdr)) - data_head; // The data portion of ICMP
  108. return len;
  109. }
  110. }
  111. #if CONFIG_LWIP_IPV6
  112. else if (IP_IS_V6_VAL(ep->recv_addr)) { // Currently we process IPv6
  113. struct ip6_hdr *iphdr = (struct ip6_hdr *)buf;
  114. struct icmp6_echo_hdr *iecho6 = (struct icmp6_echo_hdr *)(buf + sizeof(struct ip6_hdr)); // IPv6 head length is 40
  115. if ((iecho6->id == ep->packet_hdr->id) && (iecho6->seqno == ep->packet_hdr->seqno)) {
  116. ep->received++;
  117. ep->recv_len = IP6H_PLEN(iphdr) - sizeof(struct icmp6_echo_hdr); //The data portion of ICMPv6
  118. return len;
  119. }
  120. }
  121. #endif
  122. }
  123. fromlen = sizeof(from);
  124. }
  125. // if timeout, len will be -1
  126. return len;
  127. }
  128. static void esp_ping_thread(void *args)
  129. {
  130. esp_ping_t *ep = (esp_ping_t *)(args);
  131. TickType_t last_wake;
  132. struct timeval start_time, end_time;
  133. int recv_ret;
  134. while (1) {
  135. /* wait for ping start signal */
  136. if (ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(PING_CHECK_START_TIMEOUT_MS))) {
  137. /* initialize runtime statistics */
  138. ep->packet_hdr->seqno = 0;
  139. ep->transmitted = 0;
  140. ep->received = 0;
  141. ep->total_time_ms = 0;
  142. last_wake = xTaskGetTickCount();
  143. while ((ep->flags & PING_FLAGS_START) && ((ep->count == 0) || (ep->packet_hdr->seqno < ep->count))) {
  144. esp_ping_send(ep);
  145. gettimeofday(&start_time, NULL);
  146. recv_ret = esp_ping_receive(ep);
  147. gettimeofday(&end_time, NULL);
  148. ep->elapsed_time_ms = PING_TIME_DIFF_MS(end_time, start_time);
  149. ep->total_time_ms += ep->elapsed_time_ms;
  150. if (recv_ret >= 0) {
  151. if (ep->on_ping_success) {
  152. ep->on_ping_success((esp_ping_handle_t)ep, ep->cb_args);
  153. }
  154. } else {
  155. if (ep->on_ping_timeout) {
  156. ep->on_ping_timeout((esp_ping_handle_t)ep, ep->cb_args);
  157. }
  158. }
  159. if (pdMS_TO_TICKS(ep->interval_ms)) {
  160. vTaskDelayUntil(&last_wake, pdMS_TO_TICKS(ep->interval_ms)); // to get a more accurate delay
  161. }
  162. }
  163. /* batch of ping operations finished */
  164. if (ep->on_ping_end) {
  165. ep->on_ping_end((esp_ping_handle_t)ep, ep->cb_args);
  166. }
  167. } else {
  168. // check if ping has been de-initialized
  169. if (!(ep->flags & PING_FLAGS_INIT)) {
  170. break;
  171. }
  172. }
  173. }
  174. /* before exit task, free all resources */
  175. if (ep->packet_hdr) {
  176. free(ep->packet_hdr);
  177. }
  178. if (ep->sock > 0) {
  179. close(ep->sock);
  180. }
  181. free(ep);
  182. vTaskDelete(NULL);
  183. }
  184. esp_err_t esp_ping_new_session(const esp_ping_config_t *config, const esp_ping_callbacks_t *cbs, esp_ping_handle_t *hdl_out)
  185. {
  186. esp_err_t ret = ESP_FAIL;
  187. esp_ping_t *ep = NULL;
  188. ESP_GOTO_ON_FALSE(config, ESP_ERR_INVALID_ARG, err, TAG, "ping config can't be null");
  189. ESP_GOTO_ON_FALSE(hdl_out, ESP_ERR_INVALID_ARG, err, TAG, "ping handle can't be null");
  190. ep = mem_calloc(1, sizeof(esp_ping_t));
  191. ESP_GOTO_ON_FALSE(ep, ESP_ERR_NO_MEM, err, TAG, "no memory for esp_ping object");
  192. /* set INIT flag, so that ping task won't exit (must set before create ping task) */
  193. ep->flags |= PING_FLAGS_INIT;
  194. /* create ping thread */
  195. BaseType_t xReturned = xTaskCreate(esp_ping_thread, "ping", config->task_stack_size, ep,
  196. config->task_prio, &ep->ping_task_hdl);
  197. ESP_GOTO_ON_FALSE(xReturned == pdTRUE, ESP_ERR_NO_MEM, err, TAG, "create ping task failed");
  198. /* callback functions */
  199. if (cbs) {
  200. ep->cb_args = cbs->cb_args;
  201. ep->on_ping_end = cbs->on_ping_end;
  202. ep->on_ping_timeout = cbs->on_ping_timeout;
  203. ep->on_ping_success = cbs->on_ping_success;
  204. }
  205. /* set parameters for ping */
  206. ep->recv_addr = config->target_addr;
  207. ep->count = config->count;
  208. ep->interval_ms = config->interval_ms;
  209. ep->icmp_pkt_size = sizeof(struct icmp_echo_hdr) + config->data_size;
  210. ep->packet_hdr = mem_calloc(1, ep->icmp_pkt_size);
  211. ESP_GOTO_ON_FALSE(ep->packet_hdr,ESP_ERR_NO_MEM, err, TAG, "no memory for echo packet");
  212. /* set ICMP type and code field */
  213. ep->packet_hdr->code = 0;
  214. /* ping id should be unique, treat task handle as ping ID */
  215. ep->packet_hdr->id = ((uint32_t)ep->ping_task_hdl) & 0xFFFF;
  216. /* fill the additional data buffer with some data */
  217. char *d = (char *)(ep->packet_hdr) + sizeof(struct icmp_echo_hdr);
  218. for (uint32_t i = 0; i < config->data_size; i++) {
  219. d[i] = 'A' + i;
  220. }
  221. /* create socket */
  222. if (IP_IS_V4(&config->target_addr)
  223. #if CONFIG_LWIP_IPV6
  224. || ip6_addr_isipv4mappedipv6(ip_2_ip6(&config->target_addr))
  225. #endif
  226. ) {
  227. ep->sock = socket(AF_INET, SOCK_RAW, IP_PROTO_ICMP);
  228. }
  229. #if CONFIG_LWIP_IPV6
  230. else {
  231. ep->sock = socket(AF_INET6, SOCK_RAW, IP6_NEXTH_ICMP6);
  232. }
  233. #endif
  234. ESP_GOTO_ON_FALSE(ep->sock >= 0, ESP_FAIL, err, TAG, "create socket failed: %d", ep->sock);
  235. /* set if index */
  236. if(config->interface) {
  237. struct ifreq iface;
  238. if(netif_index_to_name(config->interface, iface.ifr_name) == NULL) {
  239. ESP_LOGE(TAG, "fail to find interface name with netif index %d", config->interface);
  240. goto err;
  241. }
  242. if(setsockopt(ep->sock, SOL_SOCKET, SO_BINDTODEVICE, &iface, sizeof(iface)) != 0) {
  243. ESP_LOGE(TAG, "fail to setsockopt SO_BINDTODEVICE");
  244. goto err;
  245. }
  246. }
  247. struct timeval timeout;
  248. timeout.tv_sec = config->timeout_ms / 1000;
  249. timeout.tv_usec = (config->timeout_ms % 1000) * 1000;
  250. /* set receive timeout */
  251. setsockopt(ep->sock, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));
  252. /* set tos */
  253. setsockopt(ep->sock, IPPROTO_IP, IP_TOS, &config->tos, sizeof(config->tos));
  254. /* set ttl */
  255. setsockopt(ep->sock, IPPROTO_IP, IP_TTL, &config->ttl, sizeof(config->ttl));
  256. /* set socket address */
  257. if (IP_IS_V4(&config->target_addr)) {
  258. struct sockaddr_in *to4 = (struct sockaddr_in *)&ep->target_addr;
  259. to4->sin_family = AF_INET;
  260. inet_addr_from_ip4addr(&to4->sin_addr, ip_2_ip4(&config->target_addr));
  261. ep->packet_hdr->type = ICMP_ECHO;
  262. }
  263. #if CONFIG_LWIP_IPV6
  264. if (IP_IS_V6(&config->target_addr)) {
  265. struct sockaddr_in6 *to6 = (struct sockaddr_in6 *)&ep->target_addr;
  266. to6->sin6_family = AF_INET6;
  267. inet6_addr_from_ip6addr(&to6->sin6_addr, ip_2_ip6(&config->target_addr));
  268. ep->packet_hdr->type = ICMP6_TYPE_EREQ;
  269. }
  270. #endif
  271. /* return ping handle to user */
  272. *hdl_out = (esp_ping_handle_t)ep;
  273. return ESP_OK;
  274. err:
  275. if (ep) {
  276. if (ep->sock > 0) {
  277. close(ep->sock);
  278. }
  279. if (ep->packet_hdr) {
  280. free(ep->packet_hdr);
  281. }
  282. if (ep->ping_task_hdl) {
  283. vTaskDelete(ep->ping_task_hdl);
  284. }
  285. free(ep);
  286. }
  287. return ret;
  288. }
  289. esp_err_t esp_ping_delete_session(esp_ping_handle_t hdl)
  290. {
  291. esp_err_t ret = ESP_OK;
  292. esp_ping_t *ep = (esp_ping_t *)hdl;
  293. ESP_GOTO_ON_FALSE(ep, ESP_ERR_INVALID_ARG, err, TAG, "ping handle can't be null");
  294. /* reset init flags, then ping task will exit */
  295. ep->flags &= ~PING_FLAGS_INIT;
  296. return ESP_OK;
  297. err:
  298. return ret;
  299. }
  300. esp_err_t esp_ping_start(esp_ping_handle_t hdl)
  301. {
  302. esp_err_t ret = ESP_OK;
  303. esp_ping_t *ep = (esp_ping_t *)hdl;
  304. ESP_GOTO_ON_FALSE(ep, ESP_ERR_INVALID_ARG, err, TAG, "ping handle can't be null");
  305. ep->flags |= PING_FLAGS_START;
  306. xTaskNotifyGive(ep->ping_task_hdl);
  307. return ESP_OK;
  308. err:
  309. return ret;
  310. }
  311. esp_err_t esp_ping_stop(esp_ping_handle_t hdl)
  312. {
  313. esp_err_t ret = ESP_OK;
  314. esp_ping_t *ep = (esp_ping_t *)hdl;
  315. ESP_GOTO_ON_FALSE(ep, ESP_ERR_INVALID_ARG, err, TAG, "ping handle can't be null");
  316. ep->flags &= ~PING_FLAGS_START;
  317. return ESP_OK;
  318. err:
  319. return ret;
  320. }
  321. esp_err_t esp_ping_get_profile(esp_ping_handle_t hdl, esp_ping_profile_t profile, void *data, uint32_t size)
  322. {
  323. esp_err_t ret = ESP_OK;
  324. esp_ping_t *ep = (esp_ping_t *)hdl;
  325. const void *from = NULL;
  326. uint32_t copy_size = 0;
  327. ESP_GOTO_ON_FALSE(ep, ESP_ERR_INVALID_ARG, err, TAG, "ping handle can't be null");
  328. ESP_GOTO_ON_FALSE(data, ESP_ERR_INVALID_ARG, err, TAG, "profile data can't be null");
  329. switch (profile) {
  330. case ESP_PING_PROF_SEQNO:
  331. from = &ep->packet_hdr->seqno;
  332. copy_size = sizeof(ep->packet_hdr->seqno);
  333. break;
  334. case ESP_PING_PROF_TOS:
  335. from = &ep->tos;
  336. copy_size = sizeof(ep->tos);
  337. break;
  338. case ESP_PING_PROF_TTL:
  339. from = &ep->ttl;
  340. copy_size = sizeof(ep->ttl);
  341. break;
  342. case ESP_PING_PROF_REQUEST:
  343. from = &ep->transmitted;
  344. copy_size = sizeof(ep->transmitted);
  345. break;
  346. case ESP_PING_PROF_REPLY:
  347. from = &ep->received;
  348. copy_size = sizeof(ep->received);
  349. break;
  350. case ESP_PING_PROF_IPADDR:
  351. from = &ep->recv_addr;
  352. copy_size = sizeof(ep->recv_addr);
  353. break;
  354. case ESP_PING_PROF_SIZE:
  355. from = &ep->recv_len;
  356. copy_size = sizeof(ep->recv_len);
  357. break;
  358. case ESP_PING_PROF_TIMEGAP:
  359. from = &ep->elapsed_time_ms;
  360. copy_size = sizeof(ep->elapsed_time_ms);
  361. break;
  362. case ESP_PING_PROF_DURATION:
  363. from = &ep->total_time_ms;
  364. copy_size = sizeof(ep->total_time_ms);
  365. break;
  366. default:
  367. ESP_GOTO_ON_FALSE(false, ESP_ERR_INVALID_ARG, err, TAG, "unknown profile: %d", profile);
  368. break;
  369. }
  370. ESP_GOTO_ON_FALSE(size >= copy_size, ESP_ERR_INVALID_SIZE, err, TAG, "unmatched data size for profile %d", profile);
  371. memcpy(data, from, copy_size);
  372. return ESP_OK;
  373. err:
  374. return ret;
  375. }