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