Adapted path generation to new DHT_RECORD_ROUTE behavior
[oweals/gnunet.git] / src / mesh / gnunet-service-mesh.c
1 /*
2      This file is part of GNUnet.
3      (C) 2001 - 2011 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-service-mesh.c
23  * @brief GNUnet MESH service
24  * @author Bartlomiej Polot
25  *
26  * STRUCTURE:
27  * - DATA STRUCTURES
28  * - GLOBAL VARIABLES
29  * - GENERAL HELPERS
30  * - PERIODIC FUNCTIONS
31  * - MESH NETWORK HANDLER HELPERS
32  * - MESH NETWORK HANDLES
33  * - MESH LOCAL HANDLER HELPERS
34  * - MESH LOCAL HANDLES
35  * - MAIN FUNCTIONS (main & run)
36  *
37  * TODO:
38  * - error reporting (CREATE/CHANGE/ADD/DEL?) -- new message!
39  * - partial disconnect reporting -- same as error reporting?
40  * - add vs create? change vs. keep-alive? same msg or different ones? -- thinking...
41  * - speed requirement specification (change?) in mesh API -- API call
42  * - add ping message
43  * - add connection confirmation message
44  * - handle trnsmt_rdy return values
45  */
46
47 #include "platform.h"
48 #include "mesh.h"
49 #include "mesh_protocol.h"
50 #include "gnunet_dht_service.h"
51 #include "mesh_tunnel_tree.h"
52
53 /* TODO: move into configuration file */
54 #define REFRESH_PATH_TIME       GNUNET_TIME_relative_multiply(\
55                                     GNUNET_TIME_UNIT_SECONDS,\
56                                     300)
57 #define APP_ANNOUNCE_TIME       GNUNET_TIME_relative_multiply(\
58                                     GNUNET_TIME_UNIT_SECONDS,\
59                                     5)
60
61 #define ID_ANNOUNCE_TIME        GNUNET_TIME_relative_multiply(\
62                                     GNUNET_TIME_UNIT_SECONDS,\
63                                     10)
64
65
66 /******************************************************************************/
67 /************************      DATA STRUCTURES     ****************************/
68 /******************************************************************************/
69
70 /** FWD declaration */
71 struct MeshPeerInfo;
72
73 /**
74  * Struct containing all info possibly needed to build a package when called
75  * back by core.
76  */
77 struct MeshDataDescriptor
78 {
79     /** ID of the tunnel this packet travels in */
80   struct MESH_TunnelID *origin;
81
82     /** Data itself */
83   void *data;
84
85     /** Client that asked for the transmission, if any */
86   struct GNUNET_SERVER_Client *client;
87
88     /** Who was this message being sent to */
89   struct MeshPeerInfo *peer;
90
91     /** Ultimate destination of the packet */
92   GNUNET_PEER_Id destination;
93
94     /** Number of identical messages sent to different hops (multicast) */
95   unsigned int *copies;
96
97     /** Which handler was used to request the transmission */
98   unsigned int handler_n;
99
100     /** Size of the data */
101   size_t size;
102
103 };
104
105
106 /**
107  * Struct containing all information regarding a given peer
108  */
109 struct MeshPeerInfo
110 {
111     /**
112      * ID of the peer
113      */
114   GNUNET_PEER_Id id;
115
116     /**
117      * Last time we heard from this peer
118      */
119   struct GNUNET_TIME_Absolute last_contact;
120
121     /**
122      * Number of attempts to reconnect so far
123      */
124   int n_reconnect_attempts;
125
126     /**
127      * Paths to reach the peer, ordered by ascending hop count
128      */
129   struct MeshPeerPath *path_head;
130
131     /**
132      * Paths to reach the peer, ordered by ascending hop count
133      */
134   struct MeshPeerPath *path_tail;
135
136     /**
137      * Handle to stop the DHT search for a path to this peer
138      */
139   struct GNUNET_DHT_GetHandle *dhtget;
140
141     /**
142      * Task to reissue the DHT get request a path for this peer
143      */
144   GNUNET_SCHEDULER_TaskIdentifier dhtget_task;
145
146     /**
147      * Handles to stop queued transmissions for this peer
148      */
149   struct GNUNET_CORE_TransmitHandle *core_transmit[CORE_QUEUE_SIZE];
150
151     /**
152      * Pointer to info stuctures used as cls for queued transmissions
153      */
154   void *infos[CORE_QUEUE_SIZE];
155
156     /**
157      * Type of message being in each transmission
158      */
159   uint16_t types[CORE_QUEUE_SIZE];
160
161     /**
162      * Array of tunnels this peer participates in
163      * (most probably a small amount, therefore not a hashmap)
164      * When the path to the peer changes, notify these tunnels to let them
165      * re-adjust their path trees.
166      */
167   struct MeshTunnel **tunnels;
168
169     /**
170      * Number of tunnels above
171      */
172   unsigned int ntunnels;
173 };
174
175
176 /**
177  * Data scheduled to transmit (to local client or remote peer)
178  */
179 struct MeshQueue
180 {
181     /**
182      * Double linked list
183      */
184   struct MeshQueue *next;
185   struct MeshQueue *prev;
186
187     /**
188      * Target of the data (NULL if target is client)
189      */
190   struct MeshPeerInfo *peer;
191
192     /**
193      * Client to send the data to (NULL if target is peer)
194      */
195   struct MeshClient *client;
196
197     /**
198      * Size of the message to transmit
199      */
200   unsigned int size;
201
202     /**
203      * How old is the data?
204      */
205   struct GNUNET_TIME_Absolute timestamp;
206
207     /**
208      * Data itself
209      */
210   struct GNUNET_MessageHeader *data;
211 };
212
213 /**
214  * Globally unique tunnel identification (owner + number)
215  * DO NOT USE OVER THE NETWORK
216  */
217 struct MESH_TunnelID
218 {
219     /**
220      * Node that owns the tunnel
221      */
222   GNUNET_PEER_Id oid;
223
224     /**
225      * Tunnel number to differentiate all the tunnels owned by the node oid
226      * ( tid < GNUNET_MESH_LOCAL_TUNNEL_ID_CLI )
227      */
228   MESH_TunnelNumber tid;
229 };
230
231
232 struct MeshClient;              /* FWD declaration */
233
234 /**
235  * Struct containing all information regarding a tunnel
236  * For an intermediate node the improtant info used will be:
237  * - id        Tunnel unique identification
238  * - paths[0]  To know where to send it next
239  * - metainfo: ready, speeds, accounting
240  */
241 struct MeshTunnel
242 {
243     /**
244      * Tunnel ID
245      */
246   struct MESH_TunnelID id;
247
248     /**
249      * Local tunnel number ( >= GNUNET_MESH_LOCAL_TUNNEL_ID_CLI or 0 )
250      */
251   MESH_TunnelNumber local_tid;
252
253     /**
254      * Last time the tunnel was used
255      */
256   struct GNUNET_TIME_Absolute timestamp;
257
258     /**
259      * Peers in the tunnel, indexed by PeerIdentity -> (MeshPeerInfo)
260      */
261   struct GNUNET_CONTAINER_MultiHashMap *peers;
262
263     /**
264      * Number of peers that are connected and potentially ready to receive data
265      */
266   unsigned int peers_ready;
267
268     /**
269      * Number of peers that have been added to the tunnel
270      */
271   unsigned int peers_total;
272
273     /**
274      * Client owner of the tunnel, if any
275      */
276   struct MeshClient *client;
277
278     /**
279      * Messages ready to transmit
280      */
281   struct MeshQueue *queue_head;
282   struct MeshQueue *queue_tail;
283
284   /**
285    * Tunnel paths
286    */
287   struct MeshTunnelTree *tree;
288
289   /**
290    * Task to keep the used paths alive
291    */
292   GNUNET_SCHEDULER_TaskIdentifier path_refresh_task;
293 };
294
295
296 /**
297  * Info needed to work with tunnel paths and peers
298  */
299 struct MeshPathInfo
300 {
301   /**
302    * Tunnel
303    */
304   struct MeshTunnel *t;
305
306   /**
307    * Destination peer
308    */
309   struct MeshPeerInfo *peer;
310
311   /**
312    * Path itself
313    */
314   struct MeshPeerPath *path;
315 };
316
317
318 /**
319  * Struct containing information about a client of the service
320  */
321 struct MeshClient
322 {
323     /**
324      * Linked list
325      */
326   struct MeshClient *next;
327   struct MeshClient *prev;
328
329     /**
330      * Tunnels that belong to this client, indexed by local id
331      */
332   struct GNUNET_CONTAINER_MultiHashMap *tunnels;
333
334     /**
335      * Handle to communicate with the client
336      */
337   struct GNUNET_SERVER_Client *handle;
338
339     /**
340      * Applications that this client has claimed to provide
341      */
342   struct GNUNET_CONTAINER_MultiHashMap *apps;
343
344     /**
345      * Messages that this client has declared interest in
346      */
347   struct GNUNET_CONTAINER_MultiHashMap *types;
348
349     /**
350      * Used to search peers offering a service
351      */
352   struct GNUNET_DHT_GetHandle *dht_get_type;
353
354     /**
355      * Task to reissue the DHT get request for a type
356      */
357   GNUNET_SCHEDULER_TaskIdentifier dht_get_type_task;
358
359 #if MESH_DEBUG
360     /**
361      * ID of the client, for debug messages
362      */
363   unsigned int id;
364 #endif
365
366 };
367
368
369
370 /******************************************************************************/
371 /************************      DEBUG FUNCTIONS     ****************************/
372 /******************************************************************************/
373
374
375 /**
376  * GNUNET_SCHEDULER_Task for printing a message after some operation is done
377  * @param cls string to print
378  * @param tc task context
379  */
380 static void
381 mesh_debug (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
382 {
383   char *s = cls;
384
385   if (GNUNET_SCHEDULER_REASON_SHUTDOWN == tc->reason)
386   {
387     return;
388   }
389   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: %s\n", s);
390 }
391
392
393 /******************************************************************************/
394 /***********************      GLOBAL VARIABLES     ****************************/
395 /******************************************************************************/
396
397 /**
398  * All the clients
399  */
400 static struct MeshClient *clients;
401 static struct MeshClient *clients_tail;
402
403 /**
404  * Tunnels known, indexed by MESH_TunnelID (MeshTunnel)
405  */
406 static struct GNUNET_CONTAINER_MultiHashMap *tunnels;
407
408 /**
409  * Peers known, indexed by PeerIdentity (MeshPeerInfo)
410  */
411 static struct GNUNET_CONTAINER_MultiHashMap *peers;
412
413 /**
414  * Handle to communicate with core
415  */
416 static struct GNUNET_CORE_Handle *core_handle;
417
418 /**
419  * Handle to use DHT
420  */
421 static struct GNUNET_DHT_Handle *dht_handle;
422
423 /**
424  * Handle to server
425  */
426 static struct GNUNET_SERVER_Handle *server_handle;
427
428 /**
429  * Notification context, to send messages to local clients
430  */
431 static struct GNUNET_SERVER_NotificationContext *nc;
432
433 /**
434  * Local peer own ID (memory efficient handle)
435  */
436 static GNUNET_PEER_Id myid;
437
438 /**
439  * Local peer own ID (full value)
440  */
441 static struct GNUNET_PeerIdentity my_full_id;
442
443 /**
444  * Own private key
445  */
446 static struct GNUNET_CRYPTO_RsaPrivateKey* my_private_key;
447
448 /**
449  * Own public key.
450  */
451 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
452
453 /**
454  * Tunnel ID for the next created tunnel (global tunnel number)
455  */
456 static MESH_TunnelNumber next_tid;
457
458 /**
459  * Tunnel ID for the next incoming tunnel (local tunnel number)
460  */
461 static MESH_TunnelNumber next_local_tid;
462
463 /**
464  * All application types provided by this peer
465  */
466 static struct GNUNET_CONTAINER_MultiHashMap *applications;
467
468 /**
469  * All message types clients of this peer are interested in
470  */
471 static struct GNUNET_CONTAINER_MultiHashMap *types;
472
473 /**
474  * Task to periodically announce provided applications
475  */
476 GNUNET_SCHEDULER_TaskIdentifier announce_applications_task;
477
478 /**
479  * Task to periodically announce itself in the network
480  */
481 GNUNET_SCHEDULER_TaskIdentifier announce_id_task;
482
483 #if MESH_DEBUG
484 unsigned int next_client_id;
485 #endif
486
487
488 /******************************************************************************/
489 /************************         ITERATORS        ****************************/
490 /******************************************************************************/
491
492 /* FIXME move iterators here */
493
494
495 /******************************************************************************/
496 /************************    PERIODIC FUNCTIONS    ****************************/
497 /******************************************************************************/
498
499 /**
500  * Announce iterator over for each application provided by the peer
501  *
502  * @param cls closure
503  * @param key current key code
504  * @param value value in the hash map
505  * @return GNUNET_YES if we should continue to
506  *         iterate,
507  *         GNUNET_NO if not.
508  */
509 static int
510 announce_application (void *cls, const GNUNET_HashCode * key, void *value)
511 {
512   /* FIXME are hashes in multihash map equal on all aquitectures? */
513
514   GNUNET_DHT_put (dht_handle, key, 10U, GNUNET_DHT_RO_RECORD_ROUTE,
515                   GNUNET_BLOCK_TYPE_TEST, sizeof (struct GNUNET_PeerIdentity),
516                   (const char *) &my_full_id,
517 #if MESH_DEBUG
518                   GNUNET_TIME_UNIT_FOREVER_ABS, GNUNET_TIME_UNIT_FOREVER_REL,
519                   &mesh_debug, "DHT_put for app completed");
520 #else
521                   GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get (),
522                                             APP_ANNOUNCE_TIME),
523                   APP_ANNOUNCE_TIME, NULL, NULL);
524 #endif
525   return GNUNET_OK;
526 }
527
528
529 /**
530  * Periodically announce what applications are provided by local clients
531  *
532  * @param cls closure
533  * @param tc task context
534  */
535 static void
536 announce_applications (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
537 {
538   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
539   {
540     announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
541     return;
542   }
543   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Starting PUT for apps\n");
544   GNUNET_CONTAINER_multihashmap_iterate (applications, &announce_application,
545                                          NULL);
546   announce_applications_task =
547       GNUNET_SCHEDULER_add_delayed (APP_ANNOUNCE_TIME, &announce_applications,
548                                     cls);
549   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Finished PUT for apps\n");
550   return;
551 }
552
553
554 /**
555  * Periodically announce self id in the DHT
556  *
557  * @param cls closure
558  * @param tc task context
559  */
560 static void
561 announce_id (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
562 {
563   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
564   {
565     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
566     return;
567   }
568   /* TODO
569    * - Set data expiration in function of X
570    * - Adapt X to churn
571    */
572   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: DHT_put for ID %s started.\n",
573               GNUNET_h2s_full (&my_full_id.hashPubKey));
574   GNUNET_DHT_put (dht_handle,   /* DHT handle */
575                   &my_full_id.hashPubKey,       /* Key to use */
576                   10U,          /* Replication level */
577                   GNUNET_DHT_RO_RECORD_ROUTE,   /* DHT options */
578                   GNUNET_BLOCK_TYPE_TEST,       /* Block type */
579                   sizeof(my_full_id),   /* Size of the data */
580                   (char *)&my_full_id,  /* Data itself */
581                   GNUNET_TIME_absolute_get_forever (),  /* Data expiration */
582                   GNUNET_TIME_UNIT_FOREVER_REL, /* Retry time */
583 #if MESH_DEBUG
584                   &mesh_debug, "DHT_put for id completed");
585 #else
586                   NULL,         /* Continuation */
587                   NULL);        /* Continuation closure */
588 #endif
589   announce_id_task =
590       GNUNET_SCHEDULER_add_delayed (ID_ANNOUNCE_TIME, &announce_id, cls);
591 }
592
593
594 /**
595  * Function to process paths received for a new peer addition. The recorded
596  * paths form the initial tunnel, which can be optimized later.
597  * Called on each result obtained for the DHT search.
598  *
599  * @param cls closure
600  * @param exp when will this value expire
601  * @param key key of the result
602  * @param type type of the result
603  * @param size number of bytes in data
604  * @param data pointer to the result data
605  */
606 static void
607 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
608                     const GNUNET_HashCode * key,
609                     const struct GNUNET_PeerIdentity *get_path,
610                     unsigned int get_path_length,
611                     const struct GNUNET_PeerIdentity *put_path,
612                     unsigned int put_path_length,
613                     enum GNUNET_BLOCK_Type type, size_t size, const void *data);
614
615
616 /******************************************************************************/
617 /******************      GENERAL HELPER FUNCTIONS      ************************/
618 /******************************************************************************/
619
620 /**
621  * Retrieve the MeshPeerInfo stucture associated with the peer, create one
622  * and insert it in the appropiate structures if the peer is not known yet.
623  *
624  * @param peer Identity of the peer
625  *
626  * @return Existing or newly created peer info
627  */
628 static struct MeshPeerInfo *
629 peer_info_get (const struct GNUNET_PeerIdentity *peer)
630 {
631   struct MeshPeerInfo *peer_info;
632
633   peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
634   if (NULL == peer_info)
635   {
636     peer_info =
637         (struct MeshPeerInfo *) GNUNET_malloc (sizeof (struct MeshPeerInfo));
638     GNUNET_CONTAINER_multihashmap_put (peers, &peer->hashPubKey, peer_info,
639                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
640     peer_info->id = GNUNET_PEER_intern (peer);
641   }
642
643   return peer_info;
644 }
645
646
647 #if LATER
648 /**
649  * Destroy the peer_info and free any allocated resources linked to it
650  * @param t tunnel the path belongs to
651  * @param pi the peer_info to destroy
652  * @return GNUNET_OK on success
653  */
654 static int
655 peer_info_destroy (struct MeshPeerInfo *pi)
656 {
657   GNUNET_HashCode hash;
658   struct GNUNET_PeerIdentity id;
659
660   GNUNET_PEER_resolve (pi->id, &id);
661   GNUNET_PEER_change_rc (pi->id, -1);
662   GNUNET_CRYPTO_hash (&id, sizeof (struct GNUNET_PeerIdentity), &hash);
663
664   GNUNET_CONTAINER_multihashmap_remove (peers, &hash, pi);
665   GNUNET_SCHEDULER_cancel (pi->path_refresh_task);
666   GNUNET_free (pi);
667   return GNUNET_OK;
668 }
669 #endif
670
671
672 /**
673  * Notify a tunnel that a connection has broken that affects at least
674  * some of its peers.
675  *
676  * @param t Tunnel affected.
677  * @param peer Peer that (at least) has been affected by the disconnection.
678  * @param p1 Peer that got disconnected from p2.
679  * @param p2 Peer that got disconnected from p1.
680  *
681  * @return Short ID of the peer disconnected (either p1 or p2).
682  *         0 if the tunnel remained unaffected.
683  */
684 static GNUNET_PEER_Id
685 tunnel_notify_connection_broken (struct MeshTunnel *t,
686                                  struct MeshPeerInfo *peer, GNUNET_PEER_Id p1,
687                                  GNUNET_PEER_Id p2);
688
689 /**
690  * Remove all paths that rely on a direct connection between p1 and p2
691  * from the peer itself and notify all tunnels about it.
692  *
693  * @param peer PeerInfo of affected peer.
694  * @param p1 GNUNET_PEER_Id of one peer.
695  * @param p2 GNUNET_PEER_Id of another peer that was connected to the first and
696  *           no longer is.
697  *
698  * TODO: optimize (see below)
699  */
700 static void
701 path_remove_from_peer (struct MeshPeerInfo *peer,
702                        GNUNET_PEER_Id p1,
703                        GNUNET_PEER_Id p2)
704 {
705   struct GNUNET_PeerIdentity id;
706   struct MeshPeerPath *p;
707   struct MeshPeerPath *aux;
708   struct MeshPeerInfo *peer_d;
709   GNUNET_PEER_Id d;
710   unsigned int destroyed;
711   unsigned int best;
712   unsigned int cost;
713   unsigned int i;
714
715   destroyed = 0;
716   p = peer->path_head;
717   while (NULL != p)
718   {
719     aux = p->next;
720     for (i = 0; i < (p->length - 1); i++)
721     {
722       if ((p->peers[i] == p1 && p->peers[i + 1] == p2) ||
723           (p->peers[i] == p2 && p->peers[i + 1] == p1))
724       {
725         path_destroy (p);
726         destroyed++;
727         break;
728       }
729     }
730     p = aux;
731   }
732   if (0 == destroyed)
733     return;
734
735   for (i = 0; i < peer->ntunnels; i++)
736   {
737     d = tunnel_notify_connection_broken (peer->tunnels[i], peer, p1, p2);
738     /* TODO
739      * Problem: one or more peers have been deleted from the tunnel tree.
740      * We don't know who they are to try to add them again.
741      * We need to try to find a new path for each of the disconnected peers.
742      * Some of them might already have a path to reach them that does not
743      * involve p1 and p2. Adding all anew might render in a better tree than
744      * the trivial immediate fix.
745      * 
746      * Trivial immiediate fix: try to reconnect to the disconnected node. All
747      * its children will be reachable trough him.
748      */
749     GNUNET_PEER_resolve(d, &id);
750     peer_d = peer_info_get(&id);
751     best = UINT_MAX;
752     aux = NULL;
753     for (p = peer_d->path_head; NULL != p; p = p->next)
754     {
755       if ((cost = path_get_cost(peer->tunnels[i]->tree, p)) < best)
756       {
757         best = cost;
758         aux = p;
759       }
760     }
761     if (NULL != aux)
762     {
763       /* No callback, as peer will be already disconnected */
764       tree_add_path(peer->tunnels[i]->tree, aux, NULL);
765     }
766     else
767     {
768       struct MeshPathInfo *path_info;
769
770       if (NULL != peer_d->dhtget)
771         return;
772       path_info = GNUNET_malloc(sizeof(struct MeshPathInfo));
773       path_info->path = p;
774       path_info->peer = peer_d;
775       path_info->t = peer->tunnels[i];
776       peer_d->dhtget = GNUNET_DHT_get_start(dht_handle,       /* handle */
777                                             GNUNET_TIME_UNIT_SECONDS,     /* timeout */
778                                             GNUNET_BLOCK_TYPE_TEST,   /* type */
779                                             &id.hashPubKey,   /*key to search */
780                                             4,        /* replication level */
781                                             GNUNET_DHT_RO_RECORD_ROUTE,
782                                             NULL,     /* xquery */
783                                             0,        /* xquery bits */
784                                             &dht_get_id_handler,
785                                             (void *) path_info);
786     }
787   }
788 }
789
790
791 /**
792  * Add the path to the peer and update the path used to reach it in case this
793  * is the shortest.
794  *
795  * @param peer_info Destination peer to add the path to.
796  * @param path New path to add. Last peer must be the peer in arg 1.
797  *             Path will be either used of freed if already known.
798  *
799  * TODO: trim the part from origin to us? Add it as path to origin?
800  */
801 void
802 path_add_to_peer (struct MeshPeerInfo *peer_info, struct MeshPeerPath *path)
803 {
804   struct MeshPeerPath *aux;
805   unsigned int l;
806   unsigned int l2;
807
808   if (NULL == peer_info || NULL == path)
809   {
810     GNUNET_break (0);
811     return;
812   }
813
814   l = path_get_length (path);
815
816   for (aux = peer_info->path_head; aux != NULL; aux = aux->next)
817   {
818     l2 = path_get_length (aux);
819     if (l2 > l)
820     {
821       GNUNET_CONTAINER_DLL_insert_before (peer_info->path_head,
822                                           peer_info->path_tail, aux, path);
823     }
824     else
825     {
826       if (l2 == l && memcmp(path->peers, aux->peers, l) == 0)
827       {
828         path_destroy(path);
829         return;
830       }
831     }
832   }
833   GNUNET_CONTAINER_DLL_insert_tail (peer_info->path_head, peer_info->path_tail,
834                                     path);
835   return;
836 }
837
838
839 /**
840  * Add the path to the origin peer and update the path used to reach it in case
841  * this is the shortest.
842  * The path is given in peer_info -> destination, therefore we turn the path
843  * upside down first.
844  *
845  * @param peer_info Peer to add the path to, being the origin of the path.
846  * @param path New path to add after being inversed.
847  */
848 static void
849 path_add_to_origin (struct MeshPeerInfo *peer_info, struct MeshPeerPath *path)
850 {
851   path_invert(path);
852   path_add_to_peer (peer_info, path);
853 }
854
855
856 /**
857  * Build a PeerPath from the paths returned from the DHT, reversing the paths
858  * to obtain a local peer -> destination path and interning the peer ids.
859  *
860  * @return Newly allocated and created path
861  */
862 static struct MeshPeerPath *
863 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
864                      unsigned int get_path_length,
865                      const struct GNUNET_PeerIdentity *put_path,
866                      unsigned int put_path_length)
867 {
868   struct MeshPeerPath *p;
869   GNUNET_PEER_Id id;
870   int i;
871
872   p = path_new (1);
873   p->peers[0] = myid;
874   GNUNET_PEER_change_rc(myid, 1);
875   i = get_path_length;
876   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "MESH:    GET has %d hops.\n", i);
877   for (i--; i >= 0; i--)
878   {
879     id = GNUNET_PEER_intern (&get_path[i]);
880     if (p->length > 0 && id == p->peers[p->length - 1])
881     {
882       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "MESH:    Optimizing 1 hop out.\n");
883       GNUNET_PEER_change_rc(id, -1);
884     }
885     else
886     {
887       p->length++;
888       p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
889       p->peers[p->length] = id;
890     }
891   }
892   i = put_path_length;
893   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "MESH:    PUT has %d hops.\n", i);
894   for (i--; i >= 0; i--)
895   {
896     id = GNUNET_PEER_intern (&put_path[i]);
897     if (id == myid)
898     {
899       /* PUT path went through us, so discard the path up until now and start
900        * from here to get a much shorter (and loop-free) path.
901        */
902       path_destroy (p);
903       p = path_new (0);
904     }
905     if (p->length > 0 && id == p->peers[p->length - 1])
906     {
907       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "MESH:    Optimizing 1 hop out.\n");
908       GNUNET_PEER_change_rc(id, -1);
909     }
910     else
911     {
912       p->length++;
913       p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
914       p->peers[p->length] = id;
915     }
916   }
917 #if MESH_DEBUG
918   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
919               "MESH:    (first of GET: %s)\n",
920               GNUNET_h2s_full(&get_path[0].hashPubKey));
921   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
922               "MESH:    (first of PUT: %s)\n",
923               GNUNET_h2s_full(&put_path[0].hashPubKey));
924   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
925               "MESH:    In total: %d hops\n",
926               p->length);
927 #endif
928   return p;
929 }
930
931
932 /**
933  * Send keepalive packets for a peer
934  *
935  * @param cls Closure (tunnel for which to send the keepalive).
936  * @param tc Notification context.
937  *
938  * TODO: implement explicit multicast keepalive?
939  */
940 void
941 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
942
943
944 /**
945  * Check if client has registered with the service and has not disconnected
946  *
947  * @param client the client to check
948  *
949  * @return non-NULL if client exists in the global DLL
950  */
951 static struct MeshClient *
952 client_get (struct GNUNET_SERVER_Client *client)
953 {
954   struct MeshClient *c;
955
956   c = clients;
957   while (NULL != c)
958   {
959     if (c->handle == client)
960       return c;
961     c = c->next;
962   }
963   return NULL;
964 }
965
966
967 /**
968  * Checks if a given client has subscribed to certain message type
969  *
970  * @param message_type Type of message to check
971  * @param c Client to check
972  *
973  * @return GNUNET_YES or GNUNET_NO, depending on subscription status
974  *
975  * TODO inline?
976  */
977 static int
978 client_is_subscribed (uint16_t message_type, struct MeshClient *c)
979 {
980   GNUNET_HashCode hc;
981
982   GNUNET_CRYPTO_hash (&message_type, sizeof (uint16_t), &hc);
983   return GNUNET_CONTAINER_multihashmap_contains (c->types, &hc);
984 }
985
986
987 /**
988  * Search for a tunnel among the tunnels for a client
989  *
990  * @param c the client whose tunnels to search in
991  * @param tid the local id of the tunnel
992  *
993  * @return tunnel handler, NULL if doesn't exist
994  */
995 static struct MeshTunnel *
996 tunnel_get_by_local_id (struct MeshClient *c, MESH_TunnelNumber tid)
997 {
998   GNUNET_HashCode hash;
999
1000   GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
1001   return GNUNET_CONTAINER_multihashmap_get (c->tunnels, &hash);
1002 }
1003
1004
1005 /**
1006  * Search for a tunnel by global ID using PEER_ID
1007  *
1008  * @param pi owner of the tunnel
1009  * @param tid global tunnel number
1010  *
1011  * @return tunnel handler, NULL if doesn't exist
1012  */
1013 static struct MeshTunnel *
1014 tunnel_get_by_pi (GNUNET_PEER_Id pi, MESH_TunnelNumber tid)
1015 {
1016   struct MESH_TunnelID id;
1017   GNUNET_HashCode hash;
1018
1019   id.oid = pi;
1020   id.tid = tid;
1021
1022   GNUNET_CRYPTO_hash (&id, sizeof (struct MESH_TunnelID), &hash);
1023   return GNUNET_CONTAINER_multihashmap_get (tunnels, &hash);
1024 }
1025
1026
1027 /**
1028  * Search for a tunnel by global ID using full PeerIdentities
1029  *
1030  * @param oid owner of the tunnel
1031  * @param tid global tunnel number
1032  *
1033  * @return tunnel handler, NULL if doesn't exist
1034  */
1035 static struct MeshTunnel *
1036 tunnel_get (struct GNUNET_PeerIdentity *oid, MESH_TunnelNumber tid)
1037 {
1038   return tunnel_get_by_pi (GNUNET_PEER_search (oid), tid);
1039 }
1040
1041
1042 /**
1043  * Callback used to notify a client owner of a tunnel that a peer has
1044  * disconnected, most likely because of a path change.
1045  *
1046  * @param n Node in the tree representing the disconnected peer
1047  */
1048 void
1049 notify_peer_disconnected (const struct MeshTunnelTreeNode *n)
1050 {
1051   struct GNUNET_MESH_PeerControl msg;
1052
1053   if (NULL == n->t->client || NULL == nc)
1054     return;
1055
1056   msg.header.size = htons (sizeof (msg));
1057   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL);
1058   msg.tunnel_id = htonl (n->t->local_tid);
1059   GNUNET_PEER_resolve (n->peer, &msg.peer);
1060   GNUNET_SERVER_notification_context_unicast (nc, n->t->client->handle,
1061                                               &msg.header, GNUNET_NO);
1062 }
1063
1064
1065 /**
1066  * Add a peer to a tunnel, accomodating paths accordingly and initializing all
1067  * needed rescources.
1068  *
1069  * @param t Tunnel we want to add a new peer to
1070  * @param peer PeerInfo of the peer being added
1071  *
1072  */
1073 static void
1074 tunnel_add_peer (struct MeshTunnel *t, struct MeshPeerInfo *peer)
1075 {
1076   struct MeshPeerPath *p;
1077   struct MeshPeerPath *best_p;
1078   unsigned int best_cost;
1079   unsigned int cost;
1080
1081   if (NULL != tree_find_peer(t->tree->root, peer->id))
1082   {
1083     /* Already have it, nothing to do. */
1084     return;
1085   }
1086
1087   t->peers_total++;
1088   GNUNET_array_append (peer->tunnels, peer->ntunnels, t);
1089   if (NULL == (p = peer->path_head))
1090   {
1091     GNUNET_break (0);
1092     return;
1093   }
1094
1095   best_p = p;
1096   best_cost = UINT_MAX;
1097   while (NULL != p)
1098   {
1099     if ((cost = path_get_cost (t->tree, p)) < best_cost)
1100     {
1101       best_cost = cost;
1102       best_p = p;
1103     }
1104     p = p->next;
1105   }
1106   tree_add_path (t->tree, best_p, &notify_peer_disconnected);
1107   if (GNUNET_SCHEDULER_NO_TASK == t->path_refresh_task)
1108     t->path_refresh_task =
1109         GNUNET_SCHEDULER_add_delayed (t->tree->refresh, &path_refresh, t);
1110    
1111 }
1112
1113
1114 /**
1115  * Notify a tunnel that a connection has broken that affects at least
1116  * some of its peers.
1117  *
1118  * @param t Tunnel affected.
1119  * @param peer Peer that (at least) has been affected by the disconnection.
1120  * @param p1 Peer that got disconnected from p2.
1121  * @param p2 Peer that got disconnected from p1.
1122  *
1123  * @return Short ID of the peer disconnected (either p1 or p2).
1124  *         0 if the tunnel remained unaffected.
1125  */
1126 static GNUNET_PEER_Id
1127 tunnel_notify_connection_broken (struct MeshTunnel *t,
1128                                  struct MeshPeerInfo *peer,
1129                                  GNUNET_PEER_Id p1,
1130                                  GNUNET_PEER_Id p2)
1131 {
1132   return tree_notify_connection_broken (t->tree, p1, p2,
1133                                         &notify_peer_disconnected);
1134 }
1135
1136
1137 /**
1138  * Destroy the tunnel and free any allocated resources linked to it
1139  *
1140  * @param t the tunnel to destroy
1141  *
1142  * @return GNUNET_OK on success
1143  */
1144 static int
1145 tunnel_destroy (struct MeshTunnel *t)
1146 {
1147   struct MeshClient *c;
1148   struct MeshQueue *q;
1149   struct MeshQueue *qn;
1150   GNUNET_HashCode hash;
1151   int r;
1152
1153   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: DESTROYING TUNNEL at %p\n", t);
1154   if (NULL == t)
1155     return GNUNET_OK;
1156
1157   c = t->client;
1158 #if MESH_DEBUG
1159   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   by client %u\n", c->id);
1160 #endif
1161
1162   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
1163   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &hash, t))
1164   {
1165     r = GNUNET_SYSERR;
1166   }
1167
1168   GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
1169   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (c->tunnels, &hash, t))
1170   {
1171     r = GNUNET_SYSERR;
1172   }
1173   GNUNET_CONTAINER_multihashmap_destroy (t->peers);
1174   q = t->queue_head;
1175   while (NULL != q)
1176   {
1177     if (NULL != q->data)
1178       GNUNET_free (q->data);
1179     qn = q->next;
1180     GNUNET_free (q);
1181     q = qn;
1182     /* TODO cancel core transmit ready in case it was active */
1183   }
1184   tree_destroy(t->tree);
1185   GNUNET_free (t);
1186   return r;
1187 }
1188
1189
1190 /**
1191  * tunnel_destroy_iterator: iterator for deleting each tunnel that belongs to a
1192  * client when the client disconnects.
1193  * 
1194  * @param cls closure (client that is disconnecting)
1195  * @param key the hash of the local tunnel id (used to access the hashmap)
1196  * @param value the value stored at the key (tunnel to destroy)
1197  * 
1198  * @return GNUNET_OK on success
1199  */
1200 static int
1201 tunnel_destroy_iterator (void *cls, const GNUNET_HashCode * key, void *value)
1202 {
1203   int r;
1204
1205   r = tunnel_destroy ((struct MeshTunnel *) value);
1206   return r;
1207 }
1208
1209
1210 /******************************************************************************/
1211 /****************      MESH NETWORK HANDLER HELPERS     ***********************/
1212 /******************************************************************************/
1213
1214
1215 /**
1216  * Function called to notify a client about the socket
1217  * being ready to queue more data.  "buf" will be
1218  * NULL and "size" zero if the socket was closed for
1219  * writing in the meantime.
1220  *
1221  * @param cls closure
1222  * @param size number of bytes available in buf
1223  * @param buf where the callee should write the message
1224  * @return number of bytes written to buf
1225  */
1226 static size_t
1227 send_core_create_path (void *cls, size_t size, void *buf)
1228 {
1229   struct MeshPathInfo *info = cls;
1230   struct GNUNET_MESH_ManipulatePath *msg;
1231   struct GNUNET_PeerIdentity *peer_ptr;
1232   struct MeshPeerInfo *peer = info->peer;
1233   struct MeshTunnel *t = info->t;
1234   struct MeshPeerPath *p = info->path;
1235   size_t size_needed;
1236   int i;
1237
1238   size_needed =
1239       sizeof (struct GNUNET_MESH_ManipulatePath) +
1240       p->length * sizeof (struct GNUNET_PeerIdentity);
1241
1242   if (size < size_needed || NULL == buf)
1243   {
1244     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: create path retransmit!\n");
1245     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   buf:  %p\n", buf);
1246     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   size: (%u/%u)\n",
1247                 size, size_needed);
1248     GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
1249                                        GNUNET_TIME_UNIT_FOREVER_REL,
1250                                        path_get_first_hop (t->tree, peer->id),
1251                                        size_needed,
1252                                        &send_core_create_path,
1253                                        info);
1254     return 0;
1255   }
1256
1257   msg = (struct GNUNET_MESH_ManipulatePath *) buf;
1258   msg->header.size = htons (size_needed);
1259   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE);
1260   msg->tid = ntohl (t->id.tid);
1261
1262   peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
1263   for (i = 0; i < p->length; i++)
1264   {
1265     GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
1266   }
1267
1268   path_destroy (p);
1269   GNUNET_free (info);
1270
1271   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1272               "MESH: CREATE PATH (%u bytes long) sent!\n",
1273               size_needed);
1274   return size_needed;
1275 }
1276
1277
1278 #if LATER
1279 /**
1280  * Function called to notify a client about the socket
1281  * being ready to queue more data.  "buf" will be
1282  * NULL and "size" zero if the socket was closed for
1283  * writing in the meantime.
1284  *
1285  * @param cls closure (MeshDataDescriptor with all info to build packet)
1286  * @param size number of bytes available in buf
1287  * @param buf where the callee should write the message
1288  * @return number of bytes written to buf
1289  */
1290 static size_t
1291 send_core_data_to_origin (void *cls, size_t size, void *buf)
1292 {
1293   struct MeshDataDescriptor *info = cls;
1294   struct GNUNET_MESH_ToOrigin *msg = buf;
1295   size_t total_size;
1296
1297   GNUNET_assert (NULL != info);
1298   total_size = sizeof (struct GNUNET_MESH_ToOrigin) + info->size;
1299   GNUNET_assert (total_size < 65536);   /* UNIT16_MAX */
1300
1301   if (total_size > size)
1302   {
1303     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1304                 "not enough buffer to send data to origin\n");
1305     return 0;
1306   }
1307   msg->header.size = htons (total_size);
1308   msg->header.type = htons (GNUNET_MESSAGE_TYPE_DATA_MESSAGE_TO_ORIGIN);
1309   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
1310   msg->tid = htonl (info->origin->tid);
1311   if (0 != info->size)
1312   {
1313     memcpy (&msg[1], &info[1], info->size);
1314   }
1315   if (NULL != info->client)
1316   {
1317     GNUNET_SERVER_receive_done (info->client, GNUNET_OK);
1318   }
1319   GNUNET_free (info);
1320   return total_size;
1321 }
1322 #endif
1323
1324
1325 /**
1326  * Function called to notify a client about the socket
1327  * being ready to queue more data.  "buf" will be
1328  * NULL and "size" zero if the socket was closed for
1329  * writing in the meantime.
1330  *
1331  * @param cls closure (data itself)
1332  * @param size number of bytes available in buf
1333  * @param buf where the callee should write the message
1334  * 
1335  * @return number of bytes written to buf
1336  */
1337 static size_t
1338 send_core_data_multicast (void *cls, size_t size, void *buf)
1339 {
1340   struct MeshDataDescriptor *info = cls;
1341   struct GNUNET_MESH_Multicast *msg = buf;
1342   size_t total_size;
1343
1344   GNUNET_assert (NULL != info);
1345   GNUNET_assert (NULL != info->peer);
1346   total_size = info->size + sizeof (struct GNUNET_MESH_Multicast);
1347   GNUNET_assert (total_size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1348
1349   if (total_size > size)
1350   {
1351     /* Retry */
1352     struct GNUNET_PeerIdentity id;
1353
1354     GNUNET_PEER_resolve(info->peer->id, &id);
1355     info->peer->infos[info->handler_n] = info;
1356     info->peer->types[info->handler_n] = GNUNET_MESSAGE_TYPE_MESH_MULTICAST;
1357     info->peer->core_transmit[info->handler_n] =
1358       GNUNET_CORE_notify_transmit_ready (core_handle,
1359                                          0,
1360                                          0,
1361                                          GNUNET_TIME_UNIT_FOREVER_REL,
1362                                          &id,
1363                                          total_size,
1364                                          &send_core_data_multicast,
1365                                          info);
1366     return 0;
1367   }
1368   info->peer->core_transmit[info->handler_n] = NULL;
1369   info->peer->infos[info->handler_n] = NULL;
1370   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
1371   msg->header.size = htons (total_size);
1372   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
1373   msg->tid = htonl (info->origin->tid);
1374   memcpy (&msg[1], info->data, info->size);
1375   if (0 == --(*info->copies))
1376   {
1377     if (NULL != info->client)
1378     {
1379       /* FIXME One unresponsive neighbor (who doesn't "call" tmt_rdy) can lock
1380        *       the client from sending anything else to the service.
1381        *       - Call receive_done after certain timeout.
1382        *       - Here cancel the timeout.
1383        */
1384       GNUNET_SERVER_receive_done (info->client, GNUNET_OK);
1385     }
1386     GNUNET_free (info->data);
1387     GNUNET_free (info->copies);
1388   }
1389   GNUNET_free (info);
1390   return total_size;
1391 }
1392
1393
1394 /**
1395  * Function called to notify a client about the socket
1396  * being ready to queue more data.  "buf" will be
1397  * NULL and "size" zero if the socket was closed for
1398  * writing in the meantime.
1399  *
1400  * @param cls closure (MeshDataDescriptor)
1401  * @param size number of bytes available in buf
1402  * @param buf where the callee should write the message
1403  * @return number of bytes written to buf
1404  */
1405 static size_t
1406 send_core_path_ack (void *cls, size_t size, void *buf)
1407 {
1408   struct MeshDataDescriptor *info = cls;
1409   struct GNUNET_MESH_PathACK *msg = buf;
1410
1411   GNUNET_assert (NULL != info);
1412   if (info->peer)
1413   {
1414     info->peer->core_transmit[info->handler_n] = NULL;
1415   }
1416   if (sizeof (struct GNUNET_MESH_PathACK) > size)
1417   {
1418     GNUNET_break (0);
1419     return 0;
1420   }
1421   msg->header.size = htons (sizeof (struct GNUNET_MESH_PathACK));
1422   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_ACK);
1423   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
1424   msg->tid = htonl (info->origin->tid);
1425   msg->peer_id = my_full_id;
1426   GNUNET_free (info);
1427   /* TODO add signature */
1428
1429   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: PATH ACK sent!\n");
1430   return sizeof (struct GNUNET_MESH_PathACK);
1431 }
1432
1433
1434 /**
1435  * Function called to notify a client about the socket
1436  * being ready to queue more data.  "buf" will be
1437  * NULL and "size" zero if the socket was closed for
1438  * writing in the meantime.
1439  *
1440  * @param cls closure (data itself)
1441  * @param size number of bytes available in buf
1442  * @param buf where the callee should write the message
1443  * @return number of bytes written to buf
1444  */
1445 static size_t
1446 send_core_data_raw (void *cls, size_t size, void *buf)
1447 {
1448   struct GNUNET_MessageHeader *msg = cls;
1449   size_t total_size;
1450
1451   GNUNET_assert (NULL != msg);
1452   total_size = ntohs (msg->size);
1453
1454   if (total_size > size)
1455   {
1456     GNUNET_break (0);
1457     return 0;
1458   }
1459   memcpy (buf, msg, total_size);
1460   GNUNET_free (cls);
1461   return total_size;
1462 }
1463
1464
1465 #if LATER
1466 /**
1467  * Send another peer a notification to destroy a tunnel
1468  * @param cls The tunnel to destroy
1469  * @param size Size in the buffer
1470  * @param buf Memory where to put the data to transmit
1471  * @return Size of data put in buffer
1472  */
1473 static size_t
1474 send_p2p_tunnel_destroy (void *cls, size_t size, void *buf)
1475 {
1476   struct MeshTunnel *t = cls;
1477   struct MeshClient *c;
1478   struct GNUNET_MESH_TunnelMessage *msg;
1479
1480   c = t->client;
1481   msg = buf;
1482   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
1483    /*FIXME*/ msg->header.size =
1484       htons (sizeof (struct GNUNET_MESH_TunnelMessage));
1485   msg->tunnel_id = htonl (t->id.tid);
1486
1487   tunnel_destroy (c, t);
1488   return sizeof (struct GNUNET_MESH_TunnelMessage);
1489 }
1490 #endif
1491
1492
1493 /**
1494  * Send the message to all clients that have subscribed to its type
1495  *
1496  * @param msg Pointer to the message itself
1497  * @return number of clients this message was sent to
1498  */
1499 static unsigned int
1500 send_subscribed_clients (struct GNUNET_MessageHeader *msg)
1501 {
1502   struct MeshClient *c;
1503   unsigned int count;
1504   uint16_t type;
1505
1506   type = ntohs (msg->type);
1507   for (count = 0, c = clients; c != NULL; c = c->next)
1508   {
1509     if (client_is_subscribed (type, c))
1510     {
1511       count++;
1512       GNUNET_SERVER_notification_context_unicast (nc, c->handle, msg,
1513                                                   GNUNET_YES);
1514     }
1515   }
1516   return count;
1517 }
1518
1519
1520
1521 /**
1522  * Notify the client that owns the tunnel that a peer has connected to it
1523  * 
1524  * @param t Tunnel whose owner to notify
1525  * @param id Short id of the peer that has connected
1526  */
1527 static void
1528 send_client_peer_connected (const struct MeshTunnel *t, const GNUNET_PEER_Id id)
1529 {
1530   struct GNUNET_MESH_PeerControl pc;
1531
1532   pc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD);
1533   pc.header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
1534   pc.tunnel_id = htonl (t->local_tid);
1535   GNUNET_PEER_resolve (id, &pc.peer);
1536   GNUNET_SERVER_notification_context_unicast (nc, t->client->handle,
1537                                               &pc.header, GNUNET_NO);
1538 }
1539
1540
1541 /******************************************************************************/
1542 /********************      MESH NETWORK HANDLERS     **************************/
1543 /******************************************************************************/
1544
1545
1546 /**
1547  * Core handler for path creation
1548  * struct GNUNET_CORE_MessageHandler
1549  *
1550  * @param cls closure
1551  * @param message message
1552  * @param peer peer identity this notification is about
1553  * @param atsi performance data
1554  * @return GNUNET_OK to keep the connection open,
1555  *         GNUNET_SYSERR to close it (signal serious error)
1556  *
1557  */
1558 static int
1559 handle_mesh_path_create (void *cls, const struct GNUNET_PeerIdentity *peer,
1560                          const struct GNUNET_MessageHeader *message,
1561                          const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1562 {
1563   unsigned int own_pos;
1564   uint16_t size;
1565   uint16_t i;
1566   MESH_TunnelNumber tid;
1567   struct GNUNET_MESH_ManipulatePath *msg;
1568   struct GNUNET_PeerIdentity *pi;
1569   struct GNUNET_PeerIdentity id;
1570   GNUNET_HashCode hash;
1571   struct MeshPeerPath *path;
1572   struct MeshPeerInfo *dest_peer_info;
1573   struct MeshPeerInfo *orig_peer_info;
1574   struct MeshTunnel *t;
1575
1576   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1577               "MESH: Received a path create msg\n");
1578   size = ntohs (message->size);
1579   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
1580   {
1581     GNUNET_break_op (0);
1582     return GNUNET_OK;
1583   }
1584
1585   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
1586   if (size % sizeof (struct GNUNET_PeerIdentity))
1587   {
1588     GNUNET_break_op (0);
1589     return GNUNET_OK;
1590   }
1591   size /= sizeof (struct GNUNET_PeerIdentity);
1592   if (size < 2)
1593   {
1594     GNUNET_break_op (0);
1595     return GNUNET_OK;
1596   }
1597   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1598               "MESH:     path as %u hops.\n",
1599               size);
1600   msg = (struct GNUNET_MESH_ManipulatePath *) message;
1601
1602   tid = ntohl (msg->tid);
1603   pi = (struct GNUNET_PeerIdentity *) &msg[1];
1604   t = tunnel_get (pi, tid);
1605   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1606               "MESH:     path is for tunnel %s [%X].\n",
1607               GNUNET_i2s(pi),
1608               tid);
1609   if (NULL == t)
1610   {
1611     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   Creating tunnel\n");
1612     t = GNUNET_malloc (sizeof (struct MeshTunnel));
1613     t->id.oid = GNUNET_PEER_intern (pi);
1614     t->id.tid = tid;
1615     t->peers = GNUNET_CONTAINER_multihashmap_create (32);
1616     t->local_tid = next_local_tid++;
1617     next_local_tid |= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
1618
1619     GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
1620     if (GNUNET_OK !=
1621         GNUNET_CONTAINER_multihashmap_put (tunnels, &hash, t,
1622                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
1623     {
1624       GNUNET_break (0);
1625       return GNUNET_OK;
1626     }
1627   }
1628   dest_peer_info =
1629       GNUNET_CONTAINER_multihashmap_get (peers, &pi[size - 1].hashPubKey);
1630   if (NULL == dest_peer_info)
1631   {
1632     dest_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
1633     dest_peer_info->id = GNUNET_PEER_intern (&pi[size - 1]);
1634     GNUNET_CONTAINER_multihashmap_put (peers, &pi[size - 1].hashPubKey,
1635                                        dest_peer_info,
1636                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1637   }
1638   orig_peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &pi->hashPubKey);
1639   if (NULL == orig_peer_info)
1640   {
1641     orig_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
1642     orig_peer_info->id = GNUNET_PEER_intern (pi);
1643     GNUNET_CONTAINER_multihashmap_put (peers, &pi->hashPubKey, orig_peer_info,
1644                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1645   }
1646
1647   path = path_new (size);
1648   own_pos = 0;
1649   for (i = 0; i < size; i++)
1650   {
1651     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
1652     if (path->peers[i] == myid)
1653       own_pos = i;
1654   }
1655   if (own_pos == 0)
1656   {                             /* cannot be self, must be 'not found' */
1657     /* create path: self not found in path through self */
1658     GNUNET_break_op (0);
1659     path_destroy (path);
1660     /* FIXME error. destroy tunnel? leave for timeout? */
1661     return 0;
1662   }
1663   if (own_pos == size - 1)
1664   {
1665     /* It is for us! Send ack. */
1666     struct GNUNET_MESH_TunnelNotification cmsg;
1667     struct MeshDataDescriptor *info;
1668     unsigned int j;
1669
1670     path_add_to_origin (orig_peer_info, path);  /* inverts path!  */
1671     info = GNUNET_malloc (sizeof (struct MeshDataDescriptor));
1672     info->origin = &t->id;
1673     info->peer = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
1674     GNUNET_assert (NULL != info->peer);
1675     for (j = 0; info->peer->core_transmit[j]; j++)
1676     {
1677       if (j == (CORE_QUEUE_SIZE - 1))
1678       {
1679         GNUNET_break (0);
1680         return GNUNET_OK;
1681       }
1682     }
1683     info->handler_n = j;
1684     info->peer->core_transmit[j] =
1685         GNUNET_CORE_notify_transmit_ready (core_handle, 0, 100,
1686                                            GNUNET_TIME_UNIT_FOREVER_REL, peer,
1687                                            sizeof (struct GNUNET_MESH_PathACK),
1688                                            &send_core_path_ack, info);
1689     cmsg.header.size = htons(sizeof(cmsg));
1690     cmsg.header.type = htons(GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
1691     GNUNET_PEER_resolve(t->id.oid, &cmsg.peer);
1692     cmsg.tunnel_id = htonl(t->local_tid);
1693     GNUNET_SERVER_notification_context_broadcast(nc, &cmsg.header, GNUNET_NO);
1694   }
1695   else
1696   {
1697     /* It's for somebody else! Retransmit. */
1698     struct MeshPathInfo *path_info;
1699
1700     path_info = GNUNET_malloc (sizeof (struct MeshPathInfo));
1701     path_info->t = t;
1702     path_info->path = path;
1703     path_info->peer = dest_peer_info;
1704
1705     path_add_to_peer (dest_peer_info, path);
1706     GNUNET_PEER_resolve (path->peers[own_pos + 1], &id);
1707     GNUNET_CORE_notify_transmit_ready (
1708         core_handle,
1709         0,
1710         0,
1711         GNUNET_TIME_UNIT_FOREVER_REL,
1712         &id,
1713         sizeof (struct GNUNET_MESH_ManipulatePath) +
1714         path->length * sizeof(struct GNUNET_PeerIdentity),
1715         &send_core_create_path,
1716         path_info);
1717   }
1718   return GNUNET_OK;
1719 }
1720
1721
1722 /**
1723  * Core handler for mesh network traffic going from the origin to a peer
1724  *
1725  * @param cls closure
1726  * @param peer peer identity this notification is about
1727  * @param message message
1728  * @param atsi performance data
1729  * @return GNUNET_OK to keep the connection open,
1730  *         GNUNET_SYSERR to close it (signal serious error)
1731  */
1732 static int
1733 handle_mesh_data_unicast (void *cls, const struct GNUNET_PeerIdentity *peer,
1734                           const struct GNUNET_MessageHeader *message,
1735                           const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1736 {
1737   struct GNUNET_MESH_Unicast *msg;
1738   struct MeshTunnel *t;
1739   struct MeshPeerInfo *pi;
1740   size_t size;
1741
1742   size = ntohs (message->size);
1743   if (size <
1744       sizeof (struct GNUNET_MESH_Unicast) +
1745       sizeof (struct GNUNET_MessageHeader))
1746   {
1747     GNUNET_break (0);
1748     return GNUNET_OK;
1749   }
1750   msg = (struct GNUNET_MESH_Unicast *) message;
1751   t = tunnel_get (&msg->oid, ntohl (msg->tid));
1752   if (NULL == t)
1753   {
1754     /* TODO notify back: we don't know this tunnel */
1755     GNUNET_break_op (0);
1756     return GNUNET_OK;
1757   }
1758   pi = GNUNET_CONTAINER_multihashmap_get (t->peers,
1759                                           &msg->destination.hashPubKey);
1760   if (NULL == pi)
1761   {
1762     /* TODO maybe feedback, log to statistics */
1763     GNUNET_break_op (0);
1764     return GNUNET_OK;
1765   }
1766   if (pi->id == myid)
1767   {
1768     send_subscribed_clients ((struct GNUNET_MessageHeader *) &msg[1]);
1769     return GNUNET_OK;
1770   }
1771   msg = GNUNET_malloc (size);
1772   memcpy (msg, message, size);
1773   GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
1774                                      GNUNET_TIME_UNIT_FOREVER_REL,
1775                                      path_get_first_hop (t->tree, pi->id),
1776                                      size,
1777                                      &send_core_data_raw, msg);
1778   return GNUNET_OK;
1779 }
1780
1781
1782 /**
1783  * Core handler for mesh network traffic going from the origin to all peers
1784  *
1785  * @param cls closure
1786  * @param message message
1787  * @param peer peer identity this notification is about
1788  * @param atsi performance data
1789  * @return GNUNET_OK to keep the connection open,
1790  *         GNUNET_SYSERR to close it (signal serious error)
1791  *
1792  * TODO: Check who we got this from, to validate route.
1793  */
1794 static int
1795 handle_mesh_data_multicast (void *cls, const struct GNUNET_PeerIdentity *peer,
1796                             const struct GNUNET_MessageHeader *message,
1797                             const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1798 {
1799   struct GNUNET_MESH_Multicast *msg;
1800   struct GNUNET_PeerIdentity *id;
1801   struct MeshDataDescriptor *info;
1802   struct MeshTunnelTreeNode *n;
1803   struct MeshTunnel *t;
1804   unsigned int *copies;
1805   unsigned int i;
1806   size_t size;
1807   void *data;
1808
1809   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_Multicast);
1810   if (size < sizeof (struct GNUNET_MessageHeader))
1811   {
1812     GNUNET_break_op (0);
1813     return GNUNET_OK;
1814   }
1815   msg = (struct GNUNET_MESH_Multicast *) message;
1816   t = tunnel_get (&msg->oid, ntohl (msg->tid));
1817
1818   if (NULL == t)
1819   {
1820     /* TODO notify that we dont know that tunnel */
1821     GNUNET_break_op (0);
1822     return GNUNET_OK;
1823   }
1824
1825   /* Transmit to locally interested clients */
1826   if (GNUNET_CONTAINER_multihashmap_contains (t->peers, &my_full_id.hashPubKey))
1827   {
1828     send_subscribed_clients ((struct GNUNET_MessageHeader *) &msg[1]);
1829   }
1830   n = t->tree->me->children_head;
1831   if (NULL == n)
1832     return GNUNET_OK;
1833   copies = GNUNET_malloc (sizeof (unsigned int));
1834   for (*copies = 0; NULL != n; n = n->next)
1835     (*copies)++;
1836   n = t->tree->me->children_head;
1837   data = GNUNET_malloc (size);
1838   memcpy (data, &msg[1], size);
1839   while (NULL != n)
1840   {
1841     info = GNUNET_malloc (sizeof (struct MeshDataDescriptor));
1842     info->origin = &t->id;
1843     info->data = data;
1844     info->size = size;
1845     info->copies = copies;
1846     info->client = t->client->handle;
1847     info->destination = n->peer;
1848     id = path_get_first_hop(t->tree, n->peer);
1849     info->peer = peer_info_get(id);
1850     GNUNET_assert (NULL != info->peer);
1851     for (i = 0; NULL != info->peer->core_transmit[i]; i++)
1852     {
1853       if (i == (CORE_QUEUE_SIZE - 1))
1854       {
1855         GNUNET_break (0);
1856         return GNUNET_OK;
1857       }
1858     }
1859     info->handler_n = i;
1860     info->peer->infos[i] = info;
1861     info->peer->types[i] = GNUNET_MESSAGE_TYPE_MESH_MULTICAST;
1862     info->peer->core_transmit[i] =
1863         GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
1864                                            GNUNET_TIME_UNIT_FOREVER_REL, id,
1865                                            ntohs (msg->header.size),
1866                                            &send_core_data_multicast, info);
1867   }
1868
1869   return GNUNET_OK;
1870 }
1871
1872
1873 /**
1874  * Core handler for mesh network traffic
1875  *
1876  * @param cls closure
1877  * @param message message
1878  * @param peer peer identity this notification is about
1879  * @param atsi performance data
1880  *
1881  * @return GNUNET_OK to keep the connection open,
1882  *         GNUNET_SYSERR to close it (signal serious error)
1883  */
1884 static int
1885 handle_mesh_data_to_orig (void *cls, const struct GNUNET_PeerIdentity *peer,
1886                           const struct GNUNET_MessageHeader *message,
1887                           const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1888 {
1889   struct GNUNET_MESH_ToOrigin *msg;
1890   struct GNUNET_PeerIdentity id;
1891   struct MeshPeerInfo *peer_info;
1892   struct MeshTunnel *t;
1893   size_t size;
1894
1895   size = ntohs (message->size);
1896   if (size < sizeof (struct GNUNET_MESH_ToOrigin) +     /* Payload must be */
1897       sizeof (struct GNUNET_MessageHeader))     /* at least a header */
1898   {
1899     GNUNET_break_op (0);
1900     return GNUNET_OK;
1901   }
1902   msg = (struct GNUNET_MESH_ToOrigin *) message;
1903   t = tunnel_get (&msg->oid, ntohl (msg->tid));
1904
1905   if (NULL == t)
1906   {
1907     /* TODO notify that we dont know this tunnel (whom)? */
1908     return GNUNET_OK;
1909   }
1910
1911   if (t->id.oid == myid)
1912   {
1913     if (NULL == t->client)
1914     {
1915       /* got data packet for ownerless tunnel */
1916       GNUNET_break_op (0);
1917       return GNUNET_OK;
1918     }
1919     /* TODO signature verification */
1920     GNUNET_SERVER_notification_context_unicast (nc, t->client->handle, message,
1921                                                 GNUNET_YES);
1922     return GNUNET_OK;
1923   }
1924   peer_info = peer_info_get (&msg->oid);
1925   if (NULL == peer_info)
1926   {
1927     /* unknown origin of tunnel */
1928     GNUNET_break (0);
1929     return GNUNET_OK;
1930   }
1931   GNUNET_PEER_resolve (t->tree->me->parent->peer, &id);
1932   msg = GNUNET_malloc (size);
1933   memcpy (msg, message, size);
1934   GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
1935                                      GNUNET_TIME_UNIT_FOREVER_REL, &id, size,
1936                                      &send_core_data_raw, msg);
1937
1938   return GNUNET_OK;
1939 }
1940
1941
1942 /**
1943  * Core handler for path ACKs
1944  *
1945  * @param cls closure
1946  * @param message message
1947  * @param peer peer identity this notification is about
1948  * @param atsi performance data
1949  *
1950  * @return GNUNET_OK to keep the connection open,
1951  *         GNUNET_SYSERR to close it (signal serious error)
1952  */
1953 static int
1954 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
1955                       const struct GNUNET_MessageHeader *message,
1956                       const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1957 {
1958   struct GNUNET_MESH_PathACK *msg;
1959   struct MeshTunnelTreeNode *n;
1960   struct MeshPeerInfo *peer_info;
1961   struct MeshTunnel *t;
1962
1963   msg = (struct GNUNET_MESH_PathACK *) message;
1964   t = tunnel_get (&msg->oid, msg->tid);
1965   if (NULL == t)
1966   {
1967     /* TODO notify that we don't know the tunnel */
1968     return GNUNET_OK;
1969   }
1970
1971   /* Message for us? */
1972   if (0 == memcmp (&msg->oid, &my_full_id, sizeof (struct GNUNET_PeerIdentity)))
1973   {
1974     if (NULL == t->client)
1975     {
1976       GNUNET_break_op (0);
1977       return GNUNET_OK;
1978     }
1979     peer_info = peer_info_get (&msg->peer_id);
1980     if (NULL == peer_info)
1981     {
1982       GNUNET_break_op (0);
1983       return GNUNET_OK;
1984     }
1985     n = tree_find_peer(t->tree->root, peer_info->id);
1986     if (NULL == n)
1987     {
1988       GNUNET_break_op (0);
1989       return GNUNET_OK;
1990     }
1991     n->status = MESH_PEER_READY;
1992     send_client_peer_connected(t, peer_info->id);
1993     return GNUNET_OK;
1994   }
1995
1996   peer_info = peer_info_get (&msg->oid);
1997   if (NULL == peer_info)
1998   {
1999     /* If we know the tunnel, we should DEFINITELY know the peer */
2000     GNUNET_break (0);
2001     return GNUNET_OK;
2002   }
2003   msg = GNUNET_malloc (sizeof (struct GNUNET_MESH_PathACK));
2004   memcpy (msg, message, sizeof (struct GNUNET_MESH_PathACK));
2005   GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
2006                                      GNUNET_TIME_UNIT_FOREVER_REL,
2007                                      path_get_first_hop (t->tree,
2008                                                          peer_info->id),
2009                                      sizeof (struct GNUNET_MESH_PathACK),
2010                                      &send_core_data_raw, msg);
2011   return GNUNET_OK;
2012 }
2013
2014
2015 /**
2016  * Functions to handle messages from core
2017  */
2018 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
2019   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
2020   {&handle_mesh_data_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
2021   {&handle_mesh_data_multicast, GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
2022   {&handle_mesh_data_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
2023   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
2024    sizeof (struct GNUNET_MESH_PathACK)},
2025   {NULL, 0, 0}
2026 };
2027
2028
2029
2030 /******************************************************************************/
2031 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
2032 /******************************************************************************/
2033
2034 /**
2035  * deregister_app: iterator for removing each application registered by a client
2036  * 
2037  * @param cls closure
2038  * @param key the hash of the application id (used to access the hashmap)
2039  * @param value the value stored at the key (client)
2040  * 
2041  * @return GNUNET_OK on success
2042  */
2043 static int
2044 deregister_app (void *cls, const GNUNET_HashCode * key, void *value)
2045 {
2046   GNUNET_CONTAINER_multihashmap_remove (applications, key, value);
2047   return GNUNET_OK;
2048 }
2049
2050 #if LATER
2051 /**
2052  * notify_client_connection_failure: notify a client that the connection to the
2053  * requested remote peer is not possible (for instance, no route found)
2054  * Function called when the socket is ready to queue more data. "buf" will be
2055  * NULL and "size" zero if the socket was closed for writing in the meantime.
2056  *
2057  * @param cls closure
2058  * @param size number of bytes available in buf
2059  * @param buf where the callee should write the message
2060  * @return number of bytes written to buf
2061  */
2062 static size_t
2063 notify_client_connection_failure (void *cls, size_t size, void *buf)
2064 {
2065   int size_needed;
2066   struct MeshPeerInfo *peer_info;
2067   struct GNUNET_MESH_PeerControl *msg;
2068   struct GNUNET_PeerIdentity id;
2069
2070   if (0 == size && NULL == buf)
2071   {
2072     // TODO retry? cancel?
2073     return 0;
2074   }
2075
2076   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
2077   peer_info = (struct MeshPeerInfo *) cls;
2078   msg = (struct GNUNET_MESH_PeerControl *) buf;
2079   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
2080   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
2081 //     msg->tunnel_id = htonl(peer_info->t->tid);
2082   GNUNET_PEER_resolve (peer_info->id, &id);
2083   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
2084
2085   return size_needed;
2086 }
2087 #endif
2088
2089
2090 /**
2091  * Send keepalive packets for a peer
2092  *
2093  * @param cls Closure (tunnel for which to send the keepalive).
2094  * @param tc Notification context.
2095  *
2096  * TODO: implement explicit multicast keepalive?
2097  */
2098 void
2099 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2100 {
2101   struct MeshTunnel *t = cls;
2102   struct GNUNET_MessageHeader *payload;
2103   struct GNUNET_MESH_Multicast *msg;
2104   size_t size;
2105
2106   t->path_refresh_task = GNUNET_SCHEDULER_NO_TASK;
2107   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
2108   {
2109     return;
2110   }
2111
2112   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2113               "MESH: sending keepalive for tunnel %d\n",
2114               t->id.tid);
2115
2116   size = sizeof(struct GNUNET_MESH_Multicast) +
2117          sizeof(struct GNUNET_MessageHeader);
2118   msg = GNUNET_malloc (size);
2119   msg->header.size = htons (size);
2120   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
2121   msg->oid = my_full_id;
2122   msg->tid = htonl(t->id.tid);
2123   payload = (struct GNUNET_MessageHeader *) &msg[1];
2124   payload->size = htons (sizeof(struct GNUNET_MessageHeader));
2125   payload->type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE);
2126   handle_mesh_data_multicast (NULL, &my_full_id, &msg->header, NULL);
2127
2128   GNUNET_free (msg);
2129   t->path_refresh_task =
2130       GNUNET_SCHEDULER_add_delayed (t->tree->refresh, &path_refresh, t);
2131   return;
2132 }
2133
2134
2135 /**
2136  * Function to process paths received for a new peer addition. The recorded
2137  * paths form the initial tunnel, which can be optimized later.
2138  * Called on each result obtained for the DHT search.
2139  *
2140  * @param cls closure
2141  * @param exp when will this value expire
2142  * @param key key of the result
2143  * @param type type of the result
2144  * @param size number of bytes in data
2145  * @param data pointer to the result data
2146  *
2147  * TODO: re-issue the request after certain time? cancel after X results?
2148  */
2149 static void
2150 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
2151                     const GNUNET_HashCode * key,
2152                     const struct GNUNET_PeerIdentity *get_path,
2153                     unsigned int get_path_length,
2154                     const struct GNUNET_PeerIdentity *put_path,
2155                     unsigned int put_path_length,
2156                     enum GNUNET_BLOCK_Type type, size_t size, const void *data)
2157 {
2158   struct MeshPathInfo *path_info = cls;
2159   struct MeshPathInfo *path_info_aux;
2160   struct MeshPeerPath *p;
2161   struct MeshPeerPath *aux;
2162   struct GNUNET_PeerIdentity pi;
2163   int i;
2164
2165   GNUNET_PEER_resolve (path_info->peer->id, &pi);
2166   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2167              "MESH: Got results from DHT for %s\n",
2168              GNUNET_h2s_full(&pi.hashPubKey));
2169   if (NULL == get_path || NULL == put_path)
2170   {
2171     if (NULL == path_info->peer->path_head)
2172     {
2173       // Find ourselves some alternate initial path to the destination: retry
2174       GNUNET_DHT_get_stop (path_info->peer->dhtget);
2175       path_info->peer->dhtget = GNUNET_DHT_get_start (dht_handle,       /* handle */
2176                                                       GNUNET_TIME_UNIT_SECONDS,     /* timeout */
2177                                                       GNUNET_BLOCK_TYPE_TEST,   /* type */
2178                                                       &pi.hashPubKey,   /*key to search */
2179                                                       4,        /* replication level */
2180                                                       GNUNET_DHT_RO_RECORD_ROUTE, 
2181                                                       NULL,     /* xquery */
2182                                                       0,        /* xquery bits */
2183                                                       &dht_get_id_handler,
2184                                                       (void *) path_info);
2185       return;
2186     }
2187   }
2188
2189   p = path_build_from_dht (get_path, get_path_length, put_path, put_path_length);
2190   path_add_to_peer (path_info->peer, p);
2191   for (i = 0; i < path_info->peer->ntunnels; i++)
2192   {
2193     tunnel_add_peer (path_info->peer->tunnels[i], path_info->peer);
2194     aux = tree_get_path_to_peer(path_info->peer->tunnels[i]->tree,
2195                                 path_info->peer->id);
2196     if (aux->length > 1)
2197     {
2198       struct GNUNET_PeerIdentity id;
2199
2200       path_info_aux = GNUNET_malloc (sizeof (struct MeshPathInfo));
2201       path_info_aux->path = aux;
2202       path_info_aux->peer = path_info->peer;
2203       path_info_aux->t = path_info->t;
2204       GNUNET_PEER_resolve (p->peers[1], &id);
2205       GNUNET_CORE_notify_transmit_ready (core_handle, /* handle */
2206                                       0, /* cork */
2207                                       0, /* priority */
2208                                       GNUNET_TIME_UNIT_FOREVER_REL,
2209                                       /* timeout */
2210                                       &id, /* target */
2211                                       sizeof (struct GNUNET_MESH_ManipulatePath)
2212                                       +
2213                                       (aux->length *
2214                                         sizeof (struct GNUNET_PeerIdentity)),
2215                                       /*size */
2216                                       &send_core_create_path,
2217                                       /* callback */
2218                                       path_info_aux);        /* cls */
2219     }
2220     else
2221     {
2222       send_client_peer_connected(path_info->t, myid);
2223     }
2224   }
2225   GNUNET_free (path_info);
2226
2227   return;
2228 }
2229
2230
2231 /**
2232  * Function to process paths received for a new peer addition. The recorded
2233  * paths form the initial tunnel, which can be optimized later.
2234  * Called on each result obtained for the DHT search.
2235  *
2236  * @param cls closure
2237  * @param exp when will this value expire
2238  * @param key key of the result
2239  * @param type type of the result
2240  * @param size number of bytes in data
2241  * @param data pointer to the result data
2242  */
2243 static void
2244 dht_get_type_handler (void *cls, struct GNUNET_TIME_Absolute exp,
2245                       const GNUNET_HashCode * key,
2246                       const struct GNUNET_PeerIdentity *get_path,
2247                       unsigned int get_path_length,
2248                       const struct GNUNET_PeerIdentity *put_path,
2249                       unsigned int put_path_length,
2250                       enum GNUNET_BLOCK_Type type, size_t size,
2251                       const void *data)
2252 {
2253   const struct GNUNET_PeerIdentity *pi = data;
2254   struct GNUNET_PeerIdentity id;
2255   struct MeshTunnel *t = cls;
2256   struct MeshPeerInfo *peer_info;
2257   struct MeshPathInfo *path_info;
2258   struct MeshPeerPath *p;
2259   int i;
2260
2261   if (size != sizeof (struct GNUNET_PeerIdentity))
2262   {
2263     GNUNET_break_op (0);
2264     return;
2265   }
2266   GNUNET_assert (NULL != t->client);
2267   GNUNET_DHT_get_stop (t->client->dht_get_type); /* FIXME move to task? */
2268   t->client->dht_get_type = NULL;
2269   peer_info = peer_info_get (pi);
2270   GNUNET_CONTAINER_multihashmap_put (t->peers, &pi->hashPubKey, peer_info,
2271                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2272
2273   if ((NULL == get_path || NULL == put_path) && NULL == peer_info->path_head &&
2274       NULL == peer_info->dhtget)
2275   {
2276     path_info = GNUNET_malloc (sizeof (struct MeshPathInfo));
2277     path_info->peer = peer_info;
2278     path_info->t = t;
2279     /* we don't have a route to the peer, let's try a direct lookup */
2280     peer_info->dhtget = GNUNET_DHT_get_start (dht_handle,
2281                                               /* handle */
2282                                               GNUNET_TIME_UNIT_SECONDS,
2283                                               /* timeout */
2284                                               GNUNET_BLOCK_TYPE_TEST,
2285                                               /* block type */
2286                                               &pi->hashPubKey,
2287                                               /* key to look up */
2288                                               10U,
2289                                               /* replication level */
2290                                               GNUNET_DHT_RO_RECORD_ROUTE,
2291                                               /* option to dht: record route */
2292                                               NULL,     /* xquery */
2293                                               0,        /* xquery bits */
2294                                               dht_get_id_handler,
2295                                               /* callback */
2296                                               path_info);       /* closure */
2297     return;
2298   }
2299
2300   p = path_build_from_dht (get_path, get_path_length, put_path, put_path_length);
2301   path_add_to_peer (peer_info, p);
2302   tunnel_add_peer(t, peer_info);
2303   p = tree_get_path_to_peer(t->tree, peer_info->id);
2304 #if MESH_DEBUG
2305   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2306               "MESH: new route for tunnel 0x%x found, has %u hops\n",
2307               t->local_tid, p->length);
2308   for (i = 0; i < p->length; i++)
2309   {
2310     GNUNET_PEER_resolve (p->peers[0], &id);
2311     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:\t%d\t%s\n", i,
2312                 GNUNET_h2s_full (&id.hashPubKey));
2313   }
2314 #endif
2315
2316   if (p->length > 1)
2317   {
2318     path_info = GNUNET_malloc(sizeof(struct MeshPathInfo));
2319     path_info->t = t;
2320     path_info->peer = peer_info;
2321     path_info->path = p;
2322     GNUNET_PEER_resolve (p->peers[1], &id);
2323     GNUNET_CORE_notify_transmit_ready (core_handle,
2324                                      /* handle */
2325                                      0,
2326                                      /* cork */
2327                                      0,
2328                                      /* priority */
2329                                      GNUNET_TIME_UNIT_FOREVER_REL,
2330                                      /* timeout */
2331                                      &id,
2332                                      /* target */
2333                                      sizeof (struct GNUNET_MESH_ManipulatePath)
2334                                      +
2335                                      (p->length *
2336                                       sizeof (struct GNUNET_PeerIdentity)),
2337                                      /*size */
2338                                      &send_core_create_path,
2339                                      /* callback */
2340                                      path_info);        /* cls */
2341     return;
2342   }
2343   path_destroy(p);
2344   send_client_peer_connected(t, myid);
2345 }
2346
2347
2348 /**
2349  * Task run during shutdown.
2350  *
2351  * @param cls unused
2352  * @param tc unused
2353  */
2354 static void
2355 dht_get_type_restart (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2356 {
2357
2358 }
2359
2360 /******************************************************************************/
2361 /*********************       MESH LOCAL HANDLES      **************************/
2362 /******************************************************************************/
2363
2364
2365 /**
2366  * Handler for client disconnection
2367  *
2368  * @param cls closure
2369  * @param client identification of the client; NULL
2370  *        for the last call when the server is destroyed
2371  */
2372 static void
2373 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
2374 {
2375   struct MeshClient *c;
2376   struct MeshClient *next;
2377
2378   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: client disconnected\n");
2379   if (client == NULL)
2380      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    (SERVER DOWN)\n");
2381   c = clients;
2382   while (NULL != c)
2383   {
2384     if (c->handle != client && NULL != client)
2385     {
2386       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    ... searching\n");
2387       c = c->next;
2388       continue;
2389     }
2390     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: matching client found\n");
2391     if (NULL != c->tunnels)
2392     {
2393       GNUNET_CONTAINER_multihashmap_iterate (c->tunnels,
2394                                              &tunnel_destroy_iterator,
2395                                              c);
2396       GNUNET_CONTAINER_multihashmap_destroy (c->tunnels);
2397     }
2398
2399     /* deregister clients applications */
2400     if (NULL != c->apps)
2401     {
2402       GNUNET_CONTAINER_multihashmap_iterate (c->apps, &deregister_app, NULL);
2403       GNUNET_CONTAINER_multihashmap_destroy (c->apps);
2404     }
2405     if (0 == GNUNET_CONTAINER_multihashmap_size (applications) &&
2406         GNUNET_SCHEDULER_NO_TASK != announce_applications_task)
2407     {
2408       GNUNET_SCHEDULER_cancel (announce_applications_task);
2409       announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
2410     }
2411     if (NULL != c->types)
2412       GNUNET_CONTAINER_multihashmap_destroy (c->types);
2413     if (NULL != c->dht_get_type)
2414     {
2415       GNUNET_SCHEDULER_cancel (c->dht_get_type_task);
2416       GNUNET_DHT_get_stop (c->dht_get_type);
2417     }
2418     GNUNET_CONTAINER_DLL_remove (clients, clients_tail, c);
2419     next = c->next;
2420     GNUNET_free (c);
2421     c = next;
2422   }
2423
2424   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    done!\n");
2425   return;
2426 }
2427
2428
2429 /**
2430  * Handler for new clients
2431  *
2432  * @param cls closure
2433  * @param client identification of the client
2434  * @param message the actual message, which includes messages the client wants
2435  */
2436 static void
2437 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
2438                          const struct GNUNET_MessageHeader *message)
2439 {
2440   struct GNUNET_MESH_ClientConnect *cc_msg;
2441   struct MeshClient *c;
2442   GNUNET_MESH_ApplicationType *a;
2443   unsigned int size;
2444   uint16_t ntypes;
2445   uint16_t *t;
2446   uint16_t napps;
2447   uint16_t i;
2448
2449   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new client connected\n");
2450   /* Check data sanity */
2451   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
2452   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
2453   ntypes = ntohs (cc_msg->types);
2454   napps = ntohs (cc_msg->applications);
2455   if (size !=
2456       ntypes * sizeof (uint16_t) + napps * sizeof (GNUNET_MESH_ApplicationType))
2457   {
2458     GNUNET_break (0);
2459     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2460     return;
2461   }
2462
2463   /* Create new client structure */
2464   c = GNUNET_malloc (sizeof (struct MeshClient));
2465 #if MESH_DEBUG
2466   c->id = next_client_id++;
2467 #endif
2468   c->handle = client;
2469   a = (GNUNET_MESH_ApplicationType *) &cc_msg[1];
2470   if (napps > 0)
2471   {
2472     GNUNET_MESH_ApplicationType at;
2473     GNUNET_HashCode hc;
2474
2475     c->apps = GNUNET_CONTAINER_multihashmap_create (napps);
2476     for (i = 0; i < napps; i++)
2477     {
2478       at = ntohl (a[i]);
2479       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   app type: %u\n", at);
2480       GNUNET_CRYPTO_hash (&at, sizeof (at), &hc);
2481       /* store in clients hashmap */
2482       GNUNET_CONTAINER_multihashmap_put (c->apps, &hc, c,
2483                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2484       /* store in global hashmap, for announcements */
2485       GNUNET_CONTAINER_multihashmap_put (applications, &hc, c,
2486                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2487     }
2488     if (GNUNET_SCHEDULER_NO_TASK == announce_applications_task)
2489       announce_applications_task =
2490           GNUNET_SCHEDULER_add_now (&announce_applications, NULL);
2491
2492   }
2493   if (ntypes > 0)
2494   {
2495     uint16_t u16;
2496     GNUNET_HashCode hc;
2497
2498     t = (uint16_t *) & a[napps];
2499     c->types = GNUNET_CONTAINER_multihashmap_create (ntypes);
2500     for (i = 0; i < ntypes; i++)
2501     {
2502       u16 = ntohs (t[i]);
2503       GNUNET_CRYPTO_hash (&u16, sizeof (u16), &hc);
2504
2505       /* store in clients hashmap */
2506       GNUNET_CONTAINER_multihashmap_put (c->types, &hc, c,
2507                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2508       /* store in global hashmap */
2509       GNUNET_CONTAINER_multihashmap_put (types, &hc, c,
2510                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2511     }
2512   }
2513   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2514               "MESH:  client has %u+%u subscriptions\n", napps, ntypes);
2515
2516   GNUNET_CONTAINER_DLL_insert (clients, clients_tail, c);
2517   c->tunnels = GNUNET_CONTAINER_multihashmap_create (32);
2518   GNUNET_SERVER_notification_context_add (nc, client);
2519
2520   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2521 #if MESH_DEBUG
2522   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new client processed\n");
2523 #endif
2524 }
2525
2526
2527 /**
2528  * Handler for requests of new tunnels
2529  *
2530  * @param cls closure
2531  * @param client identification of the client
2532  * @param message the actual message
2533  */
2534 static void
2535 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
2536                             const struct GNUNET_MessageHeader *message)
2537 {
2538   struct GNUNET_MESH_TunnelMessage *t_msg;
2539   struct MeshTunnel *t;
2540   struct MeshClient *c;
2541   GNUNET_HashCode hash;
2542
2543   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new tunnel requested\n");
2544
2545   /* Sanity check for client registration */
2546   if (NULL == (c = client_get (client)))
2547   {
2548     GNUNET_break (0);
2549     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2550     return;
2551   }
2552 #if MESH_DEBUG
2553   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   by client %u\n", c->id);
2554 #endif
2555
2556   /* Message sanity check */
2557   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
2558   {
2559     GNUNET_break (0);
2560     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2561     return;
2562   }
2563
2564   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
2565   /* Sanity check for tunnel numbering */
2566   if (0 == (ntohl (t_msg->tunnel_id) & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
2567   {
2568     GNUNET_break (0);
2569     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2570     return;
2571   }
2572   /* Sanity check for duplicate tunnel IDs */
2573   if (NULL != tunnel_get_by_local_id (c, ntohl (t_msg->tunnel_id)))
2574   {
2575     GNUNET_break (0);
2576     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2577     return;
2578   }
2579
2580   t = GNUNET_malloc (sizeof (struct MeshTunnel));
2581   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: CREATED TUNNEL at %p\n", t);
2582   while (NULL != tunnel_get_by_pi (myid, next_tid))
2583     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
2584   t->id.tid = next_tid++;
2585   t->id.oid = myid;
2586   t->local_tid = ntohl (t_msg->tunnel_id);
2587   t->client = c;
2588   t->peers = GNUNET_CONTAINER_multihashmap_create (32);
2589
2590   GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
2591   if (GNUNET_OK !=
2592       GNUNET_CONTAINER_multihashmap_put (c->tunnels, &hash, t,
2593                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2594   {
2595     GNUNET_break (0);
2596     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2597     return;
2598   }
2599
2600   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
2601   if (GNUNET_OK !=
2602       GNUNET_CONTAINER_multihashmap_put (tunnels, &hash, t,
2603                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2604   {
2605     GNUNET_break (0);
2606     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2607     return;
2608   }
2609   t->tree = tree_new (t, myid);
2610   t->tree->refresh = REFRESH_PATH_TIME;
2611   t->tree->root->status = MESH_PEER_READY;
2612   t->tree->me = t->tree->root;
2613
2614   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2615   return;
2616 }
2617
2618
2619 /**
2620  * Handler for requests of deleting tunnels
2621  *
2622  * @param cls closure
2623  * @param client identification of the client
2624  * @param message the actual message
2625  */
2626 static void
2627 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
2628                              const struct GNUNET_MessageHeader *message)
2629 {
2630   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
2631   struct MeshClient *c;
2632   struct MeshTunnel *t;
2633   MESH_TunnelNumber tid;
2634   GNUNET_HashCode hash;
2635
2636   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: destroying tunnel\n");
2637
2638   /* Sanity check for client registration */
2639   if (NULL == (c = client_get (client)))
2640   {
2641     GNUNET_break (0);
2642     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2643     return;
2644   }
2645   /* Message sanity check */
2646   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
2647   {
2648     GNUNET_break (0);
2649     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2650     return;
2651   }
2652 #if MESH_DEBUG
2653   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   by client %u\n", c->id);
2654 #endif
2655   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
2656
2657   /* Retrieve tunnel */
2658   tid = ntohl (tunnel_msg->tunnel_id);
2659
2660   /* Remove from local id hashmap */
2661   GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
2662   t = GNUNET_CONTAINER_multihashmap_get (c->tunnels, &hash);
2663   GNUNET_CONTAINER_multihashmap_remove (c->tunnels, &hash, t);
2664
2665   /* Remove from global id hashmap */
2666   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
2667   GNUNET_CONTAINER_multihashmap_remove (tunnels, &hash, t);
2668
2669 //     notify_tunnel_destroy(t); FIXME
2670   tunnel_destroy(t);
2671   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2672   return;
2673 }
2674
2675
2676 /**
2677  * Handler for connection requests to new peers
2678  *
2679  * @param cls closure
2680  * @param client identification of the client
2681  * @param message the actual message (PeerControl)
2682  */
2683 static void
2684 handle_local_connect_add (void *cls, struct GNUNET_SERVER_Client *client,
2685                           const struct GNUNET_MessageHeader *message)
2686 {
2687   struct GNUNET_MESH_PeerControl *peer_msg;
2688   struct MeshPathInfo *path_info;
2689   struct MeshPeerInfo *peer_info;
2690   struct MeshClient *c;
2691   struct MeshTunnel *t;
2692   MESH_TunnelNumber tid;
2693
2694   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "MESH: Got connection request\n");
2695   /* Sanity check for client registration */
2696   if (NULL == (c = client_get (client)))
2697   {
2698     GNUNET_break (0);
2699     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2700     return;
2701   }
2702
2703   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
2704   /* Sanity check for message size */
2705   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
2706   {
2707     GNUNET_break (0);
2708     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2709     return;
2710   }
2711
2712   /* Tunnel exists? */
2713   tid = ntohl (peer_msg->tunnel_id);
2714   t = tunnel_get_by_local_id (c, tid);
2715   if (NULL == t)
2716   {
2717     GNUNET_break (0);
2718     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2719     return;
2720   }
2721
2722   /* Does client own tunnel? */
2723   if (t->client->handle != client)
2724   {
2725     GNUNET_break (0);
2726     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2727     return;
2728   }
2729   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "MESH:      for %s\n",
2730              GNUNET_h2s_full(&peer_msg->peer.hashPubKey));
2731   peer_info = peer_info_get (&peer_msg->peer);
2732
2733   /* Start DHT search if needed, otherwise just add peer to tunnel. */
2734   if (NULL == peer_info->dhtget && NULL == peer_info->path_head)
2735   {
2736     path_info = GNUNET_malloc(sizeof(struct MeshPathInfo));
2737     path_info->peer = peer_info;
2738     path_info->t = t;
2739     peer_info->dhtget = GNUNET_DHT_get_start(dht_handle,       /* handle */
2740                                              GNUNET_TIME_UNIT_SECONDS,     /* timeout */
2741                                              GNUNET_BLOCK_TYPE_TEST,   /* type */
2742                                              &peer_msg->peer.hashPubKey,   /*key to search */
2743                                              4,        /* replication level */
2744                                              GNUNET_DHT_RO_RECORD_ROUTE,
2745                                              NULL,     /* xquery */
2746                                              0,        /* xquery bits */
2747                                              &dht_get_id_handler,
2748                                              (void *) path_info);
2749   }
2750   else if (NULL != peer_info->path_head)
2751   {
2752     unsigned int i;
2753     for (i = 0; i < CORE_QUEUE_SIZE; i++)
2754     {
2755       if (NULL == peer_info->core_transmit[i])
2756         break;
2757     }
2758     if (CORE_QUEUE_SIZE == i)
2759     {
2760       GNUNET_break (0);
2761       GNUNET_SERVER_receive_done (client, GNUNET_OK);
2762       return;
2763     }
2764     path_info = GNUNET_malloc(sizeof(struct MeshPathInfo));
2765     path_info->peer = peer_info;
2766     path_info->t = t;
2767     tunnel_add_peer(t, peer_info);
2768     path_info->path = tree_get_path_to_peer(t->tree, peer_info->id);
2769     peer_info = peer_info_get(path_get_first_hop(t->tree, path_info->peer->id));
2770     peer_info->infos[i] = path_info;
2771     peer_info->types[i] = GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE;
2772     peer_info->core_transmit[i] =
2773       GNUNET_CORE_notify_transmit_ready (
2774         core_handle,
2775         0,
2776         0,
2777         GNUNET_TIME_UNIT_FOREVER_REL,
2778         path_get_first_hop(t->tree, path_info->peer->id),
2779         sizeof (struct GNUNET_MESH_ManipulatePath)
2780         + path_info->path->length * sizeof(struct GNUNET_PeerIdentity),
2781         &send_core_create_path,
2782         path_info);
2783   }
2784   /* Otherwise: there is no path yet, but there is a DHT_get active already. */
2785   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2786   return;
2787 }
2788
2789
2790 /**
2791  * Handler for disconnection requests of peers in a tunnel
2792  *
2793  * @param cls closure
2794  * @param client identification of the client
2795  * @param message the actual message (PeerControl)
2796  */
2797 static void
2798 handle_local_connect_del (void *cls, struct GNUNET_SERVER_Client *client,
2799                           const struct GNUNET_MessageHeader *message)
2800 {
2801   struct GNUNET_MESH_PeerControl *peer_msg;
2802   struct MeshClient *c;
2803   struct MeshTunnel *t;
2804   MESH_TunnelNumber tid;
2805
2806   /* Sanity check for client registration */
2807   if (NULL == (c = client_get (client)))
2808   {
2809     GNUNET_break (0);
2810     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2811     return;
2812   }
2813   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
2814   /* Sanity check for message size */
2815   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
2816   {
2817     GNUNET_break (0);
2818     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2819     return;
2820   }
2821
2822   /* Tunnel exists? */
2823   tid = ntohl (peer_msg->tunnel_id);
2824   t = tunnel_get_by_local_id (c, tid);
2825   if (NULL == t)
2826   {
2827     GNUNET_break (0);
2828     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2829     return;
2830   }
2831
2832   /* Does client own tunnel? */
2833   if (t->client->handle != client)
2834   {
2835     GNUNET_break (0);
2836     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2837     return;
2838   }
2839
2840   /* Ok, delete peer from tunnel */
2841   GNUNET_CONTAINER_multihashmap_remove_all (t->peers,
2842                                             &peer_msg->peer.hashPubKey);
2843
2844   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2845   return;
2846 }
2847
2848
2849 /**
2850  * Handler for connection requests to new peers by type
2851  *
2852  * @param cls closure
2853  * @param client identification of the client
2854  * @param message the actual message (ConnectPeerByType)
2855  */
2856 static void
2857 handle_local_connect_by_type (void *cls, struct GNUNET_SERVER_Client *client,
2858                               const struct GNUNET_MessageHeader *message)
2859 {
2860   struct GNUNET_MESH_ConnectPeerByType *connect_msg;
2861   struct MeshClient *c;
2862   struct MeshTunnel *t;
2863   GNUNET_HashCode hash;
2864   GNUNET_MESH_ApplicationType type;
2865   MESH_TunnelNumber tid;
2866
2867   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: got connect by type request\n");
2868   /* Sanity check for client registration */
2869   if (NULL == (c = client_get (client)))
2870   {
2871     GNUNET_break (0);
2872     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2873     return;
2874   }
2875
2876   connect_msg = (struct GNUNET_MESH_ConnectPeerByType *) message;
2877   /* Sanity check for message size */
2878   if (sizeof (struct GNUNET_MESH_ConnectPeerByType) !=
2879       ntohs (connect_msg->header.size))
2880   {
2881     GNUNET_break (0);
2882     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2883     return;
2884   }
2885
2886   /* Tunnel exists? */
2887   tid = ntohl (connect_msg->tunnel_id);
2888   t = tunnel_get_by_local_id (c, tid);
2889   if (NULL == t)
2890   {
2891     GNUNET_break (0);
2892     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2893     return;
2894   }
2895
2896   /* Does client own tunnel? */
2897   if (t->client->handle != client)
2898   {
2899     GNUNET_break (0);
2900     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2901     return;
2902   }
2903
2904   /* Do WE have the service? */
2905   type = ntohl (connect_msg->type);
2906   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  type requested: %u\n", type);
2907   GNUNET_CRYPTO_hash (&type, sizeof (GNUNET_MESH_ApplicationType), &hash);
2908   if (GNUNET_CONTAINER_multihashmap_contains (applications, &hash) ==
2909       GNUNET_YES)
2910   {
2911     /* Yes! Fast forward, add ourselves to the tunnel and send the
2912      * good news to the client
2913      */
2914     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  available locally\n");
2915     GNUNET_CONTAINER_multihashmap_put (t->peers, &my_full_id.hashPubKey,
2916                                        peer_info_get (&my_full_id),
2917                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2918
2919     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  notifying client\n");
2920     send_client_peer_connected(t, myid);
2921     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  Done\n");
2922     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2923     return;
2924   }
2925   /* Ok, lets find a peer offering the service */
2926   if (c->dht_get_type)
2927   {
2928     GNUNET_SCHEDULER_cancel (c->dht_get_type_task);
2929     GNUNET_DHT_get_stop (c->dht_get_type);
2930   }
2931   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  looking in DHT for %s\n",
2932               GNUNET_h2s_full (&hash));
2933   c->dht_get_type =
2934       GNUNET_DHT_get_start (dht_handle, GNUNET_TIME_UNIT_FOREVER_REL,
2935                             GNUNET_BLOCK_TYPE_TEST, &hash, 10U,
2936                             GNUNET_DHT_RO_RECORD_ROUTE, NULL, 0,
2937                             &dht_get_type_handler, t);
2938   c->dht_get_type_task = GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_SECONDS,
2939                                                       &dht_get_type_restart,
2940                                                       NULL);
2941
2942   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2943   return;
2944 }
2945
2946
2947 /**
2948  * Handler for client traffic directed to one peer
2949  *
2950  * @param cls closure
2951  * @param client identification of the client
2952  * @param message the actual message
2953  */
2954 static void
2955 handle_local_unicast (void *cls, struct GNUNET_SERVER_Client *client,
2956                       const struct GNUNET_MessageHeader *message)
2957 {
2958   struct MeshClient *c;
2959   struct MeshTunnel *t;
2960   struct MeshPeerInfo *pi;
2961   struct GNUNET_MESH_Unicast *data_msg;
2962   MESH_TunnelNumber tid;
2963   size_t size;
2964
2965   /* Sanity check for client registration */
2966   if (NULL == (c = client_get (client)))
2967   {
2968     GNUNET_break (0);
2969     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2970     return;
2971   }
2972   data_msg = (struct GNUNET_MESH_Unicast *) message;
2973   /* Sanity check for message size */
2974   size = ntohs (message->size);
2975   if (sizeof (struct GNUNET_MESH_Unicast) +
2976       sizeof (struct GNUNET_MessageHeader) > size)
2977   {
2978     GNUNET_break (0);
2979     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2980     return;
2981   }
2982
2983   /* Tunnel exists? */
2984   tid = ntohl (data_msg->tid);
2985   t = tunnel_get_by_local_id (c, tid);
2986   if (NULL == t)
2987   {
2988     GNUNET_break (0);
2989     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2990     return;
2991   }
2992
2993   /*  Is it a local tunnel? Then, does client own the tunnel? */
2994   if (t->client->handle != NULL && t->client->handle != client)
2995   {
2996     GNUNET_break (0);
2997     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2998     return;
2999   }
3000
3001   pi = GNUNET_CONTAINER_multihashmap_get (t->peers,
3002                                           &data_msg->destination.hashPubKey);
3003   /* Is the selected peer in the tunnel? */
3004   if (NULL == pi)
3005   {
3006     GNUNET_break (0);
3007     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3008     return;
3009   }
3010
3011   /* Ok, everything is correct, send the message
3012    * (pretend we got it from a mesh peer)
3013    */
3014   {
3015     char buf[ntohs (message->size)];
3016     struct GNUNET_MESH_Unicast *copy;
3017
3018     /* Work around const limitation */
3019     copy = (struct GNUNET_MESH_Unicast *) buf;
3020     memcpy (buf, data_msg, size);
3021     copy->oid = my_full_id;
3022     copy->tid = htonl (t->id.tid);
3023     handle_mesh_data_unicast (NULL, &my_full_id, &copy->header, NULL);
3024   }
3025   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3026   return;
3027 }
3028
3029 /**
3030  * Handler for client traffic directed to all peers in a tunnel
3031  *
3032  * @param cls closure
3033  * @param client identification of the client
3034  * @param message the actual message
3035  */
3036 static void
3037 handle_local_multicast (void *cls, struct GNUNET_SERVER_Client *client,
3038                         const struct GNUNET_MessageHeader *message)
3039 {
3040   struct MeshClient *c;
3041   struct MeshTunnel *t;
3042   struct GNUNET_MESH_Multicast *data_msg;
3043   MESH_TunnelNumber tid;
3044
3045   /* Sanity check for client registration */
3046   if (NULL == (c = client_get (client)))
3047   {
3048     GNUNET_break (0);
3049     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3050     return;
3051   }
3052   data_msg = (struct GNUNET_MESH_Multicast *) message;
3053   /* Sanity check for message size */
3054   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (data_msg->header.size))
3055   {
3056     GNUNET_break (0);
3057     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3058     return;
3059   }
3060
3061   /* Tunnel exists? */
3062   tid = ntohl (data_msg->tid);
3063   t = tunnel_get_by_local_id (c, tid);
3064   if (NULL == t)
3065   {
3066     GNUNET_break (0);
3067     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3068     return;
3069   }
3070
3071   /* Does client own tunnel? */
3072   if (t->client->handle != client)
3073   {
3074     GNUNET_break (0);
3075     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3076     return;
3077   }
3078
3079   {
3080     char buf[ntohs(message->size)];
3081     struct GNUNET_MESH_Multicast *copy;
3082
3083     copy = (struct GNUNET_MESH_Multicast *)buf;
3084     memcpy(buf, message, ntohs(message->size));
3085     copy->oid = my_full_id;
3086     copy->tid = htonl(t->id.tid);
3087     handle_mesh_data_multicast(client, &my_full_id, &copy->header, NULL);
3088   }
3089
3090   /* receive done gets called when last copy is sent */
3091   return;
3092 }
3093
3094 /**
3095  * Functions to handle messages from clients
3096  */
3097 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
3098   {&handle_local_new_client, NULL, GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
3099   {&handle_local_tunnel_create, NULL,
3100    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
3101    sizeof (struct GNUNET_MESH_TunnelMessage)},
3102   {&handle_local_tunnel_destroy, NULL,
3103    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
3104    sizeof (struct GNUNET_MESH_TunnelMessage)},
3105   {&handle_local_connect_add, NULL,
3106    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD,
3107    sizeof (struct GNUNET_MESH_PeerControl)},
3108   {&handle_local_connect_del, NULL,
3109    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL,
3110    sizeof (struct GNUNET_MESH_PeerControl)},
3111   {&handle_local_connect_by_type, NULL,
3112    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE,
3113    sizeof (struct GNUNET_MESH_ConnectPeerByType)},
3114   {&handle_local_unicast, NULL,
3115    GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
3116   {&handle_local_unicast, NULL,
3117    GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
3118   {&handle_local_multicast, NULL,
3119    GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
3120   {NULL, NULL, 0, 0}
3121 };
3122
3123
3124 /**
3125  * To be called on core init/fail.
3126  *
3127  * @param cls service closure
3128  * @param server handle to the server for this service
3129  * @param identity the public identity of this peer
3130  * @param publicKey the public key of this peer
3131  */
3132 static void
3133 core_init (void *cls, struct GNUNET_CORE_Handle *server,
3134            const struct GNUNET_PeerIdentity *identity,
3135            const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
3136 {
3137   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Core init\n");
3138   core_handle = server;
3139   if (0 != memcmp(identity, &my_full_id, sizeof(my_full_id)) || NULL == server)
3140   {
3141     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("MESH: Wrong CORE service\n"));
3142     GNUNET_SCHEDULER_shutdown();   
3143   }
3144   return;
3145 }
3146
3147 /**
3148  * Method called whenever a given peer connects.
3149  *
3150  * @param cls closure
3151  * @param peer peer identity this notification is about
3152  * @param atsi performance data for the connection
3153  */
3154 static void
3155 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
3156               const struct GNUNET_TRANSPORT_ATS_Information *atsi)
3157 {
3158   struct MeshPeerInfo *peer_info;
3159   struct MeshPeerPath *path;
3160
3161 //   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Peer connected\n");
3162 //   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      %s\n",
3163 //               GNUNET_h2s(&my_full_id.hashPubKey));
3164   peer_info = peer_info_get (peer);
3165   if (myid == peer_info->id)
3166   {
3167 //     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      (self)\n");
3168     return;
3169   }
3170   else
3171   {
3172 //     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      %s\n",
3173 //                 GNUNET_h2s(&peer->hashPubKey));
3174   }
3175   path = path_new (2);
3176   path->peers[0] = myid;
3177   path->peers[1] = peer_info->id;
3178   GNUNET_PEER_change_rc(myid, 1);
3179   GNUNET_PEER_change_rc(peer_info->id, 1);
3180   path_add_to_peer (peer_info, path);
3181   return;
3182 }
3183
3184 /**
3185  * Method called whenever a peer disconnects.
3186  *
3187  * @param cls closure
3188  * @param peer peer identity this notification is about
3189  */
3190 static void
3191 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
3192 {
3193   struct MeshPeerInfo *pi;
3194   unsigned int i;
3195
3196   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Peer disconnected\n");
3197   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
3198   if (NULL == pi)
3199   {
3200     GNUNET_break (0);
3201     return;
3202   }
3203   for (i = 0; i < CORE_QUEUE_SIZE; i++)
3204   {
3205     if (pi->core_transmit[i])
3206     {
3207       struct MeshDataDescriptor *dd;
3208       struct MeshPathInfo *path_info;
3209       GNUNET_CORE_notify_transmit_ready_cancel (pi->core_transmit[i]);
3210       /* TODO: notify that tranmission has failed */
3211       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   data at %u\n", i);
3212       switch (pi->types[i])
3213       {
3214         case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
3215         case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
3216         case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
3217           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    type payload\n");
3218           dd = pi->infos[i];
3219           if (0 == --(*dd->copies))
3220           {
3221             GNUNET_free (dd->copies);
3222             GNUNET_free (dd->data);
3223           }
3224           break;
3225         case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
3226           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    type create path\n");
3227           path_info = pi->infos[i];
3228           path_destroy(path_info->path);
3229           break;
3230       }
3231       GNUNET_free (pi->infos[i]);
3232     }
3233   }
3234   path_remove_from_peer (pi, pi->id, myid);
3235   if (myid == pi->id)
3236   {
3237     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      (self)\n");
3238   }
3239   return;
3240 }
3241
3242
3243 /******************************************************************************/
3244 /************************      MAIN FUNCTIONS      ****************************/
3245 /******************************************************************************/
3246
3247 /**
3248  * Task run during shutdown.
3249  *
3250  * @param cls unused
3251  * @param tc unused
3252  */
3253 static void
3254 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3255 {
3256   struct MeshClient *c;
3257
3258   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: shutting down\n");
3259   if (core_handle != NULL)
3260   {
3261     GNUNET_CORE_disconnect (core_handle);
3262     core_handle = NULL;
3263   }
3264   if (dht_handle != NULL)
3265   {
3266     for (c = clients; NULL != c; c = c->next)
3267       if (NULL != c->dht_get_type)
3268       {
3269         GNUNET_SCHEDULER_cancel(c->dht_get_type_task);
3270         GNUNET_DHT_get_stop (c->dht_get_type);
3271       }
3272     GNUNET_DHT_disconnect (dht_handle);
3273     dht_handle = NULL;
3274   }
3275   if (nc != NULL)
3276   {
3277     GNUNET_SERVER_notification_context_destroy (nc);
3278     nc = NULL;
3279   }
3280   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
3281   {
3282     GNUNET_SCHEDULER_cancel (announce_id_task);
3283     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
3284   }
3285   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: shut down\n");
3286 }
3287
3288 /**
3289  * Process mesh requests.
3290  *
3291  * @param cls closure
3292  * @param server the initialized server
3293  * @param c configuration to use
3294  */
3295 static void
3296 run (void *cls, struct GNUNET_SERVER_Handle *server,
3297      const struct GNUNET_CONFIGURATION_Handle *c)
3298 {
3299   struct MeshPeerInfo *peer;
3300   struct MeshPeerPath *p;
3301   char *keyfile;
3302
3303   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: starting to run\n");
3304   server_handle = server;
3305   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
3306                                      CORE_QUEUE_SIZE,   /* queue size */
3307                                      NULL,      /* Closure passed to MESH functions */
3308                                      &core_init,        /* Call core_init once connected */
3309                                      &core_connect,     /* Handle connects */
3310                                      &core_disconnect,  /* remove peers on disconnects */
3311                                      NULL,      /* Do we care about "status" updates? */
3312                                      NULL,      /* Don't notify about all incoming messages */
3313                                      GNUNET_NO, /* For header only in notification */
3314                                      NULL,      /* Don't notify about all outbound messages */
3315                                      GNUNET_NO, /* For header-only out notification */
3316                                      core_handlers);    /* Register these handlers */
3317   if (core_handle == NULL)
3318   {
3319     GNUNET_break (0);
3320     GNUNET_SCHEDULER_shutdown ();
3321     return;
3322   }
3323
3324   if (GNUNET_OK !=
3325        GNUNET_CONFIGURATION_get_value_filename (c, "GNUNETD", "HOSTKEY",
3326                                                 &keyfile))
3327   {
3328     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3329                 _
3330                 ("Mesh service is lacking key configuration settings.  Exiting.\n"));
3331     GNUNET_SCHEDULER_shutdown ();
3332     return;
3333   }
3334   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3335   GNUNET_free (keyfile);
3336   if (my_private_key == NULL)
3337   {
3338     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3339                 _("Mesh service could not access hostkey.  Exiting.\n"));
3340     GNUNET_SCHEDULER_shutdown ();
3341     return;
3342   }
3343   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3344   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
3345                       &my_full_id.hashPubKey);
3346   myid = GNUNET_PEER_intern (&my_full_id);
3347
3348   dht_handle = GNUNET_DHT_connect (c, 64);
3349   if (dht_handle == NULL)
3350   {
3351     GNUNET_break (0);
3352   }
3353
3354   next_tid = 0;
3355   next_local_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
3356
3357   tunnels = GNUNET_CONTAINER_multihashmap_create (32);
3358   peers = GNUNET_CONTAINER_multihashmap_create (32);
3359   applications = GNUNET_CONTAINER_multihashmap_create (32);
3360   types = GNUNET_CONTAINER_multihashmap_create (32);
3361
3362   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
3363   nc = GNUNET_SERVER_notification_context_create (server_handle,
3364                                                   LOCAL_QUEUE_SIZE);
3365   GNUNET_SERVER_disconnect_notify (server_handle,
3366                                    &handle_local_client_disconnect,
3367                                    NULL);
3368
3369
3370   clients = NULL;
3371   clients_tail = NULL;
3372 #if MESH_DEBUG
3373   next_client_id = 0;
3374 #endif
3375
3376   announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
3377   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
3378
3379   /* Create a peer_info for the local peer */
3380   peer = peer_info_get(&my_full_id);
3381   p = path_new (1);
3382   p->peers[0] = myid;
3383   path_add_to_peer(peer, p);
3384
3385   /* Scheduled the task to clean up when shutdown is called */
3386   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
3387                                 NULL);
3388
3389   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: end of run()\n");
3390 }
3391
3392 /**
3393  * The main function for the mesh service.
3394  *
3395  * @param argc number of arguments from the command line
3396  * @param argv command line arguments
3397  * @return 0 ok, 1 on error
3398  */
3399 int
3400 main (int argc, char *const *argv)
3401 {
3402   int ret;
3403
3404 #if MESH_DEBUG
3405 //   fprintf (stderr, "main ()\n");
3406 #endif
3407   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: main()\n");
3408   ret =
3409       (GNUNET_OK ==
3410        GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
3411                            NULL)) ? 0 : 1;
3412   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: main() END\n");
3413 #if MESH_DEBUG
3414 //   fprintf (stderr, "main () END\n");
3415 #endif
3416   return ret;
3417 }