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