]> git.meshlink.io Git - meshlink/blob - examples/groupchat.c
Never automatically try to bind to ports >= 32768.
[meshlink] / examples / groupchat.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <strings.h>
5
6 #include "../src/meshlink.h"
7 #include "../src/devtools.h"
8
9 #define CHAT_PORT 531
10
11 static void log_message(meshlink_handle_t *mesh, meshlink_log_level_t level, const char *text) {
12         (void) mesh;
13
14         static const char *levelstr[] = {
15                 [MESHLINK_DEBUG] = "\x1b[34mDEBUG",
16                 [MESHLINK_INFO] = "\x1b[32mINFO",
17                 [MESHLINK_WARNING] = "\x1b[33mWARNING",
18                 [MESHLINK_ERROR] = "\x1b[31mERROR",
19                 [MESHLINK_CRITICAL] = "\x1b[31mCRITICAL",
20         };
21         fprintf(stderr, "%s:\x1b[0m %s\n", levelstr[level], text);
22 }
23
24 static void channel_receive(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
25         if(!len) {
26                 if(meshlink_errno) {
27                         fprintf(stderr, "Error while reading data from %s: %s\n", channel->node->name, meshlink_strerror(meshlink_errno));
28                 } else {
29                         fprintf(stderr, "Chat connection closed by %s\n", channel->node->name);
30                 }
31
32                 channel->node->priv = NULL;
33                 meshlink_channel_close(mesh, channel);
34                 return;
35         }
36
37         // TODO: we now have TCP semantics, don't expect exactly one message per receive call.
38
39         fprintf(stderr, "%s says: ", channel->node->name);
40         fwrite(data, len, 1, stderr);
41         fputc('\n', stderr);
42 }
43
44 static bool channel_accept(meshlink_handle_t *mesh, meshlink_channel_t *channel, uint16_t port, const void *data, size_t len) {
45         (void)data;
46         (void)len;
47
48         // Only accept connections to the chat port
49         if(port != CHAT_PORT) {
50                 fprintf(stderr, "Rejected incoming channel from '%s' to port %u\n", channel->node->name, port);
51                 return false;
52         }
53
54         fprintf(stderr, "Accepted incoming channel from '%s'\n", channel->node->name);
55
56         // Remember the channel
57         channel->node->priv = channel;
58
59         // Set the receive callback
60         meshlink_set_channel_receive_cb(mesh, channel, channel_receive);
61
62         // Accept this channel
63         return true;
64 }
65
66 static void channel_poll(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t len) {
67         (void)len;
68
69         fprintf(stderr, "Channel to '%s' connected\n", channel->node->name);
70         meshlink_set_channel_poll_cb(mesh, channel, NULL);
71 }
72
73 static void node_status(meshlink_handle_t *mesh, meshlink_node_t *node, bool reachable) {
74         (void)mesh;
75
76         if(reachable) {
77                 fprintf(stderr, "%s joined.\n", node->name);
78         } else {
79                 fprintf(stderr, "%s left.\n", node->name);
80         }
81 }
82
83 static void parse_command(meshlink_handle_t *mesh, char *buf) {
84         char *arg = strchr(buf, ' ');
85         char *arg1 = NULL;
86
87         if(arg) {
88                 *arg++ = 0;
89
90                 arg1 = strchr(arg, ' ');
91
92                 if(arg1) {
93                         *arg1++ = 0;
94                 }
95
96         }
97
98         if(!strcasecmp(buf, "invite")) {
99                 if(!arg) {
100                         fprintf(stderr, "/invite requires an argument!\n");
101                         return;
102                 }
103
104                 meshlink_submesh_t *s = NULL;
105
106                 if(arg1) {
107                         size_t nmemb;
108                         meshlink_submesh_t **submeshes = devtool_get_all_submeshes(mesh, NULL, &nmemb);
109
110                         if(!submeshes || !nmemb) {
111                                 fprintf(stderr, "Group does not exist!\n");
112                                 return;
113                         }
114
115                         for(size_t i = 0; i < nmemb; i++) {
116                                 if(!strcmp(arg1, submeshes[i]->name)) {
117                                         s = submeshes[i];
118                                         break;
119                                 }
120                         }
121
122                         free(submeshes);
123
124                         if(!s) {
125                                 fprintf(stderr, "Group is not yet created!\n");
126                                 return;
127                         }
128                 }
129
130                 char *invitation = meshlink_invite(mesh, s, arg);
131
132                 if(!invitation) {
133                         fprintf(stderr, "Could not invite '%s': %s\n", arg, meshlink_strerror(meshlink_errno));
134                         return;
135                 }
136
137                 fprintf(stderr, "Invitation for %s: %s\n", arg, invitation);
138                 free(invitation);
139         } else if(!strcasecmp(buf, "canonical")) {
140                 bool set;
141                 char *host = NULL, *port = NULL;
142
143                 if(!arg) {
144                         fprintf(stderr, "/canonical requires an argument!\n");
145                         return;
146                 }
147
148                 if((0 == strncasecmp(arg, "-h", 2)) && (strlen(arg) > 2)) {
149                         host = arg + 2;
150                 } else if((0 == strncasecmp(arg, "-p", 2)) && (strlen(arg) > 2)) {
151                         port = arg + 2;
152                 } else {
153                         fprintf(stderr, "Unknown argument: %s!\n", arg);
154                         return;
155                 }
156
157                 if(arg1) {
158                         if((0 == strncasecmp(arg1, "-h", 2)) && (strlen(arg1) > 2)) {
159                                 host = arg1 + 2;
160                         } else if((0 == strncasecmp(arg1, "-p", 2)) && (strlen(arg1) > 2)) {
161                                 port = arg1 + 2;
162                         } else {
163                                 fprintf(stderr, "Unknown argument: %s!\n", arg1);
164                                 return;
165                         }
166                 }
167
168                 if(!host && !port) {
169                         fprintf(stderr, "Unable to set Canonical address because no valid arguments are found!\n");
170                         return;
171                 }
172
173                 set = meshlink_set_canonical_address(mesh, meshlink_get_self(mesh), host, port);
174
175                 if(!set) {
176                         fprintf(stderr, "Could not set canonical address '%s:%s': %s\n", host, port, meshlink_strerror(meshlink_errno));
177                         return;
178                 }
179
180                 fprintf(stderr, "Canonical address set as '%s:%s'\n", host, port);
181         } else if(!strcasecmp(buf, "group")) {
182                 if(!arg) {
183                         fprintf(stderr, "/group requires an argument!\n");
184                         return;
185                 }
186
187                 meshlink_submesh_t *s = meshlink_submesh_open(mesh, arg);
188
189                 if(!s) {
190                         fprintf(stderr, "Could not create group: %s\n", meshlink_strerror(meshlink_errno));
191                 } else {
192                         fprintf(stderr, "Group '%s' created!\n", s->name);
193                 }
194         } else if(!strcasecmp(buf, "join")) {
195                 if(!arg) {
196                         fprintf(stderr, "/join requires an argument!\n");
197                         return;
198                 }
199
200                 meshlink_stop(mesh);
201
202                 if(!meshlink_join(mesh, arg)) {
203                         fprintf(stderr, "Could not join using invitation: %s\n", meshlink_strerror(meshlink_errno));
204                 } else {
205                         fprintf(stderr, "Invitation accepted!\n");
206                 }
207
208                 if(!meshlink_start(mesh)) {
209                         fprintf(stderr, "Could not restart MeshLink: %s\n", meshlink_strerror(meshlink_errno));
210                         exit(1);
211                 }
212         } else if(!strcasecmp(buf, "kick")) {
213                 if(!arg) {
214                         fprintf(stderr, "/kick requires an argument!\n");
215                         return;
216                 }
217
218                 meshlink_node_t *node = meshlink_get_node(mesh, arg);
219
220                 if(!node) {
221                         fprintf(stderr, "Error looking up '%s': %s\n", arg, meshlink_strerror(meshlink_errno));
222                         return;
223                 }
224
225                 if(!meshlink_blacklist(mesh, node)) {
226                         fprintf(stderr, "Error blacklising '%s': %s", arg, meshlink_strerror(meshlink_errno));
227                         return;
228                 }
229
230                 fprintf(stderr, "Node '%s' blacklisted.\n", arg);
231         } else if(!strcasecmp(buf, "whitelist")) {
232                 if(!arg) {
233                         fprintf(stderr, "/whitelist requires an argument!\n");
234                         return;
235                 }
236
237                 meshlink_node_t *node = meshlink_get_node(mesh, arg);
238
239                 if(!node) {
240                         fprintf(stderr, "Error looking up '%s': %s\n", arg, meshlink_strerror(meshlink_errno));
241                         return;
242                 }
243
244                 if(!meshlink_whitelist(mesh, node)) {
245                         fprintf(stderr, "Error whitelising '%s': %s", arg, meshlink_strerror(meshlink_errno));
246                         return;
247                 }
248
249                 fprintf(stderr, "Node '%s' whitelisted.\n", arg);
250         } else if(!strcasecmp(buf, "who")) {
251                 meshlink_submesh_t *node_group = NULL;
252
253                 if(!arg) {
254                         size_t nnodes;
255                         meshlink_node_t **nodes = meshlink_get_all_nodes(mesh, NULL, &nnodes);
256
257                         if(!nnodes) {
258                                 fprintf(stderr, "Could not get list of nodes: %s\n", meshlink_strerror(meshlink_errno));
259                                 return;
260                         }
261
262                         fprintf(stderr, "%lu known nodes:\n", (unsigned long)nnodes);
263
264                         for(size_t i = 0; i < nnodes; i++) {
265                                 fprintf(stderr, " %lu. %s", (unsigned long)i, nodes[i]->name);
266
267                                 if((node_group = meshlink_get_node_submesh(mesh, nodes[i]))) {
268                                         fprintf(stderr, "\t%s", node_group->name);
269                                 }
270
271                                 fprintf(stderr, "\n");
272                         }
273
274                         fprintf(stderr, "\n");
275
276                         free(nodes);
277                 } else {
278                         meshlink_node_t *node = meshlink_get_node(mesh, arg);
279
280                         if(!node) {
281                                 fprintf(stderr, "Error looking up '%s': %s\n", arg, meshlink_strerror(meshlink_errno));
282                         } else {
283                                 fprintf(stderr, "Node %s found", arg);
284
285                                 if((node_group = meshlink_get_node_submesh(mesh, node))) {
286                                         fprintf(stderr, " in group %s", node_group->name);
287                                 }
288
289                                 fprintf(stderr, "\n");
290                         }
291                 }
292         } else if(!strcasecmp(buf, "listgroup")) {
293                 if(!arg) {
294                         fprintf(stderr, "/listgroup requires an argument!\n");
295                         return;
296                 }
297
298                 size_t nmemb;
299                 meshlink_submesh_t **submeshes = devtool_get_all_submeshes(mesh, NULL, &nmemb);
300
301                 if(!submeshes || !nmemb) {
302                         fprintf(stderr, "Group does not exist!\n");
303                         return;
304                 }
305
306                 meshlink_submesh_t *s = NULL;
307
308                 for(size_t i = 0; i < nmemb; i++) {
309                         if(!strcmp(arg, submeshes[i]->name)) {
310                                 s = submeshes[i];
311                                 break;
312                         }
313                 }
314
315                 free(submeshes);
316
317                 if(!s) {
318                         fprintf(stderr, "Group %s does not exist!\n", arg);
319                         return;
320                 }
321
322                 size_t nnodes;
323                 meshlink_node_t **nodes = meshlink_get_all_nodes_by_submesh(mesh, s, NULL, &nnodes);
324
325                 if(!nodes || !nnodes) {
326                         fprintf(stderr, "Group %s does not contain any nodes!\n", arg);
327                         return;
328                 }
329
330                 fprintf(stderr, "%zu known nodes in group %s:", nnodes, arg);
331
332                 for(size_t i = 0; i < nnodes; i++) {
333                         fprintf(stderr, " %s", nodes[i]->name);
334                 }
335
336                 fprintf(stderr, "\n");
337
338                 free(nodes);
339         } else if(!strcasecmp(buf, "quit")) {
340                 fprintf(stderr, "Bye!\n");
341                 fclose(stdin);
342         } else if(!strcasecmp(buf, "help")) {
343                 fprintf(stderr,
344                         "<name>: <message>                        Send a message to the given node.\n"
345                         "                                         Subsequent messages don't need the <name>: prefix.\n"
346                         "/group <name>                            Create a new group"
347                         "/invite <name> [submesh]                 Create an invitation for a new node.\n"
348                         "                                         Node joins either coremesh or submesh depending on submesh parameter.\n"
349                         "/join <invitation>                               Join an existing mesh using an invitation.\n"
350                         "/kick <name>                             Blacklist the given node.\n"
351                         "/who [<name>]                            List all nodes or show information about the given node.\n"
352                         "/listgroup <name>                        List all nodes in a given group.\n"
353                         "/canonical -h<hostname> -p<port> Set Canonical address to be present in invitation.\n"
354                         "                                         Any one of two options an be specified. At least one option must be present\n"
355                         "/quit                                    Exit this program.\n"
356                        );
357         } else {
358                 fprintf(stderr, "Unknown command '/%s'\n", buf);
359         }
360 }
361
362 static void parse_input(meshlink_handle_t *mesh, char *buf) {
363         static meshlink_node_t *destination;
364         size_t len;
365
366         if(!buf) {
367                 return;
368         }
369
370         // Remove newline.
371
372         len = strlen(buf);
373
374         if(len && buf[len - 1] == '\n') {
375                 buf[--len] = 0;
376         }
377
378         if(len && buf[len - 1] == '\r') {
379                 buf[--len] = 0;
380         }
381
382         // Ignore empty lines.
383
384         if(!len) {
385                 return;
386         }
387
388         // Commands start with '/'
389
390         if(*buf == '/') {
391                 parse_command(mesh, buf + 1);
392                 return;
393         }
394
395         // Lines in the form "name: message..." set the destination node.
396
397         char *msg = buf;
398         char *colon = strchr(buf, ':');
399
400         if(colon) {
401                 *colon = 0;
402                 msg = colon + 1;
403
404                 if(*msg == ' ') {
405                         msg++;
406                 }
407
408                 destination = meshlink_get_node(mesh, buf);
409
410                 if(!destination) {
411                         fprintf(stderr, "Error looking up '%s': %s\n", buf, meshlink_strerror(meshlink_errno));
412                         return;
413                 }
414         }
415
416         if(!destination) {
417                 fprintf(stderr, "Who are you talking to? Write 'name: message...'\n");
418                 return;
419         }
420
421         // We want to have one channel per node.
422         // We keep the pointer to the meshlink_channel_t in the priv field of that node.
423         meshlink_channel_t *channel = destination->priv;
424
425         if(!channel) {
426                 fprintf(stderr, "Opening chat channel to '%s'\n", destination->name);
427                 channel = meshlink_channel_open(mesh, destination, CHAT_PORT, channel_receive, NULL, 0);
428
429                 if(!channel) {
430                         fprintf(stderr, "Could not create channel to '%s': %s\n", destination->name, meshlink_strerror(meshlink_errno));
431                         return;
432                 }
433
434                 destination->priv = channel;
435                 meshlink_set_channel_poll_cb(mesh, channel, channel_poll);
436         }
437
438         if(!meshlink_channel_send(mesh, channel, msg, strlen(msg))) {
439                 fprintf(stderr, "Could not send message to '%s': %s\n", destination->name, meshlink_strerror(meshlink_errno));
440                 return;
441         }
442
443         fprintf(stderr, "Message sent to '%s'.\n", destination->name);
444 }
445
446 int main(int argc, char *argv[]) {
447         const char *confbase = ".chat";
448         const char *nick = NULL;
449         char buf[1024];
450
451         if(argc > 1) {
452                 confbase = argv[1];
453         }
454
455         if(argc > 2) {
456                 nick = argv[2];
457         }
458
459         meshlink_set_log_cb(NULL, MESHLINK_DEBUG, log_message);
460
461         meshlink_handle_t *mesh = meshlink_open(confbase, nick, "chat", DEV_CLASS_STATIONARY);
462
463         if(!mesh) {
464                 fprintf(stderr, "Could not open MeshLink: %s\n", meshlink_strerror(meshlink_errno));
465                 return 1;
466         }
467
468         meshlink_set_node_status_cb(mesh, node_status);
469         meshlink_set_log_cb(mesh, MESHLINK_INFO, log_message);
470
471         // Set the channel accept callback. This implicitly turns on channels for all nodes.
472         // This replaces the call to meshlink_set_receive_cb().
473         meshlink_set_channel_accept_cb(mesh, channel_accept);
474
475         if(!meshlink_start(mesh)) {
476                 fprintf(stderr, "Could not start MeshLink: %s\n", meshlink_strerror(meshlink_errno));
477                 return 1;
478         }
479
480         fprintf(stderr, "Chat started.\nType /help for a list of commands.\n");
481
482         while(fgets(buf, sizeof(buf), stdin)) {
483                 parse_input(mesh, buf);
484         }
485
486         fprintf(stderr, "Chat stopping.\n");
487
488         meshlink_stop(mesh);
489         meshlink_close(mesh);
490
491         return 0;
492 }