Fixed bug with remote tunnel traffic reception
[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  * - relay corking down to core
44  * - set ttl relative to tree depth
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 #define UNACKNOWLEDGED_WAIT     GNUNET_TIME_relative_multiply(\
70                                     GNUNET_TIME_UNIT_SECONDS,\
71                                     2)
72 #define DEFAULT_TTL     64
73
74 #define MESH_DEBUG_DHT GNUNET_NO
75
76
77
78 /******************************************************************************/
79 /************************      DATA STRUCTURES     ****************************/
80 /******************************************************************************/
81
82 /** FWD declaration */
83 struct MeshPeerInfo;
84
85
86 /**
87  * Struct representing a piece of data being sent to other peers
88  */
89 struct MeshData
90 {
91   /** Tunnel it belongs to. */
92   struct MeshTunnel *t;
93
94   /** In case of a multicast, task to allow a client to send more data if
95    * some neighbor is too slow. */
96   GNUNET_SCHEDULER_TaskIdentifier *task;
97
98   /** How many remaining neighbors we need to send this to. */
99   unsigned int *reference_counter;
100
101   /** Size of the data. */
102   size_t data_len;
103
104   /** Data itself */
105   void *data;
106 };
107
108
109 /**
110  * Struct containing all info possibly needed to build a package when called
111  * back by core.
112  */
113 struct MeshTransmissionDescriptor
114 {
115     /** ID of the tunnel this packet travels in */
116   struct MESH_TunnelID *origin;
117
118     /** Who was this message being sent to */
119   struct MeshPeerInfo *peer;
120
121     /** Ultimate destination of the packet */
122   GNUNET_PEER_Id destination;
123
124     /** Which handler was used to request the transmission */
125   unsigned int handler_n;
126
127     /** Data descriptor */
128   struct MeshData* mesh_data;
129 };
130
131
132 /**
133  * Struct containing all information regarding a given peer
134  */
135 struct MeshPeerInfo
136 {
137     /**
138      * ID of the peer
139      */
140   GNUNET_PEER_Id id;
141
142     /**
143      * Last time we heard from this peer
144      */
145   struct GNUNET_TIME_Absolute last_contact;
146
147     /**
148      * Number of attempts to reconnect so far
149      */
150   int n_reconnect_attempts;
151
152     /**
153      * Paths to reach the peer, ordered by ascending hop count
154      */
155   struct MeshPeerPath *path_head;
156
157     /**
158      * Paths to reach the peer, ordered by ascending hop count
159      */
160   struct MeshPeerPath *path_tail;
161
162     /**
163      * Handle to stop the DHT search for a path to this peer
164      */
165   struct GNUNET_DHT_GetHandle *dhtget;
166
167     /**
168      * Closure given to the DHT GET
169      */
170   struct MeshPathInfo *dhtgetcls;
171
172     /**
173      * Handles to stop queued transmissions for this peer
174      */
175   struct GNUNET_CORE_TransmitHandle *core_transmit[CORE_QUEUE_SIZE];
176
177     /**
178      * Pointer to info stuctures used as cls for queued transmissions
179      */
180   void *infos[CORE_QUEUE_SIZE];
181
182     /**
183      * Type of message being in each transmission
184      */
185   uint16_t types[CORE_QUEUE_SIZE];
186
187     /**
188      * Array of tunnels this peer participates in
189      * (most probably a small amount, therefore not a hashmap)
190      * When the path to the peer changes, notify these tunnels to let them
191      * re-adjust their path trees.
192      */
193   struct MeshTunnel **tunnels;
194
195     /**
196      * Number of tunnels this peers participates in
197      */
198   unsigned int ntunnels;
199 };
200
201
202 /**
203  * Data scheduled to transmit (to local client or remote peer)
204  */
205 struct MeshQueue
206 {
207     /**
208      * Double linked list
209      */
210   struct MeshQueue *next;
211   struct MeshQueue *prev;
212
213     /**
214      * Target of the data (NULL if target is client)
215      */
216   struct MeshPeerInfo *peer;
217
218     /**
219      * Client to send the data to (NULL if target is peer)
220      */
221   struct MeshClient *client;
222
223     /**
224      * Size of the message to transmit
225      */
226   unsigned int size;
227
228     /**
229      * How old is the data?
230      */
231   struct GNUNET_TIME_Absolute timestamp;
232
233     /**
234      * Data itself
235      */
236   struct GNUNET_MessageHeader *data;
237 };
238
239 /**
240  * Globally unique tunnel identification (owner + number)
241  * DO NOT USE OVER THE NETWORK
242  */
243 struct MESH_TunnelID
244 {
245     /**
246      * Node that owns the tunnel
247      */
248   GNUNET_PEER_Id oid;
249
250     /**
251      * Tunnel number to differentiate all the tunnels owned by the node oid
252      * ( tid < GNUNET_MESH_LOCAL_TUNNEL_ID_CLI )
253      */
254   MESH_TunnelNumber tid;
255 };
256
257
258 struct MeshClient;              /* FWD declaration */
259
260 /**
261  * Struct containing all information regarding a tunnel
262  * For an intermediate node the improtant info used will be:
263  * - id        Tunnel unique identification
264  * - paths[0]  To know where to send it next
265  * - metainfo: ready, speeds, accounting
266  */
267 struct MeshTunnel
268 {
269     /**
270      * Tunnel ID
271      */
272   struct MESH_TunnelID id;
273
274     /**
275      * Local tunnel number ( >= GNUNET_MESH_LOCAL_TUNNEL_ID_CLI or 0 )
276      */
277   MESH_TunnelNumber local_tid;
278
279       /**
280      * Local tunnel number for local destination clients
281      */
282   MESH_TunnelNumber local_tid_dest;
283
284     /**
285      * ID of the last multicast packet seen/sent.
286      */
287   uint32_t mid;
288
289     /**
290      * Last time the tunnel was used
291      */
292   struct GNUNET_TIME_Absolute timestamp;
293
294     /**
295      * Peers in the tunnel, indexed by PeerIdentity -> (MeshPeerInfo)
296      * containing peers added by id or by type, not intermediate peers.
297      */
298   struct GNUNET_CONTAINER_MultiHashMap *peers;
299
300     /**
301      * Number of peers that are connected and potentially ready to receive data
302      */
303   unsigned int peers_ready;
304
305     /**
306      * Number of peers that have been added to the tunnel
307      */
308   unsigned int peers_total;
309
310     /**
311      * Client owner of the tunnel, if any
312      */
313   struct MeshClient *client;
314
315     /**
316      * Client destination of the tunnel, if any
317      */
318   struct MeshClient *client_dest;
319
320     /**
321      * Messages ready to transmit
322      */
323   struct MeshQueue *queue_head;
324   struct MeshQueue *queue_tail;
325
326   /**
327    * Tunnel paths
328    */
329   struct MeshTunnelTree *tree;
330
331   /**
332    * Application type we are looking for in this tunnel
333    */
334   GNUNET_MESH_ApplicationType type;
335
336     /**
337      * Used to search peers offering a service
338      */
339   struct GNUNET_DHT_GetHandle *dht_get_type;
340
341   /**
342    * Task to keep the used paths alive
343    */
344   GNUNET_SCHEDULER_TaskIdentifier path_refresh_task;
345
346   /**
347    * Task to destroy the tunnel after timeout
348    *
349    * FIXME: merge the two? a tunnel will have either
350    * a path refresh OR a timeout, never both!
351    */
352   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
353 };
354
355
356 /**
357  * Info needed to work with tunnel paths and peers
358  */
359 struct MeshPathInfo
360 {
361   /**
362    * Tunnel
363    */
364   struct MeshTunnel *t;
365
366   /**
367    * Neighbouring peer to whom we send the packet to
368    */
369   struct MeshPeerInfo *peer;
370
371   /**
372    * Path itself
373    */
374   struct MeshPeerPath *path;
375
376   /**
377    * Position in peer's transmit queue
378    */
379   unsigned int pos;
380 };
381
382
383 /**
384  * Struct containing information about a client of the service
385  */
386 struct MeshClient
387 {
388     /**
389      * Linked list
390      */
391   struct MeshClient *next;
392   struct MeshClient *prev;
393
394     /**
395      * Tunnels that belong to this client, indexed by local id
396      */
397   struct GNUNET_CONTAINER_MultiHashMap *tunnels;
398
399     /**
400      * Handle to communicate with the client
401      */
402   struct GNUNET_SERVER_Client *handle;
403
404     /**
405      * Applications that this client has claimed to provide
406      */
407   struct GNUNET_CONTAINER_MultiHashMap *apps;
408
409     /**
410      * Messages that this client has declared interest in
411      */
412   struct GNUNET_CONTAINER_MultiHashMap *types;
413
414     /**
415      * Whether the client is active or shutting down (don't send confirmations
416      * to a client that is shutting down.
417      */
418   int shutting_down;
419
420 #if MESH_DEBUG
421     /**
422      * ID of the client, for debug messages
423      */
424   unsigned int id;
425 #endif
426
427 };
428
429
430
431 /******************************************************************************/
432 /************************      DEBUG FUNCTIONS     ****************************/
433 /******************************************************************************/
434
435 #if MESH_DEBUG
436 /**
437  * GNUNET_SCHEDULER_Task for printing a message after some operation is done
438  * @param cls string to print
439  * @param tc task context
440  */
441 static void
442 mesh_debug (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
443 {
444   char *s = cls;
445
446   if (GNUNET_SCHEDULER_REASON_SHUTDOWN == tc->reason)
447   {
448     return;
449   }
450   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: %s\n", s);
451 }
452 #endif
453
454 /******************************************************************************/
455 /***********************      GLOBAL VARIABLES     ****************************/
456 /******************************************************************************/
457
458 /**
459  * All the clients
460  */
461 static struct MeshClient *clients;
462 static struct MeshClient *clients_tail;
463
464 /**
465  * Tunnels known, indexed by MESH_TunnelID (MeshTunnel)
466  */
467 static struct GNUNET_CONTAINER_MultiHashMap *tunnels;
468
469 /**
470  * Tunnels incoming, indexed by MESH_TunnelNumber
471  * (which is greater than GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
472  */
473 static struct GNUNET_CONTAINER_MultiHashMap *incoming_tunnels;
474
475 /**
476  * Peers known, indexed by PeerIdentity (MeshPeerInfo)
477  */
478 static struct GNUNET_CONTAINER_MultiHashMap *peers;
479
480 /**
481  * Handle to communicate with core
482  */
483 static struct GNUNET_CORE_Handle *core_handle;
484
485 /**
486  * Handle to communicate with transport
487  */
488 // static struct GNUNET_TRANSPORT_Handle *transport_handle;
489
490 /**
491  * Handle to use DHT
492  */
493 static struct GNUNET_DHT_Handle *dht_handle;
494
495 /**
496  * Handle to server
497  */
498 static struct GNUNET_SERVER_Handle *server_handle;
499
500 /**
501  * Notification context, to send messages to local clients
502  */
503 static struct GNUNET_SERVER_NotificationContext *nc;
504
505 /**
506  * Local peer own ID (memory efficient handle)
507  */
508 static GNUNET_PEER_Id myid;
509
510 /**
511  * Local peer own ID (full value)
512  */
513 static struct GNUNET_PeerIdentity my_full_id;
514
515 /**
516  * Own private key
517  */
518 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
519
520 /**
521  * Own public key.
522  */
523 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
524
525 /**
526  * Tunnel ID for the next created tunnel (global tunnel number)
527  */
528 static MESH_TunnelNumber next_tid;
529
530 /**
531  * Tunnel ID for the next incoming tunnel (local tunnel number)
532  */
533 static MESH_TunnelNumber next_local_tid;
534
535 /**
536  * All application types provided by this peer
537  */
538 static struct GNUNET_CONTAINER_MultiHashMap *applications;
539
540 /**
541  * All message types clients of this peer are interested in
542  */
543 static struct GNUNET_CONTAINER_MultiHashMap *types;
544
545 /**
546  * Task to periodically announce provided applications
547  */
548 GNUNET_SCHEDULER_TaskIdentifier announce_applications_task;
549
550 /**
551  * Task to periodically announce itself in the network
552  */
553 GNUNET_SCHEDULER_TaskIdentifier announce_id_task;
554
555 #if MESH_DEBUG
556 unsigned int next_client_id;
557 #endif
558
559
560 /******************************************************************************/
561 /************************         ITERATORS        ****************************/
562 /******************************************************************************/
563
564 /* FIXME move iterators here */
565
566
567 /******************************************************************************/
568 /************************    PERIODIC FUNCTIONS    ****************************/
569 /******************************************************************************/
570
571 /**
572  * Announce iterator over for each application provided by the peer
573  *
574  * @param cls closure
575  * @param key current key code
576  * @param value value in the hash map
577  * @return GNUNET_YES if we should continue to
578  *         iterate,
579  *         GNUNET_NO if not.
580  */
581 static int
582 announce_application (void *cls, const GNUNET_HashCode * key, void *value)
583 {
584   /* FIXME are hashes in multihash map equal on all aquitectures? */
585   GNUNET_DHT_put (dht_handle, key, 10U,
586                   GNUNET_DHT_RO_RECORD_ROUTE |
587                   GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE, GNUNET_BLOCK_TYPE_TEST,
588                   sizeof (struct GNUNET_PeerIdentity),
589                   (const char *) &my_full_id,
590 #if MESH_DEBUG
591                   GNUNET_TIME_UNIT_FOREVER_ABS, GNUNET_TIME_UNIT_FOREVER_REL,
592                   &mesh_debug, "DHT_put for app completed");
593 #else
594                   GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get (),
595                                             APP_ANNOUNCE_TIME),
596                   APP_ANNOUNCE_TIME, NULL, NULL);
597 #endif
598   return GNUNET_OK;
599 }
600
601
602 /**
603  * Periodically announce what applications are provided by local clients
604  *
605  * @param cls closure
606  * @param tc task context
607  */
608 static void
609 announce_applications (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
610 {
611   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
612   {
613     announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
614     return;
615   }
616 #if MESH_DEBUG_DHT
617   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Starting PUT for apps\n");
618 #endif
619   GNUNET_CONTAINER_multihashmap_iterate (applications, &announce_application,
620                                          NULL);
621   announce_applications_task =
622       GNUNET_SCHEDULER_add_delayed (APP_ANNOUNCE_TIME, &announce_applications,
623                                     cls);
624 #if MESH_DEBUG_DHT
625   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Finished PUT for apps\n");
626 #endif
627   return;
628 }
629
630
631 /**
632  * Periodically announce self id in the DHT
633  *
634  * @param cls closure
635  * @param tc task context
636  */
637 static void
638 announce_id (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
639 {
640   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
641   {
642     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
643     return;
644   }
645   /* TODO
646    * - Set data expiration in function of X
647    * - Adapt X to churn
648    */
649 #if MESH_DEBUG_DHT
650   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: DHT_put for ID %s started.\n",
651               GNUNET_i2s (&my_full_id));
652 #endif
653   GNUNET_DHT_put (dht_handle,   /* DHT handle */
654                   &my_full_id.hashPubKey,       /* Key to use */
655                   10U,          /* Replication level */
656                   GNUNET_DHT_RO_RECORD_ROUTE | GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,    /* DHT options */
657                   GNUNET_BLOCK_TYPE_TEST,       /* Block type */
658                   sizeof (my_full_id),  /* Size of the data */
659                   (char *) &my_full_id, /* Data itself */
660                   GNUNET_TIME_absolute_get_forever (),  /* Data expiration */
661                   GNUNET_TIME_UNIT_FOREVER_REL, /* Retry time */
662 #if MESH_DEBUG_DHT
663                   &mesh_debug, "DHT_put for id completed");
664 #else
665                   NULL,         /* Continuation */
666                   NULL);        /* Continuation closure */
667 #endif
668   announce_id_task =
669       GNUNET_SCHEDULER_add_delayed (ID_ANNOUNCE_TIME, &announce_id, cls);
670 }
671
672
673 /**
674  * Function to process paths received for a new peer addition. The recorded
675  * paths form the initial tunnel, which can be optimized later.
676  * Called on each result obtained for the DHT search.
677  *
678  * @param cls closure
679  * @param exp when will this value expire
680  * @param key key of the result
681  * @param type type of the result
682  * @param size number of bytes in data
683  * @param data pointer to the result data
684  */
685 static void
686 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
687                     const GNUNET_HashCode * key,
688                     const struct GNUNET_PeerIdentity *get_path,
689                     unsigned int get_path_length,
690                     const struct GNUNET_PeerIdentity *put_path,
691                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
692                     size_t size, const void *data);
693
694
695 /******************************************************************************/
696 /******************      GENERAL HELPER FUNCTIONS      ************************/
697 /******************************************************************************/
698
699 /**
700  * Check if client has registered with the service and has not disconnected
701  *
702  * @param client the client to check
703  *
704  * @return non-NULL if client exists in the global DLL
705  */
706 static struct MeshClient *
707 client_get (struct GNUNET_SERVER_Client *client)
708 {
709   struct MeshClient *c;
710
711   c = clients;
712   while (NULL != c)
713   {
714     if (c->handle == client)
715       return c;
716     c = c->next;
717   }
718   return NULL;
719 }
720
721
722 /**
723  * Checks if a given client has subscribed to certain message type
724  *
725  * @param message_type Type of message to check
726  * @param c Client to check
727  *
728  * @return GNUNET_YES or GNUNET_NO, depending on subscription status
729  *
730  * TODO inline?
731  */
732 static int
733 client_is_subscribed (uint16_t message_type, struct MeshClient *c)
734 {
735   GNUNET_HashCode hc;
736
737   GNUNET_CRYPTO_hash (&message_type, sizeof (uint16_t), &hc);
738   return GNUNET_CONTAINER_multihashmap_contains (c->types, &hc);
739 }
740
741
742 /**
743  * Allow a client to send more data after transmitting a multicast message
744  * which some neighbor has not yet accepted altough a reasonable time has
745  * passed.
746  *
747  * @param cls Closure (DataDescriptor containing the task identifier)
748  * @param tc Task Context
749  */
750 static void
751 client_allow_send (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
752 {
753   struct MeshData *mdata = cls;
754
755   if (GNUNET_SCHEDULER_REASON_SHUTDOWN == tc->reason)
756     return;
757 #if MESH_DEBUG
758   GNUNET_assert (NULL != mdata->reference_counter);
759   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
760               "MESH: CLIENT ALLOW SEND DESPITE %u COPIES PENDING\n",
761               mdata->reference_counter);
762 #endif
763   *(mdata->task) = GNUNET_SCHEDULER_NO_TASK;
764   GNUNET_SERVER_receive_done (mdata->t->client->handle, GNUNET_OK);
765 }
766
767
768 /**
769  * Search for a tunnel by global ID using full PeerIdentities
770  *
771  * @param oid owner of the tunnel
772  * @param tid global tunnel number
773  *
774  * @return tunnel handler, NULL if doesn't exist
775  */
776 static struct MeshTunnel *
777 tunnel_get (struct GNUNET_PeerIdentity *oid, MESH_TunnelNumber tid);
778
779
780 /**
781  * Notify a tunnel that a connection has broken that affects at least
782  * some of its peers.
783  *
784  * @param t Tunnel affected.
785  * @param p1 Peer that got disconnected from p2.
786  * @param p2 Peer that got disconnected from p1.
787  *
788  * @return Short ID of the peer disconnected (either p1 or p2).
789  *         0 if the tunnel remained unaffected.
790  */
791 static GNUNET_PEER_Id
792 tunnel_notify_connection_broken (struct MeshTunnel *t, GNUNET_PEER_Id p1,
793                                  GNUNET_PEER_Id p2);
794
795
796 /**
797  * Send the message to all clients that have subscribed to its type
798  *
799  * @param msg Pointer to the message itself
800  * @param payload Pointer to the payload of the message.
801  * @return number of clients this message was sent to
802  */
803 static unsigned int
804 send_subscribed_clients (const struct GNUNET_MessageHeader *msg,
805                          const struct GNUNET_MessageHeader *payload)
806 {
807   struct GNUNET_PeerIdentity *oid;
808   struct MeshClient *c;
809   struct MeshTunnel *t;
810   MESH_TunnelNumber *tid;
811   unsigned int count;
812   uint16_t type;
813   char cbuf[htons (msg->size)];
814
815 #if MESH_DEBUG
816   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Sending to clients...\n");
817   type = ntohs (payload->type);
818   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: message of type %u\n", type);
819 #endif
820
821   memcpy (cbuf, msg, sizeof (cbuf));
822   switch (htons (msg->type))
823   {
824     struct GNUNET_MESH_Unicast *uc;
825     struct GNUNET_MESH_Multicast *mc;
826     struct GNUNET_MESH_ToOrigin *to;
827
828   case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
829     uc = (struct GNUNET_MESH_Unicast *) cbuf;
830     tid = &uc->tid;
831     oid = &uc->oid;
832     break;
833   case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
834     mc = (struct GNUNET_MESH_Multicast *) cbuf;
835     tid = &mc->tid;
836     oid = &mc->oid;
837     break;
838   case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
839     to = (struct GNUNET_MESH_ToOrigin *) cbuf;
840     tid = &to->tid;
841     oid = &to->oid;
842     break;
843   default:
844     GNUNET_break (0);
845     return 0;
846   }
847   t = tunnel_get (oid, ntohl (*tid));
848   if (NULL == t)
849   {
850     GNUNET_break (0);
851     return 0;
852   }
853
854   for (count = 0, c = clients; c != NULL; c = c->next)
855   {
856 #if MESH_DEBUG
857     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    client %u\n", c->id);
858 #endif
859     if (client_is_subscribed (type, c))
860     {
861       // FIXME proper client differentiation mechanism required
862       if (htons (msg->type) == GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN)
863         *tid = htonl (t->local_tid);
864       else if(c == t->client_dest)
865         *tid = htonl (t->local_tid_dest);
866       else
867         *tid = htonl (t->local_tid);
868       count++;
869       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      sending\n");
870       GNUNET_SERVER_notification_context_unicast (nc, c->handle,
871                                                   (struct GNUNET_MessageHeader
872                                                    *) cbuf, GNUNET_YES);
873     }
874   }
875   return count;
876 }
877
878
879 /**
880  * Notify the client that owns the tunnel that a peer has connected to it
881  * (the requested path to it has been confirmed).
882  *
883  * @param t Tunnel whose owner to notify
884  * @param id Short id of the peer that has connected
885  */
886 static void
887 send_client_peer_connected (const struct MeshTunnel *t, const GNUNET_PEER_Id id)
888 {
889   struct GNUNET_MESH_PeerControl pc;
890
891   pc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD);
892   pc.header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
893   pc.tunnel_id = htonl (t->local_tid);
894   GNUNET_PEER_resolve (id, &pc.peer);
895   GNUNET_SERVER_notification_context_unicast (nc, t->client->handle, &pc.header,
896                                               GNUNET_NO);
897 }
898
899
900 /**
901  * Notify all clients (not depending on registration status) that the incoming
902  * tunnel is no longer valid.
903  *
904  * @param t Tunnel that was destroyed.
905  */
906 static void
907 send_clients_tunnel_destroy (struct MeshTunnel *t)
908 {
909   struct GNUNET_MESH_TunnelMessage msg;
910
911   msg.header.size = htons (sizeof (msg));
912   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
913   msg.tunnel_id = htonl (t->local_tid);
914   GNUNET_SERVER_notification_context_broadcast (nc, &msg.header, GNUNET_NO);
915 }
916
917
918 /**
919  * Notify a client that the other local client disconnected, if needed.
920  * In case the origin disconnects, the destination get a tunnel destroy
921  * notification. Otherwise, the origin gets a (local ID) peer disconnected.
922  *
923  * @param t Tunnel that was destroyed.
924  * @param c Client that disconnected.
925  */
926 static void
927 send_client_tunnel_disconnect (struct MeshTunnel *t, struct MeshClient *c)
928 {
929   if (c == t->client_dest)
930   {
931     struct GNUNET_MESH_PeerControl msg;
932
933     msg.header.size = htons (sizeof (msg));
934     msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL);
935     msg.tunnel_id = htonl (t->local_tid);
936     msg.peer = my_full_id;
937     GNUNET_SERVER_notification_context_unicast (nc, t->client->handle,
938                                                 &msg.header, GNUNET_NO);
939   }
940   else if (NULL != t->client_dest && c == t->client)
941   {
942     struct GNUNET_MESH_TunnelMessage msg;
943
944     msg.header.size = htons (sizeof (msg));
945     msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
946     msg.tunnel_id = htonl (t->local_tid_dest);
947     GNUNET_SERVER_notification_context_unicast (nc, t->client_dest->handle,
948                                                 &msg.header, GNUNET_NO);
949   }
950 }
951
952
953 /**
954  * Function called to notify a client about the socket
955  * being ready to queue more data.  "buf" will be
956  * NULL and "size" zero if the socket was closed for
957  * writing in the meantime.
958  *
959  * @param cls closure
960  * @param size number of bytes available in buf
961  * @param buf where the callee should write the message
962  * @return number of bytes written to buf
963  */
964 static size_t
965 send_core_create_path (void *cls, size_t size, void *buf);
966
967
968 /**
969  * Function called to notify a client about the socket
970  * being ready to queue more data.  "buf" will be
971  * NULL and "size" zero if the socket was closed for
972  * writing in the meantime.
973  *
974  * @param cls closure (data itself)
975  * @param size number of bytes available in buf
976  * @param buf where the callee should write the message
977  *
978  * @return number of bytes written to buf
979  */
980 static size_t
981 send_core_data_multicast (void *cls, size_t size, void *buf);
982
983
984 /**
985  * Decrements the reference counter and frees all resources if needed
986  *
987  * @param dd Data Descriptor used in a multicast message. Freed if needed.
988  */
989 static void
990 data_descriptor_decrement_multicast (struct MeshData *mesh_data)
991 {
992   /* Make sure it's a multicast packet */
993   GNUNET_assert (NULL != mesh_data->reference_counter);
994
995   if (0 == --(*(mesh_data->reference_counter)))
996   {
997     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Last copy!\n");
998     if (NULL != mesh_data->task)
999     {
1000       if (GNUNET_SCHEDULER_NO_TASK != *(mesh_data->task))
1001       {
1002         GNUNET_SCHEDULER_cancel (*(mesh_data->task));
1003         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  notifying client...\n");
1004         GNUNET_SERVER_receive_done (mesh_data->t->client->handle, GNUNET_OK);
1005       }
1006       GNUNET_free (mesh_data->task);
1007     }
1008     GNUNET_free (mesh_data->reference_counter);
1009     GNUNET_free (mesh_data->data);
1010     GNUNET_free (mesh_data);
1011   }
1012 }
1013
1014
1015 /**
1016  * Cancel a core transmission that was already requested and free all resources
1017  * associated to the request.
1018  *
1019  * @param peer PeeInfo of the peer whose transmission is cancelled.
1020  * @param i Position of the transmission to be cancelled.
1021  */
1022 static void
1023 peer_info_cancel_transmission (struct MeshPeerInfo *peer, unsigned int i)
1024 {
1025   if (NULL != peer->core_transmit[i])
1026   {
1027     struct MeshTransmissionDescriptor *dd;
1028     struct MeshPathInfo *path_info;
1029
1030 #if MESH_DEBUG
1031     {
1032       struct GNUNET_PeerIdentity id;
1033
1034       GNUNET_PEER_resolve (peer->id, &id);
1035       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1036                   "MESH:   Cancelling data transmission at %s [%u]\n",
1037                   GNUNET_i2s (&id), i);
1038       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    message type %u\n",
1039                   peer->types[i]);
1040     }
1041 #endif
1042     /* TODO: notify that tranmission has failed */
1043     switch (peer->types[i])
1044     {
1045     case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
1046     case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
1047     case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
1048       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    type payload\n");
1049       dd = peer->infos[i];
1050       data_descriptor_decrement_multicast (dd->mesh_data);
1051       break;
1052     case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
1053       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    type create path\n");
1054       path_info = peer->infos[i];
1055       path_destroy (path_info->path);
1056       break;
1057     default:
1058       GNUNET_break (0);
1059       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    type unknown!\n");
1060     }
1061     GNUNET_CORE_notify_transmit_ready_cancel (peer->core_transmit[i]);
1062     peer->core_transmit[i] = NULL;
1063     GNUNET_free (peer->infos[i]);
1064   }
1065 }
1066
1067
1068 /**
1069  * Get a unused CORE slot to transmit a message to a peer. If all the slots
1070  * are used, cancel one and return it's position.
1071  *
1072  * @param peer PeerInfo of the neighbor we want to transmit to.
1073  *
1074  * @return The index of an available slot to transmit to the neighbor.
1075  */
1076 static unsigned int
1077 peer_info_transmit_slot (struct MeshPeerInfo *peer)
1078 {
1079   unsigned int i;
1080
1081   for (i = 0; peer->core_transmit[i]; i++)
1082   {
1083     if (i == (CORE_QUEUE_SIZE - 1))
1084     {
1085       /* All positions are taken! Overwriting! */
1086       GNUNET_break (0);
1087       peer_info_cancel_transmission (peer, 0);
1088       return 0;
1089     }
1090   }
1091   return i;
1092 }
1093
1094
1095 /**
1096  * Retrieve the MeshPeerInfo stucture associated with the peer, create one
1097  * and insert it in the appropiate structures if the peer is not known yet.
1098  *
1099  * @param peer Full identity of the peer.
1100  *
1101  * @return Existing or newly created peer info.
1102  */
1103 static struct MeshPeerInfo *
1104 peer_info_get (const struct GNUNET_PeerIdentity *peer)
1105 {
1106   struct MeshPeerInfo *peer_info;
1107
1108   peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
1109   if (NULL == peer_info)
1110   {
1111     peer_info =
1112         (struct MeshPeerInfo *) GNUNET_malloc (sizeof (struct MeshPeerInfo));
1113     GNUNET_CONTAINER_multihashmap_put (peers, &peer->hashPubKey, peer_info,
1114                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1115     peer_info->id = GNUNET_PEER_intern (peer);
1116   }
1117
1118   return peer_info;
1119 }
1120
1121
1122 /**
1123  * Retrieve the MeshPeerInfo stucture associated with the peer, create one
1124  * and insert it in the appropiate structures if the peer is not known yet.
1125  *
1126  * @param peer Short identity of the peer.
1127  *
1128  * @return Existing or newly created peer info.
1129  */
1130 static struct MeshPeerInfo *
1131 peer_info_get_short (const GNUNET_PEER_Id peer)
1132 {
1133   struct GNUNET_PeerIdentity id;
1134
1135   GNUNET_PEER_resolve (peer, &id);
1136   return peer_info_get (&id);
1137 }
1138
1139
1140 /**
1141  * Iterator to remove the tunnel from the list of tunnels a peer participates
1142  * in.
1143  *
1144  * @param cls Closure (tunnel info)
1145  * @param key GNUNET_PeerIdentity of the peer (unused)
1146  * @param value PeerInfo of the peer
1147  *
1148  * @return always GNUNET_YES, to keep iterating
1149  */
1150 static int
1151 peer_info_delete_tunnel (void *cls, const GNUNET_HashCode * key, void *value)
1152 {
1153   struct MeshTunnel *t = cls;
1154   struct MeshPeerInfo *peer = value;
1155   unsigned int i;
1156
1157   for (i = 0; i < peer->ntunnels; i++)
1158   {
1159     if (0 ==
1160         memcmp (&peer->tunnels[i]->id, &t->id, sizeof (struct MESH_TunnelID)))
1161     {
1162       peer->ntunnels--;
1163       peer->tunnels[i] = peer->tunnels[peer->ntunnels];
1164       peer->tunnels = GNUNET_realloc (peer->tunnels, peer->ntunnels);
1165       return GNUNET_YES;
1166     }
1167   }
1168   return GNUNET_YES;
1169 }
1170
1171
1172 /**
1173   * Core callback to write a
1174   *
1175   * @param cls Closure (MeshTransmissionDescriptor with data in "data" member).
1176   * @param size Number of bytes available in buf.
1177   * @param buf Where the to write the message.
1178   *
1179   * @return number of bytes written to buf
1180   */
1181 static size_t
1182 send_core_data_raw (void *cls, size_t size, void *buf)
1183 {
1184   struct MeshTransmissionDescriptor *info = cls;
1185   struct GNUNET_MessageHeader *msg;
1186   size_t total_size;
1187
1188   GNUNET_assert (NULL != info);
1189   GNUNET_assert (NULL != info->mesh_data);
1190   msg = (struct GNUNET_MessageHeader *) info->mesh_data->data;
1191   total_size = ntohs (msg->size);
1192
1193   if (total_size > size)
1194   {
1195     struct GNUNET_PeerIdentity id;
1196
1197     GNUNET_PEER_resolve (info->peer->id, &id);
1198     info->peer->core_transmit[info->handler_n] =
1199         GNUNET_CORE_notify_transmit_ready (core_handle, 0, 100,
1200                                            GNUNET_TIME_UNIT_FOREVER_REL, &id,
1201                                            size, &send_core_data_raw, info);
1202     return 0;
1203   }
1204   info->peer->core_transmit[info->handler_n] = NULL;
1205   memcpy (buf, msg, total_size);
1206   GNUNET_free (info->mesh_data);
1207   GNUNET_free (info);
1208   return total_size;
1209 }
1210
1211
1212 /**
1213  * Sends an already built message to a peer, properly registrating
1214  * all used resources.
1215  *
1216  * @param message Message to send. Fucntion makes a copy of it.
1217  * @param peer Short ID of the neighbor whom to send the message.
1218  *
1219  * FIXME tunnel?
1220  */
1221 static void
1222 send_message (const struct GNUNET_MessageHeader *message,
1223               const struct GNUNET_PeerIdentity *peer)
1224 {
1225   struct MeshTransmissionDescriptor *info;
1226   struct MeshPeerInfo *neighbor;
1227   struct MeshPeerPath *p;
1228   unsigned int i;
1229   size_t size;
1230
1231 //   GNUNET_TRANSPORT_try_connect();
1232
1233   size = ntohs (message->size);
1234   info = GNUNET_malloc (sizeof (struct MeshTransmissionDescriptor));
1235   info->mesh_data = GNUNET_malloc (sizeof (struct MeshData));
1236   info->mesh_data->data = GNUNET_malloc (size);
1237   memcpy (info->mesh_data->data, message, size);
1238   info->mesh_data->data_len = size;
1239   neighbor = peer_info_get (peer);
1240   for (p = neighbor->path_head; NULL != p; p = p->next)
1241   {
1242     if (2 == p->length)
1243     {
1244       break;
1245     }
1246   }
1247   if (NULL == p)
1248   {
1249     GNUNET_break (0);
1250     GNUNET_free (info->mesh_data->data);
1251     GNUNET_free (info->mesh_data);
1252     GNUNET_free (info);
1253     return;
1254   }
1255   i = peer_info_transmit_slot (neighbor);
1256   info->handler_n = i;
1257   info->peer = neighbor;
1258   neighbor->types[i] = GNUNET_MESSAGE_TYPE_MESH_UNICAST;
1259   neighbor->infos[i] = info;
1260   neighbor->core_transmit[i] =
1261       GNUNET_CORE_notify_transmit_ready (core_handle, 0, 100,
1262                                          GNUNET_TIME_UNIT_FOREVER_REL, peer,
1263                                          size, &send_core_data_raw, info);
1264
1265 }
1266
1267
1268 /**
1269  * Sends a CREATE PATH message for a path to a peer, properly registrating
1270  * all used resources.
1271  *
1272  * @param peer PeerInfo of the final peer for whom this path is being created.
1273  * @param p Path itself.
1274  * @param t Tunnel for which the path is created.
1275  */
1276 static void
1277 send_create_path (struct MeshPeerInfo *peer, struct MeshPeerPath *p,
1278                   struct MeshTunnel *t)
1279 {
1280   struct GNUNET_PeerIdentity id;
1281   struct MeshPathInfo *path_info;
1282   struct MeshPeerInfo *neighbor;
1283   unsigned int i;
1284
1285   if (NULL == p)
1286   {
1287     p = tree_get_path_to_peer (t->tree, peer->id);
1288     if (NULL == p)
1289     {
1290       GNUNET_break (0);
1291       return;
1292     }
1293   }
1294   for (i = 0; i < p->length; i++)
1295   {
1296     if (p->peers[i] == myid)
1297       break;
1298   }
1299   if (i >= p->length - 1)
1300   {
1301     path_destroy (p);
1302     GNUNET_break (0);
1303     return;
1304   }
1305   GNUNET_PEER_resolve (p->peers[i + 1], &id);
1306
1307   path_info = GNUNET_malloc (sizeof (struct MeshPathInfo));
1308   path_info->path = p;
1309   path_info->t = t;
1310   neighbor = peer_info_get (&id);
1311   path_info->peer = neighbor;
1312   path_info->pos = peer_info_transmit_slot (neighbor);
1313   neighbor->types[path_info->pos] = GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE;
1314   neighbor->infos[path_info->pos] = path_info;
1315   neighbor->core_transmit[path_info->pos] = GNUNET_CORE_notify_transmit_ready (core_handle,     /* handle */
1316                                                                                0,       /* cork */
1317                                                                                0,       /* priority */
1318                                                                                GNUNET_TIME_UNIT_FOREVER_REL,    /* timeout */
1319                                                                                &id,     /* target */
1320                                                                                sizeof (struct GNUNET_MESH_ManipulatePath) + (p->length * sizeof (struct GNUNET_PeerIdentity)),  /*size */
1321                                                                                &send_core_create_path,  /* callback */
1322                                                                                path_info);      /* cls */
1323 }
1324
1325
1326 /**
1327  * Sends a DESTROY PATH message to free resources for a path in a tunnel
1328  *
1329  * @param t Tunnel whose path to destroy.
1330  * @param destination Short ID of the peer to whom the path to destroy.
1331  */
1332 static void
1333 send_destroy_path (struct MeshTunnel *t, GNUNET_PEER_Id destination)
1334 {
1335   struct MeshPeerPath *p;
1336   size_t size;
1337
1338   p = tree_get_path_to_peer (t->tree, destination);
1339   if (NULL == p)
1340   {
1341     GNUNET_break (0);
1342     return;
1343   }
1344   size = sizeof (struct GNUNET_MESH_ManipulatePath);
1345   size += p->length * sizeof (struct GNUNET_PeerIdentity);
1346   {
1347     struct GNUNET_MESH_ManipulatePath *msg;
1348     struct GNUNET_PeerIdentity *pi;
1349     char cbuf[size];
1350     unsigned int i;
1351
1352     msg = (struct GNUNET_MESH_ManipulatePath *) cbuf;
1353     msg->header.size = htons (size);
1354     msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY);
1355     msg->tid = htonl (t->id.tid);
1356     pi = (struct GNUNET_PeerIdentity *) &msg[1];
1357     for (i = 0; i < p->length; i++)
1358     {
1359       GNUNET_PEER_resolve (p->peers[i], &pi[i]);
1360     }
1361     send_message (&msg->header, tree_get_first_hop (t->tree, destination));
1362   }
1363   path_destroy (p);
1364 }
1365
1366
1367 /**
1368  * Try to establish a new connection to this peer.
1369  * Use the best path for the given tunnel.
1370  * If the peer doesn't have any path to it yet, try to get one.
1371  * If the peer already has some path, send a CREATE PATH towards it.
1372  *
1373  * @param peer PeerInfo of the peer.
1374  * @param t Tunnel for which to create the path, if possible.
1375  */
1376 static void
1377 peer_info_connect (struct MeshPeerInfo *peer, struct MeshTunnel *t)
1378 {
1379   struct MeshPeerPath *p;
1380   struct MeshPathInfo *path_info;
1381
1382   if (NULL != peer->path_head)
1383   {
1384     p = tree_get_path_to_peer (t->tree, peer->id);
1385     if (NULL == p)
1386     {
1387       GNUNET_break (0);
1388       return;
1389     }
1390
1391     if (p->length > 1)
1392     {
1393       send_create_path (peer, p, t);
1394     }
1395     else
1396     {
1397       path_destroy (p);
1398       send_client_peer_connected (t, myid);
1399     }
1400   }
1401   else if (NULL == peer->dhtget)
1402   {
1403     struct GNUNET_PeerIdentity id;
1404
1405     GNUNET_PEER_resolve (peer->id, &id);
1406     path_info = GNUNET_malloc (sizeof (struct MeshPathInfo));
1407     path_info->peer = peer;
1408     path_info->t = t;
1409     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1410                 "MESH:   Starting DHT GET for peer %s\n", GNUNET_i2s (&id));
1411     peer->dhtgetcls = path_info;
1412     peer->dhtget = GNUNET_DHT_get_start (dht_handle,    /* handle */
1413                                          GNUNET_TIME_UNIT_FOREVER_REL,  /* timeout */
1414                                          GNUNET_BLOCK_TYPE_TEST,        /* type */
1415                                          &id.hashPubKey,        /* key to search */
1416                                          4,     /* replication level */
1417                                          GNUNET_DHT_RO_RECORD_ROUTE | GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE, NULL,       /* xquery */
1418                                          0,     /* xquery bits */
1419                                          &dht_get_id_handler, path_info);
1420   }
1421   /* Otherwise, there is no path but the DHT get is already started. */
1422 }
1423
1424
1425 /**
1426  * Task to delay the connection of a peer
1427  *
1428  * @param cls Closure (path info with tunnel and peer to connect).
1429  *            Will be free'd on exection.
1430  * @param tc TaskContext
1431  */
1432 static void
1433 peer_info_connect_task (void *cls,
1434                         const struct GNUNET_SCHEDULER_TaskContext *tc)
1435 {
1436   struct MeshPathInfo *path_info = cls;
1437
1438   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1439   {
1440     GNUNET_free (cls);
1441     return;
1442   }
1443   peer_info_connect (path_info->peer, path_info->t);
1444   GNUNET_free (cls);
1445 }
1446
1447
1448 /**
1449  * Destroy the peer_info and free any allocated resources linked to it
1450  *
1451  * @param pi The peer_info to destroy.
1452  *
1453  * @return GNUNET_OK on success
1454  */
1455 static int
1456 peer_info_destroy (struct MeshPeerInfo *pi)
1457 {
1458   struct GNUNET_PeerIdentity id;
1459   struct MeshPeerPath *p;
1460   struct MeshPeerPath *nextp;
1461   unsigned int i;
1462
1463   GNUNET_PEER_resolve (pi->id, &id);
1464   GNUNET_PEER_change_rc (pi->id, -1);
1465
1466   if (GNUNET_YES !=
1467       GNUNET_CONTAINER_multihashmap_remove (peers, &id.hashPubKey, pi))
1468   {
1469     GNUNET_break (0);
1470     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1471                 "MESH: removing peer %s, not in hashmap\n", GNUNET_i2s (&id));
1472   }
1473   if (NULL != pi->dhtget)
1474   {
1475     GNUNET_DHT_get_stop (pi->dhtget);
1476     GNUNET_free (pi->dhtgetcls);
1477   }
1478   for (i = 0; i < CORE_QUEUE_SIZE; i++)
1479   {
1480     peer_info_cancel_transmission (pi, i);
1481   }
1482   p = pi->path_head;
1483   while (NULL != p)
1484   {
1485     nextp = p->next;
1486     GNUNET_CONTAINER_DLL_remove (pi->path_head, pi->path_tail, p);
1487     path_destroy (p);
1488     p = nextp;
1489   }
1490   GNUNET_free (pi);
1491   return GNUNET_OK;
1492 }
1493
1494
1495 /**
1496  * Remove all paths that rely on a direct connection between p1 and p2
1497  * from the peer itself and notify all tunnels about it.
1498  *
1499  * @param peer PeerInfo of affected peer.
1500  * @param p1 GNUNET_PEER_Id of one peer.
1501  * @param p2 GNUNET_PEER_Id of another peer that was connected to the first and
1502  *           no longer is.
1503  *
1504  * TODO: optimize (see below)
1505  */
1506 static void
1507 peer_info_remove_path (struct MeshPeerInfo *peer, GNUNET_PEER_Id p1,
1508                        GNUNET_PEER_Id p2)
1509 {
1510   struct MeshPeerPath *p;
1511   struct MeshPeerPath *aux;
1512   struct MeshPeerInfo *peer_d;
1513   GNUNET_PEER_Id d;
1514   unsigned int destroyed;
1515   unsigned int best;
1516   unsigned int cost;
1517   unsigned int i;
1518
1519   destroyed = 0;
1520   p = peer->path_head;
1521   while (NULL != p)
1522   {
1523     aux = p->next;
1524     for (i = 0; i < (p->length - 1); i++)
1525     {
1526       if ((p->peers[i] == p1 && p->peers[i + 1] == p2) ||
1527           (p->peers[i] == p2 && p->peers[i + 1] == p1))
1528       {
1529         GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, p);
1530         path_destroy (p);
1531         destroyed++;
1532         break;
1533       }
1534     }
1535     p = aux;
1536   }
1537   if (0 == destroyed)
1538     return;
1539
1540   for (i = 0; i < peer->ntunnels; i++)
1541   {
1542     d = tunnel_notify_connection_broken (peer->tunnels[i], p1, p2);
1543     if (0 == d)
1544       continue;
1545     /* TODO
1546      * Problem: one or more peers have been deleted from the tunnel tree.
1547      * We don't know who they are to try to add them again.
1548      * We need to try to find a new path for each of the disconnected peers.
1549      * Some of them might already have a path to reach them that does not
1550      * involve p1 and p2. Adding all anew might render in a better tree than
1551      * the trivial immediate fix.
1552      *
1553      * Trivial immiediate fix: try to reconnect to the disconnected node. All
1554      * its children will be reachable trough him.
1555      */
1556     peer_d = peer_info_get_short (d);
1557     best = UINT_MAX;
1558     aux = NULL;
1559     for (p = peer_d->path_head; NULL != p; p = p->next)
1560     {
1561       if ((cost = tree_get_path_cost (peer->tunnels[i]->tree, p)) < best)
1562       {
1563         best = cost;
1564         aux = p;
1565       }
1566     }
1567     if (NULL != aux)
1568     {
1569       /* No callback, as peer will be already disconnected and a connection
1570        * scheduled by tunnel_notify_connection_broken.
1571        */
1572       tree_add_path (peer->tunnels[i]->tree, aux, NULL, NULL);
1573     }
1574     else
1575     {
1576       peer_info_connect (peer_d, peer->tunnels[i]);
1577     }
1578   }
1579 }
1580
1581
1582 /**
1583  * Add the path to the peer and update the path used to reach it in case this
1584  * is the shortest.
1585  *
1586  * @param peer_info Destination peer to add the path to.
1587  * @param path New path to add. Last peer must be the peer in arg 1.
1588  *             Path will be either used of freed if already known.
1589  * @param trusted Do we trust that this path is real?
1590  */
1591 void
1592 peer_info_add_path (struct MeshPeerInfo *peer_info, struct MeshPeerPath *path,
1593                     int trusted)
1594 {
1595   struct MeshPeerPath *aux;
1596   unsigned int l;
1597   unsigned int l2;
1598
1599   if ((NULL == peer_info) || (NULL == path))
1600   {
1601     GNUNET_break (0);
1602     path_destroy (path);
1603     return;
1604   }
1605   if (path->peers[path->length - 1] != peer_info->id)
1606   {
1607     GNUNET_break (0);
1608     path_destroy (path);
1609     return;
1610   }
1611   if (path->length <= 2 && GNUNET_NO == trusted)
1612   {
1613     /* Only allow CORE to tell us about direct paths */
1614     path_destroy (path);
1615     return;
1616   }
1617   GNUNET_assert (peer_info->id == path->peers[path->length - 1]);
1618   for (l = 1; l < path->length; l++)
1619   {
1620     if (path->peers[l] == myid)
1621     {
1622       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: shortening path by %u\n", l);
1623       for (l2 = 0; l2 < path->length - l; l2++)
1624       {
1625         path->peers[l2] = path->peers[l + l2];
1626       }
1627       path->length -= l;
1628       l = 1;
1629       path->peers =
1630           GNUNET_realloc (path->peers, path->length * sizeof (GNUNET_PEER_Id));
1631     }
1632   }
1633 #if MESH_DEBUG
1634   {
1635     struct GNUNET_PeerIdentity id;
1636
1637     GNUNET_PEER_resolve (peer_info->id, &id);
1638     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: adding path [%u] to peer %s\n",
1639                 path->length, GNUNET_i2s (&id));
1640   }
1641 #endif
1642   l = path_get_length (path);
1643   if (0 == l)
1644   {
1645     GNUNET_free (path);
1646     return;
1647   }
1648
1649   GNUNET_assert (peer_info->id == path->peers[path->length - 1]);
1650   for (aux = peer_info->path_head; aux != NULL; aux = aux->next)
1651   {
1652     l2 = path_get_length (aux);
1653     if (l2 > l)
1654     {
1655       GNUNET_CONTAINER_DLL_insert_before (peer_info->path_head,
1656                                           peer_info->path_tail, aux, path);
1657       return;
1658     }
1659     else
1660     {
1661       if (l2 == l && memcmp (path->peers, aux->peers, l) == 0)
1662       {
1663         path_destroy (path);
1664         return;
1665       }
1666     }
1667   }
1668   GNUNET_CONTAINER_DLL_insert_tail (peer_info->path_head, peer_info->path_tail,
1669                                     path);
1670   return;
1671 }
1672
1673
1674 /**
1675  * Add the path to the origin peer and update the path used to reach it in case
1676  * this is the shortest.
1677  * The path is given in peer_info -> destination, therefore we turn the path
1678  * upside down first.
1679  *
1680  * @param peer_info Peer to add the path to, being the origin of the path.
1681  * @param path New path to add after being inversed.
1682  * @param trusted Do we trust that this path is real?
1683  */
1684 static void
1685 peer_info_add_path_to_origin (struct MeshPeerInfo *peer_info,
1686                               struct MeshPeerPath *path, int trusted)
1687 {
1688   path_invert (path);
1689   peer_info_add_path (peer_info, path, trusted);
1690 }
1691
1692
1693 /**
1694  * Build a PeerPath from the paths returned from the DHT, reversing the paths
1695  * to obtain a local peer -> destination path and interning the peer ids.
1696  *
1697  * @return Newly allocated and created path
1698  */
1699 static struct MeshPeerPath *
1700 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
1701                      unsigned int get_path_length,
1702                      const struct GNUNET_PeerIdentity *put_path,
1703                      unsigned int put_path_length)
1704 {
1705   struct MeshPeerPath *p;
1706   GNUNET_PEER_Id id;
1707   int i;
1708
1709   p = path_new (1);
1710   p->peers[0] = myid;
1711   GNUNET_PEER_change_rc (myid, 1);
1712   i = get_path_length;
1713   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    GET has %d hops.\n", i);
1714   for (i--; i >= 0; i--)
1715   {
1716     id = GNUNET_PEER_intern (&get_path[i]);
1717     if (p->length > 0 && id == p->peers[p->length - 1])
1718     {
1719       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    Optimizing 1 hop out.\n");
1720       GNUNET_PEER_change_rc (id, -1);
1721     }
1722     else
1723     {
1724       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    Adding from GET: %s.\n",
1725                   GNUNET_i2s (&get_path[i]));
1726       p->length++;
1727       p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
1728       p->peers[p->length - 1] = id;
1729     }
1730   }
1731   i = put_path_length;
1732   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    PUT has %d hops.\n", i);
1733   for (i--; i >= 0; i--)
1734   {
1735     id = GNUNET_PEER_intern (&put_path[i]);
1736     if (id == myid)
1737     {
1738       /* PUT path went through us, so discard the path up until now and start
1739        * from here to get a much shorter (and loop-free) path.
1740        */
1741       path_destroy (p);
1742       p = path_new (0);
1743     }
1744     if (p->length > 0 && id == p->peers[p->length - 1])
1745     {
1746       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    Optimizing 1 hop out.\n");
1747       GNUNET_PEER_change_rc (id, -1);
1748     }
1749     else
1750     {
1751       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    Adding from PUT: %s.\n",
1752                   GNUNET_i2s (&put_path[i]));
1753       p->length++;
1754       p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
1755       p->peers[p->length - 1] = id;
1756     }
1757   }
1758 #if MESH_DEBUG
1759   if (get_path_length > 0)
1760     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    (first of GET: %s)\n",
1761                 GNUNET_i2s (&get_path[0]));
1762   if (put_path_length > 0)
1763     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    (first of PUT: %s)\n",
1764                 GNUNET_i2s (&put_path[0]));
1765   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    In total: %d hops\n",
1766               p->length);
1767   for (i = 0; i < p->length; i++)
1768   {
1769     struct GNUNET_PeerIdentity peer_id;
1770
1771     GNUNET_PEER_resolve (p->peers[i], &peer_id);
1772     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:        %u: %s\n", p->peers[i],
1773                 GNUNET_i2s (&peer_id));
1774   }
1775 #endif
1776   return p;
1777 }
1778
1779
1780 /**
1781  * Adds a path to the peer_infos of all the peers in the path
1782  *
1783  * @param p Path to process.
1784  * @param confirmed Whether we know if the path works or not. FIXME use
1785  */
1786 static void
1787 path_add_to_peers (struct MeshPeerPath *p, int confirmed)
1788 {
1789   unsigned int i;
1790
1791   /* TODO: invert and add */
1792   for (i = 0; i < p->length && p->peers[i] != myid; i++) /* skip'em */ ;
1793   for (i++; i < p->length; i++)
1794   {
1795     struct MeshPeerInfo *aux;
1796     struct MeshPeerPath *copy;
1797
1798     aux = peer_info_get_short (p->peers[i]);
1799     copy = path_duplicate (p);
1800     copy->length = i + 1;
1801     peer_info_add_path (aux, copy, GNUNET_NO);
1802   }
1803 }
1804
1805
1806 /**
1807  * Send keepalive packets for a peer
1808  *
1809  * @param cls Closure (tunnel for which to send the keepalive).
1810  * @param tc Notification context.
1811  *
1812  * TODO: implement explicit multicast keepalive?
1813  */
1814 static void
1815 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1816
1817
1818 /**
1819  * Search for a tunnel among the incoming tunnels
1820  *
1821  * @param tid the local id of the tunnel
1822  *
1823  * @return tunnel handler, NULL if doesn't exist
1824  */
1825 static struct MeshTunnel *
1826 tunnel_get_incoming (MESH_TunnelNumber tid)
1827 {
1828   GNUNET_HashCode hash;
1829
1830   GNUNET_assert (tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV);
1831   GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
1832   return GNUNET_CONTAINER_multihashmap_get (incoming_tunnels, &hash);
1833 }
1834
1835
1836 /**
1837  * Search for a tunnel among the tunnels for a client
1838  *
1839  * @param c the client whose tunnels to search in
1840  * @param tid the local id of the tunnel
1841  *
1842  * @return tunnel handler, NULL if doesn't exist
1843  */
1844 static struct MeshTunnel *
1845 tunnel_get_by_local_id (struct MeshClient *c, MESH_TunnelNumber tid)
1846 {
1847   if (tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
1848   {
1849     return tunnel_get_incoming (tid);
1850   }
1851   else
1852   {
1853     GNUNET_HashCode hash;
1854
1855     GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
1856     return GNUNET_CONTAINER_multihashmap_get (c->tunnels, &hash);
1857   }
1858 }
1859
1860
1861 /**
1862  * Search for a tunnel by global ID using PEER_ID
1863  *
1864  * @param pi owner of the tunnel
1865  * @param tid global tunnel number
1866  *
1867  * @return tunnel handler, NULL if doesn't exist
1868  */
1869 static struct MeshTunnel *
1870 tunnel_get_by_pi (GNUNET_PEER_Id pi, MESH_TunnelNumber tid)
1871 {
1872   struct MESH_TunnelID id;
1873   GNUNET_HashCode hash;
1874
1875   id.oid = pi;
1876   id.tid = tid;
1877
1878   GNUNET_CRYPTO_hash (&id, sizeof (struct MESH_TunnelID), &hash);
1879   return GNUNET_CONTAINER_multihashmap_get (tunnels, &hash);
1880 }
1881
1882
1883 /**
1884  * Search for a tunnel by global ID using full PeerIdentities
1885  *
1886  * @param oid owner of the tunnel
1887  * @param tid global tunnel number
1888  *
1889  * @return tunnel handler, NULL if doesn't exist
1890  */
1891 static struct MeshTunnel *
1892 tunnel_get (struct GNUNET_PeerIdentity *oid, MESH_TunnelNumber tid)
1893 {
1894   return tunnel_get_by_pi (GNUNET_PEER_search (oid), tid);
1895 }
1896
1897
1898 /**
1899  * Callback used to notify a client owner of a tunnel that a peer has
1900  * disconnected, most likely because of a path change.
1901  *
1902  * @param cls Closure (tunnel this notification is about).
1903  * @param peer_id Short ID of disconnected peer.
1904  */
1905 void
1906 notify_peer_disconnected (void *cls, GNUNET_PEER_Id peer_id)
1907 {
1908   struct MeshTunnel *t = cls;
1909   struct MeshPeerInfo *peer;
1910   struct MeshPathInfo *path_info;
1911
1912   if (NULL != t->client && NULL != nc)
1913   {
1914     struct GNUNET_MESH_PeerControl msg;
1915
1916     msg.header.size = htons (sizeof (msg));
1917     msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL);
1918     msg.tunnel_id = htonl (t->local_tid);
1919     GNUNET_PEER_resolve (peer_id, &msg.peer);
1920     GNUNET_SERVER_notification_context_unicast (nc, t->client->handle,
1921                                                 &msg.header, GNUNET_NO);
1922   }
1923   peer = peer_info_get_short (peer_id);
1924   path_info = GNUNET_malloc (sizeof (struct MeshPathInfo));
1925   path_info->peer = peer;
1926   path_info->t = t;
1927   GNUNET_SCHEDULER_add_now (&peer_info_connect_task, path_info);
1928 }
1929
1930
1931 /**
1932  * Add a peer to a tunnel, accomodating paths accordingly and initializing all
1933  * needed rescources.
1934  * If peer already exists, reevaluate shortest path and change if different.
1935  *
1936  * @param t Tunnel we want to add a new peer to
1937  * @param peer PeerInfo of the peer being added
1938  *
1939  */
1940 static void
1941 tunnel_add_peer (struct MeshTunnel *t, struct MeshPeerInfo *peer)
1942 {
1943   struct GNUNET_PeerIdentity id;
1944   struct MeshPeerPath *best_p;
1945   struct MeshPeerPath *p;
1946   unsigned int best_cost;
1947   unsigned int cost;
1948
1949   GNUNET_PEER_resolve (peer->id, &id);
1950   if (GNUNET_NO ==
1951       GNUNET_CONTAINER_multihashmap_contains (t->peers, &id.hashPubKey))
1952   {
1953     t->peers_total++;
1954     GNUNET_array_append (peer->tunnels, peer->ntunnels, t);
1955     GNUNET_assert (GNUNET_OK ==
1956                    GNUNET_CONTAINER_multihashmap_put (t->peers, &id.hashPubKey,
1957                                                       peer,
1958                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
1959   }
1960
1961   if (NULL != (p = peer->path_head))
1962   {
1963     best_p = p;
1964     best_cost = tree_get_path_cost (t->tree, p);
1965     while (NULL != p)
1966     {
1967       if ((cost = tree_get_path_cost (t->tree, p)) < best_cost)
1968       {
1969         best_cost = cost;
1970         best_p = p;
1971       }
1972       p = p->next;
1973     }
1974     tree_add_path (t->tree, best_p, &notify_peer_disconnected, t);
1975     if (GNUNET_SCHEDULER_NO_TASK == t->path_refresh_task)
1976       t->path_refresh_task =
1977           GNUNET_SCHEDULER_add_delayed (REFRESH_PATH_TIME, &path_refresh, t);
1978   }
1979   else
1980   {
1981     /* Start a DHT get */
1982     peer_info_connect (peer, t);
1983   }
1984 }
1985
1986 /**
1987  * Add a path to a tunnel which we don't own, just to remember the next hop.
1988  * If destination node was already in the tunnel, the first hop information
1989  * will be replaced with the new path.
1990  *
1991  * @param t Tunnel we want to add a new peer to
1992  * @param p Path to add
1993  * @param own_pos Position of local node in path.
1994  *
1995  */
1996 static void
1997 tunnel_add_path (struct MeshTunnel *t, struct MeshPeerPath *p,
1998                  unsigned int own_pos)
1999 {
2000   struct GNUNET_PeerIdentity id;
2001
2002   GNUNET_assert (0 != own_pos);
2003   tree_add_path (t->tree, p, NULL, NULL);
2004   if (own_pos < p->length - 1)
2005   {
2006     GNUNET_PEER_resolve (p->peers[own_pos + 1], &id);
2007     tree_update_first_hops (t->tree, myid, &id);
2008   }
2009 }
2010
2011
2012 /**
2013  * Notifies a tunnel that a connection has broken that affects at least
2014  * some of its peers. Sends a notification towards the root of the tree.
2015  * In case the peer is the owner of the tree, notifies the client that owns
2016  * the tunnel and tries to reconnect.
2017  *
2018  * @param t Tunnel affected.
2019  * @param p1 Peer that got disconnected from p2.
2020  * @param p2 Peer that got disconnected from p1.
2021  *
2022  * @return Short ID of the peer disconnected (either p1 or p2).
2023  *         0 if the tunnel remained unaffected.
2024  */
2025 static GNUNET_PEER_Id
2026 tunnel_notify_connection_broken (struct MeshTunnel *t, GNUNET_PEER_Id p1,
2027                                  GNUNET_PEER_Id p2)
2028 {
2029   GNUNET_PEER_Id pid;
2030
2031   pid =
2032       tree_notify_connection_broken (t->tree, p1, p2, &notify_peer_disconnected,
2033                                      t);
2034   if (myid != p1 && myid != p2)
2035   {
2036     return pid;
2037   }
2038   if (pid != myid)
2039   {
2040     if (tree_get_predecessor (t->tree) != 0)
2041     {
2042       /* We are the peer still connected, notify owner of the disconnection. */
2043       struct GNUNET_MESH_PathBroken msg;
2044       struct GNUNET_PeerIdentity neighbor;
2045
2046       msg.header.size = htons (sizeof (msg));
2047       msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN);
2048       GNUNET_PEER_resolve (t->id.oid, &msg.oid);
2049       msg.tid = htonl (t->id.tid);
2050       msg.peer1 = my_full_id;
2051       GNUNET_PEER_resolve (pid, &msg.peer2);
2052       GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &neighbor);
2053       send_message (&msg.header, &neighbor);
2054     }
2055   }
2056   return pid;
2057 }
2058
2059
2060 /**
2061  * Send a multicast packet to a neighbor.
2062  *
2063  * @param cls Closure (Info about the multicast packet)
2064  * @param neighbor_id Short ID of the neighbor to send the packet to.
2065  */
2066 static void
2067 tunnel_send_multicast_iterator (void *cls, GNUNET_PEER_Id neighbor_id)
2068 {
2069   struct MeshData *mdata = cls;
2070   struct MeshTransmissionDescriptor *info;
2071   struct GNUNET_PeerIdentity neighbor;
2072   unsigned int i;
2073
2074   info = GNUNET_malloc (sizeof (struct MeshTransmissionDescriptor));
2075
2076   info->mesh_data = mdata;
2077   (*(mdata->reference_counter)) ++;
2078   info->destination = neighbor_id;
2079   GNUNET_PEER_resolve (neighbor_id, &neighbor);
2080 #if MESH_DEBUG
2081   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    sending to %s...\n",
2082               GNUNET_i2s (&neighbor));
2083 #endif
2084   info->peer = peer_info_get (&neighbor);
2085   GNUNET_assert (NULL != info->peer);
2086   i = peer_info_transmit_slot (info->peer);
2087   info->handler_n = i;
2088   info->peer->infos[i] = info;
2089   info->peer->types[i] = GNUNET_MESSAGE_TYPE_MESH_MULTICAST;
2090   info->peer->core_transmit[i] =
2091       GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
2092                                          GNUNET_TIME_UNIT_FOREVER_REL,
2093                                          &neighbor, info->mesh_data->data_len,
2094                                          &send_core_data_multicast, info);
2095 }
2096
2097 /**
2098  * Send a message in a tunnel in multicast, sending a copy to each child node
2099  * down the local one in the tunnel tree.
2100  *
2101  * @param t Tunnel in which to send the data.
2102  * @param msg Message to be sent.
2103  * @param internal Has the service generated this message?
2104  */
2105 static void
2106 tunnel_send_multicast (struct MeshTunnel *t,
2107                        const struct GNUNET_MessageHeader *msg,
2108                        int internal)
2109 {
2110   struct MeshData *mdata;
2111
2112 #if MESH_DEBUG
2113   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2114               "MESH:  sending a multicast packet...\n");
2115 #endif
2116   mdata = GNUNET_malloc (sizeof (struct MeshData));
2117   mdata->data_len = ntohs (msg->size);
2118   mdata->reference_counter = GNUNET_malloc (sizeof (unsigned int));
2119   mdata->t = t;
2120   mdata->data = GNUNET_malloc (mdata->data_len);
2121   memcpy (mdata->data, msg, mdata->data_len);
2122   if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_MESH_MULTICAST)
2123   {
2124     struct GNUNET_MESH_Multicast *mcast;
2125
2126     mcast = (struct GNUNET_MESH_Multicast *) mdata->data;
2127     mcast->ttl = htonl (ntohl (mcast->ttl) - 1);
2128 #if MESH_DEBUG
2129     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   data packet, ttl: %u\n",
2130                 ntohl (mcast->ttl));
2131   }
2132   else
2133   {
2134     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   not a data packet, no ttl\n");
2135 #endif
2136   }
2137   if (NULL != t->client && GNUNET_YES != t->client->shutting_down
2138       && GNUNET_NO == internal)
2139   {
2140     mdata->task = GNUNET_malloc (sizeof (GNUNET_SCHEDULER_TaskIdentifier));
2141     (*(mdata->task)) =
2142         GNUNET_SCHEDULER_add_delayed (UNACKNOWLEDGED_WAIT, &client_allow_send,
2143                                       mdata);
2144     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: timeout task %u\n",
2145                 *(mdata->task));
2146   }
2147
2148   tree_iterate_children (t->tree, &tunnel_send_multicast_iterator, mdata);
2149   if (*(mdata->reference_counter) == 0)
2150   {
2151     GNUNET_free (mdata->data);
2152     GNUNET_free (mdata->reference_counter);
2153     if (NULL != mdata->task)
2154     {
2155       GNUNET_SCHEDULER_cancel(*(mdata->task));
2156       GNUNET_free (mdata->task);
2157       GNUNET_SERVER_receive_done(t->client->handle, GNUNET_OK);
2158     }
2159     // FIXME change order?
2160     GNUNET_free (mdata);
2161   }
2162 #if MESH_DEBUG
2163   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2164               "MESH:  sending a multicast packet done\n");
2165 #endif
2166   return;
2167 }
2168
2169
2170 /**
2171  * Send a message to all peers in this tunnel that the tunnel is no longer
2172  * valid.
2173  *
2174  * @param t The tunnel whose peers to notify.
2175  */
2176 static void
2177 tunnel_send_destroy (struct MeshTunnel *t)
2178 {
2179   struct GNUNET_MESH_TunnelDestroy msg;
2180
2181   msg.header.size = htons (sizeof (msg));
2182   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY);
2183   GNUNET_PEER_resolve (t->id.oid, &msg.oid);
2184   msg.tid = htonl (t->id.tid);
2185   tunnel_send_multicast (t, &msg.header, GNUNET_NO);
2186 }
2187
2188
2189
2190 /**
2191  * Destroy the tunnel and free any allocated resources linked to it
2192  *
2193  * @param t the tunnel to destroy
2194  *
2195  * @return GNUNET_OK on success
2196  */
2197 static int
2198 tunnel_destroy (struct MeshTunnel *t)
2199 {
2200   struct MeshClient *c;
2201   struct MeshQueue *q;
2202   struct MeshQueue *qn;
2203   GNUNET_HashCode hash;
2204   int r;
2205
2206   if (NULL == t)
2207     return GNUNET_OK;
2208
2209   r = GNUNET_OK;
2210   c = t->client;
2211 #if MESH_DEBUG
2212   {
2213     struct GNUNET_PeerIdentity id;
2214
2215     GNUNET_PEER_resolve (t->id.oid, &id);
2216     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: destroying tunnel %s [%x]\n",
2217                 GNUNET_i2s (&id), t->id.tid);
2218     if (NULL != c)
2219       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   by client %u\n", c->id);
2220   }
2221 #endif
2222
2223   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
2224   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &hash, t))
2225   {
2226     r = GNUNET_SYSERR;
2227   }
2228   
2229   GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
2230   if (NULL != c &&
2231       GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (c->tunnels, &hash, t))
2232   {
2233     r = GNUNET_SYSERR;
2234   }
2235   c = t->client_dest;
2236   GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
2237   if (NULL != c &&
2238       GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (c->tunnels, &hash, t))
2239   {
2240     r = GNUNET_SYSERR;
2241   }
2242   if (t->local_tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
2243   {
2244     GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
2245     GNUNET_break (GNUNET_YES ==
2246                   GNUNET_CONTAINER_multihashmap_remove (incoming_tunnels, &hash,
2247                                                         t));
2248   }
2249   if (NULL != t->peers)
2250   {
2251     GNUNET_CONTAINER_multihashmap_iterate (t->peers, &peer_info_delete_tunnel,
2252                                            t);
2253     GNUNET_CONTAINER_multihashmap_destroy (t->peers);
2254   }
2255   q = t->queue_head;
2256   while (NULL != q)
2257   {
2258     if (NULL != q->data)
2259       GNUNET_free (q->data);
2260     qn = q->next;
2261     GNUNET_free (q);
2262     q = qn;
2263     /* TODO cancel core transmit ready in case it was active */
2264   }
2265   tree_destroy (t->tree);
2266   if (NULL != t->dht_get_type)
2267     GNUNET_DHT_get_stop (t->dht_get_type);
2268   if (GNUNET_SCHEDULER_NO_TASK != t->timeout_task)
2269     GNUNET_SCHEDULER_cancel (t->timeout_task);
2270   if (GNUNET_SCHEDULER_NO_TASK != t->path_refresh_task)
2271     GNUNET_SCHEDULER_cancel (t->path_refresh_task);
2272   GNUNET_free (t);
2273   return r;
2274 }
2275
2276
2277 /**
2278  * Removes an explicit path from a tunnel, freeing all intermediate nodes
2279  * that are no longer needed, as well as nodes of no longer reachable peers.
2280  * The tunnel itself is also destoyed if results in a remote empty tunnel.
2281  *
2282  * @param t Tunnel from which to remove the path.
2283  * @param peer Short id of the peer which should be removed.
2284  */
2285 static void
2286 tunnel_delete_peer (struct MeshTunnel *t, GNUNET_PEER_Id peer)
2287 {
2288   if (GNUNET_NO == tree_del_peer (t->tree, peer, NULL, NULL))
2289     tunnel_destroy (t);
2290 }
2291
2292
2293 /**
2294  * tunnel_destroy_iterator: iterator for deleting each tunnel that belongs to a
2295  * client when the client disconnects.
2296  *
2297  * @param cls closure (client that is disconnecting)
2298  * @param key the hash of the local tunnel id (used to access the hashmap)
2299  * @param value the value stored at the key (tunnel to destroy)
2300  *
2301  * @return GNUNET_OK on success
2302  */
2303 static int
2304 tunnel_destroy_iterator (void *cls, const GNUNET_HashCode * key, void *value)
2305 {
2306   struct MeshTunnel *t = value;
2307   struct MeshClient *c = cls;
2308   int r;
2309
2310   send_client_tunnel_disconnect(t, c);
2311   if (c == t->client_dest)
2312   {
2313 #if MESH_DEBUG
2314     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2315                 "Client %u is destination, keeping the tunnel alive.\n", c->id);
2316 #endif
2317     t->client_dest = NULL;
2318     t->local_tid_dest = 0;
2319     return GNUNET_OK;
2320   }
2321   tunnel_send_destroy(t);
2322   r = tunnel_destroy (t);
2323   return r;
2324 }
2325
2326
2327 /**
2328  * Timeout function, destroys tunnel if called
2329  *
2330  * @param cls Closure (tunnel to destroy).
2331  * @param tc TaskContext
2332  */
2333 static void
2334 tunnel_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2335 {
2336   struct MeshTunnel *t = cls;
2337
2338   if (GNUNET_SCHEDULER_REASON_SHUTDOWN == tc->reason)
2339     return;
2340   t->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2341   tunnel_destroy (t);
2342 }
2343
2344 /**
2345  * Resets the tunnel timeout. Starts it if no timeout was running.
2346  *
2347  * @param t Tunnel whose timeout to reset.
2348  */
2349 static void
2350 tunnel_reset_timeout (struct MeshTunnel *t)
2351 {
2352   if (GNUNET_SCHEDULER_NO_TASK != t->timeout_task)
2353     GNUNET_SCHEDULER_cancel (t->timeout_task);
2354   t->timeout_task =
2355       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
2356                                     (REFRESH_PATH_TIME, 4), &tunnel_timeout, t);
2357 }
2358
2359
2360 /******************************************************************************/
2361 /****************      MESH NETWORK HANDLER HELPERS     ***********************/
2362 /******************************************************************************/
2363
2364 /**
2365  * Function called to notify a client about the socket
2366  * being ready to queue more data.  "buf" will be
2367  * NULL and "size" zero if the socket was closed for
2368  * writing in the meantime.
2369  *
2370  * @param cls closure
2371  * @param size number of bytes available in buf
2372  * @param buf where the callee should write the message
2373  * @return number of bytes written to buf
2374  */
2375 static size_t
2376 send_core_create_path (void *cls, size_t size, void *buf)
2377 {
2378   struct MeshPathInfo *info = cls;
2379   struct GNUNET_MESH_ManipulatePath *msg;
2380   struct GNUNET_PeerIdentity *peer_ptr;
2381   struct MeshPeerInfo *peer = info->peer;
2382   struct MeshTunnel *t = info->t;
2383   struct MeshPeerPath *p = info->path;
2384   size_t size_needed;
2385   int i;
2386
2387   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: CREATE PATH sending...\n");
2388   size_needed =
2389       sizeof (struct GNUNET_MESH_ManipulatePath) +
2390       p->length * sizeof (struct GNUNET_PeerIdentity);
2391
2392   if (size < size_needed || NULL == buf)
2393   {
2394     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: create path retransmit!\n");
2395     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   buf:  %p\n", buf);
2396     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   size: (%u/%u)\n", size,
2397                 size_needed);
2398     info->peer->core_transmit[info->pos] =
2399         GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
2400                                            GNUNET_TIME_UNIT_FOREVER_REL,
2401                                            tree_get_first_hop (t->tree,
2402                                                                peer->id),
2403                                            size_needed, &send_core_create_path,
2404                                            info);
2405     return 0;
2406   }
2407   info->peer->core_transmit[info->pos] = NULL;
2408 #if MESH_DEBUG
2409   {
2410     struct GNUNET_PeerIdentity id;
2411
2412     GNUNET_PEER_resolve (peer->id, &id);
2413     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2414                 "MESH:   setting core_transmit %s [%u] to NULL\n",
2415                 GNUNET_i2s (&id), info->pos);
2416   }
2417 #endif
2418   msg = (struct GNUNET_MESH_ManipulatePath *) buf;
2419   msg->header.size = htons (size_needed);
2420   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE);
2421   msg->tid = ntohl (t->id.tid);
2422
2423   peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
2424   for (i = 0; i < p->length; i++)
2425   {
2426     GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
2427   }
2428
2429   path_destroy (p);
2430   GNUNET_free (info);
2431
2432   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2433               "MESH: CREATE PATH (%u bytes long) sent!\n", size_needed);
2434   return size_needed;
2435 }
2436
2437
2438 /**
2439  * Function called to notify a client about the socket
2440  * being ready to queue more data.  "buf" will be
2441  * NULL and "size" zero if the socket was closed for
2442  * writing in the meantime.
2443  *
2444  * @param cls closure (data itself)
2445  * @param size number of bytes available in buf
2446  * @param buf where the callee should write the message
2447  *
2448  * @return number of bytes written to buf
2449  */
2450 static size_t
2451 send_core_data_multicast (void *cls, size_t size, void *buf)
2452 {
2453   struct MeshTransmissionDescriptor *info = cls;
2454   size_t total_size;
2455
2456   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Multicast callback.\n");
2457   GNUNET_assert (NULL != info);
2458   GNUNET_assert (NULL != info->peer);
2459   total_size = info->mesh_data->data_len;
2460   GNUNET_assert (total_size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
2461
2462   if (total_size > size)
2463   {
2464     /* Retry */
2465     struct GNUNET_PeerIdentity id;
2466
2467     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2468                 "MESH: Multicast: retransmitting... (%u/%u)\n", size,
2469                 total_size);
2470     GNUNET_PEER_resolve (info->peer->id, &id);
2471     info->peer->core_transmit[info->handler_n] =
2472         GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
2473                                            GNUNET_TIME_UNIT_FOREVER_REL, &id,
2474                                            total_size,
2475                                            &send_core_data_multicast, info);
2476     return 0;
2477   }
2478   info->peer->core_transmit[info->handler_n] = NULL;
2479   info->peer->infos[info->handler_n] = NULL;
2480   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  copying data...\n");
2481   memcpy (buf, info->mesh_data->data, total_size);
2482 #if MESH_DEBUG
2483   {
2484     struct GNUNET_MESH_Multicast *mc;
2485     struct GNUNET_MessageHeader *mh;
2486
2487     mh = buf;
2488     if (ntohs (mh->type) == GNUNET_MESSAGE_TYPE_MESH_MULTICAST)
2489     {
2490       mc = (struct GNUNET_MESH_Multicast *) mh;
2491       mh = (struct GNUNET_MessageHeader *) &mc[1];
2492       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2493                   "MESH:  multicast, payload type %u\n", ntohs (mh->type));
2494       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2495                   "MESH:  multicast, payload size %u\n", ntohs (mh->size));
2496     }
2497     else
2498     {
2499       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  type %u\n",
2500                   ntohs (mh->type));
2501     }
2502   }
2503 #endif
2504   data_descriptor_decrement_multicast (info->mesh_data);
2505   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: freeing info...\n");
2506   GNUNET_free (info);
2507   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: return %u\n", total_size);
2508   return total_size;
2509 }
2510
2511
2512 /**
2513  * Function called to notify a client about the socket
2514  * being ready to queue more data.  "buf" will be
2515  * NULL and "size" zero if the socket was closed for
2516  * writing in the meantime.
2517  *
2518  * @param cls closure (MeshTransmissionDescriptor)
2519  * @param size number of bytes available in buf
2520  * @param buf where the callee should write the message
2521  * @return number of bytes written to buf
2522  */
2523 static size_t
2524 send_core_path_ack (void *cls, size_t size, void *buf)
2525 {
2526   struct MeshTransmissionDescriptor *info = cls;
2527   struct GNUNET_MESH_PathACK *msg = buf;
2528
2529   GNUNET_assert (NULL != info);
2530   if (info->peer)
2531   {
2532     info->peer->core_transmit[info->handler_n] = NULL;
2533   }
2534   if (sizeof (struct GNUNET_MESH_PathACK) > size)
2535   {
2536     GNUNET_break (0);
2537     return 0;
2538   }
2539   msg->header.size = htons (sizeof (struct GNUNET_MESH_PathACK));
2540   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_ACK);
2541   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
2542   msg->tid = htonl (info->origin->tid);
2543   msg->peer_id = my_full_id;
2544   GNUNET_free (info);
2545   /* TODO add signature */
2546
2547   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: PATH ACK sent!\n");
2548   return sizeof (struct GNUNET_MESH_PathACK);
2549 }
2550
2551
2552 /******************************************************************************/
2553 /********************      MESH NETWORK HANDLERS     **************************/
2554 /******************************************************************************/
2555
2556
2557 /**
2558  * Core handler for path creation
2559  *
2560  * @param cls closure
2561  * @param message message
2562  * @param peer peer identity this notification is about
2563  * @param atsi performance data
2564  * @param atsi_count number of records in 'atsi'
2565  *
2566  * @return GNUNET_OK to keep the connection open,
2567  *         GNUNET_SYSERR to close it (signal serious error)
2568  */
2569 static int
2570 handle_mesh_path_create (void *cls, const struct GNUNET_PeerIdentity *peer,
2571                          const struct GNUNET_MessageHeader *message,
2572                          const struct GNUNET_ATS_Information *atsi,
2573                          unsigned int atsi_count)
2574 {
2575   unsigned int own_pos;
2576   uint16_t size;
2577   uint16_t i;
2578   MESH_TunnelNumber tid;
2579   struct GNUNET_MESH_ManipulatePath *msg;
2580   struct GNUNET_PeerIdentity *pi;
2581   GNUNET_HashCode hash;
2582   struct MeshPeerPath *path;
2583   struct MeshPeerInfo *dest_peer_info;
2584   struct MeshPeerInfo *orig_peer_info;
2585   struct MeshTunnel *t;
2586
2587   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2588               "MESH: Received a path create msg [%s]\n",
2589               GNUNET_i2s (&my_full_id));
2590   size = ntohs (message->size);
2591   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
2592   {
2593     GNUNET_break_op (0);
2594     return GNUNET_OK;
2595   }
2596
2597   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
2598   if (size % sizeof (struct GNUNET_PeerIdentity))
2599   {
2600     GNUNET_break_op (0);
2601     return GNUNET_OK;
2602   }
2603   size /= sizeof (struct GNUNET_PeerIdentity);
2604   if (size < 2)
2605   {
2606     GNUNET_break_op (0);
2607     return GNUNET_OK;
2608   }
2609   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:     path has %u hops.\n", size);
2610   msg = (struct GNUNET_MESH_ManipulatePath *) message;
2611
2612   tid = ntohl (msg->tid);
2613   pi = (struct GNUNET_PeerIdentity *) &msg[1];
2614   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2615               "MESH:     path is for tunnel %s [%X].\n", GNUNET_i2s (pi), tid);
2616   t = tunnel_get (pi, tid);
2617   if (NULL == t)
2618   {
2619     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   Creating tunnel\n");
2620     t = GNUNET_malloc (sizeof (struct MeshTunnel));
2621     t->id.oid = GNUNET_PEER_intern (pi);
2622     t->id.tid = tid;
2623     while (NULL != tunnel_get_incoming (next_local_tid))
2624       next_local_tid = (next_local_tid + 1) | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
2625     t->local_tid = next_local_tid++;
2626     next_local_tid = next_local_tid | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
2627     t->tree = tree_new (t->id.oid);
2628
2629     GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
2630     if (GNUNET_OK !=
2631         GNUNET_CONTAINER_multihashmap_put (tunnels, &hash, t,
2632                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2633     {
2634       tunnel_destroy (t);
2635       GNUNET_break (0);
2636       return GNUNET_OK;
2637     }
2638     tunnel_reset_timeout (t);
2639     GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
2640     if (GNUNET_OK !=
2641         GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
2642                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2643     {
2644       tunnel_destroy (t);
2645       GNUNET_break (0);
2646       return GNUNET_OK;
2647     }
2648   }
2649   dest_peer_info =
2650       GNUNET_CONTAINER_multihashmap_get (peers, &pi[size - 1].hashPubKey);
2651   if (NULL == dest_peer_info)
2652   {
2653     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2654                 "MESH:   Creating PeerInfo for destination.\n");
2655     dest_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
2656     dest_peer_info->id = GNUNET_PEER_intern (&pi[size - 1]);
2657     GNUNET_CONTAINER_multihashmap_put (peers, &pi[size - 1].hashPubKey,
2658                                        dest_peer_info,
2659                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2660   }
2661   orig_peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &pi->hashPubKey);
2662   if (NULL == orig_peer_info)
2663   {
2664     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2665                 "MESH:   Creating PeerInfo for origin.\n");
2666     orig_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
2667     orig_peer_info->id = GNUNET_PEER_intern (pi);
2668     GNUNET_CONTAINER_multihashmap_put (peers, &pi->hashPubKey, orig_peer_info,
2669                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2670   }
2671   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   Creating path...\n");
2672   path = path_new (size);
2673   own_pos = 0;
2674   for (i = 0; i < size; i++)
2675   {
2676     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   ... adding %s\n",
2677                 GNUNET_i2s (&pi[i]));
2678     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
2679     if (path->peers[i] == myid)
2680       own_pos = i;
2681   }
2682   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   Own position: %u\n", own_pos);
2683   if (own_pos == 0)
2684   {
2685     /* cannot be self, must be 'not found' */
2686     /* create path: self not found in path through self */
2687     GNUNET_break_op (0);
2688     path_destroy (path);
2689     /* FIXME error. destroy tunnel? leave for timeout? */
2690     return 0;
2691   }
2692   path_add_to_peers (path, GNUNET_NO);
2693   tunnel_add_path (t, path, own_pos);
2694   if (own_pos == size - 1)
2695   {
2696     /* It is for us! Send ack. */
2697     struct MeshTransmissionDescriptor *info;
2698     unsigned int j;
2699
2700     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   It's for us!\n");
2701     peer_info_add_path_to_origin (orig_peer_info, path, GNUNET_NO);
2702     if (NULL == t->peers)
2703     {
2704       /* New tunnel! Notify clients! */
2705       struct GNUNET_MESH_TunnelNotification cmsg;
2706
2707       cmsg.header.size = htons (sizeof (cmsg));
2708       cmsg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
2709       GNUNET_PEER_resolve (t->id.oid, &cmsg.peer);
2710       cmsg.tunnel_id = htonl (t->local_tid);
2711       GNUNET_SERVER_notification_context_broadcast (nc, &cmsg.header,
2712                                                     GNUNET_NO);
2713
2714       t->peers = GNUNET_CONTAINER_multihashmap_create (4);
2715     }
2716     GNUNET_break (GNUNET_OK ==
2717                   GNUNET_CONTAINER_multihashmap_put (t->peers,
2718                                                      &my_full_id.hashPubKey,
2719                                                      peer_info_get
2720                                                      (&my_full_id),
2721                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE));
2722     /* FIXME use send_message */
2723     info = GNUNET_malloc (sizeof (struct MeshTransmissionDescriptor));
2724     info->origin = &t->id;
2725     info->peer = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
2726     GNUNET_assert (NULL != info->peer);
2727     j = peer_info_transmit_slot (info->peer);
2728     info->handler_n = j;
2729     info->peer->types[j] = GNUNET_MESSAGE_TYPE_MESH_PATH_ACK;
2730     info->peer->infos[j] = info;
2731     info->peer->core_transmit[j] =
2732         GNUNET_CORE_notify_transmit_ready (core_handle, 0, 100,
2733                                            GNUNET_TIME_UNIT_FOREVER_REL, peer,
2734                                            sizeof (struct GNUNET_MESH_PathACK),
2735                                            &send_core_path_ack, info);
2736   }
2737   else
2738   {
2739     struct MeshPeerPath *path2;
2740
2741     /* It's for somebody else! Retransmit. */
2742     path2 = path_duplicate (path);
2743     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   Retransmitting.\n");
2744     peer_info_add_path (dest_peer_info, path2, GNUNET_NO);
2745     path2 = path_duplicate (path);
2746     peer_info_add_path_to_origin (orig_peer_info, path2, GNUNET_NO);
2747     send_create_path (dest_peer_info, path, t);
2748   }
2749   return GNUNET_OK;
2750 }
2751
2752
2753 /**
2754  * Core handler for path destruction
2755  *
2756  * @param cls closure
2757  * @param message message
2758  * @param peer peer identity this notification is about
2759  * @param atsi performance data
2760  * @param atsi_count number of records in 'atsi'
2761  *
2762  * @return GNUNET_OK to keep the connection open,
2763  *         GNUNET_SYSERR to close it (signal serious error)
2764  */
2765 static int
2766 handle_mesh_path_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
2767                           const struct GNUNET_MessageHeader *message,
2768                           const struct GNUNET_ATS_Information *atsi,
2769                           unsigned int atsi_count)
2770 {
2771   struct GNUNET_MESH_ManipulatePath *msg;
2772   struct GNUNET_PeerIdentity *pi;
2773   struct MeshPeerPath *path;
2774   struct MeshTunnel *t;
2775   unsigned int own_pos;
2776   unsigned int i;
2777   size_t size;
2778
2779   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2780               "MESH: Received a PATH DESTROY msg from %s\n", GNUNET_i2s (peer));
2781   size = ntohs (message->size);
2782   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
2783   {
2784     GNUNET_break_op (0);
2785     return GNUNET_OK;
2786   }
2787
2788   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
2789   if (size % sizeof (struct GNUNET_PeerIdentity))
2790   {
2791     GNUNET_break_op (0);
2792     return GNUNET_OK;
2793   }
2794   size /= sizeof (struct GNUNET_PeerIdentity);
2795   if (size < 2)
2796   {
2797     GNUNET_break_op (0);
2798     return GNUNET_OK;
2799   }
2800   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:     path has %u hops.\n", size);
2801
2802   msg = (struct GNUNET_MESH_ManipulatePath *) message;
2803   pi = (struct GNUNET_PeerIdentity *) &msg[1];
2804   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2805               "MESH:     path is for tunnel %s [%X].\n", GNUNET_i2s (pi),
2806               msg->tid);
2807   t = tunnel_get (pi, ntohl (msg->tid));
2808   if (NULL == t)
2809   {
2810     /* TODO notify back: we don't know this tunnel */
2811     GNUNET_break_op (0);
2812     return GNUNET_OK;
2813   }
2814   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   Creating path...\n");
2815   path = path_new (size);
2816   own_pos = 0;
2817   for (i = 0; i < size; i++)
2818   {
2819     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   ... adding %s\n",
2820                 GNUNET_i2s (&pi[i]));
2821     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
2822     if (path->peers[i] == myid)
2823       own_pos = i;
2824   }
2825   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   Own position: %u\n", own_pos);
2826   if (own_pos < path->length - 1)
2827     send_message (message, &pi[own_pos + 1]);
2828   tunnel_delete_peer (t, path->peers[path->length - 1]);
2829   path_destroy (path);
2830   return GNUNET_OK;
2831 }
2832
2833
2834 /**
2835  * Core handler for notifications of broken paths
2836  *
2837  * @param cls closure
2838  * @param message message
2839  * @param peer peer identity this notification is about
2840  * @param atsi performance data
2841  * @param atsi_count number of records in 'atsi'
2842  *
2843  * @return GNUNET_OK to keep the connection open,
2844  *         GNUNET_SYSERR to close it (signal serious error)
2845  */
2846 static int
2847 handle_mesh_path_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
2848                          const struct GNUNET_MessageHeader *message,
2849                          const struct GNUNET_ATS_Information *atsi,
2850                          unsigned int atsi_count)
2851 {
2852   struct GNUNET_MESH_PathBroken *msg;
2853   struct MeshTunnel *t;
2854
2855   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2856               "MESH: Received a PATH BROKEN msg from %s\n", GNUNET_i2s (peer));
2857   msg = (struct GNUNET_MESH_PathBroken *) message;
2858   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   regarding %s\n",
2859               GNUNET_i2s (&msg->peer1));
2860   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   regarding %s\n",
2861               GNUNET_i2s (&msg->peer2));
2862   t = tunnel_get (&msg->oid, ntohl (msg->tid));
2863   if (NULL == t)
2864   {
2865     GNUNET_break_op (0);
2866     return GNUNET_OK;
2867   }
2868   tunnel_notify_connection_broken (t, GNUNET_PEER_search (&msg->peer1),
2869                                    GNUNET_PEER_search (&msg->peer2));
2870   return GNUNET_OK;
2871
2872 }
2873
2874
2875 /**
2876  * Core handler for tunnel destruction
2877  *
2878  * @param cls closure
2879  * @param message message
2880  * @param peer peer identity this notification is about
2881  * @param atsi performance data
2882  * @param atsi_count number of records in 'atsi'
2883  *
2884  * @return GNUNET_OK to keep the connection open,
2885  *         GNUNET_SYSERR to close it (signal serious error)
2886  */
2887 static int
2888 handle_mesh_tunnel_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
2889                             const struct GNUNET_MessageHeader *message,
2890                             const struct GNUNET_ATS_Information *atsi,
2891                             unsigned int atsi_count)
2892 {
2893   struct GNUNET_MESH_TunnelDestroy *msg;
2894   struct MeshTunnel *t;
2895
2896   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2897               "MESH: Got a TUNNEL DESTROY packet from %s\n", GNUNET_i2s (peer));
2898   msg = (struct GNUNET_MESH_TunnelDestroy *) message;
2899   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   for tunnel %s [%u]\n",
2900               GNUNET_i2s (&msg->oid), ntohl (msg->tid));
2901   t = tunnel_get (&msg->oid, ntohl (msg->tid));
2902   if (NULL == t)
2903   {
2904     /* Probably already got the message from another path,
2905      * destroyed the tunnel and retransmitted to children.
2906      * Safe to ignore.
2907      */
2908     return GNUNET_OK;
2909   }
2910   if (t->id.oid == myid)
2911   {
2912     GNUNET_break_op (0);
2913     return GNUNET_OK;
2914   }
2915   if (t->local_tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
2916   {
2917     /* Tunnel was incoming, notify clients */
2918     send_clients_tunnel_destroy (t);
2919   }
2920   tunnel_send_destroy (t);
2921   tunnel_destroy (t);
2922   return GNUNET_OK;
2923 }
2924
2925
2926 /**
2927  * Core handler for mesh network traffic going from the origin to a peer
2928  *
2929  * @param cls closure
2930  * @param peer peer identity this notification is about
2931  * @param message message
2932  * @param atsi performance data
2933  * @param atsi_count number of records in 'atsi'
2934  * @return GNUNET_OK to keep the connection open,
2935  *         GNUNET_SYSERR to close it (signal serious error)
2936  */
2937 static int
2938 handle_mesh_data_unicast (void *cls, const struct GNUNET_PeerIdentity *peer,
2939                           const struct GNUNET_MessageHeader *message,
2940                           const struct GNUNET_ATS_Information *atsi,
2941                           unsigned int atsi_count)
2942 {
2943   struct GNUNET_MESH_Unicast *msg;
2944   struct MeshTunnel *t;
2945   GNUNET_PEER_Id pid;
2946   size_t size;
2947
2948   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: got a unicast packet from %s\n",
2949               GNUNET_i2s (peer));
2950   size = ntohs (message->size);
2951   if (size <
2952       sizeof (struct GNUNET_MESH_Unicast) +
2953       sizeof (struct GNUNET_MessageHeader))
2954   {
2955     GNUNET_break (0);
2956     return GNUNET_OK;
2957   }
2958   msg = (struct GNUNET_MESH_Unicast *) message;
2959   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  of type %u\n",
2960               ntohs (msg[1].header.type));
2961   t = tunnel_get (&msg->oid, ntohl (msg->tid));
2962   if (NULL == t)
2963   {
2964     /* TODO notify back: we don't know this tunnel */
2965     GNUNET_break_op (0);
2966     return GNUNET_OK;
2967   }
2968   tunnel_reset_timeout (t);
2969   pid = GNUNET_PEER_search (&msg->destination);
2970   if (pid == myid)
2971   {
2972     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2973                 "MESH:   it's for us! sending to clients...\n");
2974     send_subscribed_clients (message, (struct GNUNET_MessageHeader *) &msg[1]);
2975     return GNUNET_OK;
2976   }
2977   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2978               "MESH:   not for us, retransmitting...\n");
2979   send_message (message, tree_get_first_hop (t->tree, pid));
2980   return GNUNET_OK;
2981 }
2982
2983
2984 /**
2985  * Core handler for mesh network traffic going from the origin to all peers
2986  *
2987  * @param cls closure
2988  * @param message message
2989  * @param peer peer identity this notification is about
2990  * @param atsi performance data
2991  * @param atsi_count number of records in 'atsi'
2992  * @return GNUNET_OK to keep the connection open,
2993  *         GNUNET_SYSERR to close it (signal serious error)
2994  *
2995  * TODO: Check who we got this from, to validate route.
2996  */
2997 static int
2998 handle_mesh_data_multicast (void *cls, const struct GNUNET_PeerIdentity *peer,
2999                             const struct GNUNET_MessageHeader *message,
3000                             const struct GNUNET_ATS_Information *atsi,
3001                             unsigned int atsi_count)
3002 {
3003   struct GNUNET_MESH_Multicast *msg;
3004   struct MeshTunnel *t;
3005   size_t size;
3006
3007   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: got a multicast packet from %s\n",
3008               GNUNET_i2s (peer));
3009   size = ntohs (message->size);
3010   if (sizeof (struct GNUNET_MESH_Multicast) +
3011       sizeof (struct GNUNET_MessageHeader) > size)
3012   {
3013     GNUNET_break_op (0);
3014     return GNUNET_OK;
3015   }
3016   msg = (struct GNUNET_MESH_Multicast *) message;
3017   t = tunnel_get (&msg->oid, ntohl (msg->tid));
3018
3019   if (NULL == t)
3020   {
3021     /* TODO notify that we dont know that tunnel */
3022     GNUNET_break_op (0);
3023     return GNUNET_OK;
3024   }
3025   if (t->mid == ntohl (msg->mid))
3026   {
3027     /* FIXME: already seen this packet, log dropping */
3028     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3029                 "MESH:  Already seen mid %u, DROPPING!\n", t->mid);
3030     return GNUNET_OK;
3031   }
3032 #if MESH_DEBUG
3033   else
3034   {
3035     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3036                 "MESH:  mid %u not seen yet, forwarding\n", ntohl (msg->mid));
3037   }
3038 #endif
3039   t->mid = ntohl (msg->mid);
3040   tunnel_reset_timeout (t);
3041
3042   /* Transmit to locally interested clients */
3043   if (NULL != t->peers &&
3044       GNUNET_CONTAINER_multihashmap_contains (t->peers, &my_full_id.hashPubKey))
3045   {
3046     send_subscribed_clients (message, &msg[1].header);
3047   }
3048 #if MESH_DEBUG
3049   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    ttl: %u\n", ntohl (msg->ttl));
3050 #endif
3051   if (ntohl (msg->ttl) == 0)
3052   {
3053     /* FIXME: ttl is 0, log dropping */
3054     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "MESH:  TTL is 0, DROPPING!\n");
3055     return GNUNET_OK;
3056   }
3057   tunnel_send_multicast (t, message, GNUNET_NO);
3058   return GNUNET_OK;
3059 }
3060
3061
3062 /**
3063  * Core handler for mesh network traffic toward the owner of a tunnel
3064  *
3065  * @param cls closure
3066  * @param message message
3067  * @param peer peer identity this notification is about
3068  * @param atsi performance data
3069  * @param atsi_count number of records in 'atsi'
3070  *
3071  * @return GNUNET_OK to keep the connection open,
3072  *         GNUNET_SYSERR to close it (signal serious error)
3073  */
3074 static int
3075 handle_mesh_data_to_orig (void *cls, const struct GNUNET_PeerIdentity *peer,
3076                           const struct GNUNET_MessageHeader *message,
3077                           const struct GNUNET_ATS_Information *atsi,
3078                           unsigned int atsi_count)
3079 {
3080   struct GNUNET_MESH_ToOrigin *msg;
3081   struct GNUNET_PeerIdentity id;
3082   struct MeshPeerInfo *peer_info;
3083   struct MeshTunnel *t;
3084   size_t size;
3085
3086   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: got a ToOrigin packet from %s\n",
3087               GNUNET_i2s (peer));
3088   size = ntohs (message->size);
3089   if (size < sizeof (struct GNUNET_MESH_ToOrigin) +     /* Payload must be */
3090       sizeof (struct GNUNET_MessageHeader))     /* at least a header */
3091   {
3092     GNUNET_break_op (0);
3093     return GNUNET_OK;
3094   }
3095   msg = (struct GNUNET_MESH_ToOrigin *) message;
3096   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  of type %u\n",
3097               ntohs (msg[1].header.type));
3098   t = tunnel_get (&msg->oid, ntohl (msg->tid));
3099
3100   if (NULL == t)
3101   {
3102     /* TODO notify that we dont know this tunnel (whom)? */
3103     GNUNET_break_op (0);
3104     return GNUNET_OK;
3105   }
3106
3107   if (t->id.oid == myid)
3108   {
3109     char cbuf[size];
3110     struct GNUNET_MESH_ToOrigin *copy;
3111
3112     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3113                 "MESH:   it's for us! sending to clients...\n");
3114     if (NULL == t->client)
3115     {
3116       /* got data packet for ownerless tunnel */
3117       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   no clients!\n");
3118       GNUNET_break_op (0);
3119       return GNUNET_OK;
3120     }
3121     /* TODO signature verification */
3122     memcpy (cbuf, message, size);
3123     copy = (struct GNUNET_MESH_ToOrigin *) cbuf;
3124     copy->tid = htonl (t->local_tid);
3125     GNUNET_SERVER_notification_context_unicast (nc, t->client->handle,
3126                                                 &copy->header, GNUNET_YES);
3127     return GNUNET_OK;
3128   }
3129   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3130               "MESH:   not for us, retransmitting...\n");
3131
3132   peer_info = peer_info_get (&msg->oid);
3133   if (NULL == peer_info)
3134   {
3135     /* unknown origin of tunnel */
3136     GNUNET_break (0);
3137     return GNUNET_OK;
3138   }
3139   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
3140   send_message (message, &id);
3141
3142   return GNUNET_OK;
3143 }
3144
3145
3146 /**
3147  * Core handler for path ACKs
3148  *
3149  * @param cls closure
3150  * @param message message
3151  * @param peer peer identity this notification is about
3152  * @param atsi performance data
3153  * @param atsi_count number of records in 'atsi'
3154  *
3155  * @return GNUNET_OK to keep the connection open,
3156  *         GNUNET_SYSERR to close it (signal serious error)
3157  */
3158 static int
3159 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
3160                       const struct GNUNET_MessageHeader *message,
3161                       const struct GNUNET_ATS_Information *atsi,
3162                       unsigned int atsi_count)
3163 {
3164   struct GNUNET_MESH_PathACK *msg;
3165   struct GNUNET_PeerIdentity id;
3166   struct MeshPeerInfo *peer_info;
3167   struct MeshPeerPath *p;
3168   struct MeshTunnel *t;
3169
3170   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Received a path ACK msg [%s]\n",
3171               GNUNET_i2s (&my_full_id));
3172   msg = (struct GNUNET_MESH_PathACK *) message;
3173   t = tunnel_get (&msg->oid, msg->tid);
3174   if (NULL == t)
3175   {
3176     /* TODO notify that we don't know the tunnel */
3177     return GNUNET_OK;
3178   }
3179
3180   peer_info = peer_info_get (&msg->peer_id);
3181
3182   /* Add paths to peers? */
3183   p = tree_get_path_to_peer (t->tree, peer_info->id);
3184   if (NULL != p)
3185   {
3186     path_add_to_peers (p, GNUNET_YES);
3187     path_destroy (p);
3188   }
3189   else
3190   {
3191     GNUNET_break (0);
3192   }
3193
3194   /* Message for us? */
3195   if (0 == memcmp (&msg->oid, &my_full_id, sizeof (struct GNUNET_PeerIdentity)))
3196   {
3197     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   It's for us!\n");
3198     if (NULL == t->client)
3199     {
3200       GNUNET_break_op (0);
3201       return GNUNET_OK;
3202     }
3203     if (NULL != t->dht_get_type)
3204     {
3205       GNUNET_DHT_get_stop (t->dht_get_type);
3206       t->dht_get_type = NULL;
3207     }
3208     if (tree_get_status (t->tree, peer_info->id) != MESH_PEER_READY)
3209     {
3210       tree_set_status (t->tree, peer_info->id, MESH_PEER_READY);
3211       send_client_peer_connected (t, peer_info->id);
3212     }
3213     return GNUNET_OK;
3214   }
3215
3216   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3217               "MESH:   not for us, retransmitting...\n");
3218   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
3219   peer_info = peer_info_get (&msg->oid);
3220   if (NULL == peer_info)
3221   {
3222     /* If we know the tunnel, we should DEFINITELY know the peer */
3223     GNUNET_break (0);
3224     return GNUNET_OK;
3225   }
3226   send_message (message, &id);
3227   return GNUNET_OK;
3228 }
3229
3230
3231 /**
3232  * Functions to handle messages from core
3233  */
3234 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
3235   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
3236   {&handle_mesh_path_destroy, GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY, 0},
3237   {&handle_mesh_path_broken, GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN,
3238    sizeof (struct GNUNET_MESH_PathBroken)},
3239   {&handle_mesh_tunnel_destroy, GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY, 0},
3240   {&handle_mesh_data_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
3241   {&handle_mesh_data_multicast, GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
3242   {&handle_mesh_data_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
3243   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
3244    sizeof (struct GNUNET_MESH_PathACK)},
3245   {NULL, 0, 0}
3246 };
3247
3248
3249
3250 /******************************************************************************/
3251 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
3252 /******************************************************************************/
3253
3254 /**
3255  * deregister_app: iterator for removing each application registered by a client
3256  *
3257  * @param cls closure
3258  * @param key the hash of the application id (used to access the hashmap)
3259  * @param value the value stored at the key (client)
3260  *
3261  * @return GNUNET_OK on success
3262  */
3263 static int
3264 deregister_app (void *cls, const GNUNET_HashCode * key, void *value)
3265 {
3266   GNUNET_break (GNUNET_YES ==
3267                 GNUNET_CONTAINER_multihashmap_remove (applications, key,
3268                                                       value));
3269   return GNUNET_OK;
3270 }
3271
3272 #if LATER
3273 /**
3274  * notify_client_connection_failure: notify a client that the connection to the
3275  * requested remote peer is not possible (for instance, no route found)
3276  * Function called when the socket is ready to queue more data. "buf" will be
3277  * NULL and "size" zero if the socket was closed for writing in the meantime.
3278  *
3279  * @param cls closure
3280  * @param size number of bytes available in buf
3281  * @param buf where the callee should write the message
3282  * @return number of bytes written to buf
3283  */
3284 static size_t
3285 notify_client_connection_failure (void *cls, size_t size, void *buf)
3286 {
3287   int size_needed;
3288   struct MeshPeerInfo *peer_info;
3289   struct GNUNET_MESH_PeerControl *msg;
3290   struct GNUNET_PeerIdentity id;
3291
3292   if (0 == size && NULL == buf)
3293   {
3294     // TODO retry? cancel?
3295     return 0;
3296   }
3297
3298   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
3299   peer_info = (struct MeshPeerInfo *) cls;
3300   msg = (struct GNUNET_MESH_PeerControl *) buf;
3301   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
3302   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
3303 //     msg->tunnel_id = htonl(peer_info->t->tid);
3304   GNUNET_PEER_resolve (peer_info->id, &id);
3305   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
3306
3307   return size_needed;
3308 }
3309 #endif
3310
3311
3312 /**
3313  * Send keepalive packets for a peer
3314  *
3315  * @param cls Closure (tunnel for which to send the keepalive).
3316  * @param tc Notification context.
3317  *
3318  * TODO: implement explicit multicast keepalive?
3319  */
3320 static void
3321 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3322 {
3323   struct MeshTunnel *t = cls;
3324   struct GNUNET_MessageHeader *payload;
3325   struct GNUNET_MESH_Multicast *msg;
3326   size_t size =
3327       sizeof (struct GNUNET_MESH_Multicast) +
3328       sizeof (struct GNUNET_MessageHeader);
3329   char cbuf[size];
3330
3331   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3332   {
3333     return;
3334   }
3335   t->path_refresh_task = GNUNET_SCHEDULER_NO_TASK;
3336
3337   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3338               "MESH: sending keepalive for tunnel %d\n", t->id.tid);
3339
3340   msg = (struct GNUNET_MESH_Multicast *) cbuf;
3341   msg->header.size = htons (size);
3342   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
3343   msg->oid = my_full_id;
3344   msg->tid = htonl (t->id.tid);
3345   msg->ttl = htonl (DEFAULT_TTL);
3346   msg->mid = htonl (t->mid + 1);
3347   t->mid++;
3348   payload = (struct GNUNET_MessageHeader *) &msg[1];
3349   payload->size = htons (sizeof (struct GNUNET_MessageHeader));
3350   payload->type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE);
3351   tunnel_send_multicast (t, &msg->header, GNUNET_YES);
3352
3353   t->path_refresh_task =
3354       GNUNET_SCHEDULER_add_delayed (REFRESH_PATH_TIME, &path_refresh, t);
3355   return;
3356 }
3357
3358
3359 /**
3360  * Function to process paths received for a new peer addition. The recorded
3361  * paths form the initial tunnel, which can be optimized later.
3362  * Called on each result obtained for the DHT search.
3363  *
3364  * @param cls closure
3365  * @param exp when will this value expire
3366  * @param key key of the result
3367  * @param get_path path of the get request
3368  * @param get_path_length lenght of get_path
3369  * @param put_path path of the put request
3370  * @param put_path_length length of the put_path
3371  * @param type type of the result
3372  * @param size number of bytes in data
3373  * @param data pointer to the result data
3374  *
3375  * TODO: re-issue the request after certain time? cancel after X results?
3376  */
3377 static void
3378 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
3379                     const GNUNET_HashCode * key,
3380                     const struct GNUNET_PeerIdentity *get_path,
3381                     unsigned int get_path_length,
3382                     const struct GNUNET_PeerIdentity *put_path,
3383                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
3384                     size_t size, const void *data)
3385 {
3386   struct MeshPathInfo *path_info = cls;
3387   struct MeshPeerPath *p;
3388   struct GNUNET_PeerIdentity pi;
3389   int i;
3390
3391   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Got results from DHT!\n");
3392   GNUNET_PEER_resolve (path_info->peer->id, &pi);
3393   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   for %s\n", GNUNET_i2s (&pi));
3394
3395   p = path_build_from_dht (get_path, get_path_length, put_path,
3396                            put_path_length);
3397   path_add_to_peers (p, GNUNET_NO);
3398   path_destroy(p);
3399   for (i = 0; i < path_info->peer->ntunnels; i++)
3400   {
3401     tunnel_add_peer (path_info->peer->tunnels[i], path_info->peer);
3402     peer_info_connect (path_info->peer, path_info->t);
3403   }
3404
3405   return;
3406 }
3407
3408
3409 /**
3410  * Function to process paths received for a new peer addition. The recorded
3411  * paths form the initial tunnel, which can be optimized later.
3412  * Called on each result obtained for the DHT search.
3413  *
3414  * @param cls closure
3415  * @param exp when will this value expire
3416  * @param key key of the result
3417  * @param get_path path of the get request
3418  * @param get_path_length lenght of get_path
3419  * @param put_path path of the put request
3420  * @param put_path_length length of the put_path
3421  * @param type type of the result
3422  * @param size number of bytes in data
3423  * @param data pointer to the result data
3424  */
3425 static void
3426 dht_get_type_handler (void *cls, struct GNUNET_TIME_Absolute exp,
3427                       const GNUNET_HashCode * key,
3428                       const struct GNUNET_PeerIdentity *get_path,
3429                       unsigned int get_path_length,
3430                       const struct GNUNET_PeerIdentity *put_path,
3431                       unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
3432                       size_t size, const void *data)
3433 {
3434   const struct GNUNET_PeerIdentity *pi = data;
3435   struct MeshTunnel *t = cls;
3436   struct MeshPeerInfo *peer_info;
3437   struct MeshPeerPath *p;
3438
3439   if (size != sizeof (struct GNUNET_PeerIdentity))
3440   {
3441     GNUNET_break_op (0);
3442     return;
3443   }
3444   GNUNET_assert (NULL != t->client);
3445   peer_info = peer_info_get (pi);
3446   (void) GNUNET_CONTAINER_multihashmap_put (t->peers, &pi->hashPubKey,
3447                                             peer_info,
3448                                             GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
3449
3450   p = path_build_from_dht (get_path, get_path_length, put_path,
3451                            put_path_length);
3452   path_add_to_peers (p, GNUNET_NO);
3453   path_destroy(p);
3454   tunnel_add_peer (t, peer_info);
3455   peer_info_connect (peer_info, t);
3456 }
3457
3458
3459 /******************************************************************************/
3460 /*********************       MESH LOCAL HANDLES      **************************/
3461 /******************************************************************************/
3462
3463
3464 /**
3465  * Handler for client disconnection
3466  *
3467  * @param cls closure
3468  * @param client identification of the client; NULL
3469  *        for the last call when the server is destroyed
3470  */
3471 static void
3472 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
3473 {
3474   struct MeshClient *c;
3475   struct MeshClient *next;
3476
3477 #if MESH_DEBUG
3478   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: client disconnected\n");
3479 #endif
3480   if (client == NULL)
3481   {
3482     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    (SERVER DOWN)\n");
3483     return;
3484   }
3485   c = clients;
3486   while (NULL != c)
3487   {
3488     if (c->handle != client)
3489     {
3490 #if MESH_DEBUG
3491       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    ... searching\n");
3492 #endif
3493       c = c->next;
3494       continue;
3495     }
3496 #if MESH_DEBUG
3497     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: matching client found (%u)\n",
3498                 c->id);
3499 #endif
3500     GNUNET_SERVER_client_drop (c->handle);
3501     c->shutting_down = GNUNET_YES;
3502     if (NULL != c->tunnels)
3503     {
3504       GNUNET_CONTAINER_multihashmap_iterate (c->tunnels,
3505                                              &tunnel_destroy_iterator, c);
3506       GNUNET_CONTAINER_multihashmap_destroy (c->tunnels);
3507     }
3508
3509     /* deregister clients applications */
3510     if (NULL != c->apps)
3511     {
3512       GNUNET_CONTAINER_multihashmap_iterate (c->apps, &deregister_app, NULL);
3513       GNUNET_CONTAINER_multihashmap_destroy (c->apps);
3514     }
3515     if (0 == GNUNET_CONTAINER_multihashmap_size (applications) &&
3516         GNUNET_SCHEDULER_NO_TASK != announce_applications_task)
3517     {
3518       GNUNET_SCHEDULER_cancel (announce_applications_task);
3519       announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
3520     }
3521     if (NULL != c->types)
3522       GNUNET_CONTAINER_multihashmap_destroy (c->types);
3523     next = c->next;
3524     GNUNET_CONTAINER_DLL_remove (clients, clients_tail, c);
3525 #if MESH_DEBUG
3526     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   CLIENT FREE at %p\n", c);
3527 #endif
3528     GNUNET_free (c);
3529     c = next;
3530   }
3531
3532 #if MESH_DEBUG
3533   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    done!\n");
3534 #endif
3535   return;
3536 }
3537
3538
3539 /**
3540  * Handler for new clients
3541  *
3542  * @param cls closure
3543  * @param client identification of the client
3544  * @param message the actual message, which includes messages the client wants
3545  */
3546 static void
3547 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
3548                          const struct GNUNET_MessageHeader *message)
3549 {
3550   struct GNUNET_MESH_ClientConnect *cc_msg;
3551   struct MeshClient *c;
3552   GNUNET_MESH_ApplicationType *a;
3553   unsigned int size;
3554   uint16_t ntypes;
3555   uint16_t *t;
3556   uint16_t napps;
3557   uint16_t i;
3558
3559   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new client connected\n");
3560   /* Check data sanity */
3561   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
3562   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
3563   ntypes = ntohs (cc_msg->types);
3564   napps = ntohs (cc_msg->applications);
3565   if (size !=
3566       ntypes * sizeof (uint16_t) + napps * sizeof (GNUNET_MESH_ApplicationType))
3567   {
3568     GNUNET_break (0);
3569     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3570     return;
3571   }
3572
3573   /* Create new client structure */
3574   c = GNUNET_malloc (sizeof (struct MeshClient));
3575 #if MESH_DEBUG
3576   c->id = next_client_id++;
3577   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   CLIENT NEW %u\n", c->id);
3578 #endif
3579   c->handle = client;
3580   GNUNET_SERVER_client_keep (client);
3581   a = (GNUNET_MESH_ApplicationType *) &cc_msg[1];
3582   if (napps > 0)
3583   {
3584     GNUNET_MESH_ApplicationType at;
3585     GNUNET_HashCode hc;
3586
3587     c->apps = GNUNET_CONTAINER_multihashmap_create (napps);
3588     for (i = 0; i < napps; i++)
3589     {
3590       at = ntohl (a[i]);
3591 #if MESH_DEBUG
3592       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   app type: %u\n", at);
3593 #endif
3594       GNUNET_CRYPTO_hash (&at, sizeof (at), &hc);
3595       /* store in clients hashmap */
3596       GNUNET_CONTAINER_multihashmap_put (c->apps, &hc, c,
3597                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3598       /* store in global hashmap, for announcements */
3599       GNUNET_CONTAINER_multihashmap_put (applications, &hc, c,
3600                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3601     }
3602     if (GNUNET_SCHEDULER_NO_TASK == announce_applications_task)
3603       announce_applications_task =
3604           GNUNET_SCHEDULER_add_now (&announce_applications, NULL);
3605
3606   }
3607   if (ntypes > 0)
3608   {
3609     uint16_t u16;
3610     GNUNET_HashCode hc;
3611
3612     t = (uint16_t *) & a[napps];
3613     c->types = GNUNET_CONTAINER_multihashmap_create (ntypes);
3614     for (i = 0; i < ntypes; i++)
3615     {
3616       u16 = ntohs (t[i]);
3617 #if MESH_DEBUG
3618       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   msg type: %u\n", u16);
3619 #endif
3620       GNUNET_CRYPTO_hash (&u16, sizeof (u16), &hc);
3621
3622       /* store in clients hashmap */
3623       GNUNET_CONTAINER_multihashmap_put (c->types, &hc, c,
3624                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3625       /* store in global hashmap */
3626       GNUNET_CONTAINER_multihashmap_put (types, &hc, c,
3627                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3628     }
3629   }
3630   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3631               "MESH:  client has %u+%u subscriptions\n", napps, ntypes);
3632
3633   GNUNET_CONTAINER_DLL_insert (clients, clients_tail, c);
3634   c->tunnels = GNUNET_CONTAINER_multihashmap_create (32);
3635   GNUNET_SERVER_notification_context_add (nc, client);
3636
3637   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3638 #if MESH_DEBUG
3639   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new client processed\n");
3640 #endif
3641 }
3642
3643
3644 /**
3645  * Handler for requests of new tunnels
3646  *
3647  * @param cls closure
3648  * @param client identification of the client
3649  * @param message the actual message
3650  */
3651 static void
3652 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
3653                             const struct GNUNET_MessageHeader *message)
3654 {
3655   struct GNUNET_MESH_TunnelMessage *t_msg;
3656   struct MeshTunnel *t;
3657   struct MeshClient *c;
3658   GNUNET_HashCode hash;
3659
3660   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new tunnel requested\n");
3661
3662   /* Sanity check for client registration */
3663   if (NULL == (c = client_get (client)))
3664   {
3665     GNUNET_break (0);
3666     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3667     return;
3668   }
3669 #if MESH_DEBUG
3670   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   by client %u\n", c->id);
3671 #endif
3672
3673   /* Message sanity check */
3674   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
3675   {
3676     GNUNET_break (0);
3677     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3678     return;
3679   }
3680
3681   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
3682   /* Sanity check for tunnel numbering */
3683   if (0 == (ntohl (t_msg->tunnel_id) & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
3684   {
3685     GNUNET_break (0);
3686     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3687     return;
3688   }
3689   /* Sanity check for duplicate tunnel IDs */
3690   if (NULL != tunnel_get_by_local_id (c, ntohl (t_msg->tunnel_id)))
3691   {
3692     GNUNET_break (0);
3693     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3694     return;
3695   }
3696
3697   t = GNUNET_malloc (sizeof (struct MeshTunnel));
3698   while (NULL != tunnel_get_by_pi (myid, next_tid))
3699     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
3700   t->id.tid = next_tid++;
3701   next_tid = next_tid & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
3702   t->id.oid = myid;
3703   t->local_tid = ntohl (t_msg->tunnel_id);
3704 #if MESH_DEBUG
3705   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: CREATED TUNNEL %s [%x] (%x)\n",
3706               GNUNET_i2s (&my_full_id), t->id.tid, t->local_tid);
3707 #endif
3708   t->client = c;
3709   t->peers = GNUNET_CONTAINER_multihashmap_create (32);
3710
3711   GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
3712   if (GNUNET_OK !=
3713       GNUNET_CONTAINER_multihashmap_put (c->tunnels, &hash, t,
3714                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
3715   {
3716     GNUNET_break (0);
3717     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3718     return;
3719   }
3720
3721   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
3722   if (GNUNET_OK !=
3723       GNUNET_CONTAINER_multihashmap_put (tunnels, &hash, t,
3724                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
3725   {
3726     GNUNET_break (0);
3727     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3728     return;
3729   }
3730   t->tree = tree_new (myid);
3731
3732   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3733   return;
3734 }
3735
3736
3737 /**
3738  * Handler for requests of deleting tunnels
3739  *
3740  * @param cls closure
3741  * @param client identification of the client
3742  * @param message the actual message
3743  */
3744 static void
3745 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
3746                              const struct GNUNET_MessageHeader *message)
3747 {
3748   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
3749   struct MeshClient *c;
3750   struct MeshTunnel *t;
3751   MESH_TunnelNumber tid;
3752   GNUNET_HashCode hash;
3753
3754   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3755               "MESH: Got a DESTROY TUNNEL from client!\n");
3756
3757   /* Sanity check for client registration */
3758   if (NULL == (c = client_get (client)))
3759   {
3760     GNUNET_break (0);
3761     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3762     return;
3763   }
3764   /* Message sanity check */
3765   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
3766   {
3767     GNUNET_break (0);
3768     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3769     return;
3770   }
3771 #if MESH_DEBUG
3772   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   by client %u\n", c->id);
3773 #endif
3774   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
3775
3776   /* Retrieve tunnel */
3777   tid = ntohl (tunnel_msg->tunnel_id);
3778
3779   /* Remove from local id hashmap */
3780   GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
3781   t = GNUNET_CONTAINER_multihashmap_get (c->tunnels, &hash);
3782   send_client_tunnel_disconnect(t, c);
3783   GNUNET_assert (GNUNET_YES ==
3784                  GNUNET_CONTAINER_multihashmap_remove (c->tunnels, &hash, t));
3785
3786   t->client = NULL;
3787   tunnel_send_destroy (t);
3788   tunnel_destroy (t);
3789   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3790   return;
3791 }
3792
3793
3794 /**
3795  * Handler for connection requests to new peers
3796  *
3797  * @param cls closure
3798  * @param client identification of the client
3799  * @param message the actual message (PeerControl)
3800  */
3801 static void
3802 handle_local_connect_add (void *cls, struct GNUNET_SERVER_Client *client,
3803                           const struct GNUNET_MessageHeader *message)
3804 {
3805   struct GNUNET_MESH_PeerControl *peer_msg;
3806   struct MeshPeerInfo *peer_info;
3807   struct MeshClient *c;
3808   struct MeshTunnel *t;
3809   MESH_TunnelNumber tid;
3810
3811   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Got connection request\n");
3812   /* Sanity check for client registration */
3813   if (NULL == (c = client_get (client)))
3814   {
3815     GNUNET_break (0);
3816     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3817     return;
3818   }
3819
3820   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
3821   /* Sanity check for message size */
3822   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
3823   {
3824     GNUNET_break (0);
3825     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3826     return;
3827   }
3828
3829   /* Tunnel exists? */
3830   tid = ntohl (peer_msg->tunnel_id);
3831   t = tunnel_get_by_local_id (c, tid);
3832   if (NULL == t)
3833   {
3834     GNUNET_break (0);
3835     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3836     return;
3837   }
3838
3839   /* Does client own tunnel? */
3840   if (t->client->handle != client)
3841   {
3842     GNUNET_break (0);
3843     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3844     return;
3845   }
3846   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      for %s\n",
3847               GNUNET_i2s (&peer_msg->peer));
3848   peer_info = peer_info_get (&peer_msg->peer);
3849
3850   tunnel_add_peer (t, peer_info);
3851   peer_info_connect (peer_info, t);
3852
3853   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3854   return;
3855 }
3856
3857
3858 /**
3859  * Handler for disconnection requests of peers in a tunnel
3860  *
3861  * @param cls closure
3862  * @param client identification of the client
3863  * @param message the actual message (PeerControl)
3864  */
3865 static void
3866 handle_local_connect_del (void *cls, struct GNUNET_SERVER_Client *client,
3867                           const struct GNUNET_MessageHeader *message)
3868 {
3869   struct GNUNET_MESH_PeerControl *peer_msg;
3870   struct MeshPeerInfo *peer_info;
3871   struct MeshClient *c;
3872   struct MeshTunnel *t;
3873   MESH_TunnelNumber tid;
3874
3875   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Got a PEER DEL request\n");
3876   /* Sanity check for client registration */
3877   if (NULL == (c = client_get (client)))
3878   {
3879     GNUNET_break (0);
3880     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3881     return;
3882   }
3883   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
3884   /* Sanity check for message size */
3885   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
3886   {
3887     GNUNET_break (0);
3888     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3889     return;
3890   }
3891
3892   /* Tunnel exists? */
3893   tid = ntohl (peer_msg->tunnel_id);
3894   t = tunnel_get_by_local_id (c, tid);
3895   if (NULL == t)
3896   {
3897     GNUNET_break (0);
3898     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3899     return;
3900   }
3901   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   on tunnel %X\n", t->id.tid);
3902
3903   /* Does client own tunnel? */
3904   if (t->client->handle != client)
3905   {
3906     GNUNET_break (0);
3907     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3908     return;
3909   }
3910
3911   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   for peer %s\n",
3912               GNUNET_i2s (&peer_msg->peer));
3913   /* Is the peer in the tunnel? */
3914   peer_info =
3915       GNUNET_CONTAINER_multihashmap_get (t->peers, &peer_msg->peer.hashPubKey);
3916   if (NULL == peer_info)
3917   {
3918     GNUNET_break (0);
3919     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3920     return;
3921   }
3922
3923   /* Ok, delete peer from tunnel */
3924   GNUNET_CONTAINER_multihashmap_remove_all (t->peers,
3925                                             &peer_msg->peer.hashPubKey);
3926
3927   send_destroy_path (t, peer_info->id);
3928   tunnel_delete_peer (t, peer_info->id);
3929   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3930   return;
3931 }
3932
3933
3934 /**
3935  * Handler for connection requests to new peers by type
3936  *
3937  * @param cls closure
3938  * @param client identification of the client
3939  * @param message the actual message (ConnectPeerByType)
3940  */
3941 static void
3942 handle_local_connect_by_type (void *cls, struct GNUNET_SERVER_Client *client,
3943                               const struct GNUNET_MessageHeader *message)
3944 {
3945   struct GNUNET_MESH_ConnectPeerByType *connect_msg;
3946   struct MeshClient *c;
3947   struct MeshTunnel *t;
3948   GNUNET_HashCode hash;
3949   MESH_TunnelNumber tid;
3950
3951   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: got connect by type request\n");
3952   /* Sanity check for client registration */
3953   if (NULL == (c = client_get (client)))
3954   {
3955     GNUNET_break (0);
3956     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3957     return;
3958   }
3959
3960   connect_msg = (struct GNUNET_MESH_ConnectPeerByType *) message;
3961   /* Sanity check for message size */
3962   if (sizeof (struct GNUNET_MESH_ConnectPeerByType) !=
3963       ntohs (connect_msg->header.size))
3964   {
3965     GNUNET_break (0);
3966     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3967     return;
3968   }
3969
3970   /* Tunnel exists? */
3971   tid = ntohl (connect_msg->tunnel_id);
3972   t = tunnel_get_by_local_id (c, tid);
3973   if (NULL == t)
3974   {
3975     GNUNET_break (0);
3976     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3977     return;
3978   }
3979
3980   /* Does client own tunnel? */
3981   if (t->client->handle != client)
3982   {
3983     GNUNET_break (0);
3984     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3985     return;
3986   }
3987
3988   /* Do WE have the service? */
3989   t->type = ntohl (connect_msg->type);
3990   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  type requested: %u\n", t->type);
3991   GNUNET_CRYPTO_hash (&t->type, sizeof (GNUNET_MESH_ApplicationType), &hash);
3992   if (GNUNET_CONTAINER_multihashmap_contains (applications, &hash) ==
3993       GNUNET_YES)
3994   {
3995     /* Yes! Fast forward, add ourselves to the tunnel and send the
3996      * good news to the client, and alert the destination client of
3997      * an incoming tunnel.
3998      */
3999     struct GNUNET_MESH_TunnelNotification cmsg;
4000     struct MeshClient *c;
4001
4002     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  available locally\n");
4003     GNUNET_CONTAINER_multihashmap_put (t->peers, &my_full_id.hashPubKey,
4004                                        peer_info_get (&my_full_id),
4005                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
4006
4007     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  notifying client\n");
4008     send_client_peer_connected (t, myid);
4009     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  Done\n");
4010     GNUNET_SERVER_receive_done (client, GNUNET_OK);
4011
4012     /* FIXME implement a proper handling of this case,
4013        a client differentiation mechanism */
4014     cmsg.header.size = htons (sizeof (cmsg));
4015     cmsg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
4016     cmsg.peer = my_full_id;
4017     t->local_tid_dest = next_local_tid++;
4018     cmsg.tunnel_id = htonl (t->local_tid_dest);
4019     c = (struct MeshClient *) GNUNET_CONTAINER_multihashmap_get(applications,
4020                                                                 &hash);
4021     t->client_dest = c;
4022     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
4023     GNUNET_CONTAINER_multihashmap_put (c->tunnels, &hash, t,
4024                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
4025     GNUNET_SERVER_notification_context_unicast (nc, c->handle, &cmsg.header,
4026                                                 GNUNET_NO);
4027     
4028
4029     return;
4030   }
4031   /* Ok, lets find a peer offering the service */
4032   if (NULL != t->dht_get_type)
4033   {
4034     GNUNET_DHT_get_stop (t->dht_get_type);
4035   }
4036   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  looking in DHT for %s\n",
4037               GNUNET_h2s (&hash));
4038   t->dht_get_type =
4039       GNUNET_DHT_get_start (dht_handle, GNUNET_TIME_UNIT_FOREVER_REL,
4040                             GNUNET_BLOCK_TYPE_TEST, &hash, 10U,
4041                             GNUNET_DHT_RO_RECORD_ROUTE |
4042                             GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE, NULL, 0,
4043                             &dht_get_type_handler, t);
4044
4045   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4046   return;
4047 }
4048
4049
4050 /**
4051  * Handler for client traffic directed to one peer
4052  *
4053  * @param cls closure
4054  * @param client identification of the client
4055  * @param message the actual message
4056  */
4057 static void
4058 handle_local_unicast (void *cls, struct GNUNET_SERVER_Client *client,
4059                       const struct GNUNET_MessageHeader *message)
4060 {
4061   struct MeshClient *c;
4062   struct MeshTunnel *t;
4063   struct MeshPeerInfo *pi;
4064   struct GNUNET_MESH_Unicast *data_msg;
4065   MESH_TunnelNumber tid;
4066   size_t size;
4067
4068   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4069               "MESH: Got a unicast request from a client!\n");
4070
4071   /* Sanity check for client registration */
4072   if (NULL == (c = client_get (client)))
4073   {
4074     GNUNET_break (0);
4075     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4076     return;
4077   }
4078   data_msg = (struct GNUNET_MESH_Unicast *) message;
4079   /* Sanity check for message size */
4080   size = ntohs (message->size);
4081   if (sizeof (struct GNUNET_MESH_Unicast) +
4082       sizeof (struct GNUNET_MessageHeader) > size)
4083   {
4084     GNUNET_break (0);
4085     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4086     return;
4087   }
4088
4089   /* Tunnel exists? */
4090   tid = ntohl (data_msg->tid);
4091   t = tunnel_get_by_local_id (c, tid);
4092   if (NULL == t)
4093   {
4094     GNUNET_break (0);
4095     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4096     return;
4097   }
4098
4099   /*  Is it a local tunnel? Then, does client own the tunnel? */
4100   if (NULL != t->client && NULL != t->client->handle &&
4101       t->client->handle != client)
4102   {
4103     GNUNET_break (0);
4104     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4105     return;
4106   }
4107
4108   pi = GNUNET_CONTAINER_multihashmap_get (t->peers,
4109                                           &data_msg->destination.hashPubKey);
4110   /* Is the selected peer in the tunnel? */
4111   if (NULL == pi)
4112   {
4113     GNUNET_break (0);
4114     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4115     return;
4116   }
4117
4118   /* Ok, everything is correct, send the message
4119    * (pretend we got it from a mesh peer)
4120    */
4121   {
4122     char buf[ntohs (message->size)];
4123     struct GNUNET_MESH_Unicast *copy;
4124
4125     /* Work around const limitation */
4126     copy = (struct GNUNET_MESH_Unicast *) buf;
4127     memcpy (buf, data_msg, size);
4128     copy->oid = my_full_id;
4129     copy->tid = htonl (t->id.tid);
4130     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4131                 "MESH:   calling generic handler...\n");
4132     handle_mesh_data_unicast (NULL, &my_full_id, &copy->header, NULL, 0);
4133   }
4134   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4135   return;
4136 }
4137
4138
4139 /**
4140  * Handler for client traffic directed to the origin
4141  *
4142  * @param cls closure
4143  * @param client identification of the client
4144  * @param message the actual message
4145  */
4146 static void
4147 handle_local_to_origin (void *cls, struct GNUNET_SERVER_Client *client,
4148                         const struct GNUNET_MessageHeader *message)
4149 {
4150   struct GNUNET_MESH_ToOrigin *data_msg;
4151   struct GNUNET_PeerIdentity id;
4152   struct MeshClient *c;
4153   struct MeshTunnel *t;
4154   MESH_TunnelNumber tid;
4155   size_t size;
4156
4157   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4158               "MESH: Got a ToOrigin request from a client!\n");
4159
4160   /* Sanity check for client registration */
4161   if (NULL == (c = client_get (client)))
4162   {
4163     GNUNET_break (0);
4164     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4165     return;
4166   }
4167   data_msg = (struct GNUNET_MESH_ToOrigin *) message;
4168   /* Sanity check for message size */
4169   size = ntohs (message->size);
4170   if (sizeof (struct GNUNET_MESH_ToOrigin) +
4171       sizeof (struct GNUNET_MessageHeader) > size)
4172   {
4173     GNUNET_break (0);
4174     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4175     return;
4176   }
4177
4178   /* Tunnel exists? */
4179   tid = ntohl (data_msg->tid);
4180   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
4181   {
4182     GNUNET_break (0);
4183     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4184     return;
4185   }
4186   t = tunnel_get_by_local_id (c, tid);
4187   if (NULL == t)
4188   {
4189     GNUNET_break (0);
4190     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4191     return;
4192   }
4193
4194   /*  It shouldn't be a local tunnel.  */
4195   if (NULL != t->client)
4196   {
4197     GNUNET_break (0);
4198     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4199     return;
4200   }
4201   GNUNET_PEER_resolve (t->id.oid, &id);
4202
4203   /* Ok, everything is correct, send the message
4204    * (pretend we got it from a mesh peer)
4205    */
4206   {
4207     char buf[ntohs (message->size)];
4208     struct GNUNET_MESH_ToOrigin *copy;
4209
4210     /* Work around const limitation */
4211     copy = (struct GNUNET_MESH_ToOrigin *) buf;
4212     memcpy (buf, data_msg, size);
4213     copy->oid = id;
4214     copy->tid = htonl (t->id.tid);
4215     copy->sender = my_full_id;
4216     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4217                 "MESH:   calling generic handler...\n");
4218     handle_mesh_data_to_orig (NULL, &my_full_id, &copy->header, NULL, 0);
4219   }
4220   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4221   return;
4222 }
4223
4224
4225 /**
4226  * Handler for client traffic directed to all peers in a tunnel
4227  *
4228  * @param cls closure
4229  * @param client identification of the client
4230  * @param message the actual message
4231  */
4232 static void
4233 handle_local_multicast (void *cls, struct GNUNET_SERVER_Client *client,
4234                         const struct GNUNET_MessageHeader *message)
4235 {
4236   struct MeshClient *c;
4237   struct MeshTunnel *t;
4238   struct GNUNET_MESH_Multicast *data_msg;
4239   MESH_TunnelNumber tid;
4240
4241   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4242               "MESH: Got a multicast request from a client!\n");
4243
4244   /* Sanity check for client registration */
4245   if (NULL == (c = client_get (client)))
4246   {
4247     GNUNET_break (0);
4248     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4249     return;
4250   }
4251   data_msg = (struct GNUNET_MESH_Multicast *) message;
4252   /* Sanity check for message size */
4253   if (sizeof (struct GNUNET_MESH_Multicast) +
4254       sizeof (struct GNUNET_MessageHeader) > ntohs (data_msg->header.size))
4255   {
4256     GNUNET_break (0);
4257     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4258     return;
4259   }
4260
4261   /* Tunnel exists? */
4262   tid = ntohl (data_msg->tid);
4263   t = tunnel_get_by_local_id (c, tid);
4264   if (NULL == t)
4265   {
4266     GNUNET_break (0);
4267     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4268     return;
4269   }
4270
4271   /* Does client own tunnel? */
4272   if (t->client->handle != client)
4273   {
4274     GNUNET_break (0);
4275     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4276     return;
4277   }
4278
4279   {
4280     char buf[ntohs (message->size)];
4281     struct GNUNET_MESH_Multicast *copy;
4282
4283     copy = (struct GNUNET_MESH_Multicast *) buf;
4284     memcpy (buf, message, ntohs (message->size));
4285     copy->oid = my_full_id;
4286     copy->tid = htonl (t->id.tid);
4287     copy->ttl = htonl (DEFAULT_TTL);
4288     copy->mid = htonl (t->mid + 1);
4289     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4290                 "MESH:   calling generic handler...\n");
4291     handle_mesh_data_multicast (client, &my_full_id, &copy->header, NULL, 0);
4292   }
4293
4294   /* receive done gets called when last copy is sent to a neighbor */
4295   return;
4296 }
4297
4298 /**
4299  * Functions to handle messages from clients
4300  */
4301 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
4302   {&handle_local_new_client, NULL,
4303    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
4304   {&handle_local_tunnel_create, NULL,
4305    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
4306    sizeof (struct GNUNET_MESH_TunnelMessage)},
4307   {&handle_local_tunnel_destroy, NULL,
4308    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
4309    sizeof (struct GNUNET_MESH_TunnelMessage)},
4310   {&handle_local_connect_add, NULL,
4311    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD,
4312    sizeof (struct GNUNET_MESH_PeerControl)},
4313   {&handle_local_connect_del, NULL,
4314    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL,
4315    sizeof (struct GNUNET_MESH_PeerControl)},
4316   {&handle_local_connect_by_type, NULL,
4317    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE,
4318    sizeof (struct GNUNET_MESH_ConnectPeerByType)},
4319   {&handle_local_unicast, NULL,
4320    GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
4321   {&handle_local_to_origin, NULL,
4322    GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
4323   {&handle_local_multicast, NULL,
4324    GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
4325   {NULL, NULL, 0, 0}
4326 };
4327
4328
4329 /**
4330  * To be called on core init/fail.
4331  *
4332  * @param cls service closure
4333  * @param server handle to the server for this service
4334  * @param identity the public identity of this peer
4335  */
4336 static void
4337 core_init (void *cls, struct GNUNET_CORE_Handle *server,
4338            const struct GNUNET_PeerIdentity *identity)
4339 {
4340   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Core init\n");
4341   core_handle = server;
4342   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)) ||
4343       NULL == server)
4344   {
4345     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("MESH: Wrong CORE service\n"));
4346     GNUNET_SCHEDULER_shutdown ();
4347   }
4348   return;
4349 }
4350
4351 /**
4352  * Method called whenever a given peer connects.
4353  *
4354  * @param cls closure
4355  * @param peer peer identity this notification is about
4356  * @param atsi performance data for the connection
4357  * @param atsi_count number of records in 'atsi'
4358  */
4359 static void
4360 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
4361               const struct GNUNET_ATS_Information *atsi,
4362               unsigned int atsi_count)
4363 {
4364   struct MeshPeerInfo *peer_info;
4365   struct MeshPeerPath *path;
4366
4367 #if MESH_DEBUG_CONNECTION
4368   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Peer connected\n");
4369   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      %s\n",
4370               GNUNET_i2s (&my_full_id));
4371 #endif
4372   peer_info = peer_info_get (peer);
4373   if (myid == peer_info->id)
4374   {
4375 #if MESH_DEBUG_CONNECTION
4376     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      (self)\n");
4377 #endif
4378     return;
4379   }
4380 #if MESH_DEBUG_CONNECTION
4381   else
4382   {
4383     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      %s\n", GNUNET_i2s (peer));
4384   }
4385 #endif
4386   path = path_new (2);
4387   path->peers[0] = myid;
4388   path->peers[1] = peer_info->id;
4389   GNUNET_PEER_change_rc (myid, 1);
4390   GNUNET_PEER_change_rc (peer_info->id, 1);
4391   peer_info_add_path (peer_info, path, GNUNET_YES);
4392   return;
4393 }
4394
4395 /**
4396  * Method called whenever a peer disconnects.
4397  *
4398  * @param cls closure
4399  * @param peer peer identity this notification is about
4400  */
4401 static void
4402 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
4403 {
4404   struct MeshPeerInfo *pi;
4405   unsigned int i;
4406
4407 #if MESH_DEBUG_CONNECTION
4408   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Peer disconnected\n");
4409 #endif
4410   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
4411   if (NULL == pi)
4412   {
4413     GNUNET_break (0);
4414     return;
4415   }
4416   for (i = 0; i < CORE_QUEUE_SIZE; i++)
4417   {
4418     /* TODO: notify that the transmission failed */
4419     peer_info_cancel_transmission (pi, i);
4420   }
4421   peer_info_remove_path (pi, pi->id, myid);
4422 #if MESH_DEBUG_CONNECTION
4423   if (myid == pi->id)
4424   {
4425     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      (self)\n");
4426   }
4427 #endif
4428   return;
4429 }
4430
4431
4432 /******************************************************************************/
4433 /************************      MAIN FUNCTIONS      ****************************/
4434 /******************************************************************************/
4435
4436 /**
4437  * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
4438  *
4439  * @param cls closure
4440  * @param key current key code
4441  * @param value value in the hash map
4442  * @return GNUNET_YES if we should continue to iterate,
4443  *         GNUNET_NO if not.
4444  */
4445 static int
4446 shutdown_tunnel (void *cls, const GNUNET_HashCode * key, void *value)
4447 {
4448   struct MeshTunnel *t = value;
4449
4450   tunnel_destroy (t);
4451   return GNUNET_YES;
4452 }
4453
4454 /**
4455  * Iterator over peer hash map entries to destroy the tunnel during shutdown.
4456  *
4457  * @param cls closure
4458  * @param key current key code
4459  * @param value value in the hash map
4460  * @return GNUNET_YES if we should continue to iterate,
4461  *         GNUNET_NO if not.
4462  */
4463 static int
4464 shutdown_peer (void *cls, const GNUNET_HashCode * key, void *value)
4465 {
4466   struct MeshPeerInfo *p = value;
4467
4468   peer_info_destroy (p);
4469   return GNUNET_YES;
4470 }
4471
4472 /**
4473  * Task run during shutdown.
4474  *
4475  * @param cls unused
4476  * @param tc unused
4477  */
4478 static void
4479 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4480 {
4481   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: shutting down\n");
4482
4483   if (core_handle != NULL)
4484   {
4485     GNUNET_CORE_disconnect (core_handle);
4486     core_handle = NULL;
4487   }
4488   GNUNET_CONTAINER_multihashmap_iterate (tunnels, &shutdown_tunnel, NULL);
4489   GNUNET_CONTAINER_multihashmap_iterate (peers, &shutdown_peer, NULL);
4490   if (dht_handle != NULL)
4491   {
4492     GNUNET_DHT_disconnect (dht_handle);
4493     dht_handle = NULL;
4494   }
4495   if (nc != NULL)
4496   {
4497     GNUNET_SERVER_notification_context_destroy (nc);
4498     nc = NULL;
4499   }
4500   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
4501   {
4502     GNUNET_SCHEDULER_cancel (announce_id_task);
4503     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
4504   }
4505   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: shut down\n");
4506 }
4507
4508 /**
4509  * Process mesh requests.
4510  *
4511  * @param cls closure
4512  * @param server the initialized server
4513  * @param c configuration to use
4514  */
4515 static void
4516 run (void *cls, struct GNUNET_SERVER_Handle *server,
4517      const struct GNUNET_CONFIGURATION_Handle *c)
4518 {
4519   struct MeshPeerInfo *peer;
4520   struct MeshPeerPath *p;
4521   char *keyfile;
4522
4523   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: starting to run\n");
4524   server_handle = server;
4525   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
4526                                      CORE_QUEUE_SIZE,   /* queue size */
4527                                      NULL,      /* Closure passed to MESH functions */
4528                                      &core_init,        /* Call core_init once connected */
4529                                      &core_connect,     /* Handle connects */
4530                                      &core_disconnect,  /* remove peers on disconnects */
4531                                      NULL,      /* Don't notify about all incoming messages */
4532                                      GNUNET_NO, /* For header only in notification */
4533                                      NULL,      /* Don't notify about all outbound messages */
4534                                      GNUNET_NO, /* For header-only out notification */
4535                                      core_handlers);    /* Register these handlers */
4536
4537   if (core_handle == NULL)
4538   {
4539     GNUNET_break (0);
4540     GNUNET_SCHEDULER_shutdown ();
4541     return;
4542   }
4543
4544   if (GNUNET_OK !=
4545       GNUNET_CONFIGURATION_get_value_filename (c, "GNUNETD", "HOSTKEY",
4546                                                &keyfile))
4547   {
4548     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4549                 _
4550                 ("Mesh service is lacking key configuration settings.  Exiting.\n"));
4551     GNUNET_SCHEDULER_shutdown ();
4552     return;
4553   }
4554   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
4555   GNUNET_free (keyfile);
4556   if (my_private_key == NULL)
4557   {
4558     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4559                 _("Mesh service could not access hostkey.  Exiting.\n"));
4560     GNUNET_SCHEDULER_shutdown ();
4561     return;
4562   }
4563   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
4564   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
4565                       &my_full_id.hashPubKey);
4566   myid = GNUNET_PEER_intern (&my_full_id);
4567
4568 // //   transport_handle = GNUNET_TRANSPORT_connect(c,
4569 // //                                               &my_full_id,
4570 // //                                               NULL,
4571 // //                                               NULL,
4572 // //                                               NULL,
4573 // //                                               NULL);
4574
4575   dht_handle = GNUNET_DHT_connect (c, 64);
4576   if (dht_handle == NULL)
4577   {
4578     GNUNET_break (0);
4579   }
4580
4581   next_tid = 0;
4582   next_local_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
4583
4584   tunnels = GNUNET_CONTAINER_multihashmap_create (32);
4585   incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
4586   peers = GNUNET_CONTAINER_multihashmap_create (32);
4587   applications = GNUNET_CONTAINER_multihashmap_create (32);
4588   types = GNUNET_CONTAINER_multihashmap_create (32);
4589
4590   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
4591   nc = GNUNET_SERVER_notification_context_create (server_handle,
4592                                                   LOCAL_QUEUE_SIZE);
4593   GNUNET_SERVER_disconnect_notify (server_handle,
4594                                    &handle_local_client_disconnect, NULL);
4595
4596
4597   clients = NULL;
4598   clients_tail = NULL;
4599 #if MESH_DEBUG
4600   next_client_id = 0;
4601 #endif
4602
4603   announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
4604   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
4605
4606   /* Create a peer_info for the local peer */
4607   peer = peer_info_get (&my_full_id);
4608   p = path_new (1);
4609   p->peers[0] = myid;
4610   GNUNET_PEER_change_rc (myid, 1);
4611   peer_info_add_path (peer, p, GNUNET_YES);
4612
4613   /* Scheduled the task to clean up when shutdown is called */
4614   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
4615                                 NULL);
4616
4617   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: end of run()\n");
4618 }
4619
4620 /**
4621  * The main function for the mesh service.
4622  *
4623  * @param argc number of arguments from the command line
4624  * @param argv command line arguments
4625  * @return 0 ok, 1 on error
4626  */
4627 int
4628 main (int argc, char *const *argv)
4629 {
4630   int ret;
4631
4632   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: main()\n");
4633   ret =
4634       (GNUNET_OK ==
4635        GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
4636                            NULL)) ? 0 : 1;
4637   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: main() END\n");
4638
4639   return ret;
4640 }