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