]> git.meshlink.io Git - meshlink-tiny/blob - src/protocol.c
d95edceda62b99f506ddfe714241d7e63b222adf
[meshlink-tiny] / src / protocol.c
1 /*
2     protocol.c -- handle the meta-protocol, basic functions
3     Copyright (C) 2014-2017 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 #include "system.h"
21
22 #include "conf.h"
23 #include "connection.h"
24 #include "logger.h"
25 #include "meshlink_internal.h"
26 #include "meta.h"
27 #include "protocol.h"
28 #include "utils.h"
29 #include "xalloc.h"
30
31 /* Jumptable for the request handlers */
32
33 static bool (*request_handlers[NUM_REQUESTS])(meshlink_handle_t *, connection_t *, const char *) = {
34         [ID] = id_h,
35         [ACK] = ack_h,
36         [STATUS] = status_h,
37         [ERROR] = error_h,
38         [TERMREQ] = termreq_h,
39         [PING] = ping_h,
40         [PONG] = pong_h,
41         [ADD_EDGE] = add_edge_h,
42         [DEL_EDGE] = del_edge_h,
43         [KEY_CHANGED] = key_changed_h,
44         [REQ_KEY] = req_key_h,
45         [ANS_KEY] = ans_key_h,
46 };
47
48 /* Request names */
49
50 static const char *request_name[NUM_REQUESTS] = {
51         [ID] = "ID",
52         [ACK] = "ACK",
53         [STATUS] = "STATUS",
54         [ERROR] = "ERROR",
55         [TERMREQ] = "TERMREQ",
56         [PING] = "PING",
57         [PONG] = "PONG",
58         [ADD_EDGE] = "ADD_EDGE",
59         [DEL_EDGE] = "DEL_EDGE",
60         [KEY_CHANGED] = "KEY_CHANGED",
61         [REQ_KEY] = "REQ_KEY",
62         [ANS_KEY] = "ANS_KEY",
63 };
64
65 bool check_id(const char *id) {
66         if(!id || !*id) {
67                 return false;
68         }
69
70         for(; *id; id++)
71                 if(!isalnum(*id) && *id != '_' && *id != '-') {
72                         return false;
73                 }
74
75         return true;
76 }
77
78 /* Generic request routines - takes care of logging and error
79    detection as well */
80
81 bool send_request(meshlink_handle_t *mesh, connection_t *c, const char *format, ...) {
82         assert(format);
83         assert(*format);
84
85         if(!c) {
86                 logger(mesh, MESHLINK_ERROR, "Trying to send request to non-existing connection");
87                 return false;
88         }
89
90         va_list args;
91         char request[MAXBUFSIZE];
92         int len;
93
94         /* Use vsnprintf instead of vxasprintf: faster, no memory
95            fragmentation, cleanup is automatic, and there is a limit on the
96            input buffer anyway */
97
98         va_start(args, format);
99         len = vsnprintf(request, MAXBUFSIZE, format, args);
100         va_end(args);
101
102         if(len < 0 || len > MAXBUFSIZE - 1) {
103                 logger(mesh, MESHLINK_ERROR, "Output buffer overflow while sending request to %s", c->name);
104                 return false;
105         }
106
107         logger(mesh, MESHLINK_DEBUG, "Sending %s to %s: %s", request_name[atoi(request)], c->name, request);
108
109         request[len++] = '\n';
110
111         if(c == mesh->everyone) {
112                 broadcast_meta(mesh, NULL, request, len);
113                 return true;
114         } else {
115                 return send_meta(mesh, c, request, len);
116         }
117 }
118
119 void forward_request(meshlink_handle_t *mesh, connection_t *from, const char *request) {
120         assert(from);
121         assert(request);
122         assert(*request);
123
124         logger(mesh, MESHLINK_DEBUG, "Forwarding %s from %s: %s", request_name[atoi(request)], from->name, request);
125
126         // Create a temporary newline-terminated copy of the request
127         int len = strlen(request);
128         char tmp[len + 1];
129
130         memcpy(tmp, request, len);
131         tmp[len] = '\n';
132
133         broadcast_meta(mesh, from, tmp, sizeof(tmp));
134 }
135
136 bool receive_request(meshlink_handle_t *mesh, connection_t *c, const char *request) {
137         assert(request);
138
139         int reqno = atoi(request);
140
141         if(reqno || *request == '0') {
142                 if((reqno < 0) || (reqno >= NUM_REQUESTS) || !request_handlers[reqno]) {
143                         logger(mesh, MESHLINK_DEBUG, "Unknown request from %s: %s", c->name, request);
144                         return false;
145                 } else {
146                         logger(mesh, MESHLINK_DEBUG, "Got %s from %s: %s", request_name[reqno], c->name, request);
147                 }
148
149                 if((c->allow_request != ALL) && (c->allow_request != reqno) && (reqno != ERROR)) {
150                         logger(mesh, MESHLINK_ERROR, "Unauthorized request from %s", c->name);
151                         return false;
152                 }
153
154                 if(!request_handlers[reqno](mesh, c, request)) {
155                         /* Something went wrong. Probably scriptkiddies. Terminate. */
156
157                         logger(mesh, MESHLINK_ERROR, "Error while processing %s from %s", request_name[reqno], c->name);
158                         return false;
159                 }
160         } else {
161                 logger(mesh, MESHLINK_ERROR, "Bogus data received from %s", c->name);
162                 return false;
163         }
164
165         return true;
166 }
167
168 static int past_request_compare(const past_request_t *a, const past_request_t *b) {
169         return strcmp(a->request, b->request);
170 }
171
172 static void free_past_request(past_request_t *r) {
173         if(r->request) {
174                 free((void *)r->request);
175         }
176
177         free(r);
178 }
179
180 static const int request_timeout = 60;
181
182 static void age_past_requests(event_loop_t *loop, void *data) {
183         (void)data;
184         meshlink_handle_t *mesh = loop->data;
185         int left = 0, deleted = 0;
186
187         for splay_each(past_request_t, p, mesh->past_request_tree) {
188                 if(p->firstseen + request_timeout <= mesh->loop.now.tv_sec) {
189                         splay_delete_node(mesh->past_request_tree, splay_node), deleted++;
190                 } else {
191                         left++;
192                 }
193         }
194
195         if(left || deleted) {
196                 logger(mesh, MESHLINK_DEBUG, "Aging past requests: deleted %d, left %d", deleted, left);
197         }
198
199         if(left) {
200                 timeout_set(&mesh->loop, &mesh->past_request_timeout, &(struct timespec) {
201                         10, prng(mesh, TIMER_FUDGE)
202                 });
203         }
204 }
205
206 bool seen_request(meshlink_handle_t *mesh, const char *request) {
207         assert(request);
208         assert(*request);
209
210         past_request_t *new, p = {.request = request};
211
212         if(splay_search(mesh->past_request_tree, &p)) {
213                 logger(mesh, MESHLINK_DEBUG, "Already seen request");
214                 return true;
215         } else {
216                 new = xmalloc(sizeof(*new));
217                 new->request = xstrdup(request);
218                 new->firstseen = mesh->loop.now.tv_sec;
219
220                 if(!mesh->past_request_tree->head && mesh->past_request_timeout.cb) {
221                         timeout_set(&mesh->loop, &mesh->past_request_timeout, &(struct timespec) {
222                                 10, prng(mesh, TIMER_FUDGE)
223                         });
224                 }
225
226                 splay_insert(mesh->past_request_tree, new);
227                 return false;
228         }
229 }
230
231 void init_requests(meshlink_handle_t *mesh) {
232         assert(!mesh->past_request_tree);
233
234         mesh->past_request_tree = splay_alloc_tree((splay_compare_t) past_request_compare, (splay_action_t) free_past_request);
235         timeout_add(&mesh->loop, &mesh->past_request_timeout, age_past_requests, NULL, &(struct timespec) {
236                 0, 0
237         });
238 }
239
240 void exit_requests(meshlink_handle_t *mesh) {
241         if(mesh->past_request_tree) {
242                 splay_delete_tree(mesh->past_request_tree);
243         }
244
245         mesh->past_request_tree = NULL;
246
247         timeout_del(&mesh->loop, &mesh->past_request_timeout);
248 }