ping_sock.c 15 KB

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