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