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