ping_sock.c 14 KB

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