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