ping_sock.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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. int 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 != 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. } else {
  106. // IPv6
  107. struct sockaddr_in6 *from6 = (struct sockaddr_in6 *)&from;
  108. inet6_addr_to_ip6addr(ip_2_ip6(&ep->recv_addr), &from6->sin6_addr);
  109. IP_SET_TYPE_VAL(ep->recv_addr, IPADDR_TYPE_V6);
  110. data_head = (uint16_t)(sizeof(struct ip6_hdr) + sizeof(struct icmp6_echo_hdr));
  111. }
  112. if (len >= data_head) {
  113. if (IP_IS_V4_VAL(ep->recv_addr)) { // Currently we process IPv4
  114. struct ip_hdr *iphdr = (struct ip_hdr *)buf;
  115. struct icmp_echo_hdr *iecho = (struct icmp_echo_hdr *)(buf + (IPH_HL(iphdr) * 4));
  116. if ((iecho->id == ep->packet_hdr->id) && (iecho->seqno == ep->packet_hdr->seqno)) {
  117. ep->received++;
  118. ep->ttl = iphdr->_ttl;
  119. ep->recv_len = lwip_ntohs(IPH_LEN(iphdr)) - data_head; // The data portion of ICMP
  120. return len;
  121. }
  122. } else if (IP_IS_V6_VAL(ep->recv_addr)) { // Currently we process IPv6
  123. struct ip6_hdr *iphdr = (struct ip6_hdr *)buf;
  124. struct icmp6_echo_hdr *iecho6 = (struct icmp6_echo_hdr *)(buf + sizeof(struct ip6_hdr)); // IPv6 head length is 40
  125. if ((iecho6->id == ep->packet_hdr->id) && (iecho6->seqno == ep->packet_hdr->seqno)) {
  126. ep->received++;
  127. ep->recv_len = IP6H_PLEN(iphdr) - sizeof(struct icmp6_echo_hdr); //The data portion of ICMPv6
  128. return len;
  129. }
  130. }
  131. }
  132. fromlen = sizeof(from);
  133. }
  134. // if timeout, len will be -1
  135. return len;
  136. }
  137. static void esp_ping_thread(void *args)
  138. {
  139. esp_ping_t *ep = (esp_ping_t *)(args);
  140. TickType_t last_wake;
  141. struct timeval start_time, end_time;
  142. int recv_ret;
  143. while (1) {
  144. /* wait for ping start signal */
  145. if (ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(PING_CHECK_START_TIMEOUT_MS))) {
  146. /* initialize runtime statistics */
  147. ep->packet_hdr->seqno = 0;
  148. ep->transmitted = 0;
  149. ep->received = 0;
  150. ep->total_time_ms = 0;
  151. last_wake = xTaskGetTickCount();
  152. while ((ep->flags & PING_FLAGS_START) && ((ep->count == 0) || (ep->packet_hdr->seqno < ep->count))) {
  153. esp_ping_send(ep);
  154. gettimeofday(&start_time, NULL);
  155. recv_ret = esp_ping_receive(ep);
  156. gettimeofday(&end_time, NULL);
  157. ep->elapsed_time_ms = PING_TIME_DIFF_MS(end_time, start_time);
  158. ep->total_time_ms += ep->elapsed_time_ms;
  159. if (recv_ret >= 0) {
  160. if (ep->on_ping_success) {
  161. ep->on_ping_success((esp_ping_handle_t)ep, ep->cb_args);
  162. }
  163. } else {
  164. if (ep->on_ping_timeout) {
  165. ep->on_ping_timeout((esp_ping_handle_t)ep, ep->cb_args);
  166. }
  167. }
  168. if (pdMS_TO_TICKS(ep->interval_ms)) {
  169. vTaskDelayUntil(&last_wake, pdMS_TO_TICKS(ep->interval_ms)); // to get a more accurate delay
  170. }
  171. }
  172. /* batch of ping operations finished */
  173. if (ep->on_ping_end) {
  174. ep->on_ping_end((esp_ping_handle_t)ep, ep->cb_args);
  175. }
  176. } else {
  177. // check if ping has been de-initialized
  178. if (!(ep->flags & PING_FLAGS_INIT)) {
  179. break;
  180. }
  181. }
  182. }
  183. /* before exit task, free all resources */
  184. if (ep->packet_hdr) {
  185. free(ep->packet_hdr);
  186. }
  187. if (ep->sock > 0) {
  188. close(ep->sock);
  189. }
  190. free(ep);
  191. vTaskDelete(NULL);
  192. }
  193. 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)
  194. {
  195. esp_err_t ret = ESP_OK;
  196. esp_ping_t *ep = NULL;
  197. PING_CHECK(config, "ping config can't be null", err, ESP_ERR_INVALID_ARG);
  198. PING_CHECK(hdl_out, "ping handle can't be null", err, ESP_ERR_INVALID_ARG);
  199. ep = mem_calloc(1, sizeof(esp_ping_t));
  200. PING_CHECK(ep, "no memory for esp_ping object", err, ESP_ERR_NO_MEM);
  201. /* set INIT flag, so that ping task won't exit (must set before create ping task) */
  202. ep->flags |= PING_FLAGS_INIT;
  203. /* create ping thread */
  204. BaseType_t xReturned = xTaskCreate(esp_ping_thread, "ping", config->task_stack_size, ep,
  205. config->task_prio, &ep->ping_task_hdl);
  206. PING_CHECK(xReturned == pdTRUE, "create ping task failed", err, ESP_ERR_NO_MEM);
  207. /* callback functions */
  208. if (cbs) {
  209. ep->cb_args = cbs->cb_args;
  210. ep->on_ping_end = cbs->on_ping_end;
  211. ep->on_ping_timeout = cbs->on_ping_timeout;
  212. ep->on_ping_success = cbs->on_ping_success;
  213. }
  214. /* set parameters for ping */
  215. ep->recv_addr = config->target_addr;
  216. ep->count = config->count;
  217. ep->interval_ms = config->interval_ms;
  218. ep->icmp_pkt_size = sizeof(struct icmp_echo_hdr) + config->data_size;
  219. ep->packet_hdr = mem_calloc(1, ep->icmp_pkt_size);
  220. PING_CHECK(ep->packet_hdr, "no memory for echo packet", err, ESP_ERR_NO_MEM);
  221. /* set ICMP type and code field */
  222. ep->packet_hdr->code = 0;
  223. /* ping id should be unique, treat task handle as ping ID */
  224. ep->packet_hdr->id = ((uint32_t)ep->ping_task_hdl) & 0xFFFF;
  225. /* fill the additional data buffer with some data */
  226. char *d = (char *)(ep->packet_hdr) + sizeof(struct icmp_echo_hdr);
  227. for (uint32_t i = 0; i < config->data_size; i++) {
  228. d[i] = 'A' + i;
  229. }
  230. /* create socket */
  231. if (IP_IS_V4(&config->target_addr) || ip6_addr_isipv4mappedipv6(ip_2_ip6(&config->target_addr))) {
  232. ep->sock = socket(AF_INET, SOCK_RAW, IP_PROTO_ICMP);
  233. } else {
  234. ep->sock = socket(AF_INET6, SOCK_RAW, IP6_NEXTH_ICMP6);
  235. }
  236. PING_CHECK(ep->sock > 0, "create socket failed: %d", err, ESP_FAIL, ep->sock);
  237. /* set if index */
  238. if(config->interface) {
  239. struct ifreq iface;
  240. if(netif_index_to_name(config->interface, iface.ifr_name) == NULL) {
  241. goto err;
  242. }
  243. if(setsockopt(ep->sock, SOL_SOCKET, SO_BINDTODEVICE, &iface, sizeof(iface) !=0)) {
  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 socket address */
  255. if (IP_IS_V4(&config->target_addr)) {
  256. struct sockaddr_in *to4 = (struct sockaddr_in *)&ep->target_addr;
  257. to4->sin_family = AF_INET;
  258. inet_addr_from_ip4addr(&to4->sin_addr, ip_2_ip4(&config->target_addr));
  259. ep->packet_hdr->type = ICMP_ECHO;
  260. }
  261. if (IP_IS_V6(&config->target_addr)) {
  262. struct sockaddr_in6 *to6 = (struct sockaddr_in6 *)&ep->target_addr;
  263. to6->sin6_family = AF_INET6;
  264. inet6_addr_from_ip6addr(&to6->sin6_addr, ip_2_ip6(&config->target_addr));
  265. ep->packet_hdr->type = ICMP6_TYPE_EREQ;
  266. }
  267. /* return ping handle to user */
  268. *hdl_out = (esp_ping_handle_t)ep;
  269. return ESP_OK;
  270. err:
  271. if (ep) {
  272. if (ep->sock > 0) {
  273. close(ep->sock);
  274. }
  275. if (ep->packet_hdr) {
  276. free(ep->packet_hdr);
  277. }
  278. if (ep->ping_task_hdl) {
  279. vTaskDelete(ep->ping_task_hdl);
  280. }
  281. free(ep);
  282. }
  283. return ret;
  284. }
  285. esp_err_t esp_ping_delete_session(esp_ping_handle_t hdl)
  286. {
  287. esp_err_t ret = ESP_OK;
  288. esp_ping_t *ep = (esp_ping_t *)hdl;
  289. PING_CHECK(ep, "ping handle can't be null", err, ESP_ERR_INVALID_ARG);
  290. /* reset init flags, then ping task will exit */
  291. ep->flags &= ~PING_FLAGS_INIT;
  292. return ESP_OK;
  293. err:
  294. return ret;
  295. }
  296. esp_err_t esp_ping_start(esp_ping_handle_t hdl)
  297. {
  298. esp_err_t ret = ESP_OK;
  299. esp_ping_t *ep = (esp_ping_t *)hdl;
  300. PING_CHECK(ep, "ping handle can't be null", err, ESP_ERR_INVALID_ARG);
  301. ep->flags |= PING_FLAGS_START;
  302. xTaskNotifyGive(ep->ping_task_hdl);
  303. return ESP_OK;
  304. err:
  305. return ret;
  306. }
  307. esp_err_t esp_ping_stop(esp_ping_handle_t hdl)
  308. {
  309. esp_err_t ret = ESP_OK;
  310. esp_ping_t *ep = (esp_ping_t *)hdl;
  311. PING_CHECK(ep, "ping handle can't be null", err, ESP_ERR_INVALID_ARG);
  312. ep->flags &= ~PING_FLAGS_START;
  313. return ESP_OK;
  314. err:
  315. return ret;
  316. }
  317. esp_err_t esp_ping_get_profile(esp_ping_handle_t hdl, esp_ping_profile_t profile, void *data, uint32_t size)
  318. {
  319. esp_err_t ret = ESP_OK;
  320. esp_ping_t *ep = (esp_ping_t *)hdl;
  321. const void *from = NULL;
  322. uint32_t copy_size = 0;
  323. PING_CHECK(ep, "ping handle can't be null", err, ESP_ERR_INVALID_ARG);
  324. PING_CHECK(data, "profile data can't be null", err, ESP_ERR_INVALID_ARG);
  325. switch (profile) {
  326. case ESP_PING_PROF_SEQNO:
  327. from = &ep->packet_hdr->seqno;
  328. copy_size = sizeof(ep->packet_hdr->seqno);
  329. break;
  330. case ESP_PING_PROF_TTL:
  331. from = &ep->ttl;
  332. copy_size = sizeof(ep->ttl);
  333. break;
  334. case ESP_PING_PROF_REQUEST:
  335. from = &ep->transmitted;
  336. copy_size = sizeof(ep->transmitted);
  337. break;
  338. case ESP_PING_PROF_REPLY:
  339. from = &ep->received;
  340. copy_size = sizeof(ep->received);
  341. break;
  342. case ESP_PING_PROF_IPADDR:
  343. from = &ep->recv_addr;
  344. copy_size = sizeof(ep->recv_addr);
  345. break;
  346. case ESP_PING_PROF_SIZE:
  347. from = &ep->recv_len;
  348. copy_size = sizeof(ep->recv_len);
  349. break;
  350. case ESP_PING_PROF_TIMEGAP:
  351. from = &ep->elapsed_time_ms;
  352. copy_size = sizeof(ep->elapsed_time_ms);
  353. break;
  354. case ESP_PING_PROF_DURATION:
  355. from = &ep->total_time_ms;
  356. copy_size = sizeof(ep->total_time_ms);
  357. break;
  358. default:
  359. PING_CHECK(false, "unknow profile: %d", err, ESP_ERR_INVALID_ARG, profile);
  360. break;
  361. }
  362. PING_CHECK(size >= copy_size, "unmatched data size for profile %d", err, ESP_ERR_INVALID_SIZE, profile);
  363. memcpy(data, from, copy_size);
  364. return ESP_OK;
  365. err:
  366. return ret;
  367. }