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