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