Fixed #2087, wrong local tunnel number sent when multiple clients are subscribed...
[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  */
2109 static void
2110 tunnel_send_multicast (struct MeshTunnel *t,
2111                        const struct GNUNET_MessageHeader *msg)
2112 {
2113   struct MeshData *mdata;
2114
2115 #if MESH_DEBUG
2116   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2117               "MESH:  sending a multicast packet...\n");
2118 #endif
2119   mdata = GNUNET_malloc (sizeof (struct MeshData));
2120   mdata->data_len = ntohs (msg->size);
2121   mdata->reference_counter = GNUNET_malloc (sizeof (unsigned int));
2122   mdata->t = t;
2123   mdata->data = GNUNET_malloc (mdata->data_len);
2124   memcpy (mdata->data, msg, mdata->data_len);
2125   if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_MESH_MULTICAST)
2126   {
2127     struct GNUNET_MESH_Multicast *mcast;
2128
2129     mcast = (struct GNUNET_MESH_Multicast *) mdata->data;
2130     mcast->ttl = htonl (ntohl (mcast->ttl) - 1);
2131 #if MESH_DEBUG
2132     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   data packet, ttl: %u\n",
2133                 ntohl (mcast->ttl));
2134   }
2135   else
2136   {
2137     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   not a data packet, no ttl\n");
2138 #endif
2139   }
2140   if (NULL != t->client && GNUNET_YES != t->client->shutting_down)
2141   {
2142     mdata->task = GNUNET_malloc (sizeof (GNUNET_SCHEDULER_TaskIdentifier));
2143     (*(mdata->task)) =
2144         GNUNET_SCHEDULER_add_delayed (UNACKNOWLEDGED_WAIT, &client_allow_send,
2145                                       mdata);
2146     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: timeout task %u\n",
2147                 *(mdata->task));
2148   }
2149
2150   tree_iterate_children (t->tree, &tunnel_send_multicast_iterator, mdata);
2151   if (*(mdata->reference_counter) == 0)
2152   {
2153     GNUNET_free (mdata->data);
2154     GNUNET_free (mdata->reference_counter);
2155     if (NULL != mdata->task)
2156     {
2157       GNUNET_SCHEDULER_cancel(*(mdata->task));
2158       GNUNET_free (mdata->task);
2159       GNUNET_SERVER_receive_done(t->client->handle, GNUNET_OK);
2160     }
2161     // FIXME change order?
2162     GNUNET_free (mdata);
2163   }
2164 #if MESH_DEBUG
2165   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2166               "MESH:  sending a multicast packet done\n");
2167 #endif
2168   return;
2169 }
2170
2171
2172 /**
2173  * Send a message to all peers in this tunnel that the tunnel is no longer
2174  * valid.
2175  *
2176  * @param t The tunnel whose peers to notify.
2177  */
2178 static void
2179 tunnel_send_destroy (struct MeshTunnel *t)
2180 {
2181   struct GNUNET_MESH_TunnelDestroy msg;
2182
2183   msg.header.size = htons (sizeof (msg));
2184   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY);
2185   GNUNET_PEER_resolve (t->id.oid, &msg.oid);
2186   msg.tid = htonl (t->id.tid);
2187   tunnel_send_multicast (t, &msg.header);
2188 }
2189
2190
2191
2192 /**
2193  * Destroy the tunnel and free any allocated resources linked to it
2194  *
2195  * @param t the tunnel to destroy
2196  *
2197  * @return GNUNET_OK on success
2198  */
2199 static int
2200 tunnel_destroy (struct MeshTunnel *t)
2201 {
2202   struct MeshClient *c;
2203   struct MeshQueue *q;
2204   struct MeshQueue *qn;
2205   GNUNET_HashCode hash;
2206   int r;
2207
2208   if (NULL == t)
2209     return GNUNET_OK;
2210
2211   r = GNUNET_OK;
2212   c = t->client;
2213 #if MESH_DEBUG
2214   {
2215     struct GNUNET_PeerIdentity id;
2216
2217     GNUNET_PEER_resolve (t->id.oid, &id);
2218     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: destroying tunnel %s [%x]\n",
2219                 GNUNET_i2s (&id), t->id.tid);
2220     if (NULL != c)
2221       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   by client %u\n", c->id);
2222   }
2223 #endif
2224
2225   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
2226   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &hash, t))
2227   {
2228     r = GNUNET_SYSERR;
2229   }
2230   
2231   GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
2232   if (NULL != c &&
2233       GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (c->tunnels, &hash, t))
2234   {
2235     r = GNUNET_SYSERR;
2236   }
2237   c = t->client_dest;
2238   GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
2239   if (NULL != c &&
2240       GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (c->tunnels, &hash, t))
2241   {
2242     r = GNUNET_SYSERR;
2243   }
2244   if (t->local_tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
2245   {
2246     GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
2247     GNUNET_break (GNUNET_YES ==
2248                   GNUNET_CONTAINER_multihashmap_remove (incoming_tunnels, &hash,
2249                                                         t));
2250   }
2251   if (NULL != t->peers)
2252   {
2253     GNUNET_CONTAINER_multihashmap_iterate (t->peers, &peer_info_delete_tunnel,
2254                                            t);
2255     GNUNET_CONTAINER_multihashmap_destroy (t->peers);
2256   }
2257   q = t->queue_head;
2258   while (NULL != q)
2259   {
2260     if (NULL != q->data)
2261       GNUNET_free (q->data);
2262     qn = q->next;
2263     GNUNET_free (q);
2264     q = qn;
2265     /* TODO cancel core transmit ready in case it was active */
2266   }
2267   tree_destroy (t->tree);
2268   if (NULL != t->dht_get_type)
2269     GNUNET_DHT_get_stop (t->dht_get_type);
2270   if (GNUNET_SCHEDULER_NO_TASK != t->timeout_task)
2271     GNUNET_SCHEDULER_cancel (t->timeout_task);
2272   if (GNUNET_SCHEDULER_NO_TASK != t->path_refresh_task)
2273     GNUNET_SCHEDULER_cancel (t->path_refresh_task);
2274   GNUNET_free (t);
2275   return r;
2276 }
2277
2278
2279 /**
2280  * Removes an explicit path from a tunnel, freeing all intermediate nodes
2281  * that are no longer needed, as well as nodes of no longer reachable peers.
2282  * The tunnel itself is also destoyed if results in a remote empty tunnel.
2283  *
2284  * @param t Tunnel from which to remove the path.
2285  * @param peer Short id of the peer which should be removed.
2286  */
2287 static void
2288 tunnel_delete_peer (struct MeshTunnel *t, GNUNET_PEER_Id peer)
2289 {
2290   if (GNUNET_NO == tree_del_peer (t->tree, peer, NULL, NULL))
2291     tunnel_destroy (t);
2292 }
2293
2294
2295 /**
2296  * tunnel_destroy_iterator: iterator for deleting each tunnel that belongs to a
2297  * client when the client disconnects.
2298  *
2299  * @param cls closure (client that is disconnecting)
2300  * @param key the hash of the local tunnel id (used to access the hashmap)
2301  * @param value the value stored at the key (tunnel to destroy)
2302  *
2303  * @return GNUNET_OK on success
2304  */
2305 static int
2306 tunnel_destroy_iterator (void *cls, const GNUNET_HashCode * key, void *value)
2307 {
2308   struct MeshTunnel *t = value;
2309   struct MeshClient *c = cls;
2310   int r;
2311
2312   send_client_tunnel_disconnect(t, c);
2313   if (c == t->client_dest)
2314   {
2315 #if MESH_DEBUG
2316     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2317                 "Client %u is destination, keeping the tunnel alive.\n", c->id);
2318 #endif
2319     t->client_dest = NULL;
2320     t->local_tid_dest = 0;
2321     return GNUNET_OK;
2322   }
2323   tunnel_send_destroy(t);
2324   r = tunnel_destroy (t);
2325   return r;
2326 }
2327
2328
2329 /**
2330  * Timeout function, destroys tunnel if called
2331  *
2332  * @param cls Closure (tunnel to destroy).
2333  * @param tc TaskContext
2334  */
2335 static void
2336 tunnel_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2337 {
2338   struct MeshTunnel *t = cls;
2339
2340   if (GNUNET_SCHEDULER_REASON_SHUTDOWN == tc->reason)
2341     return;
2342   t->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2343   tunnel_destroy (t);
2344 }
2345
2346 /**
2347  * Resets the tunnel timeout. Starts it if no timeout was running.
2348  *
2349  * @param t Tunnel whose timeout to reset.
2350  */
2351 static void
2352 tunnel_reset_timeout (struct MeshTunnel *t)
2353 {
2354   if (GNUNET_SCHEDULER_NO_TASK != t->timeout_task)
2355     GNUNET_SCHEDULER_cancel (t->timeout_task);
2356   t->timeout_task =
2357       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
2358                                     (REFRESH_PATH_TIME, 4), &tunnel_timeout, t);
2359 }
2360
2361
2362 /******************************************************************************/
2363 /****************      MESH NETWORK HANDLER HELPERS     ***********************/
2364 /******************************************************************************/
2365
2366 /**
2367  * Function called to notify a client about the socket
2368  * being ready to queue more data.  "buf" will be
2369  * NULL and "size" zero if the socket was closed for
2370  * writing in the meantime.
2371  *
2372  * @param cls closure
2373  * @param size number of bytes available in buf
2374  * @param buf where the callee should write the message
2375  * @return number of bytes written to buf
2376  */
2377 static size_t
2378 send_core_create_path (void *cls, size_t size, void *buf)
2379 {
2380   struct MeshPathInfo *info = cls;
2381   struct GNUNET_MESH_ManipulatePath *msg;
2382   struct GNUNET_PeerIdentity *peer_ptr;
2383   struct MeshPeerInfo *peer = info->peer;
2384   struct MeshTunnel *t = info->t;
2385   struct MeshPeerPath *p = info->path;
2386   size_t size_needed;
2387   int i;
2388
2389   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: CREATE PATH sending...\n");
2390   size_needed =
2391       sizeof (struct GNUNET_MESH_ManipulatePath) +
2392       p->length * sizeof (struct GNUNET_PeerIdentity);
2393
2394   if (size < size_needed || NULL == buf)
2395   {
2396     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: create path retransmit!\n");
2397     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   buf:  %p\n", buf);
2398     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   size: (%u/%u)\n", size,
2399                 size_needed);
2400     info->peer->core_transmit[info->pos] =
2401         GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
2402                                            GNUNET_TIME_UNIT_FOREVER_REL,
2403                                            tree_get_first_hop (t->tree,
2404                                                                peer->id),
2405                                            size_needed, &send_core_create_path,
2406                                            info);
2407     return 0;
2408   }
2409   info->peer->core_transmit[info->pos] = NULL;
2410 #if MESH_DEBUG
2411   {
2412     struct GNUNET_PeerIdentity id;
2413
2414     GNUNET_PEER_resolve (peer->id, &id);
2415     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2416                 "MESH:   setting core_transmit %s [%u] to NULL\n",
2417                 GNUNET_i2s (&id), info->pos);
2418   }
2419 #endif
2420   msg = (struct GNUNET_MESH_ManipulatePath *) buf;
2421   msg->header.size = htons (size_needed);
2422   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE);
2423   msg->tid = ntohl (t->id.tid);
2424
2425   peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
2426   for (i = 0; i < p->length; i++)
2427   {
2428     GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
2429   }
2430
2431   path_destroy (p);
2432   GNUNET_free (info);
2433
2434   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2435               "MESH: CREATE PATH (%u bytes long) sent!\n", size_needed);
2436   return size_needed;
2437 }
2438
2439
2440 /**
2441  * Function called to notify a client about the socket
2442  * being ready to queue more data.  "buf" will be
2443  * NULL and "size" zero if the socket was closed for
2444  * writing in the meantime.
2445  *
2446  * @param cls closure (data itself)
2447  * @param size number of bytes available in buf
2448  * @param buf where the callee should write the message
2449  *
2450  * @return number of bytes written to buf
2451  */
2452 static size_t
2453 send_core_data_multicast (void *cls, size_t size, void *buf)
2454 {
2455   struct MeshTransmissionDescriptor *info = cls;
2456   size_t total_size;
2457
2458   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Multicast callback.\n");
2459   GNUNET_assert (NULL != info);
2460   GNUNET_assert (NULL != info->peer);
2461   total_size = info->mesh_data->data_len;
2462   GNUNET_assert (total_size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
2463
2464   if (total_size > size)
2465   {
2466     /* Retry */
2467     struct GNUNET_PeerIdentity id;
2468
2469     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2470                 "MESH: Multicast: retransmitting... (%u/%u)\n", size,
2471                 total_size);
2472     GNUNET_PEER_resolve (info->peer->id, &id);
2473     info->peer->core_transmit[info->handler_n] =
2474         GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
2475                                            GNUNET_TIME_UNIT_FOREVER_REL, &id,
2476                                            total_size,
2477                                            &send_core_data_multicast, info);
2478     return 0;
2479   }
2480   info->peer->core_transmit[info->handler_n] = NULL;
2481   info->peer->infos[info->handler_n] = NULL;
2482   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  copying data...\n");
2483   memcpy (buf, info->mesh_data->data, total_size);
2484 #if MESH_DEBUG
2485   {
2486     struct GNUNET_MESH_Multicast *mc;
2487     struct GNUNET_MessageHeader *mh;
2488
2489     mh = buf;
2490     if (ntohs (mh->type) == GNUNET_MESSAGE_TYPE_MESH_MULTICAST)
2491     {
2492       mc = (struct GNUNET_MESH_Multicast *) mh;
2493       mh = (struct GNUNET_MessageHeader *) &mc[1];
2494       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2495                   "MESH:  multicast, payload type %u\n", ntohs (mh->type));
2496       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2497                   "MESH:  multicast, payload size %u\n", ntohs (mh->size));
2498     }
2499     else
2500     {
2501       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  type %u\n",
2502                   ntohs (mh->type));
2503     }
2504   }
2505 #endif
2506   data_descriptor_decrement_multicast (info->mesh_data);
2507   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: freeing info...\n");
2508   GNUNET_free (info);
2509   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: return %u\n", total_size);
2510   return total_size;
2511 }
2512
2513
2514 /**
2515  * Function called to notify a client about the socket
2516  * being ready to queue more data.  "buf" will be
2517  * NULL and "size" zero if the socket was closed for
2518  * writing in the meantime.
2519  *
2520  * @param cls closure (MeshTransmissionDescriptor)
2521  * @param size number of bytes available in buf
2522  * @param buf where the callee should write the message
2523  * @return number of bytes written to buf
2524  */
2525 static size_t
2526 send_core_path_ack (void *cls, size_t size, void *buf)
2527 {
2528   struct MeshTransmissionDescriptor *info = cls;
2529   struct GNUNET_MESH_PathACK *msg = buf;
2530
2531   GNUNET_assert (NULL != info);
2532   if (info->peer)
2533   {
2534     info->peer->core_transmit[info->handler_n] = NULL;
2535   }
2536   if (sizeof (struct GNUNET_MESH_PathACK) > size)
2537   {
2538     GNUNET_break (0);
2539     return 0;
2540   }
2541   msg->header.size = htons (sizeof (struct GNUNET_MESH_PathACK));
2542   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_ACK);
2543   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
2544   msg->tid = htonl (info->origin->tid);
2545   msg->peer_id = my_full_id;
2546   GNUNET_free (info);
2547   /* TODO add signature */
2548
2549   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: PATH ACK sent!\n");
2550   return sizeof (struct GNUNET_MESH_PathACK);
2551 }
2552
2553
2554 /******************************************************************************/
2555 /********************      MESH NETWORK HANDLERS     **************************/
2556 /******************************************************************************/
2557
2558
2559 /**
2560  * Core handler for path creation
2561  *
2562  * @param cls closure
2563  * @param message message
2564  * @param peer peer identity this notification is about
2565  * @param atsi performance data
2566  * @param atsi_count number of records in 'atsi'
2567  *
2568  * @return GNUNET_OK to keep the connection open,
2569  *         GNUNET_SYSERR to close it (signal serious error)
2570  */
2571 static int
2572 handle_mesh_path_create (void *cls, const struct GNUNET_PeerIdentity *peer,
2573                          const struct GNUNET_MessageHeader *message,
2574                          const struct GNUNET_ATS_Information *atsi,
2575                          unsigned int atsi_count)
2576 {
2577   unsigned int own_pos;
2578   uint16_t size;
2579   uint16_t i;
2580   MESH_TunnelNumber tid;
2581   struct GNUNET_MESH_ManipulatePath *msg;
2582   struct GNUNET_PeerIdentity *pi;
2583   GNUNET_HashCode hash;
2584   struct MeshPeerPath *path;
2585   struct MeshPeerInfo *dest_peer_info;
2586   struct MeshPeerInfo *orig_peer_info;
2587   struct MeshTunnel *t;
2588
2589   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2590               "MESH: Received a path create msg [%s]\n",
2591               GNUNET_i2s (&my_full_id));
2592   size = ntohs (message->size);
2593   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
2594   {
2595     GNUNET_break_op (0);
2596     return GNUNET_OK;
2597   }
2598
2599   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
2600   if (size % sizeof (struct GNUNET_PeerIdentity))
2601   {
2602     GNUNET_break_op (0);
2603     return GNUNET_OK;
2604   }
2605   size /= sizeof (struct GNUNET_PeerIdentity);
2606   if (size < 2)
2607   {
2608     GNUNET_break_op (0);
2609     return GNUNET_OK;
2610   }
2611   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:     path has %u hops.\n", size);
2612   msg = (struct GNUNET_MESH_ManipulatePath *) message;
2613
2614   tid = ntohl (msg->tid);
2615   pi = (struct GNUNET_PeerIdentity *) &msg[1];
2616   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2617               "MESH:     path is for tunnel %s [%X].\n", GNUNET_i2s (pi), tid);
2618   t = tunnel_get (pi, tid);
2619   if (NULL == t)
2620   {
2621     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   Creating tunnel\n");
2622     t = GNUNET_malloc (sizeof (struct MeshTunnel));
2623     t->id.oid = GNUNET_PEER_intern (pi);
2624     t->id.tid = tid;
2625     while (NULL != tunnel_get_incoming (next_local_tid))
2626       next_local_tid = (next_local_tid + 1) | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
2627     t->local_tid = next_local_tid++;
2628     next_local_tid = next_local_tid | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
2629     t->tree = tree_new (t->id.oid);
2630
2631     GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
2632     if (GNUNET_OK !=
2633         GNUNET_CONTAINER_multihashmap_put (tunnels, &hash, t,
2634                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2635     {
2636       tunnel_destroy (t);
2637       GNUNET_break (0);
2638       return GNUNET_OK;
2639     }
2640     tunnel_reset_timeout (t);
2641     GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
2642     if (GNUNET_OK !=
2643         GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
2644                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2645     {
2646       tunnel_destroy (t);
2647       GNUNET_break (0);
2648       return GNUNET_OK;
2649     }
2650   }
2651   dest_peer_info =
2652       GNUNET_CONTAINER_multihashmap_get (peers, &pi[size - 1].hashPubKey);
2653   if (NULL == dest_peer_info)
2654   {
2655     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2656                 "MESH:   Creating PeerInfo for destination.\n");
2657     dest_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
2658     dest_peer_info->id = GNUNET_PEER_intern (&pi[size - 1]);
2659     GNUNET_CONTAINER_multihashmap_put (peers, &pi[size - 1].hashPubKey,
2660                                        dest_peer_info,
2661                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2662   }
2663   orig_peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &pi->hashPubKey);
2664   if (NULL == orig_peer_info)
2665   {
2666     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2667                 "MESH:   Creating PeerInfo for origin.\n");
2668     orig_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
2669     orig_peer_info->id = GNUNET_PEER_intern (pi);
2670     GNUNET_CONTAINER_multihashmap_put (peers, &pi->hashPubKey, orig_peer_info,
2671                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2672   }
2673   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   Creating path...\n");
2674   path = path_new (size);
2675   own_pos = 0;
2676   for (i = 0; i < size; i++)
2677   {
2678     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   ... adding %s\n",
2679                 GNUNET_i2s (&pi[i]));
2680     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
2681     if (path->peers[i] == myid)
2682       own_pos = i;
2683   }
2684   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   Own position: %u\n", own_pos);
2685   if (own_pos == 0)
2686   {
2687     /* cannot be self, must be 'not found' */
2688     /* create path: self not found in path through self */
2689     GNUNET_break_op (0);
2690     path_destroy (path);
2691     /* FIXME error. destroy tunnel? leave for timeout? */
2692     return 0;
2693   }
2694   path_add_to_peers (path, GNUNET_NO);
2695   tunnel_add_path (t, path, own_pos);
2696   if (own_pos == size - 1)
2697   {
2698     /* It is for us! Send ack. */
2699     struct MeshTransmissionDescriptor *info;
2700     unsigned int j;
2701
2702     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   It's for us!\n");
2703     peer_info_add_path_to_origin (orig_peer_info, path, GNUNET_NO);
2704     if (NULL == t->peers)
2705     {
2706       /* New tunnel! Notify clients! */
2707       struct GNUNET_MESH_TunnelNotification cmsg;
2708
2709       cmsg.header.size = htons (sizeof (cmsg));
2710       cmsg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
2711       GNUNET_PEER_resolve (t->id.oid, &cmsg.peer);
2712       cmsg.tunnel_id = htonl (t->local_tid);
2713       GNUNET_SERVER_notification_context_broadcast (nc, &cmsg.header,
2714                                                     GNUNET_NO);
2715
2716       t->peers = GNUNET_CONTAINER_multihashmap_create (4);
2717     }
2718     GNUNET_break (GNUNET_OK ==
2719                   GNUNET_CONTAINER_multihashmap_put (t->peers,
2720                                                      &my_full_id.hashPubKey,
2721                                                      peer_info_get
2722                                                      (&my_full_id),
2723                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE));
2724     /* FIXME use send_message */
2725     info = GNUNET_malloc (sizeof (struct MeshTransmissionDescriptor));
2726     info->origin = &t->id;
2727     info->peer = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
2728     GNUNET_assert (NULL != info->peer);
2729     j = peer_info_transmit_slot (info->peer);
2730     info->handler_n = j;
2731     info->peer->types[j] = GNUNET_MESSAGE_TYPE_MESH_PATH_ACK;
2732     info->peer->infos[j] = info;
2733     info->peer->core_transmit[j] =
2734         GNUNET_CORE_notify_transmit_ready (core_handle, 0, 100,
2735                                            GNUNET_TIME_UNIT_FOREVER_REL, peer,
2736                                            sizeof (struct GNUNET_MESH_PathACK),
2737                                            &send_core_path_ack, info);
2738   }
2739   else
2740   {
2741     struct MeshPeerPath *path2;
2742
2743     /* It's for somebody else! Retransmit. */
2744     path2 = path_duplicate (path);
2745     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   Retransmitting.\n");
2746     peer_info_add_path (dest_peer_info, path2, GNUNET_NO);
2747     path2 = path_duplicate (path);
2748     peer_info_add_path_to_origin (orig_peer_info, path2, GNUNET_NO);
2749     send_create_path (dest_peer_info, path, t);
2750   }
2751   return GNUNET_OK;
2752 }
2753
2754
2755 /**
2756  * Core handler for path destruction
2757  *
2758  * @param cls closure
2759  * @param message message
2760  * @param peer peer identity this notification is about
2761  * @param atsi performance data
2762  * @param atsi_count number of records in 'atsi'
2763  *
2764  * @return GNUNET_OK to keep the connection open,
2765  *         GNUNET_SYSERR to close it (signal serious error)
2766  */
2767 static int
2768 handle_mesh_path_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
2769                           const struct GNUNET_MessageHeader *message,
2770                           const struct GNUNET_ATS_Information *atsi,
2771                           unsigned int atsi_count)
2772 {
2773   struct GNUNET_MESH_ManipulatePath *msg;
2774   struct GNUNET_PeerIdentity *pi;
2775   struct MeshPeerPath *path;
2776   struct MeshTunnel *t;
2777   unsigned int own_pos;
2778   unsigned int i;
2779   size_t size;
2780
2781   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2782               "MESH: Received a PATH DESTROY msg from %s\n", GNUNET_i2s (peer));
2783   size = ntohs (message->size);
2784   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
2785   {
2786     GNUNET_break_op (0);
2787     return GNUNET_OK;
2788   }
2789
2790   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
2791   if (size % sizeof (struct GNUNET_PeerIdentity))
2792   {
2793     GNUNET_break_op (0);
2794     return GNUNET_OK;
2795   }
2796   size /= sizeof (struct GNUNET_PeerIdentity);
2797   if (size < 2)
2798   {
2799     GNUNET_break_op (0);
2800     return GNUNET_OK;
2801   }
2802   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:     path has %u hops.\n", size);
2803
2804   msg = (struct GNUNET_MESH_ManipulatePath *) message;
2805   pi = (struct GNUNET_PeerIdentity *) &msg[1];
2806   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2807               "MESH:     path is for tunnel %s [%X].\n", GNUNET_i2s (pi),
2808               msg->tid);
2809   t = tunnel_get (pi, ntohl (msg->tid));
2810   if (NULL == t)
2811   {
2812     /* TODO notify back: we don't know this tunnel */
2813     GNUNET_break_op (0);
2814     return GNUNET_OK;
2815   }
2816   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   Creating path...\n");
2817   path = path_new (size);
2818   own_pos = 0;
2819   for (i = 0; i < size; i++)
2820   {
2821     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   ... adding %s\n",
2822                 GNUNET_i2s (&pi[i]));
2823     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
2824     if (path->peers[i] == myid)
2825       own_pos = i;
2826   }
2827   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   Own position: %u\n", own_pos);
2828   if (own_pos < path->length - 1)
2829     send_message (message, &pi[own_pos + 1]);
2830   tunnel_delete_peer (t, path->peers[path->length - 1]);
2831   path_destroy (path);
2832   return GNUNET_OK;
2833 }
2834
2835
2836 /**
2837  * Core handler for notifications of broken paths
2838  *
2839  * @param cls closure
2840  * @param message message
2841  * @param peer peer identity this notification is about
2842  * @param atsi performance data
2843  * @param atsi_count number of records in 'atsi'
2844  *
2845  * @return GNUNET_OK to keep the connection open,
2846  *         GNUNET_SYSERR to close it (signal serious error)
2847  */
2848 static int
2849 handle_mesh_path_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
2850                          const struct GNUNET_MessageHeader *message,
2851                          const struct GNUNET_ATS_Information *atsi,
2852                          unsigned int atsi_count)
2853 {
2854   struct GNUNET_MESH_PathBroken *msg;
2855   struct MeshTunnel *t;
2856
2857   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2858               "MESH: Received a PATH BROKEN msg from %s\n", GNUNET_i2s (peer));
2859   msg = (struct GNUNET_MESH_PathBroken *) message;
2860   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   regarding %s\n",
2861               GNUNET_i2s (&msg->peer1));
2862   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   regarding %s\n",
2863               GNUNET_i2s (&msg->peer2));
2864   t = tunnel_get (&msg->oid, ntohl (msg->tid));
2865   if (NULL == t)
2866   {
2867     GNUNET_break_op (0);
2868     return GNUNET_OK;
2869   }
2870   tunnel_notify_connection_broken (t, GNUNET_PEER_search (&msg->peer1),
2871                                    GNUNET_PEER_search (&msg->peer2));
2872   return GNUNET_OK;
2873
2874 }
2875
2876
2877 /**
2878  * Core handler for tunnel destruction
2879  *
2880  * @param cls closure
2881  * @param message message
2882  * @param peer peer identity this notification is about
2883  * @param atsi performance data
2884  * @param atsi_count number of records in 'atsi'
2885  *
2886  * @return GNUNET_OK to keep the connection open,
2887  *         GNUNET_SYSERR to close it (signal serious error)
2888  */
2889 static int
2890 handle_mesh_tunnel_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
2891                             const struct GNUNET_MessageHeader *message,
2892                             const struct GNUNET_ATS_Information *atsi,
2893                             unsigned int atsi_count)
2894 {
2895   struct GNUNET_MESH_TunnelDestroy *msg;
2896   struct MeshTunnel *t;
2897
2898   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2899               "MESH: Got a TUNNEL DESTROY packet from %s\n", GNUNET_i2s (peer));
2900   msg = (struct GNUNET_MESH_TunnelDestroy *) message;
2901   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   for tunnel %s [%u]\n",
2902               GNUNET_i2s (&msg->oid), ntohl (msg->tid));
2903   t = tunnel_get (&msg->oid, ntohl (msg->tid));
2904   if (NULL == t)
2905   {
2906     /* Probably already got the message from another path,
2907      * destroyed the tunnel and retransmitted to children.
2908      * Safe to ignore.
2909      */
2910     return GNUNET_OK;
2911   }
2912   if (t->id.oid == myid)
2913   {
2914     GNUNET_break_op (0);
2915     return GNUNET_OK;
2916   }
2917   if (t->local_tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
2918   {
2919     /* Tunnel was incoming, notify clients */
2920     send_clients_tunnel_destroy (t);
2921   }
2922   tunnel_send_destroy (t);
2923   tunnel_destroy (t);
2924   return GNUNET_OK;
2925 }
2926
2927
2928 /**
2929  * Core handler for mesh network traffic going from the origin to a peer
2930  *
2931  * @param cls closure
2932  * @param peer peer identity this notification is about
2933  * @param message message
2934  * @param atsi performance data
2935  * @param atsi_count number of records in 'atsi'
2936  * @return GNUNET_OK to keep the connection open,
2937  *         GNUNET_SYSERR to close it (signal serious error)
2938  */
2939 static int
2940 handle_mesh_data_unicast (void *cls, const struct GNUNET_PeerIdentity *peer,
2941                           const struct GNUNET_MessageHeader *message,
2942                           const struct GNUNET_ATS_Information *atsi,
2943                           unsigned int atsi_count)
2944 {
2945   struct GNUNET_MESH_Unicast *msg;
2946   struct MeshTunnel *t;
2947   GNUNET_PEER_Id pid;
2948   size_t size;
2949
2950   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: got a unicast packet from %s\n",
2951               GNUNET_i2s (peer));
2952   size = ntohs (message->size);
2953   if (size <
2954       sizeof (struct GNUNET_MESH_Unicast) +
2955       sizeof (struct GNUNET_MessageHeader))
2956   {
2957     GNUNET_break (0);
2958     return GNUNET_OK;
2959   }
2960   msg = (struct GNUNET_MESH_Unicast *) message;
2961   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  of type %u\n",
2962               ntohs (msg[1].header.type));
2963   t = tunnel_get (&msg->oid, ntohl (msg->tid));
2964   if (NULL == t)
2965   {
2966     /* TODO notify back: we don't know this tunnel */
2967     GNUNET_break_op (0);
2968     return GNUNET_OK;
2969   }
2970   tunnel_reset_timeout (t);
2971   pid = GNUNET_PEER_search (&msg->destination);
2972   if (pid == myid)
2973   {
2974     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2975                 "MESH:   it's for us! sending to clients...\n");
2976     send_subscribed_clients (message, (struct GNUNET_MessageHeader *) &msg[1]);
2977     return GNUNET_OK;
2978   }
2979   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2980               "MESH:   not for us, retransmitting...\n");
2981   send_message (message, tree_get_first_hop (t->tree, pid));
2982   return GNUNET_OK;
2983 }
2984
2985
2986 /**
2987  * Core handler for mesh network traffic going from the origin to all peers
2988  *
2989  * @param cls closure
2990  * @param message message
2991  * @param peer peer identity this notification is about
2992  * @param atsi performance data
2993  * @param atsi_count number of records in 'atsi'
2994  * @return GNUNET_OK to keep the connection open,
2995  *         GNUNET_SYSERR to close it (signal serious error)
2996  *
2997  * TODO: Check who we got this from, to validate route.
2998  */
2999 static int
3000 handle_mesh_data_multicast (void *cls, const struct GNUNET_PeerIdentity *peer,
3001                             const struct GNUNET_MessageHeader *message,
3002                             const struct GNUNET_ATS_Information *atsi,
3003                             unsigned int atsi_count)
3004 {
3005   struct GNUNET_MESH_Multicast *msg;
3006   struct MeshTunnel *t;
3007   size_t size;
3008
3009   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: got a multicast packet from %s\n",
3010               GNUNET_i2s (peer));
3011   size = ntohs (message->size);
3012   if (sizeof (struct GNUNET_MESH_Multicast) +
3013       sizeof (struct GNUNET_MessageHeader) > size)
3014   {
3015     GNUNET_break_op (0);
3016     return GNUNET_OK;
3017   }
3018   msg = (struct GNUNET_MESH_Multicast *) message;
3019   t = tunnel_get (&msg->oid, ntohl (msg->tid));
3020
3021   if (NULL == t)
3022   {
3023     /* TODO notify that we dont know that tunnel */
3024     GNUNET_break_op (0);
3025     return GNUNET_OK;
3026   }
3027   if (t->mid == ntohl (msg->mid))
3028   {
3029     /* FIXME: already seen this packet, log dropping */
3030     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3031                 "MESH:  Already seen mid %u, DROPPING!\n", t->mid);
3032     return GNUNET_OK;
3033   }
3034 #if MESH_DEBUG
3035   else
3036   {
3037     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3038                 "MESH:  mid %u not seen yet, forwarding\n", ntohl (msg->mid));
3039   }
3040 #endif
3041   t->mid = ntohl (msg->mid);
3042   tunnel_reset_timeout (t);
3043
3044   /* Transmit to locally interested clients */
3045   if (NULL != t->peers &&
3046       GNUNET_CONTAINER_multihashmap_contains (t->peers, &my_full_id.hashPubKey))
3047   {
3048     send_subscribed_clients (message, &msg[1].header);
3049   }
3050 #if MESH_DEBUG
3051   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    ttl: %u\n", ntohl (msg->ttl));
3052 #endif
3053   if (ntohl (msg->ttl) == 0)
3054   {
3055     /* FIXME: ttl is 0, log dropping */
3056     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "MESH:  TTL is 0, DROPPING!\n");
3057     return GNUNET_OK;
3058   }
3059   tunnel_send_multicast (t, message);
3060   return GNUNET_OK;
3061 }
3062
3063
3064 /**
3065  * Core handler for mesh network traffic toward the owner of a tunnel
3066  *
3067  * @param cls closure
3068  * @param message message
3069  * @param peer peer identity this notification is about
3070  * @param atsi performance data
3071  * @param atsi_count number of records in 'atsi'
3072  *
3073  * @return GNUNET_OK to keep the connection open,
3074  *         GNUNET_SYSERR to close it (signal serious error)
3075  */
3076 static int
3077 handle_mesh_data_to_orig (void *cls, const struct GNUNET_PeerIdentity *peer,
3078                           const struct GNUNET_MessageHeader *message,
3079                           const struct GNUNET_ATS_Information *atsi,
3080                           unsigned int atsi_count)
3081 {
3082   struct GNUNET_MESH_ToOrigin *msg;
3083   struct GNUNET_PeerIdentity id;
3084   struct MeshPeerInfo *peer_info;
3085   struct MeshTunnel *t;
3086   size_t size;
3087
3088   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: got a ToOrigin packet from %s\n",
3089               GNUNET_i2s (peer));
3090   size = ntohs (message->size);
3091   if (size < sizeof (struct GNUNET_MESH_ToOrigin) +     /* Payload must be */
3092       sizeof (struct GNUNET_MessageHeader))     /* at least a header */
3093   {
3094     GNUNET_break_op (0);
3095     return GNUNET_OK;
3096   }
3097   msg = (struct GNUNET_MESH_ToOrigin *) message;
3098   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  of type %u\n",
3099               ntohs (msg[1].header.type));
3100   t = tunnel_get (&msg->oid, ntohl (msg->tid));
3101
3102   if (NULL == t)
3103   {
3104     /* TODO notify that we dont know this tunnel (whom)? */
3105     GNUNET_break_op (0);
3106     return GNUNET_OK;
3107   }
3108
3109   if (t->id.oid == myid)
3110   {
3111     char cbuf[size];
3112     struct GNUNET_MESH_ToOrigin *copy;
3113
3114     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3115                 "MESH:   it's for us! sending to clients...\n");
3116     if (NULL == t->client)
3117     {
3118       /* got data packet for ownerless tunnel */
3119       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   no clients!\n");
3120       GNUNET_break_op (0);
3121       return GNUNET_OK;
3122     }
3123     /* TODO signature verification */
3124     memcpy (cbuf, message, size);
3125     copy = (struct GNUNET_MESH_ToOrigin *) cbuf;
3126     copy->tid = htonl (t->local_tid);
3127     GNUNET_SERVER_notification_context_unicast (nc, t->client->handle,
3128                                                 &copy->header, GNUNET_YES);
3129     return GNUNET_OK;
3130   }
3131   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3132               "MESH:   not for us, retransmitting...\n");
3133
3134   peer_info = peer_info_get (&msg->oid);
3135   if (NULL == peer_info)
3136   {
3137     /* unknown origin of tunnel */
3138     GNUNET_break (0);
3139     return GNUNET_OK;
3140   }
3141   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
3142   send_message (message, &id);
3143
3144   return GNUNET_OK;
3145 }
3146
3147
3148 /**
3149  * Core handler for path ACKs
3150  *
3151  * @param cls closure
3152  * @param message message
3153  * @param peer peer identity this notification is about
3154  * @param atsi performance data
3155  * @param atsi_count number of records in 'atsi'
3156  *
3157  * @return GNUNET_OK to keep the connection open,
3158  *         GNUNET_SYSERR to close it (signal serious error)
3159  */
3160 static int
3161 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
3162                       const struct GNUNET_MessageHeader *message,
3163                       const struct GNUNET_ATS_Information *atsi,
3164                       unsigned int atsi_count)
3165 {
3166   struct GNUNET_MESH_PathACK *msg;
3167   struct GNUNET_PeerIdentity id;
3168   struct MeshPeerInfo *peer_info;
3169   struct MeshPeerPath *p;
3170   struct MeshTunnel *t;
3171
3172   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Received a path ACK msg [%s]\n",
3173               GNUNET_i2s (&my_full_id));
3174   msg = (struct GNUNET_MESH_PathACK *) message;
3175   t = tunnel_get (&msg->oid, msg->tid);
3176   if (NULL == t)
3177   {
3178     /* TODO notify that we don't know the tunnel */
3179     return GNUNET_OK;
3180   }
3181
3182   peer_info = peer_info_get (&msg->peer_id);
3183
3184   /* Add paths to peers? */
3185   p = tree_get_path_to_peer (t->tree, peer_info->id);
3186   if (NULL != p)
3187   {
3188     path_add_to_peers (p, GNUNET_YES);
3189     path_destroy (p);
3190   }
3191   else
3192   {
3193     GNUNET_break (0);
3194   }
3195
3196   /* Message for us? */
3197   if (0 == memcmp (&msg->oid, &my_full_id, sizeof (struct GNUNET_PeerIdentity)))
3198   {
3199     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   It's for us!\n");
3200     if (NULL == t->client)
3201     {
3202       GNUNET_break_op (0);
3203       return GNUNET_OK;
3204     }
3205     if (NULL != t->dht_get_type)
3206     {
3207       GNUNET_DHT_get_stop (t->dht_get_type);
3208       t->dht_get_type = NULL;
3209     }
3210     if (tree_get_status (t->tree, peer_info->id) != MESH_PEER_READY)
3211     {
3212       tree_set_status (t->tree, peer_info->id, MESH_PEER_READY);
3213       send_client_peer_connected (t, peer_info->id);
3214     }
3215     return GNUNET_OK;
3216   }
3217
3218   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3219               "MESH:   not for us, retransmitting...\n");
3220   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
3221   peer_info = peer_info_get (&msg->oid);
3222   if (NULL == peer_info)
3223   {
3224     /* If we know the tunnel, we should DEFINITELY know the peer */
3225     GNUNET_break (0);
3226     return GNUNET_OK;
3227   }
3228   send_message (message, &id);
3229   return GNUNET_OK;
3230 }
3231
3232
3233 /**
3234  * Functions to handle messages from core
3235  */
3236 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
3237   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
3238   {&handle_mesh_path_destroy, GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY, 0},
3239   {&handle_mesh_path_broken, GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN,
3240    sizeof (struct GNUNET_MESH_PathBroken)},
3241   {&handle_mesh_tunnel_destroy, GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY, 0},
3242   {&handle_mesh_data_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
3243   {&handle_mesh_data_multicast, GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
3244   {&handle_mesh_data_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
3245   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
3246    sizeof (struct GNUNET_MESH_PathACK)},
3247   {NULL, 0, 0}
3248 };
3249
3250
3251
3252 /******************************************************************************/
3253 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
3254 /******************************************************************************/
3255
3256 /**
3257  * deregister_app: iterator for removing each application registered by a client
3258  *
3259  * @param cls closure
3260  * @param key the hash of the application id (used to access the hashmap)
3261  * @param value the value stored at the key (client)
3262  *
3263  * @return GNUNET_OK on success
3264  */
3265 static int
3266 deregister_app (void *cls, const GNUNET_HashCode * key, void *value)
3267 {
3268   GNUNET_break (GNUNET_YES ==
3269                 GNUNET_CONTAINER_multihashmap_remove (applications, key,
3270                                                       value));
3271   return GNUNET_OK;
3272 }
3273
3274 #if LATER
3275 /**
3276  * notify_client_connection_failure: notify a client that the connection to the
3277  * requested remote peer is not possible (for instance, no route found)
3278  * Function called when the socket is ready to queue more data. "buf" will be
3279  * NULL and "size" zero if the socket was closed for writing in the meantime.
3280  *
3281  * @param cls closure
3282  * @param size number of bytes available in buf
3283  * @param buf where the callee should write the message
3284  * @return number of bytes written to buf
3285  */
3286 static size_t
3287 notify_client_connection_failure (void *cls, size_t size, void *buf)
3288 {
3289   int size_needed;
3290   struct MeshPeerInfo *peer_info;
3291   struct GNUNET_MESH_PeerControl *msg;
3292   struct GNUNET_PeerIdentity id;
3293
3294   if (0 == size && NULL == buf)
3295   {
3296     // TODO retry? cancel?
3297     return 0;
3298   }
3299
3300   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
3301   peer_info = (struct MeshPeerInfo *) cls;
3302   msg = (struct GNUNET_MESH_PeerControl *) buf;
3303   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
3304   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
3305 //     msg->tunnel_id = htonl(peer_info->t->tid);
3306   GNUNET_PEER_resolve (peer_info->id, &id);
3307   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
3308
3309   return size_needed;
3310 }
3311 #endif
3312
3313
3314 /**
3315  * Send keepalive packets for a peer
3316  *
3317  * @param cls Closure (tunnel for which to send the keepalive).
3318  * @param tc Notification context.
3319  *
3320  * TODO: implement explicit multicast keepalive?
3321  */
3322 static void
3323 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3324 {
3325   struct MeshTunnel *t = cls;
3326   struct GNUNET_MessageHeader *payload;
3327   struct GNUNET_MESH_Multicast *msg;
3328   size_t size =
3329       sizeof (struct GNUNET_MESH_Multicast) +
3330       sizeof (struct GNUNET_MessageHeader);
3331   char cbuf[size];
3332
3333   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3334   {
3335     return;
3336   }
3337   t->path_refresh_task = GNUNET_SCHEDULER_NO_TASK;
3338
3339   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3340               "MESH: sending keepalive for tunnel %d\n", t->id.tid);
3341
3342   msg = (struct GNUNET_MESH_Multicast *) cbuf;
3343   msg->header.size = htons (size);
3344   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
3345   msg->oid = my_full_id;
3346   msg->tid = htonl (t->id.tid);
3347   payload = (struct GNUNET_MessageHeader *) &msg[1];
3348   payload->size = htons (sizeof (struct GNUNET_MessageHeader));
3349   payload->type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE);
3350   tunnel_send_multicast (t, &msg->header);
3351
3352   t->path_refresh_task =
3353       GNUNET_SCHEDULER_add_delayed (REFRESH_PATH_TIME, &path_refresh, t);
3354   return;
3355 }
3356
3357
3358 /**
3359  * Function to process paths received for a new peer addition. The recorded
3360  * paths form the initial tunnel, which can be optimized later.
3361  * Called on each result obtained for the DHT search.
3362  *
3363  * @param cls closure
3364  * @param exp when will this value expire
3365  * @param key key of the result
3366  * @param get_path path of the get request
3367  * @param get_path_length lenght of get_path
3368  * @param put_path path of the put request
3369  * @param put_path_length length of the put_path
3370  * @param type type of the result
3371  * @param size number of bytes in data
3372  * @param data pointer to the result data
3373  *
3374  * TODO: re-issue the request after certain time? cancel after X results?
3375  */
3376 static void
3377 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
3378                     const GNUNET_HashCode * key,
3379                     const struct GNUNET_PeerIdentity *get_path,
3380                     unsigned int get_path_length,
3381                     const struct GNUNET_PeerIdentity *put_path,
3382                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
3383                     size_t size, const void *data)
3384 {
3385   struct MeshPathInfo *path_info = cls;
3386   struct MeshPeerPath *p;
3387   struct GNUNET_PeerIdentity pi;
3388   int i;
3389
3390   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Got results from DHT!\n");
3391   GNUNET_PEER_resolve (path_info->peer->id, &pi);
3392   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   for %s\n", GNUNET_i2s (&pi));
3393
3394   p = path_build_from_dht (get_path, get_path_length, put_path,
3395                            put_path_length);
3396   path_add_to_peers (p, GNUNET_NO);
3397   path_destroy(p);
3398   for (i = 0; i < path_info->peer->ntunnels; i++)
3399   {
3400     tunnel_add_peer (path_info->peer->tunnels[i], path_info->peer);
3401     peer_info_connect (path_info->peer, path_info->t);
3402   }
3403
3404   return;
3405 }
3406
3407
3408 /**
3409  * Function to process paths received for a new peer addition. The recorded
3410  * paths form the initial tunnel, which can be optimized later.
3411  * Called on each result obtained for the DHT search.
3412  *
3413  * @param cls closure
3414  * @param exp when will this value expire
3415  * @param key key of the result
3416  * @param get_path path of the get request
3417  * @param get_path_length lenght of get_path
3418  * @param put_path path of the put request
3419  * @param put_path_length length of the put_path
3420  * @param type type of the result
3421  * @param size number of bytes in data
3422  * @param data pointer to the result data
3423  */
3424 static void
3425 dht_get_type_handler (void *cls, struct GNUNET_TIME_Absolute exp,
3426                       const GNUNET_HashCode * key,
3427                       const struct GNUNET_PeerIdentity *get_path,
3428                       unsigned int get_path_length,
3429                       const struct GNUNET_PeerIdentity *put_path,
3430                       unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
3431                       size_t size, const void *data)
3432 {
3433   const struct GNUNET_PeerIdentity *pi = data;
3434   struct MeshTunnel *t = cls;
3435   struct MeshPeerInfo *peer_info;
3436   struct MeshPeerPath *p;
3437
3438   if (size != sizeof (struct GNUNET_PeerIdentity))
3439   {
3440     GNUNET_break_op (0);
3441     return;
3442   }
3443   GNUNET_assert (NULL != t->client);
3444   peer_info = peer_info_get (pi);
3445   (void) GNUNET_CONTAINER_multihashmap_put (t->peers, &pi->hashPubKey,
3446                                             peer_info,
3447                                             GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
3448
3449   p = path_build_from_dht (get_path, get_path_length, put_path,
3450                            put_path_length);
3451   path_add_to_peers (p, GNUNET_NO);
3452   path_destroy(p);
3453   tunnel_add_peer (t, peer_info);
3454   peer_info_connect (peer_info, t);
3455 }
3456
3457
3458 /******************************************************************************/
3459 /*********************       MESH LOCAL HANDLES      **************************/
3460 /******************************************************************************/
3461
3462
3463 /**
3464  * Handler for client disconnection
3465  *
3466  * @param cls closure
3467  * @param client identification of the client; NULL
3468  *        for the last call when the server is destroyed
3469  */
3470 static void
3471 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
3472 {
3473   struct MeshClient *c;
3474   struct MeshClient *next;
3475
3476 #if MESH_DEBUG
3477   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: client disconnected\n");
3478 #endif
3479   if (client == NULL)
3480   {
3481     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    (SERVER DOWN)\n");
3482     return;
3483   }
3484   c = clients;
3485   while (NULL != c)
3486   {
3487     if (c->handle != client)
3488     {
3489 #if MESH_DEBUG
3490       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    ... searching\n");
3491 #endif
3492       c = c->next;
3493       continue;
3494     }
3495 #if MESH_DEBUG
3496     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: matching client found (%u)\n",
3497                 c->id);
3498 #endif
3499     GNUNET_SERVER_client_drop (c->handle);
3500     c->shutting_down = GNUNET_YES;
3501     if (NULL != c->tunnels)
3502     {
3503       GNUNET_CONTAINER_multihashmap_iterate (c->tunnels,
3504                                              &tunnel_destroy_iterator, c);
3505       GNUNET_CONTAINER_multihashmap_destroy (c->tunnels);
3506     }
3507
3508     /* deregister clients applications */
3509     if (NULL != c->apps)
3510     {
3511       GNUNET_CONTAINER_multihashmap_iterate (c->apps, &deregister_app, NULL);
3512       GNUNET_CONTAINER_multihashmap_destroy (c->apps);
3513     }
3514     if (0 == GNUNET_CONTAINER_multihashmap_size (applications) &&
3515         GNUNET_SCHEDULER_NO_TASK != announce_applications_task)
3516     {
3517       GNUNET_SCHEDULER_cancel (announce_applications_task);
3518       announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
3519     }
3520     if (NULL != c->types)
3521       GNUNET_CONTAINER_multihashmap_destroy (c->types);
3522     next = c->next;
3523     GNUNET_CONTAINER_DLL_remove (clients, clients_tail, c);
3524 #if MESH_DEBUG
3525     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   CLIENT FREE at %p\n", c);
3526 #endif
3527     GNUNET_free (c);
3528     c = next;
3529   }
3530
3531 #if MESH_DEBUG
3532   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    done!\n");
3533 #endif
3534   return;
3535 }
3536
3537
3538 /**
3539  * Handler for new clients
3540  *
3541  * @param cls closure
3542  * @param client identification of the client
3543  * @param message the actual message, which includes messages the client wants
3544  */
3545 static void
3546 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
3547                          const struct GNUNET_MessageHeader *message)
3548 {
3549   struct GNUNET_MESH_ClientConnect *cc_msg;
3550   struct MeshClient *c;
3551   GNUNET_MESH_ApplicationType *a;
3552   unsigned int size;
3553   uint16_t ntypes;
3554   uint16_t *t;
3555   uint16_t napps;
3556   uint16_t i;
3557
3558   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new client connected\n");
3559   /* Check data sanity */
3560   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
3561   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
3562   ntypes = ntohs (cc_msg->types);
3563   napps = ntohs (cc_msg->applications);
3564   if (size !=
3565       ntypes * sizeof (uint16_t) + napps * sizeof (GNUNET_MESH_ApplicationType))
3566   {
3567     GNUNET_break (0);
3568     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3569     return;
3570   }
3571
3572   /* Create new client structure */
3573   c = GNUNET_malloc (sizeof (struct MeshClient));
3574 #if MESH_DEBUG
3575   c->id = next_client_id++;
3576   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   CLIENT NEW %u at %p\n", c->id,
3577               c);
3578 #endif
3579   c->handle = client;
3580   GNUNET_SERVER_client_keep (client);
3581   a = (GNUNET_MESH_ApplicationType *) &cc_msg[1];
3582   if (napps > 0)
3583   {
3584     GNUNET_MESH_ApplicationType at;
3585     GNUNET_HashCode hc;
3586
3587     c->apps = GNUNET_CONTAINER_multihashmap_create (napps);
3588     for (i = 0; i < napps; i++)
3589     {
3590       at = ntohl (a[i]);
3591       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   app type: %u\n", at);
3592       GNUNET_CRYPTO_hash (&at, sizeof (at), &hc);
3593       /* store in clients hashmap */
3594       GNUNET_CONTAINER_multihashmap_put (c->apps, &hc, c,
3595                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3596       /* store in global hashmap, for announcements */
3597       GNUNET_CONTAINER_multihashmap_put (applications, &hc, c,
3598                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3599     }
3600     if (GNUNET_SCHEDULER_NO_TASK == announce_applications_task)
3601       announce_applications_task =
3602           GNUNET_SCHEDULER_add_now (&announce_applications, NULL);
3603
3604   }
3605   if (ntypes > 0)
3606   {
3607     uint16_t u16;
3608     GNUNET_HashCode hc;
3609
3610     t = (uint16_t *) & a[napps];
3611     c->types = GNUNET_CONTAINER_multihashmap_create (ntypes);
3612     for (i = 0; i < ntypes; i++)
3613     {
3614       u16 = ntohs (t[i]);
3615       GNUNET_CRYPTO_hash (&u16, sizeof (u16), &hc);
3616
3617       /* store in clients hashmap */
3618       GNUNET_CONTAINER_multihashmap_put (c->types, &hc, c,
3619                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3620       /* store in global hashmap */
3621       GNUNET_CONTAINER_multihashmap_put (types, &hc, c,
3622                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3623     }
3624   }
3625   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3626               "MESH:  client has %u+%u subscriptions\n", napps, ntypes);
3627
3628   GNUNET_CONTAINER_DLL_insert (clients, clients_tail, c);
3629   c->tunnels = GNUNET_CONTAINER_multihashmap_create (32);
3630   GNUNET_SERVER_notification_context_add (nc, client);
3631
3632   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3633 #if MESH_DEBUG
3634   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new client processed\n");
3635 #endif
3636 }
3637
3638
3639 /**
3640  * Handler for requests of new tunnels
3641  *
3642  * @param cls closure
3643  * @param client identification of the client
3644  * @param message the actual message
3645  */
3646 static void
3647 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
3648                             const struct GNUNET_MessageHeader *message)
3649 {
3650   struct GNUNET_MESH_TunnelMessage *t_msg;
3651   struct MeshTunnel *t;
3652   struct MeshClient *c;
3653   GNUNET_HashCode hash;
3654
3655   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new tunnel requested\n");
3656
3657   /* Sanity check for client registration */
3658   if (NULL == (c = client_get (client)))
3659   {
3660     GNUNET_break (0);
3661     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3662     return;
3663   }
3664 #if MESH_DEBUG
3665   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   by client %u\n", c->id);
3666 #endif
3667
3668   /* Message sanity check */
3669   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
3670   {
3671     GNUNET_break (0);
3672     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3673     return;
3674   }
3675
3676   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
3677   /* Sanity check for tunnel numbering */
3678   if (0 == (ntohl (t_msg->tunnel_id) & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
3679   {
3680     GNUNET_break (0);
3681     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3682     return;
3683   }
3684   /* Sanity check for duplicate tunnel IDs */
3685   if (NULL != tunnel_get_by_local_id (c, ntohl (t_msg->tunnel_id)))
3686   {
3687     GNUNET_break (0);
3688     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3689     return;
3690   }
3691
3692   t = GNUNET_malloc (sizeof (struct MeshTunnel));
3693   while (NULL != tunnel_get_by_pi (myid, next_tid))
3694     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
3695   t->id.tid = next_tid++;
3696   next_tid = next_tid & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
3697   t->id.oid = myid;
3698   t->local_tid = ntohl (t_msg->tunnel_id);
3699 #if MESH_DEBUG
3700   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: CREATED TUNNEL %s [%x] (%x)\n",
3701               GNUNET_i2s (&my_full_id), t->id.tid, t->local_tid);
3702 #endif
3703   t->client = c;
3704   t->peers = GNUNET_CONTAINER_multihashmap_create (32);
3705
3706   GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
3707   if (GNUNET_OK !=
3708       GNUNET_CONTAINER_multihashmap_put (c->tunnels, &hash, t,
3709                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
3710   {
3711     GNUNET_break (0);
3712     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3713     return;
3714   }
3715
3716   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
3717   if (GNUNET_OK !=
3718       GNUNET_CONTAINER_multihashmap_put (tunnels, &hash, t,
3719                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
3720   {
3721     GNUNET_break (0);
3722     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3723     return;
3724   }
3725   t->tree = tree_new (myid);
3726
3727   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3728   return;
3729 }
3730
3731
3732 /**
3733  * Handler for requests of deleting tunnels
3734  *
3735  * @param cls closure
3736  * @param client identification of the client
3737  * @param message the actual message
3738  */
3739 static void
3740 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
3741                              const struct GNUNET_MessageHeader *message)
3742 {
3743   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
3744   struct MeshClient *c;
3745   struct MeshTunnel *t;
3746   MESH_TunnelNumber tid;
3747   GNUNET_HashCode hash;
3748
3749   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3750               "MESH: Got a DESTROY TUNNEL from client!\n");
3751
3752   /* Sanity check for client registration */
3753   if (NULL == (c = client_get (client)))
3754   {
3755     GNUNET_break (0);
3756     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3757     return;
3758   }
3759   /* Message sanity check */
3760   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
3761   {
3762     GNUNET_break (0);
3763     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3764     return;
3765   }
3766 #if MESH_DEBUG
3767   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   by client %u\n", c->id);
3768 #endif
3769   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
3770
3771   /* Retrieve tunnel */
3772   tid = ntohl (tunnel_msg->tunnel_id);
3773
3774   /* Remove from local id hashmap */
3775   GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
3776   t = GNUNET_CONTAINER_multihashmap_get (c->tunnels, &hash);
3777   send_client_tunnel_disconnect(t, c);
3778   GNUNET_assert (GNUNET_YES ==
3779                  GNUNET_CONTAINER_multihashmap_remove (c->tunnels, &hash, t));
3780
3781   t->client = NULL;
3782   tunnel_send_destroy (t);
3783   tunnel_destroy (t);
3784   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3785   return;
3786 }
3787
3788
3789 /**
3790  * Handler for connection requests to new peers
3791  *
3792  * @param cls closure
3793  * @param client identification of the client
3794  * @param message the actual message (PeerControl)
3795  */
3796 static void
3797 handle_local_connect_add (void *cls, struct GNUNET_SERVER_Client *client,
3798                           const struct GNUNET_MessageHeader *message)
3799 {
3800   struct GNUNET_MESH_PeerControl *peer_msg;
3801   struct MeshPeerInfo *peer_info;
3802   struct MeshClient *c;
3803   struct MeshTunnel *t;
3804   MESH_TunnelNumber tid;
3805
3806   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Got connection request\n");
3807   /* Sanity check for client registration */
3808   if (NULL == (c = client_get (client)))
3809   {
3810     GNUNET_break (0);
3811     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3812     return;
3813   }
3814
3815   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
3816   /* Sanity check for message size */
3817   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
3818   {
3819     GNUNET_break (0);
3820     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3821     return;
3822   }
3823
3824   /* Tunnel exists? */
3825   tid = ntohl (peer_msg->tunnel_id);
3826   t = tunnel_get_by_local_id (c, tid);
3827   if (NULL == t)
3828   {
3829     GNUNET_break (0);
3830     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3831     return;
3832   }
3833
3834   /* Does client own tunnel? */
3835   if (t->client->handle != client)
3836   {
3837     GNUNET_break (0);
3838     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3839     return;
3840   }
3841   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      for %s\n",
3842               GNUNET_i2s (&peer_msg->peer));
3843   peer_info = peer_info_get (&peer_msg->peer);
3844
3845   tunnel_add_peer (t, peer_info);
3846   peer_info_connect (peer_info, t);
3847
3848   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3849   return;
3850 }
3851
3852
3853 /**
3854  * Handler for disconnection requests of peers in a tunnel
3855  *
3856  * @param cls closure
3857  * @param client identification of the client
3858  * @param message the actual message (PeerControl)
3859  */
3860 static void
3861 handle_local_connect_del (void *cls, struct GNUNET_SERVER_Client *client,
3862                           const struct GNUNET_MessageHeader *message)
3863 {
3864   struct GNUNET_MESH_PeerControl *peer_msg;
3865   struct MeshPeerInfo *peer_info;
3866   struct MeshClient *c;
3867   struct MeshTunnel *t;
3868   MESH_TunnelNumber tid;
3869
3870   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Got a PEER DEL request\n");
3871   /* Sanity check for client registration */
3872   if (NULL == (c = client_get (client)))
3873   {
3874     GNUNET_break (0);
3875     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3876     return;
3877   }
3878   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
3879   /* Sanity check for message size */
3880   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
3881   {
3882     GNUNET_break (0);
3883     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3884     return;
3885   }
3886
3887   /* Tunnel exists? */
3888   tid = ntohl (peer_msg->tunnel_id);
3889   t = tunnel_get_by_local_id (c, tid);
3890   if (NULL == t)
3891   {
3892     GNUNET_break (0);
3893     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3894     return;
3895   }
3896   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   on tunnel %X\n", t->id.tid);
3897
3898   /* Does client own tunnel? */
3899   if (t->client->handle != client)
3900   {
3901     GNUNET_break (0);
3902     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3903     return;
3904   }
3905
3906   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   for peer %s\n",
3907               GNUNET_i2s (&peer_msg->peer));
3908   /* Is the peer in the tunnel? */
3909   peer_info =
3910       GNUNET_CONTAINER_multihashmap_get (t->peers, &peer_msg->peer.hashPubKey);
3911   if (NULL == peer_info)
3912   {
3913     GNUNET_break (0);
3914     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3915     return;
3916   }
3917
3918   /* Ok, delete peer from tunnel */
3919   GNUNET_CONTAINER_multihashmap_remove_all (t->peers,
3920                                             &peer_msg->peer.hashPubKey);
3921
3922   send_destroy_path (t, peer_info->id);
3923   tunnel_delete_peer (t, peer_info->id);
3924   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3925   return;
3926 }
3927
3928
3929 /**
3930  * Handler for connection requests to new peers by type
3931  *
3932  * @param cls closure
3933  * @param client identification of the client
3934  * @param message the actual message (ConnectPeerByType)
3935  */
3936 static void
3937 handle_local_connect_by_type (void *cls, struct GNUNET_SERVER_Client *client,
3938                               const struct GNUNET_MessageHeader *message)
3939 {
3940   struct GNUNET_MESH_ConnectPeerByType *connect_msg;
3941   struct MeshClient *c;
3942   struct MeshTunnel *t;
3943   GNUNET_HashCode hash;
3944   MESH_TunnelNumber tid;
3945
3946   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: got connect by type request\n");
3947   /* Sanity check for client registration */
3948   if (NULL == (c = client_get (client)))
3949   {
3950     GNUNET_break (0);
3951     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3952     return;
3953   }
3954
3955   connect_msg = (struct GNUNET_MESH_ConnectPeerByType *) message;
3956   /* Sanity check for message size */
3957   if (sizeof (struct GNUNET_MESH_ConnectPeerByType) !=
3958       ntohs (connect_msg->header.size))
3959   {
3960     GNUNET_break (0);
3961     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3962     return;
3963   }
3964
3965   /* Tunnel exists? */
3966   tid = ntohl (connect_msg->tunnel_id);
3967   t = tunnel_get_by_local_id (c, tid);
3968   if (NULL == t)
3969   {
3970     GNUNET_break (0);
3971     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3972     return;
3973   }
3974
3975   /* Does client own tunnel? */
3976   if (t->client->handle != client)
3977   {
3978     GNUNET_break (0);
3979     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3980     return;
3981   }
3982
3983   /* Do WE have the service? */
3984   t->type = ntohl (connect_msg->type);
3985   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  type requested: %u\n", t->type);
3986   GNUNET_CRYPTO_hash (&t->type, sizeof (GNUNET_MESH_ApplicationType), &hash);
3987   if (GNUNET_CONTAINER_multihashmap_contains (applications, &hash) ==
3988       GNUNET_YES)
3989   {
3990     /* Yes! Fast forward, add ourselves to the tunnel and send the
3991      * good news to the client, and alert the destination client of
3992      * an incoming tunnel.
3993      */
3994     struct GNUNET_MESH_TunnelNotification cmsg;
3995     struct MeshClient *c;
3996
3997     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  available locally\n");
3998     GNUNET_CONTAINER_multihashmap_put (t->peers, &my_full_id.hashPubKey,
3999                                        peer_info_get (&my_full_id),
4000                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
4001
4002     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  notifying client\n");
4003     send_client_peer_connected (t, myid);
4004     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  Done\n");
4005     GNUNET_SERVER_receive_done (client, GNUNET_OK);
4006
4007     /* FIXME implement a proper handling of this case,
4008        a client differentiation mechanism */
4009     cmsg.header.size = htons (sizeof (cmsg));
4010     cmsg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
4011     cmsg.peer = my_full_id;
4012     t->local_tid_dest = next_local_tid++;
4013     cmsg.tunnel_id = htonl (t->local_tid_dest);
4014     c = (struct MeshClient *) GNUNET_CONTAINER_multihashmap_get(applications,
4015                                                                 &hash);
4016     t->client_dest = c;
4017     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
4018     GNUNET_CONTAINER_multihashmap_put (c->tunnels, &hash, t,
4019                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
4020     GNUNET_SERVER_notification_context_unicast (nc, c->handle, &cmsg.header,
4021                                                 GNUNET_NO);
4022     
4023
4024     return;
4025   }
4026   /* Ok, lets find a peer offering the service */
4027   if (NULL != t->dht_get_type)
4028   {
4029     GNUNET_DHT_get_stop (t->dht_get_type);
4030   }
4031   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  looking in DHT for %s\n",
4032               GNUNET_h2s (&hash));
4033   t->dht_get_type =
4034       GNUNET_DHT_get_start (dht_handle, GNUNET_TIME_UNIT_FOREVER_REL,
4035                             GNUNET_BLOCK_TYPE_TEST, &hash, 10U,
4036                             GNUNET_DHT_RO_RECORD_ROUTE |
4037                             GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE, NULL, 0,
4038                             &dht_get_type_handler, t);
4039
4040   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4041   return;
4042 }
4043
4044
4045 /**
4046  * Handler for client traffic directed to one peer
4047  *
4048  * @param cls closure
4049  * @param client identification of the client
4050  * @param message the actual message
4051  */
4052 static void
4053 handle_local_unicast (void *cls, struct GNUNET_SERVER_Client *client,
4054                       const struct GNUNET_MessageHeader *message)
4055 {
4056   struct MeshClient *c;
4057   struct MeshTunnel *t;
4058   struct MeshPeerInfo *pi;
4059   struct GNUNET_MESH_Unicast *data_msg;
4060   MESH_TunnelNumber tid;
4061   size_t size;
4062
4063   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4064               "MESH: Got a unicast request from a client!\n");
4065
4066   /* Sanity check for client registration */
4067   if (NULL == (c = client_get (client)))
4068   {
4069     GNUNET_break (0);
4070     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4071     return;
4072   }
4073   data_msg = (struct GNUNET_MESH_Unicast *) message;
4074   /* Sanity check for message size */
4075   size = ntohs (message->size);
4076   if (sizeof (struct GNUNET_MESH_Unicast) +
4077       sizeof (struct GNUNET_MessageHeader) > size)
4078   {
4079     GNUNET_break (0);
4080     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4081     return;
4082   }
4083
4084   /* Tunnel exists? */
4085   tid = ntohl (data_msg->tid);
4086   t = tunnel_get_by_local_id (c, tid);
4087   if (NULL == t)
4088   {
4089     GNUNET_break (0);
4090     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4091     return;
4092   }
4093
4094   /*  Is it a local tunnel? Then, does client own the tunnel? */
4095   if (NULL != t->client && NULL != t->client->handle &&
4096       t->client->handle != client)
4097   {
4098     GNUNET_break (0);
4099     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4100     return;
4101   }
4102
4103   pi = GNUNET_CONTAINER_multihashmap_get (t->peers,
4104                                           &data_msg->destination.hashPubKey);
4105   /* Is the selected peer in the tunnel? */
4106   if (NULL == pi)
4107   {
4108     GNUNET_break (0);
4109     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4110     return;
4111   }
4112
4113   /* Ok, everything is correct, send the message
4114    * (pretend we got it from a mesh peer)
4115    */
4116   {
4117     char buf[ntohs (message->size)];
4118     struct GNUNET_MESH_Unicast *copy;
4119
4120     /* Work around const limitation */
4121     copy = (struct GNUNET_MESH_Unicast *) buf;
4122     memcpy (buf, data_msg, size);
4123     copy->oid = my_full_id;
4124     copy->tid = htonl (t->id.tid);
4125     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4126                 "MESH:   calling generic handler...\n");
4127     handle_mesh_data_unicast (NULL, &my_full_id, &copy->header, NULL, 0);
4128   }
4129   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4130   return;
4131 }
4132
4133
4134 /**
4135  * Handler for client traffic directed to the origin
4136  *
4137  * @param cls closure
4138  * @param client identification of the client
4139  * @param message the actual message
4140  */
4141 static void
4142 handle_local_to_origin (void *cls, struct GNUNET_SERVER_Client *client,
4143                         const struct GNUNET_MessageHeader *message)
4144 {
4145   struct GNUNET_MESH_ToOrigin *data_msg;
4146   struct GNUNET_PeerIdentity id;
4147   struct MeshClient *c;
4148   struct MeshTunnel *t;
4149   MESH_TunnelNumber tid;
4150   size_t size;
4151
4152   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4153               "MESH: Got a ToOrigin request from a client!\n");
4154
4155   /* Sanity check for client registration */
4156   if (NULL == (c = client_get (client)))
4157   {
4158     GNUNET_break (0);
4159     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4160     return;
4161   }
4162   data_msg = (struct GNUNET_MESH_ToOrigin *) message;
4163   /* Sanity check for message size */
4164   size = ntohs (message->size);
4165   if (sizeof (struct GNUNET_MESH_ToOrigin) +
4166       sizeof (struct GNUNET_MessageHeader) > size)
4167   {
4168     GNUNET_break (0);
4169     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4170     return;
4171   }
4172
4173   /* Tunnel exists? */
4174   tid = ntohl (data_msg->tid);
4175   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
4176   {
4177     GNUNET_break (0);
4178     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4179     return;
4180   }
4181   t = tunnel_get_by_local_id (c, tid);
4182   if (NULL == t)
4183   {
4184     GNUNET_break (0);
4185     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4186     return;
4187   }
4188
4189   /*  It shouldn't be a local tunnel.  */
4190   if (NULL != t->client)
4191   {
4192     GNUNET_break (0);
4193     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4194     return;
4195   }
4196   GNUNET_PEER_resolve (t->id.oid, &id);
4197
4198   /* Ok, everything is correct, send the message
4199    * (pretend we got it from a mesh peer)
4200    */
4201   {
4202     char buf[ntohs (message->size)];
4203     struct GNUNET_MESH_ToOrigin *copy;
4204
4205     /* Work around const limitation */
4206     copy = (struct GNUNET_MESH_ToOrigin *) buf;
4207     memcpy (buf, data_msg, size);
4208     copy->oid = id;
4209     copy->tid = htonl (t->id.tid);
4210     copy->sender = my_full_id;
4211     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4212                 "MESH:   calling generic handler...\n");
4213     handle_mesh_data_to_orig (NULL, &my_full_id, &copy->header, NULL, 0);
4214   }
4215   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4216   return;
4217 }
4218
4219
4220 /**
4221  * Handler for client traffic directed to all peers in a tunnel
4222  *
4223  * @param cls closure
4224  * @param client identification of the client
4225  * @param message the actual message
4226  */
4227 static void
4228 handle_local_multicast (void *cls, struct GNUNET_SERVER_Client *client,
4229                         const struct GNUNET_MessageHeader *message)
4230 {
4231   struct MeshClient *c;
4232   struct MeshTunnel *t;
4233   struct GNUNET_MESH_Multicast *data_msg;
4234   MESH_TunnelNumber tid;
4235
4236   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4237               "MESH: Got a multicast request from a client!\n");
4238
4239   /* Sanity check for client registration */
4240   if (NULL == (c = client_get (client)))
4241   {
4242     GNUNET_break (0);
4243     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4244     return;
4245   }
4246   data_msg = (struct GNUNET_MESH_Multicast *) message;
4247   /* Sanity check for message size */
4248   if (sizeof (struct GNUNET_MESH_Multicast) +
4249       sizeof (struct GNUNET_MessageHeader) > ntohs (data_msg->header.size))
4250   {
4251     GNUNET_break (0);
4252     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4253     return;
4254   }
4255
4256   /* Tunnel exists? */
4257   tid = ntohl (data_msg->tid);
4258   t = tunnel_get_by_local_id (c, tid);
4259   if (NULL == t)
4260   {
4261     GNUNET_break (0);
4262     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4263     return;
4264   }
4265
4266   /* Does client own tunnel? */
4267   if (t->client->handle != client)
4268   {
4269     GNUNET_break (0);
4270     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4271     return;
4272   }
4273
4274   {
4275     char buf[ntohs (message->size)];
4276     struct GNUNET_MESH_Multicast *copy;
4277
4278     copy = (struct GNUNET_MESH_Multicast *) buf;
4279     memcpy (buf, message, ntohs (message->size));
4280     copy->oid = my_full_id;
4281     copy->tid = htonl (t->id.tid);
4282     copy->ttl = htonl (DEFAULT_TTL);
4283     copy->mid = htonl (t->mid + 1);
4284     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4285                 "MESH:   calling generic handler...\n");
4286     handle_mesh_data_multicast (client, &my_full_id, &copy->header, NULL, 0);
4287   }
4288
4289   /* receive done gets called when last copy is sent to a neighbor */
4290   return;
4291 }
4292
4293 /**
4294  * Functions to handle messages from clients
4295  */
4296 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
4297   {&handle_local_new_client, NULL,
4298    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
4299   {&handle_local_tunnel_create, NULL,
4300    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
4301    sizeof (struct GNUNET_MESH_TunnelMessage)},
4302   {&handle_local_tunnel_destroy, NULL,
4303    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
4304    sizeof (struct GNUNET_MESH_TunnelMessage)},
4305   {&handle_local_connect_add, NULL,
4306    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD,
4307    sizeof (struct GNUNET_MESH_PeerControl)},
4308   {&handle_local_connect_del, NULL,
4309    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL,
4310    sizeof (struct GNUNET_MESH_PeerControl)},
4311   {&handle_local_connect_by_type, NULL,
4312    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE,
4313    sizeof (struct GNUNET_MESH_ConnectPeerByType)},
4314   {&handle_local_unicast, NULL,
4315    GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
4316   {&handle_local_to_origin, NULL,
4317    GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
4318   {&handle_local_multicast, NULL,
4319    GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
4320   {NULL, NULL, 0, 0}
4321 };
4322
4323
4324 /**
4325  * To be called on core init/fail.
4326  *
4327  * @param cls service closure
4328  * @param server handle to the server for this service
4329  * @param identity the public identity of this peer
4330  */
4331 static void
4332 core_init (void *cls, struct GNUNET_CORE_Handle *server,
4333            const struct GNUNET_PeerIdentity *identity)
4334 {
4335   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Core init\n");
4336   core_handle = server;
4337   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)) ||
4338       NULL == server)
4339   {
4340     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("MESH: Wrong CORE service\n"));
4341     GNUNET_SCHEDULER_shutdown ();
4342   }
4343   return;
4344 }
4345
4346 /**
4347  * Method called whenever a given peer connects.
4348  *
4349  * @param cls closure
4350  * @param peer peer identity this notification is about
4351  * @param atsi performance data for the connection
4352  * @param atsi_count number of records in 'atsi'
4353  */
4354 static void
4355 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
4356               const struct GNUNET_ATS_Information *atsi,
4357               unsigned int atsi_count)
4358 {
4359   struct MeshPeerInfo *peer_info;
4360   struct MeshPeerPath *path;
4361
4362 #if MESH_DEBUG_CONNECTION
4363   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Peer connected\n");
4364   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      %s\n",
4365               GNUNET_i2s (&my_full_id));
4366 #endif
4367   peer_info = peer_info_get (peer);
4368   if (myid == peer_info->id)
4369   {
4370 #if MESH_DEBUG_CONNECTION
4371     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      (self)\n");
4372 #endif
4373     return;
4374   }
4375 #if MESH_DEBUG_CONNECTION
4376   else
4377   {
4378     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      %s\n", GNUNET_i2s (peer));
4379   }
4380 #endif
4381   path = path_new (2);
4382   path->peers[0] = myid;
4383   path->peers[1] = peer_info->id;
4384   GNUNET_PEER_change_rc (myid, 1);
4385   GNUNET_PEER_change_rc (peer_info->id, 1);
4386   peer_info_add_path (peer_info, path, GNUNET_YES);
4387   return;
4388 }
4389
4390 /**
4391  * Method called whenever a peer disconnects.
4392  *
4393  * @param cls closure
4394  * @param peer peer identity this notification is about
4395  */
4396 static void
4397 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
4398 {
4399   struct MeshPeerInfo *pi;
4400   unsigned int i;
4401
4402 #if MESH_DEBUG_CONNECTION
4403   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Peer disconnected\n");
4404 #endif
4405   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
4406   if (NULL == pi)
4407   {
4408     GNUNET_break (0);
4409     return;
4410   }
4411   for (i = 0; i < CORE_QUEUE_SIZE; i++)
4412   {
4413     /* TODO: notify that the transmission failed */
4414     peer_info_cancel_transmission (pi, i);
4415   }
4416   peer_info_remove_path (pi, pi->id, myid);
4417 #if MESH_DEBUG_CONNECTION
4418   if (myid == pi->id)
4419   {
4420     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      (self)\n");
4421   }
4422 #endif
4423   return;
4424 }
4425
4426
4427 /******************************************************************************/
4428 /************************      MAIN FUNCTIONS      ****************************/
4429 /******************************************************************************/
4430
4431 /**
4432  * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
4433  *
4434  * @param cls closure
4435  * @param key current key code
4436  * @param value value in the hash map
4437  * @return GNUNET_YES if we should continue to iterate,
4438  *         GNUNET_NO if not.
4439  */
4440 static int
4441 shutdown_tunnel (void *cls, const GNUNET_HashCode * key, void *value)
4442 {
4443   struct MeshTunnel *t = value;
4444
4445   tunnel_destroy (t);
4446   return GNUNET_YES;
4447 }
4448
4449 /**
4450  * Iterator over peer hash map entries to destroy the tunnel during shutdown.
4451  *
4452  * @param cls closure
4453  * @param key current key code
4454  * @param value value in the hash map
4455  * @return GNUNET_YES if we should continue to iterate,
4456  *         GNUNET_NO if not.
4457  */
4458 static int
4459 shutdown_peer (void *cls, const GNUNET_HashCode * key, void *value)
4460 {
4461   struct MeshPeerInfo *p = value;
4462
4463   peer_info_destroy (p);
4464   return GNUNET_YES;
4465 }
4466
4467 /**
4468  * Task run during shutdown.
4469  *
4470  * @param cls unused
4471  * @param tc unused
4472  */
4473 static void
4474 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4475 {
4476   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: shutting down\n");
4477
4478   if (core_handle != NULL)
4479   {
4480     GNUNET_CORE_disconnect (core_handle);
4481     core_handle = NULL;
4482   }
4483   GNUNET_CONTAINER_multihashmap_iterate (tunnels, &shutdown_tunnel, NULL);
4484   GNUNET_CONTAINER_multihashmap_iterate (peers, &shutdown_peer, NULL);
4485   if (dht_handle != NULL)
4486   {
4487     GNUNET_DHT_disconnect (dht_handle);
4488     dht_handle = NULL;
4489   }
4490   if (nc != NULL)
4491   {
4492     GNUNET_SERVER_notification_context_destroy (nc);
4493     nc = NULL;
4494   }
4495   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
4496   {
4497     GNUNET_SCHEDULER_cancel (announce_id_task);
4498     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
4499   }
4500   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: shut down\n");
4501 }
4502
4503 /**
4504  * Process mesh requests.
4505  *
4506  * @param cls closure
4507  * @param server the initialized server
4508  * @param c configuration to use
4509  */
4510 static void
4511 run (void *cls, struct GNUNET_SERVER_Handle *server,
4512      const struct GNUNET_CONFIGURATION_Handle *c)
4513 {
4514   struct MeshPeerInfo *peer;
4515   struct MeshPeerPath *p;
4516   char *keyfile;
4517
4518   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: starting to run\n");
4519   server_handle = server;
4520   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
4521                                      CORE_QUEUE_SIZE,   /* queue size */
4522                                      NULL,      /* Closure passed to MESH functions */
4523                                      &core_init,        /* Call core_init once connected */
4524                                      &core_connect,     /* Handle connects */
4525                                      &core_disconnect,  /* remove peers on disconnects */
4526                                      NULL,      /* Don't notify about all incoming messages */
4527                                      GNUNET_NO, /* For header only in notification */
4528                                      NULL,      /* Don't notify about all outbound messages */
4529                                      GNUNET_NO, /* For header-only out notification */
4530                                      core_handlers);    /* Register these handlers */
4531
4532   if (core_handle == NULL)
4533   {
4534     GNUNET_break (0);
4535     GNUNET_SCHEDULER_shutdown ();
4536     return;
4537   }
4538
4539   if (GNUNET_OK !=
4540       GNUNET_CONFIGURATION_get_value_filename (c, "GNUNETD", "HOSTKEY",
4541                                                &keyfile))
4542   {
4543     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4544                 _
4545                 ("Mesh service is lacking key configuration settings.  Exiting.\n"));
4546     GNUNET_SCHEDULER_shutdown ();
4547     return;
4548   }
4549   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
4550   GNUNET_free (keyfile);
4551   if (my_private_key == NULL)
4552   {
4553     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4554                 _("Mesh service could not access hostkey.  Exiting.\n"));
4555     GNUNET_SCHEDULER_shutdown ();
4556     return;
4557   }
4558   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
4559   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
4560                       &my_full_id.hashPubKey);
4561   myid = GNUNET_PEER_intern (&my_full_id);
4562
4563 // //   transport_handle = GNUNET_TRANSPORT_connect(c,
4564 // //                                               &my_full_id,
4565 // //                                               NULL,
4566 // //                                               NULL,
4567 // //                                               NULL,
4568 // //                                               NULL);
4569
4570   dht_handle = GNUNET_DHT_connect (c, 64);
4571   if (dht_handle == NULL)
4572   {
4573     GNUNET_break (0);
4574   }
4575
4576   next_tid = 0;
4577   next_local_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
4578
4579   tunnels = GNUNET_CONTAINER_multihashmap_create (32);
4580   incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
4581   peers = GNUNET_CONTAINER_multihashmap_create (32);
4582   applications = GNUNET_CONTAINER_multihashmap_create (32);
4583   types = GNUNET_CONTAINER_multihashmap_create (32);
4584
4585   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
4586   nc = GNUNET_SERVER_notification_context_create (server_handle,
4587                                                   LOCAL_QUEUE_SIZE);
4588   GNUNET_SERVER_disconnect_notify (server_handle,
4589                                    &handle_local_client_disconnect, NULL);
4590
4591
4592   clients = NULL;
4593   clients_tail = NULL;
4594 #if MESH_DEBUG
4595   next_client_id = 0;
4596 #endif
4597
4598   announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
4599   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
4600
4601   /* Create a peer_info for the local peer */
4602   peer = peer_info_get (&my_full_id);
4603   p = path_new (1);
4604   p->peers[0] = myid;
4605   GNUNET_PEER_change_rc (myid, 1);
4606   peer_info_add_path (peer, p, GNUNET_YES);
4607
4608   /* Scheduled the task to clean up when shutdown is called */
4609   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
4610                                 NULL);
4611
4612   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: end of run()\n");
4613 }
4614
4615 /**
4616  * The main function for the mesh service.
4617  *
4618  * @param argc number of arguments from the command line
4619  * @param argv command line arguments
4620  * @return 0 ok, 1 on error
4621  */
4622 int
4623 main (int argc, char *const *argv)
4624 {
4625   int ret;
4626
4627   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: main()\n");
4628   ret =
4629       (GNUNET_OK ==
4630        GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
4631                            NULL)) ? 0 : 1;
4632   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: main() END\n");
4633
4634   return ret;
4635 }