]> git.meshlink.io Git - meshlink/blob - test/blackbox/common/mesh_event_handler.c
Ensure NDEBUG is not set in the test suite.
[meshlink] / test / blackbox / common / mesh_event_handler.c
1 /*
2     mesh_event_handler.c -- handling of mesh events API
3     Copyright (C) 2018  Guus Sliepen <guus@meshlink.io>
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License along
16     with this program; if not, write to the Free Software Foundation, Inc.,
17     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #ifdef NDEBUG
21 #undef NDEBUG
22 #endif
23
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <netinet/in.h>
28 #include <arpa/inet.h>
29 #include <sys/types.h>
30 #include <net/if.h>
31 #include <sys/ioctl.h>
32 #include <sys/socket.h>
33 #include <stdbool.h>
34 #include <errno.h>
35 #include <assert.h>
36 #include <fcntl.h>
37 #include <time.h>
38 #include <pthread.h>
39 #include "../../../src/meshlink_queue.h"
40 #include "../../utils.h"
41 #include "mesh_event_handler.h"
42
43 #define SERVER_LISTEN_PORT "9000" /* Port number that is binded with mesh event server socket */
44 #define UDP_BUFF_MAX 2000
45
46 const char *event_status[] = {
47         [NODE_STARTED]                          = "Node Started",
48         [NODE_JOINED]                           = "Node Joined",
49         [ERR_NETWORK]                           = "Network Error",
50         [CHANNEL_OPENED]                        = "Channel Opened",
51         [CHANNEL_DATA_RECIEVED]                         = "Channel Data Received",
52         [SIG_ABORT]                             = "SIG_ABORT Received",
53         [MESH_EVENT_COMPLETED]                          = "MESH_EVENT_COMPLETED Received"
54 };
55
56 // TODO: Implement mesh event handling with reentrancy .
57 static struct sockaddr_in server_addr;
58 static int client_fd = -1;
59 static int server_fd = -1;
60 static pthread_t event_receive_thread, event_handle_thread;
61 static meshlink_queue_t event_queue;
62 static bool event_receive_thread_running, event_handle_thread_running;
63 static struct cond_flag sync_event = {.mutex  = PTHREAD_MUTEX_INITIALIZER, .cond = PTHREAD_COND_INITIALIZER};
64
65 static void set_cond_flag(struct cond_flag *s, bool flag) {
66         pthread_mutex_lock(&s->mutex);
67         s->flag = flag;
68         pthread_cond_broadcast(&s->cond);
69         pthread_mutex_unlock(&s->mutex);
70 }
71
72 static bool wait_cond_flag(struct cond_flag *s, int seconds) {
73         struct timespec timeout;
74         clock_gettime(CLOCK_REALTIME, &timeout);
75         timeout.tv_sec += seconds;
76
77         pthread_mutex_lock(&s->mutex);
78
79         while(!s->flag)
80                 if(!pthread_cond_timedwait(&s->cond, &s->mutex, &timeout) || errno != EINTR) {
81                         break;
82                 }
83
84         pthread_mutex_unlock(&s->mutex);
85
86         return s->flag;
87 }
88
89 // event_receive_handler running in a separate thread queues all the events received from the UDP port
90 static void *event_receive_handler(void *arg) {
91         (void)arg;
92         size_t recv_ret;
93         char udp_buff[UDP_BUFF_MAX];
94         struct sockaddr client;
95         socklen_t soc_len;
96
97         while(event_receive_thread_running) {
98                 recv_ret = recvfrom(server_fd, udp_buff, sizeof(udp_buff), 0, &client, &soc_len);
99                 assert(recv_ret >= sizeof(mesh_event_payload_t));
100
101                 // Push received mesh event data into the event_queue
102                 mesh_event_payload_t *data = malloc(sizeof(mesh_event_payload_t));
103                 assert(data);
104                 memcpy(data, udp_buff, sizeof(mesh_event_payload_t));
105
106                 // Also receive if there is any payload
107                 if(data->payload_length) {
108                         void *payload_data = malloc(data->payload_length);
109                         assert(payload_data);
110                         memcpy(payload_data, udp_buff + (int)sizeof(mesh_event_payload_t), data->payload_length);
111                         data->payload = payload_data;
112                 } else {
113                         data->payload = NULL;
114                 }
115
116                 // Push the event into the event queue
117                 assert(meshlink_queue_push(&event_queue, data));
118         }
119
120         return NULL;
121 }
122
123 // `event_handler' runs in a separate thread which invokes the event handle callback with
124 // event packet as argument returns from the thread when the callback returns `true' or timeout
125 static void *event_handler(void *argv) {
126         bool callback_return = false;
127         void *data;
128         mesh_event_payload_t mesh_event_rec_packet;
129         mesh_event_callback_t callback = *(mesh_event_callback_t *)argv;
130
131         while(event_handle_thread_running) {
132
133                 // Pops the event if found in the event queue
134                 while((data = meshlink_queue_pop(&event_queue)) != NULL) {
135                         memcpy(&mesh_event_rec_packet, data, sizeof(mesh_event_payload_t));
136                         free(data);
137
138                         // Invokes the callback with the popped event packet
139                         callback_return = callback(mesh_event_rec_packet);
140
141                         if(mesh_event_rec_packet.payload_length) {
142                                 free(mesh_event_rec_packet.payload);
143                         }
144
145                         // Return or Close the event handle thread if callback returns true
146                         if(callback_return) {
147                                 set_cond_flag(&sync_event, true);
148                                 event_handle_thread_running = false;
149                                 break;
150                         }
151                 }
152         }
153
154         return NULL;
155 }
156
157 char *mesh_event_sock_create(const char *if_name) {
158         struct sockaddr_in server = {0};
159         char *ip;
160         struct ifreq req_if = {0};
161         struct sockaddr_in *resp_if_addr;
162
163         assert(if_name);
164         assert(!event_receive_thread_running);
165
166         server_fd = socket(AF_INET, SOCK_DGRAM, 0);
167         assert(server_fd >= 0);
168
169         int reuse = 1;
170         assert(setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) != -1);
171
172         req_if.ifr_addr.sa_family = AF_INET;
173         strncpy(req_if.ifr_name, if_name, IFNAMSIZ - 1);
174         assert(ioctl(server_fd, SIOCGIFADDR, &req_if) != -1);
175         resp_if_addr = (struct sockaddr_in *) & (req_if.ifr_addr);
176
177         server.sin_family = AF_INET;
178         server.sin_addr   = resp_if_addr->sin_addr;
179         server.sin_port   = htons(atoi(SERVER_LISTEN_PORT));
180         assert(bind(server_fd, (struct sockaddr *) &server, sizeof(struct sockaddr)) != -1);
181
182         assert((ip = malloc(30)));
183         strncpy(ip, inet_ntoa(resp_if_addr->sin_addr), 20);
184         strcat(ip, ":");
185         strcat(ip, SERVER_LISTEN_PORT);
186
187         meshlink_queue_init(&event_queue);
188         event_receive_thread_running = true;
189         assert(!pthread_create(&event_receive_thread, NULL, event_receive_handler, NULL));
190
191         return ip;
192 }
193
194 void mesh_event_sock_connect(const char *import) {
195         assert(import);
196
197         char *ip = strdup(import);
198         assert(ip);
199         char *port = strchr(ip, ':');
200         assert(port);
201         *port = '\0';
202         port++;
203
204         memset(&server_addr, 0, sizeof(server_addr));
205         server_addr.sin_family      = AF_INET;
206         server_addr.sin_addr.s_addr = inet_addr(ip);
207         server_addr.sin_port        = htons(atoi(port));
208         client_fd = socket(AF_INET, SOCK_DGRAM, 0);
209         free(ip);
210         assert(client_fd >= 0);
211 }
212
213 bool mesh_event_sock_send(int client_id, mesh_event_t event, const void *payload, size_t payload_length) {
214         if(client_fd < 0) {
215                 fprintf(stderr, "mesh_event_sock_send called without calling mesh_event_sock_connect\n");
216                 return false;
217         }
218
219         if(client_id < 0 || event < 0 || event >= MAX_EVENT || (payload == NULL && payload_length)) {
220                 fprintf(stderr, "Invalid parameters\n");
221                 return false;
222         }
223
224         ssize_t send_size = sizeof(mesh_event_payload_t) + payload_length;
225         char *send_packet = malloc(send_size);
226         assert(send_packet);
227         mesh_event_payload_t mesh_event_send_packet;
228
229         mesh_event_send_packet.client_id   = client_id;
230         mesh_event_send_packet.mesh_event  = event;
231         mesh_event_send_packet.payload_length = payload_length;
232         mesh_event_send_packet.payload = NULL;
233         memcpy(send_packet, &mesh_event_send_packet, sizeof(mesh_event_send_packet));
234
235         if(payload_length) {
236                 memcpy(send_packet + sizeof(mesh_event_send_packet), payload, payload_length);
237         }
238
239         ssize_t send_ret = sendto(client_fd, send_packet, send_size, 0, (const struct sockaddr *) &server_addr, sizeof(server_addr));
240         free(send_packet);
241
242         if(send_ret < 0) {
243                 perror("sendto status");
244                 return false;
245         } else {
246                 return true;
247         }
248 }
249
250 bool wait_for_event(mesh_event_callback_t callback, int seconds) {
251         if(callback == NULL || seconds == 0) {
252                 fprintf(stderr, "Invalid parameters\n");
253                 return false;
254         }
255
256         if(event_handle_thread_running) {
257                 fprintf(stderr, "Event handle thread is already running\n");
258                 return false;
259         } else {
260                 event_handle_thread_running = true;
261         }
262
263         set_cond_flag(&sync_event, false);
264         assert(!pthread_create(&event_handle_thread, NULL, event_handler, (void *)&callback));
265         bool wait_ret = wait_cond_flag(&sync_event, seconds);
266         event_handle_thread_running = false;
267         pthread_cancel(event_handle_thread);
268
269         return wait_ret;
270 }
271
272 void mesh_events_flush(void) {
273         mesh_event_payload_t *data;
274
275         while((data = meshlink_queue_pop(&event_queue)) != NULL) {
276                 if(data->payload_length) {
277                         free(data->payload);
278                 }
279
280                 free(data);
281         }
282 }
283
284 void mesh_event_destroy(void) {
285         mesh_events_flush();
286         event_receive_thread_running = false;
287         pthread_cancel(event_receive_thread);
288 }