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