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