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