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