]> git.meshlink.io Git - meshlink/blob - examples/channels.c
e56d9d1686e96ac3c2b7b7fca3c18899be541154
[meshlink] / examples / channels.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <strings.h>
5 #include "../src/meshlink.h"
6
7 #define CHAT_PORT 531
8
9 static void log_message(meshlink_handle_t *mesh, meshlink_log_level_t level, const char *text) {
10         const char *levelstr[] = {
11                 [MESHLINK_DEBUG] = "\x1b[34mDEBUG",
12                 [MESHLINK_INFO] = "\x1b[32mINFO",
13                 [MESHLINK_WARNING] = "\x1b[33mWARNING",
14                 [MESHLINK_ERROR] = "\x1b[31mERROR",
15                 [MESHLINK_CRITICAL] = "\x1b[31mCRITICAL",
16         };
17         fprintf(stderr, "%s:\x1b[0m %s\n", levelstr[level], text);
18 }
19
20 static void channel_receive(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
21         if(!len) {
22                 if(meshlink_errno) {
23                         fprintf(stderr, "Error while reading data from %s: %s\n", channel->node->name, meshlink_strerror(meshlink_errno));
24                 } else {
25                         fprintf(stderr, "Chat connection closed by %s\n", channel->node->name);
26                 }
27
28                 channel->node->priv = NULL;
29                 meshlink_channel_close(mesh, channel);
30                 return;
31         }
32
33         // TODO: we now have TCP semantics, don't expect exactly one message per receive call.
34
35         printf("%s says: ", channel->node->name);
36         fwrite(data, len, 1, stdout);
37         fputc('\n', stdout);
38 }
39
40 static bool channel_accept(meshlink_handle_t *mesh, meshlink_channel_t *channel, uint16_t port, const void *data, size_t len) {
41         // Only accept connections to the chat port
42         if(port != CHAT_PORT) {
43                 fprintf(stderr, "Rejected incoming channel from '%s' to port %u\n", channel->node->name, port);
44                 return false;
45         }
46
47         fprintf(stderr, "Accepted incoming channel from '%s'\n", channel->node->name);
48
49         // Remember the channel
50         channel->node->priv = channel;
51
52         // Set the receive callback
53         meshlink_set_channel_receive_cb(mesh, channel, channel_receive);
54
55         // Accept this channel
56         return true;
57 }
58
59 static void channel_poll(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t len) {
60         fprintf(stderr, "Channel to '%s' connected\n", channel->node->name);
61         meshlink_set_channel_poll_cb(mesh, channel, NULL);
62 }
63
64 static void node_status(meshlink_handle_t *mesh, meshlink_node_t *node, bool reachable) {
65         if(reachable) {
66                 printf("%s joined.\n", node->name);
67         } else {
68                 printf("%s left.\n", node->name);
69         }
70 }
71
72 static meshlink_node_t **nodes;
73 static size_t nnodes;
74
75 static void parse_command(meshlink_handle_t *mesh, char *buf) {
76         char *arg = strchr(buf, ' ');
77
78         if(arg) {
79                 *arg++ = 0;
80         }
81
82         if(!strcasecmp(buf, "invite")) {
83                 char *invitation;
84
85                 if(!arg) {
86                         fprintf(stderr, "/invite requires an argument!\n");
87                         return;
88                 }
89
90                 invitation = meshlink_invite(mesh, arg);
91
92                 if(!invitation) {
93                         fprintf(stderr, "Could not invite '%s': %s\n", arg, meshlink_strerror(meshlink_errno));
94                         return;
95                 }
96
97                 printf("Invitation for %s: %s\n", arg, invitation);
98                 free(invitation);
99         } else if(!strcasecmp(buf, "join")) {
100                 if(!arg) {
101                         fprintf(stderr, "/join requires an argument!\n");
102                         return;
103                 }
104
105                 meshlink_stop(mesh);
106
107                 if(!meshlink_join(mesh, arg)) {
108                         fprintf(stderr, "Could not join using invitation: %s\n", meshlink_strerror(meshlink_errno));
109                 } else {
110                         fprintf(stderr, "Invitation accepted!\n");
111                 }
112
113                 if(!meshlink_start(mesh)) {
114                         fprintf(stderr, "Could not restart MeshLink: %s\n", meshlink_strerror(meshlink_errno));
115                         exit(1);
116                 }
117         } else if(!strcasecmp(buf, "kick")) {
118                 if(!arg) {
119                         fprintf(stderr, "/kick requires an argument!\n");
120                         return;
121                 }
122
123                 meshlink_node_t *node = meshlink_get_node(mesh, arg);
124
125                 if(!node) {
126                         fprintf(stderr, "Error looking up '%s': %s\n", arg, meshlink_strerror(meshlink_errno));
127                         return;
128                 }
129
130                 meshlink_blacklist(mesh, node);
131
132                 printf("Node '%s' blacklisted.\n", arg);
133         } else if(!strcasecmp(buf, "who")) {
134                 if(!arg) {
135                         nodes = meshlink_get_all_nodes(mesh, nodes, &nnodes);
136
137                         if(!nnodes) {
138                                 fprintf(stderr, "Could not get list of nodes: %s\n", meshlink_strerror(meshlink_errno));
139                         } else {
140                                 printf("%zu known nodes:", nnodes);
141
142                                 for(int i = 0; i < nnodes; i++) {
143                                         printf(" %s", nodes[i]->name);
144                                 }
145
146                                 printf("\n");
147                         }
148                 } else {
149                         meshlink_node_t *node = meshlink_get_node(mesh, arg);
150
151                         if(!node) {
152                                 fprintf(stderr, "Error looking up '%s': %s\n", arg, meshlink_strerror(meshlink_errno));
153                         } else {
154                                 printf("Node %s found\n", arg);
155                         }
156                 }
157         } else if(!strcasecmp(buf, "quit")) {
158                 printf("Bye!\n");
159                 fclose(stdin);
160         } else if(!strcasecmp(buf, "help")) {
161                 printf(
162                         "<name>: <message>     Send a message to the given node.\n"
163                         "                      Subsequent messages don't need the <name>: prefix.\n"
164                         "/invite <name>        Create an invitation for a new node.\n"
165                         "/join <invitation>    Join an existing mesh using an invitation.\n"
166                         "/kick <name>          Blacklist the given node.\n"
167                         "/who [<name>]         List all nodes or show information about the given node.\n"
168                         "/quit                 Exit this program.\n"
169                 );
170         } else {
171                 fprintf(stderr, "Unknown command '/%s'\n", buf);
172         }
173 }
174
175 static void parse_input(meshlink_handle_t *mesh, char *buf) {
176         static meshlink_node_t *destination;
177         size_t len;
178
179         if(!buf) {
180                 return;
181         }
182
183         // Remove newline.
184
185         len = strlen(buf);
186
187         if(len && buf[len - 1] == '\n') {
188                 buf[--len] = 0;
189         }
190
191         if(len && buf[len - 1] == '\r') {
192                 buf[--len] = 0;
193         }
194
195         // Ignore empty lines.
196
197         if(!len) {
198                 return;
199         }
200
201         // Commands start with '/'
202
203         if(*buf == '/') {
204                 return parse_command(mesh, buf + 1);
205         }
206
207         // Lines in the form "name: message..." set the destination node.
208
209         char *msg = buf;
210         char *colon = strchr(buf, ':');
211
212         if(colon) {
213                 *colon = 0;
214                 msg = colon + 1;
215
216                 if(*msg == ' ') {
217                         msg++;
218                 }
219
220                 destination = meshlink_get_node(mesh, buf);
221
222                 if(!destination) {
223                         fprintf(stderr, "Error looking up '%s': %s\n", buf, meshlink_strerror(meshlink_errno));
224                         return;
225                 }
226         }
227
228         if(!destination) {
229                 fprintf(stderr, "Who are you talking to? Write 'name: message...'\n");
230                 return;
231         }
232
233         // We want to have one channel per node.
234         // We keep the pointer to the meshlink_channel_t in the priv field of that node.
235         meshlink_channel_t *channel = destination->priv;
236
237         if(!channel) {
238                 fprintf(stderr, "Opening chat channel to '%s'\n", destination->name);
239                 channel = meshlink_channel_open(mesh, destination, CHAT_PORT, channel_receive, NULL, 0);
240
241                 if(!channel) {
242                         fprintf(stderr, "Could not create channel to '%s': %s\n", destination->name, meshlink_strerror(meshlink_errno));
243                         return;
244                 }
245
246                 destination->priv = channel;
247                 meshlink_set_channel_poll_cb(mesh, channel, channel_poll);
248         }
249
250         if(!meshlink_channel_send(mesh, channel, msg, strlen(msg))) {
251                 fprintf(stderr, "Could not send message to '%s': %s\n", destination->name, meshlink_strerror(meshlink_errno));
252                 return;
253         }
254
255         printf("Message sent to '%s'.\n", destination->name);
256 }
257
258 int main(int argc, char *argv[]) {
259         const char *confbase = ".chat";
260         const char *nick = NULL;
261         char buf[1024];
262
263         if(argc > 1) {
264                 confbase = argv[1];
265         }
266
267         if(argc > 2) {
268                 nick = argv[2];
269         }
270
271         meshlink_set_log_cb(NULL, MESHLINK_DEBUG, log_message);
272
273         meshlink_handle_t *mesh = meshlink_open(confbase, nick, "chat", DEV_CLASS_STATIONARY);
274
275         if(!mesh) {
276                 fprintf(stderr, "Could not open MeshLink: %s\n", meshlink_strerror(meshlink_errno));
277                 return 1;
278         }
279
280         meshlink_set_node_status_cb(mesh, node_status);
281         meshlink_set_log_cb(mesh, MESHLINK_INFO, log_message);
282
283         // Set the channel accept callback. This implicitly turns on channels for all nodes.
284         // This replaces the call to meshlink_set_receive_cb().
285         meshlink_set_channel_accept_cb(mesh, channel_accept);
286
287         if(!meshlink_start(mesh)) {
288                 fprintf(stderr, "Could not start MeshLink: %s\n", meshlink_strerror(meshlink_errno));
289                 return 1;
290         }
291
292         printf("Chat started.\nType /help for a list of commands.\n");
293
294         while(fgets(buf, sizeof(buf), stdin)) {
295                 parse_input(mesh, buf);
296         }
297
298         printf("Chat stopping.\n");
299
300         meshlink_stop(mesh);
301         meshlink_close(mesh);
302
303         return 0;
304 }