- use proper signedness
[oweals/gnunet.git] / src / mesh / gnunet-mesh.c
1 /*
2      This file is part of GNUnet.
3      (C) 2012 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file mesh/gnunet-mesh.c
23  * @brief Print information about mesh tunnels and peers.
24  * @author Bartlomiej Polot
25  */
26 #include "platform.h"
27 #include "gnunet_util_lib.h"
28 #include "gnunet_mesh_service.h"
29
30
31 /**
32  * Option -m.
33  */
34 static int monitor_connections;
35
36 /**
37  * Option -i.
38  */
39 static int get_info;
40
41 /**
42  * Option --tunnel
43  */
44 static char *tunnel_id;
45
46 /**
47  * Option --connection
48  */
49 static char *conn_id;
50
51 /**
52  * Option --channel
53  */
54 static char *channel_id;
55
56 /**
57  * Port to listen on (-p).
58  */
59 static uint32_t listen_port;
60
61 /**
62  * Peer to connect to.
63  */
64 static char *target_id;
65
66 /**
67  * Port to connect to
68  */
69 static uint32_t target_port;
70
71 /**
72  * Data pending in netcat mode.
73  */
74 size_t data_size;
75
76
77 /**
78  * Mesh handle.
79  */
80 static struct GNUNET_MESH_Handle *mh;
81
82 /**
83  * Channel handle.
84  */
85 static struct GNUNET_MESH_Channel *ch;
86
87 /**
88  * Shutdown task handle.
89  */
90 GNUNET_SCHEDULER_TaskIdentifier sd;
91
92
93
94 static void
95 listen_stdio (void);
96
97
98
99 /**
100  * Task run in monitor mode when the user presses CTRL-C to abort.
101  * Stops monitoring activity.
102  *
103  * @param cls Closure (unused).
104  * @param tc scheduler context
105  */
106 static void
107 shutdown_task (void *cls,
108                const struct GNUNET_SCHEDULER_TaskContext *tc)
109 {
110   if (NULL != ch)
111   {
112     GNUNET_MESH_channel_destroy (ch);
113     ch = NULL;
114   }
115   if (NULL != mh)
116   {
117     GNUNET_MESH_disconnect (mh);
118         mh = NULL;
119   }
120 }
121
122
123 /**
124  * Function called to notify a client about the connection
125  * begin ready to queue more data.  "buf" will be
126  * NULL and "size" zero if the connection was closed for
127  * writing in the meantime.
128  *
129  * FIXME
130  *
131  * @param cls closure
132  * @param size number of bytes available in buf
133  * @param buf where the callee should write the message
134  * @return number of bytes written to buf
135  */
136 size_t
137 data_ready (void *cls, size_t size, void *buf)
138 {
139   struct GNUNET_MessageHeader *msg;
140   size_t total_size;
141
142   if (NULL == buf || 0 == size)
143   {
144     GNUNET_SCHEDULER_shutdown();
145     return 0;
146   }
147
148   total_size = data_size + sizeof (struct GNUNET_MessageHeader);
149   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "sending %u bytes\n", data_size);
150   GNUNET_assert (size >= total_size);
151
152   msg = buf;
153   msg->size = htons (total_size);
154   msg->type = htons (GNUNET_MESSAGE_TYPE_MESH_CLI);
155   memcpy (&msg[1], cls, data_size);
156   listen_stdio ();
157
158   return total_size;
159 }
160
161
162 /**
163  * Task run in monitor mode when the user presses CTRL-C to abort.
164  * Stops monitoring activity.
165  *
166  * @param cls Closure (unused).
167  * @param tc scheduler context
168  */
169 static void
170 read_stdio (void *cls,
171             const struct GNUNET_SCHEDULER_TaskContext *tc)
172 {
173   char buf[60000];
174
175   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
176   {
177     return;
178   }
179
180   data_size = read (0, buf, 60000);
181   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "stdio read %u bytes\n", data_size);
182   if (data_size < 1)
183   {
184     GNUNET_SCHEDULER_shutdown();
185     return;
186   }
187   GNUNET_MESH_notify_transmit_ready (ch, GNUNET_NO,
188                                      GNUNET_TIME_UNIT_FOREVER_REL,
189                                      data_size
190                                      + sizeof (struct GNUNET_MessageHeader),
191                                      &data_ready, buf);
192 }
193
194
195 /**
196  * Start listening to stdin
197  */
198 static void
199 listen_stdio (void)
200 {
201   struct GNUNET_NETWORK_FDSet *rs;
202
203   rs = GNUNET_NETWORK_fdset_create ();
204   GNUNET_NETWORK_fdset_set_native (rs, 0);
205   GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
206                                GNUNET_TIME_UNIT_FOREVER_REL,
207                                rs, NULL,
208                                &read_stdio, NULL);
209   GNUNET_NETWORK_fdset_destroy (rs);
210 }
211
212
213 /**
214  * Function called whenever a channel is destroyed.  Should clean up
215  * any associated state.
216  *
217  * It must NOT call #GNUNET_MESH_channel_destroy on the channel.
218  *
219  * @param cls closure (set from #GNUNET_MESH_connect)
220  * @param channel connection to the other end (henceforth invalid)
221  * @param channel_ctx place where local state associated
222  *                   with the channel is stored
223  */
224 static void
225 channel_ended (void *cls,
226                const struct GNUNET_MESH_Channel *channel,
227                void *channel_ctx)
228 {
229   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Channel ended!\n");
230   GNUNET_break (channel == ch);
231   ch = NULL;
232   GNUNET_SCHEDULER_shutdown ();
233 }
234
235
236 /**
237  * Method called whenever another peer has added us to a channel
238  * the other peer initiated.
239  * Only called (once) upon reception of data with a message type which was
240  * subscribed to in #GNUNET_MESH_connect.
241  *
242  * A call to #GNUNET_MESH_channel_destroy causes te channel to be ignored. In
243  * this case the handler MUST return NULL.
244  *
245  * @param cls closure
246  * @param channel new handle to the channel
247  * @param initiator peer that started the channel
248  * @param port Port this channel is for.
249  * @param options MeshOption flag field, with all active option bits set to 1.
250  *
251  * @return initial channel context for the channel
252  *         (can be NULL -- that's not an error)
253  */
254 static void *
255 channel_incoming (void *cls,
256                   struct GNUNET_MESH_Channel * channel,
257                   const struct GNUNET_PeerIdentity * initiator,
258                   uint32_t port, enum GNUNET_MESH_ChannelOption options)
259 {
260   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
261               "Incoming channel %p on port %u\n",
262               channel, port);
263   if (NULL != ch)
264   {
265     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "A channel already exists\n");
266     return NULL;
267   }
268   if (0 == listen_port)
269   {
270     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not listening to channels\n");
271     return NULL;
272   }
273   ch = channel;
274   listen_stdio ();
275   return NULL;
276 }
277
278
279
280 /**
281  * Call MESH's monitor API, get info of one connection.
282  *
283  * @param cls Closure (unused).
284  * @param tc TaskContext
285  */
286 static void
287 create_channel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
288 {
289   struct GNUNET_PeerIdentity pid;
290   enum GNUNET_MESH_ChannelOption opt;
291
292   GNUNET_assert (NULL == ch);
293
294   if (GNUNET_OK !=
295       GNUNET_CRYPTO_eddsa_public_key_from_string (target_id,
296                                                   strlen (target_id),
297                                                   &pid.public_key))
298   {
299     FPRINTF (stderr,
300              _("Invalid target `%s'\n"),
301              target_id);
302     GNUNET_SCHEDULER_shutdown ();
303     return;
304   }
305   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connecting to `%s'\n", target_id);
306   opt = GNUNET_MESH_OPTION_DEFAULT | GNUNET_MESH_OPTION_RELIABLE;
307   ch = GNUNET_MESH_channel_create (mh, NULL, &pid, target_port, opt);
308   listen_stdio ();
309 }
310
311
312 /**
313  * Function called whenever a message is received.
314  *
315  * Each time the function must call #GNUNET_MESH_receive_done on the channel
316  * in order to receive the next message. This doesn't need to be immediate:
317  * can be delayed if some processing is done on the message.
318  *
319  * @param cls Closure (set from #GNUNET_MESH_connect).
320  * @param channel Connection to the other end.
321  * @param channel_ctx Place to store local state associated with the channel.
322  * @param message The actual message.
323  * @return #GNUNET_OK to keep the channel open,
324  *         #GNUNET_SYSERR to close it (signal serious error).
325  */
326 static int
327 data_callback (void *cls,
328                struct GNUNET_MESH_Channel *channel,
329                void **channel_ctx,
330                const struct GNUNET_MessageHeader *message)
331 {
332   uint16_t len;
333   GNUNET_break (ch == channel);
334
335   len = ntohs (message->size) - sizeof (*message);
336   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got %u bytes\n", len);
337   FPRINTF (stdout, "%.*s", len, (char *) &message[1]);
338   return GNUNET_OK;
339 }
340
341
342 /**
343  * Method called to retrieve information about each tunnel the mesh peer
344  * is aware of.
345  *
346  * @param cls Closure.
347  * @param tunnel_number Tunnel number.
348  * @param origin that started the tunnel (owner).
349  * @param target other endpoint of the tunnel
350  */
351 void /* FIXME static */
352 tunnels_callback (void *cls,
353                   uint32_t tunnel_number,
354                   const struct GNUNET_PeerIdentity *origin,
355                   const struct GNUNET_PeerIdentity *target)
356 {
357   FPRINTF (stdout, "Tunnel %s [%u]\n",
358            GNUNET_i2s_full (origin), tunnel_number);
359   FPRINTF (stdout, "\n");
360 }
361
362
363 /**
364  * Method called to retrieve information about each tunnel the mesh peer
365  * is aware of.
366  *
367  * @param cls Closure.
368  * @param peer Peer in the tunnel's tree.
369  * @param parent Parent of the current peer. All 0 when peer is root.
370  *
371  */
372 void /* FIXME static */
373 tunnel_callback (void *cls,
374                  const struct GNUNET_PeerIdentity *peer,
375                  const struct GNUNET_PeerIdentity *parent)
376 {
377 }
378
379
380 /**
381  * Call MESH's monitor API, get all tunnels known to peer.
382  *
383  * @param cls Closure (unused).
384  * @param tc TaskContext
385  */
386 static void
387 get_tunnels (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
388 {
389   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
390   {
391     return;
392   }
393 //   GNUNET_MESH_get_tunnels (mh, &tunnels_callback, NULL);
394   if (GNUNET_YES != monitor_connections)
395   {
396     GNUNET_SCHEDULER_shutdown();
397   }
398 }
399
400
401 /**
402  * Call MESH's monitor API, get info of one tunnel.
403  *
404  * @param cls Closure (unused).
405  * @param tc TaskContext
406  */
407 static void
408 show_tunnel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
409 {
410   struct GNUNET_PeerIdentity pid;
411
412   if (GNUNET_OK !=
413       GNUNET_CRYPTO_eddsa_public_key_from_string (tunnel_id,
414                                                   strlen (tunnel_id),
415                                                   &pid.public_key))
416   {
417     fprintf (stderr,
418              _("Invalid tunnel owner `%s'\n"),
419              tunnel_id);
420     GNUNET_SCHEDULER_shutdown();
421     return;
422   }
423 //   GNUNET_MESH_show_tunnel (mh, &pid, 0, tunnel_callback, NULL);
424 }
425
426
427 /**
428  * Call MESH's monitor API, get info of one channel.
429  *
430  * @param cls Closure (unused).
431  * @param tc TaskContext
432  */
433 static void
434 show_channel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
435 {
436
437 }
438
439
440 /**
441  * Call MESH's monitor API, get info of one connection.
442  *
443  * @param cls Closure (unused).
444  * @param tc TaskContext
445  */
446 static void
447 show_connection (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
448 {
449
450 }
451
452
453 /**
454  * Main function that will be run by the scheduler.
455  *
456  * @param cls closure
457  * @param args remaining command-line arguments
458  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
459  * @param cfg configuration
460  */
461 static void
462 run (void *cls, char *const *args, const char *cfgfile,
463      const struct GNUNET_CONFIGURATION_Handle *cfg)
464 {
465   GNUNET_MESH_InboundChannelNotificationHandler *newch = NULL;
466   GNUNET_MESH_ChannelEndHandler *endch = NULL;
467   static const struct GNUNET_MESH_MessageHandler handlers[] = {
468     {&data_callback, GNUNET_MESSAGE_TYPE_MESH_CLI, 0},
469     {NULL, 0, 0} /* FIXME add option to monitor msg types */
470   };
471   static uint32_t *ports = NULL;
472   /* FIXME add option to monitor apps */
473
474   target_id = args[0];
475   target_port = args[0] && args[1] ? atoi(args[1]) : 0;
476   if ( (0 != get_info
477         || 0 != monitor_connections
478         || NULL != tunnel_id
479         || NULL != conn_id
480         || NULL != channel_id)
481        && target_id != NULL)
482   {
483     FPRINTF (stderr, _("You must NOT give a TARGET when using options\n"));
484     return;
485   }
486
487   if (NULL != target_id)
488   {
489     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
490                 "Creating channel to %s\n",
491                 target_id);
492     GNUNET_SCHEDULER_add_now (&create_channel, NULL);
493     endch = &channel_ended;
494   }
495   else if (0 != listen_port)
496   {
497     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Listen\n");
498     newch = &channel_incoming;
499     endch = &channel_ended;
500     ports = GNUNET_malloc (sizeof (uint32_t) * 2);
501     ports[0] = listen_port;
502   }
503   else if (NULL != tunnel_id)
504   {
505     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Show tunnel\n");
506     GNUNET_SCHEDULER_add_now (&show_tunnel, NULL);
507   }
508   else if (NULL != channel_id)
509   {
510     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Show channel\n");
511     GNUNET_SCHEDULER_add_now (&show_channel, NULL);
512   }
513   else if (NULL != conn_id)
514   {
515     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Show connection\n");
516     GNUNET_SCHEDULER_add_now (&show_connection, NULL);
517   }
518   else if (GNUNET_YES == get_info)
519   {
520     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Show all tunnels\n");
521     GNUNET_SCHEDULER_add_now (&get_tunnels, NULL);
522   }
523   else
524   {
525     FPRINTF (stderr, "No action requested\n");
526     return;
527   }
528
529   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connecting to mesh\n");
530   mh = GNUNET_MESH_connect (cfg,
531                             NULL, /* cls */
532                             newch, /* new channel */
533                             endch, /* cleaner */
534                             handlers,
535                             ports);
536   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Done\n");
537   if (NULL == mh)
538     GNUNET_SCHEDULER_add_now (shutdown_task, NULL);
539   else
540     sd = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
541                                        shutdown_task, NULL);
542
543 }
544
545
546 /**
547  * The main function to obtain peer information.
548  *
549  * @param argc number of arguments from the command line
550  * @param argv command line arguments
551  * @return 0 ok, 1 on error
552  */
553 int
554 main (int argc, char *const *argv)
555 {
556   int res;
557   const char helpstr[] = "Create channels and retreive info about meshs status.";
558   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
559     {'a', "channel", "TUNNEL_ID:CHANNEL_ID",
560      gettext_noop ("provide information about a particular channel"),
561      GNUNET_YES, &GNUNET_GETOPT_set_string, &channel_id},
562     {'b', "connection", "TUNNEL_ID:CONNECTION_ID",
563      gettext_noop ("provide information about a particular connection"),
564      GNUNET_YES, &GNUNET_GETOPT_set_string, &conn_id},
565     {'i', "info", NULL,
566      gettext_noop ("provide information about all tunnels"),
567      GNUNET_NO, &GNUNET_GETOPT_set_one, &get_info},
568     {'m', "monitor", NULL,
569      gettext_noop ("provide information about all tunnels (continuously) NOT IMPLEMENTED"), /* FIXME */
570      GNUNET_NO, &GNUNET_GETOPT_set_one, &monitor_connections},
571     {'p', "port", NULL,
572      gettext_noop ("port to listen to (default; 0)"),
573      GNUNET_YES, &GNUNET_GETOPT_set_uint, &listen_port},
574     {'t', "tunnel", "TUNNEL_ID",
575      gettext_noop ("provide information about a particular tunnel"),
576      GNUNET_YES, &GNUNET_GETOPT_set_string, &tunnel_id},
577     GNUNET_GETOPT_OPTION_END
578   };
579
580   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
581     return 2;
582
583   res = GNUNET_PROGRAM_run (argc, argv, "gnunet-mesh (OPTIONS | TARGET PORT)",
584                             gettext_noop (helpstr),
585                             options, &run, NULL);
586
587   GNUNET_free ((void *) argv);
588
589   if (GNUNET_OK == res)
590     return 0;
591   else
592     return 1;
593 }
594
595 /* end of gnunet-mesh.c */