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