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