Various fixes in data traffic, expansion of unicast testcase
[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  * - add connection confirmation message
44  * - handle trnsmt_rdy return values
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 /******************************************************************************/
70 /************************      DATA STRUCTURES     ****************************/
71 /******************************************************************************/
72
73 /** FWD declaration */
74 struct MeshPeerInfo;
75
76 /**
77  * Struct containing all info possibly needed to build a package when called
78  * back by core.
79  */
80 struct MeshDataDescriptor
81 {
82     /** ID of the tunnel this packet travels in */
83   struct MESH_TunnelID *origin;
84
85     /** Data itself */
86   void *data;
87
88     /** Client that asked for the transmission, if any */
89   struct GNUNET_SERVER_Client *client;
90
91     /** Who was this message being sent to */
92   struct MeshPeerInfo *peer;
93
94     /** Ultimate destination of the packet */
95   GNUNET_PEER_Id destination;
96
97     /** Number of identical messages sent to different hops (multicast) */
98   unsigned int *copies;
99
100     /** Which handler was used to request the transmission */
101   unsigned int handler_n;
102
103     /** Size of the data */
104   size_t size;
105
106 };
107
108
109 /**
110  * Struct containing all information regarding a given peer
111  */
112 struct MeshPeerInfo
113 {
114     /**
115      * ID of the peer
116      */
117   GNUNET_PEER_Id id;
118
119     /**
120      * Last time we heard from this peer
121      */
122   struct GNUNET_TIME_Absolute last_contact;
123
124     /**
125      * Number of attempts to reconnect so far
126      */
127   int n_reconnect_attempts;
128
129     /**
130      * Paths to reach the peer, ordered by ascending hop count
131      */
132   struct MeshPeerPath *path_head;
133
134     /**
135      * Paths to reach the peer, ordered by ascending hop count
136      */
137   struct MeshPeerPath *path_tail;
138
139     /**
140      * Handle to stop the DHT search for a path to this peer
141      */
142   struct GNUNET_DHT_GetHandle *dhtget;
143
144     /**
145      * Handles to stop queued transmissions for this peer
146      */
147   struct GNUNET_CORE_TransmitHandle *core_transmit[CORE_QUEUE_SIZE];
148
149     /**
150      * Pointer to info stuctures used as cls for queued transmissions
151      */
152   void *infos[CORE_QUEUE_SIZE];
153
154     /**
155      * Type of message being in each transmission
156      */
157   uint16_t types[CORE_QUEUE_SIZE];
158
159     /**
160      * Array of tunnels this peer participates in
161      * (most probably a small amount, therefore not a hashmap)
162      * When the path to the peer changes, notify these tunnels to let them
163      * re-adjust their path trees.
164      */
165   struct MeshTunnel **tunnels;
166
167     /**
168      * Number of tunnels this peers participates in
169      */
170   unsigned int ntunnels;
171 };
172
173
174 /**
175  * Data scheduled to transmit (to local client or remote peer)
176  */
177 struct MeshQueue
178 {
179     /**
180      * Double linked list
181      */
182   struct MeshQueue *next;
183   struct MeshQueue *prev;
184
185     /**
186      * Target of the data (NULL if target is client)
187      */
188   struct MeshPeerInfo *peer;
189
190     /**
191      * Client to send the data to (NULL if target is peer)
192      */
193   struct MeshClient *client;
194
195     /**
196      * Size of the message to transmit
197      */
198   unsigned int size;
199
200     /**
201      * How old is the data?
202      */
203   struct GNUNET_TIME_Absolute timestamp;
204
205     /**
206      * Data itself
207      */
208   struct GNUNET_MessageHeader *data;
209 };
210
211 /**
212  * Globally unique tunnel identification (owner + number)
213  * DO NOT USE OVER THE NETWORK
214  */
215 struct MESH_TunnelID
216 {
217     /**
218      * Node that owns the tunnel
219      */
220   GNUNET_PEER_Id oid;
221
222     /**
223      * Tunnel number to differentiate all the tunnels owned by the node oid
224      * ( tid < GNUNET_MESH_LOCAL_TUNNEL_ID_CLI )
225      */
226   MESH_TunnelNumber tid;
227 };
228
229
230 struct MeshClient;              /* FWD declaration */
231
232 /**
233  * Struct containing all information regarding a tunnel
234  * For an intermediate node the improtant info used will be:
235  * - id        Tunnel unique identification
236  * - paths[0]  To know where to send it next
237  * - metainfo: ready, speeds, accounting
238  */
239 struct MeshTunnel
240 {
241     /**
242      * Tunnel ID
243      */
244   struct MESH_TunnelID id;
245
246     /**
247      * Local tunnel number ( >= GNUNET_MESH_LOCAL_TUNNEL_ID_CLI or 0 )
248      */
249   MESH_TunnelNumber local_tid;
250
251     /**
252      * Last time the tunnel was used
253      */
254   struct GNUNET_TIME_Absolute timestamp;
255
256     /**
257      * Peers in the tunnel, indexed by PeerIdentity -> (MeshPeerInfo)
258      */
259   struct GNUNET_CONTAINER_MultiHashMap *peers;
260
261     /**
262      * Number of peers that are connected and potentially ready to receive data
263      */
264   unsigned int peers_ready;
265
266     /**
267      * Number of peers that have been added to the tunnel
268      */
269   unsigned int peers_total;
270
271     /**
272      * Client owner of the tunnel, if any
273      */
274   struct MeshClient *client;
275
276     /**
277      * Messages ready to transmit
278      */
279   struct MeshQueue *queue_head;
280   struct MeshQueue *queue_tail;
281
282   /**
283    * Tunnel paths
284    */
285   struct MeshTunnelTree *tree;
286
287   /**
288    * Application type we are looking for in this tunnel
289    */
290   GNUNET_MESH_ApplicationType type;
291
292     /**
293      * Used to search peers offering a service
294      */
295   struct GNUNET_DHT_GetHandle *dht_get_type;
296
297   /**
298    * Task to keep the used paths alive
299    */
300   GNUNET_SCHEDULER_TaskIdentifier path_refresh_task;
301 };
302
303
304 /**
305  * Info needed to work with tunnel paths and peers
306  */
307 struct MeshPathInfo
308 {
309   /**
310    * Tunnel
311    */
312   struct MeshTunnel *t;
313
314   /**
315    * Destination peer
316    */
317   struct MeshPeerInfo *peer;
318
319   /**
320    * Path itself
321    */
322   struct MeshPeerPath *path;
323   
324   /**
325    * Position in peer's transmit queue
326    */
327   unsigned int pos;
328 };
329
330
331 /**
332  * Struct containing information about a client of the service
333  */
334 struct MeshClient
335 {
336     /**
337      * Linked list
338      */
339   struct MeshClient *next;
340   struct MeshClient *prev;
341
342     /**
343      * Tunnels that belong to this client, indexed by local id
344      */
345   struct GNUNET_CONTAINER_MultiHashMap *tunnels;
346
347     /**
348      * Handle to communicate with the client
349      */
350   struct GNUNET_SERVER_Client *handle;
351
352     /**
353      * Applications that this client has claimed to provide
354      */
355   struct GNUNET_CONTAINER_MultiHashMap *apps;
356
357     /**
358      * Messages that this client has declared interest in
359      */
360   struct GNUNET_CONTAINER_MultiHashMap *types;
361
362 #if MESH_DEBUG
363     /**
364      * ID of the client, for debug messages
365      */
366   unsigned int id;
367 #endif
368
369 };
370
371
372
373 /******************************************************************************/
374 /************************      DEBUG FUNCTIONS     ****************************/
375 /******************************************************************************/
376
377
378 /**
379  * GNUNET_SCHEDULER_Task for printing a message after some operation is done
380  * @param cls string to print
381  * @param tc task context
382  */
383 static void
384 mesh_debug (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
385 {
386   char *s = cls;
387
388   if (GNUNET_SCHEDULER_REASON_SHUTDOWN == tc->reason)
389   {
390     return;
391   }
392   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: %s\n", s);
393 }
394
395
396 /******************************************************************************/
397 /***********************      GLOBAL VARIABLES     ****************************/
398 /******************************************************************************/
399
400 /**
401  * All the clients
402  */
403 static struct MeshClient *clients;
404 static struct MeshClient *clients_tail;
405
406 /**
407  * Tunnels known, indexed by MESH_TunnelID (MeshTunnel)
408  */
409 static struct GNUNET_CONTAINER_MultiHashMap *tunnels;
410
411 /**
412  * Tunnels incoming, indexed by MESH_TunnelNumber
413  * (which is greater than GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
414  */
415 static struct GNUNET_CONTAINER_MultiHashMap *incoming_tunnels;
416
417 /**
418  * Peers known, indexed by PeerIdentity (MeshPeerInfo)
419  */
420 static struct GNUNET_CONTAINER_MultiHashMap *peers;
421
422 /**
423  * Handle to communicate with core
424  */
425 static struct GNUNET_CORE_Handle *core_handle;
426
427 /**
428  * Handle to use DHT
429  */
430 static struct GNUNET_DHT_Handle *dht_handle;
431
432 /**
433  * Handle to server
434  */
435 static struct GNUNET_SERVER_Handle *server_handle;
436
437 /**
438  * Notification context, to send messages to local clients
439  */
440 static struct GNUNET_SERVER_NotificationContext *nc;
441
442 /**
443  * Local peer own ID (memory efficient handle)
444  */
445 static GNUNET_PEER_Id myid;
446
447 /**
448  * Local peer own ID (full value)
449  */
450 static struct GNUNET_PeerIdentity my_full_id;
451
452 /**
453  * Own private key
454  */
455 static struct GNUNET_CRYPTO_RsaPrivateKey* my_private_key;
456
457 /**
458  * Own public key.
459  */
460 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
461
462 /**
463  * Tunnel ID for the next created tunnel (global tunnel number)
464  */
465 static MESH_TunnelNumber next_tid;
466
467 /**
468  * Tunnel ID for the next incoming tunnel (local tunnel number)
469  */
470 static MESH_TunnelNumber next_local_tid;
471
472 /**
473  * All application types provided by this peer
474  */
475 static struct GNUNET_CONTAINER_MultiHashMap *applications;
476
477 /**
478  * All message types clients of this peer are interested in
479  */
480 static struct GNUNET_CONTAINER_MultiHashMap *types;
481
482 /**
483  * Task to periodically announce provided applications
484  */
485 GNUNET_SCHEDULER_TaskIdentifier announce_applications_task;
486
487 /**
488  * Task to periodically announce itself in the network
489  */
490 GNUNET_SCHEDULER_TaskIdentifier announce_id_task;
491
492 #if MESH_DEBUG
493 unsigned int next_client_id;
494 #endif
495
496
497 /******************************************************************************/
498 /************************         ITERATORS        ****************************/
499 /******************************************************************************/
500
501 /* FIXME move iterators here */
502
503
504 /******************************************************************************/
505 /************************    PERIODIC FUNCTIONS    ****************************/
506 /******************************************************************************/
507
508 /**
509  * Announce iterator over for each application provided by the peer
510  *
511  * @param cls closure
512  * @param key current key code
513  * @param value value in the hash map
514  * @return GNUNET_YES if we should continue to
515  *         iterate,
516  *         GNUNET_NO if not.
517  */
518 static int
519 announce_application (void *cls, const GNUNET_HashCode * key, void *value)
520 {
521   /* FIXME are hashes in multihash map equal on all aquitectures? */
522   GNUNET_DHT_put (dht_handle,
523                   key,
524                   10U,
525                   GNUNET_DHT_RO_RECORD_ROUTE |
526                     GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
527                   GNUNET_BLOCK_TYPE_TEST,
528                   sizeof (struct GNUNET_PeerIdentity),
529                   (const char *) &my_full_id,
530 #if MESH_DEBUG
531                   GNUNET_TIME_UNIT_FOREVER_ABS, GNUNET_TIME_UNIT_FOREVER_REL,
532                   &mesh_debug, "DHT_put for app completed");
533 #else
534                   GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get (),
535                                             APP_ANNOUNCE_TIME),
536                   APP_ANNOUNCE_TIME, NULL, NULL);
537 #endif
538   return GNUNET_OK;
539 }
540
541
542 /**
543  * Periodically announce what applications are provided by local clients
544  *
545  * @param cls closure
546  * @param tc task context
547  */
548 static void
549 announce_applications (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
550 {
551   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
552   {
553     announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
554     return;
555   }
556   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Starting PUT for apps\n");
557   GNUNET_CONTAINER_multihashmap_iterate (applications, &announce_application,
558                                          NULL);
559   announce_applications_task =
560       GNUNET_SCHEDULER_add_delayed (APP_ANNOUNCE_TIME, &announce_applications,
561                                     cls);
562   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Finished PUT for apps\n");
563   return;
564 }
565
566
567 /**
568  * Periodically announce self id in the DHT
569  *
570  * @param cls closure
571  * @param tc task context
572  */
573 static void
574 announce_id (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
575 {
576   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
577   {
578     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
579     return;
580   }
581   /* TODO
582    * - Set data expiration in function of X
583    * - Adapt X to churn
584    */
585   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: DHT_put for ID %s started.\n",
586               GNUNET_h2s_full (&my_full_id.hashPubKey));
587   GNUNET_DHT_put (dht_handle,   /* DHT handle */
588                   &my_full_id.hashPubKey,       /* Key to use */
589                   10U,          /* Replication level */
590                   GNUNET_DHT_RO_RECORD_ROUTE |
591                     GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,   /* DHT options */
592                   GNUNET_BLOCK_TYPE_TEST,       /* Block type */
593                   sizeof(my_full_id),   /* Size of the data */
594                   (char *)&my_full_id,  /* Data itself */
595                   GNUNET_TIME_absolute_get_forever (),  /* Data expiration */
596                   GNUNET_TIME_UNIT_FOREVER_REL, /* Retry time */
597 #if MESH_DEBUG
598                   &mesh_debug, "DHT_put for id completed");
599 #else
600                   NULL,         /* Continuation */
601                   NULL);        /* Continuation closure */
602 #endif
603   announce_id_task =
604       GNUNET_SCHEDULER_add_delayed (ID_ANNOUNCE_TIME, &announce_id, cls);
605 }
606
607
608 /**
609  * Function to process paths received for a new peer addition. The recorded
610  * paths form the initial tunnel, which can be optimized later.
611  * Called on each result obtained for the DHT search.
612  *
613  * @param cls closure
614  * @param exp when will this value expire
615  * @param key key of the result
616  * @param type type of the result
617  * @param size number of bytes in data
618  * @param data pointer to the result data
619  */
620 static void
621 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
622                     const GNUNET_HashCode * key,
623                     const struct GNUNET_PeerIdentity *get_path,
624                     unsigned int get_path_length,
625                     const struct GNUNET_PeerIdentity *put_path,
626                     unsigned int put_path_length,
627                     enum GNUNET_BLOCK_Type type, size_t size, const void *data);
628
629
630 /******************************************************************************/
631 /******************      GENERAL HELPER FUNCTIONS      ************************/
632 /******************************************************************************/
633
634 /**
635  * Check if client has registered with the service and has not disconnected
636  *
637  * @param client the client to check
638  *
639  * @return non-NULL if client exists in the global DLL
640  */
641 static struct MeshClient *
642 client_get (struct GNUNET_SERVER_Client *client)
643 {
644   struct MeshClient *c;
645
646   c = clients;
647   while (NULL != c)
648   {
649     if (c->handle == client)
650       return c;
651     c = c->next;
652   }
653   return NULL;
654 }
655
656
657 /**
658  * Checks if a given client has subscribed to certain message type
659  *
660  * @param message_type Type of message to check
661  * @param c Client to check
662  *
663  * @return GNUNET_YES or GNUNET_NO, depending on subscription status
664  *
665  * TODO inline?
666  */
667 static int
668 client_is_subscribed (uint16_t message_type, struct MeshClient *c)
669 {
670   GNUNET_HashCode hc;
671
672   GNUNET_CRYPTO_hash (&message_type, sizeof (uint16_t), &hc);
673   return GNUNET_CONTAINER_multihashmap_contains (c->types, &hc);
674 }
675
676
677 /**
678  * Search for a tunnel by global ID using full PeerIdentities
679  *
680  * @param oid owner of the tunnel
681  * @param tid global tunnel number
682  *
683  * @return tunnel handler, NULL if doesn't exist
684  */
685 static struct MeshTunnel *
686 tunnel_get (struct GNUNET_PeerIdentity *oid, MESH_TunnelNumber tid);
687
688
689 /**
690  * Send the message to all clients that have subscribed to its type
691  *
692  * @param msg Pointer to the message itself
693  * @return number of clients this message was sent to
694  */
695 static unsigned int
696 send_subscribed_clients (const struct GNUNET_MessageHeader *msg,
697                          const struct GNUNET_MessageHeader *payload)
698 {
699   struct GNUNET_PeerIdentity *oid;
700   struct MeshClient *c;
701   MESH_TunnelNumber *tid;
702   unsigned int count;
703   uint16_t type;
704   char cbuf[htons(msg->size)];
705
706   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Sending to clients...\n");
707   type = ntohs (payload->type);
708   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: message of type %u\n", type);
709
710   memcpy (cbuf, msg, sizeof(cbuf));
711   switch (htons(msg->type))
712   {
713     struct GNUNET_MESH_Unicast *uc;
714     struct GNUNET_MESH_Multicast *mc;
715     struct GNUNET_MESH_ToOrigin *to;
716
717     case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
718       uc = (struct GNUNET_MESH_Unicast *) cbuf;
719       tid = &uc->tid;
720       oid = &uc->oid;
721       break;
722     case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
723       mc = (struct GNUNET_MESH_Multicast *) cbuf;
724       tid = &mc->tid;
725       oid = &mc->oid;
726       break;
727     case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
728       to = (struct GNUNET_MESH_ToOrigin *) cbuf;
729       tid = &to->tid;
730       oid = &to->oid;
731       break;
732     default:
733       GNUNET_break (0);
734       return 0;
735   }
736   *tid = htonl (tunnel_get (oid, ntohl(*tid))->local_tid);
737   for (count = 0, c = clients; c != NULL; c = c->next)
738   {
739     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    client %u\n", c->id);
740     if (client_is_subscribed (type, c))
741     {
742       count++;
743       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      sending\n");
744       GNUNET_SERVER_notification_context_unicast (
745           nc,
746           c->handle,
747           (struct GNUNET_MessageHeader *) cbuf,
748           GNUNET_YES);
749     }
750   }
751   return count;
752 }
753
754
755 /**
756  * Notify the client that owns the tunnel that a peer has connected to it
757  * 
758  * @param t Tunnel whose owner to notify
759  * @param id Short id of the peer that has connected
760  */
761 static void
762 send_client_peer_connected (const struct MeshTunnel *t, const GNUNET_PEER_Id id)
763 {
764   struct GNUNET_MESH_PeerControl pc;
765
766   pc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD);
767   pc.header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
768   pc.tunnel_id = htonl (t->local_tid);
769   GNUNET_PEER_resolve (id, &pc.peer);
770   GNUNET_SERVER_notification_context_unicast (nc, t->client->handle,
771                                               &pc.header, GNUNET_NO);
772 }
773
774
775 /**
776  * Function called to notify a client about the socket
777  * being ready to queue more data.  "buf" will be
778  * NULL and "size" zero if the socket was closed for
779  * writing in the meantime.
780  *
781  * @param cls closure
782  * @param size number of bytes available in buf
783  * @param buf where the callee should write the message
784  * @return number of bytes written to buf
785  */
786 static size_t
787 send_core_create_path (void *cls, size_t size, void *buf);
788
789 /**
790  * Cancel a core transmission that was already requested and free all resources
791  * associated to the request.
792  * 
793  * @param peer PeeInfo of the peer whose transmission is cancelled.
794  * @param i Position of the transmission to be cancelled.
795  */
796 static void
797 peer_info_cancel_transmission(struct MeshPeerInfo *peer, unsigned int i)
798 {
799   if (NULL != peer->core_transmit[i])
800   {
801     struct MeshDataDescriptor *dd;
802     struct MeshPathInfo *path_info;
803
804     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
805                 "MESH:   Cancelling data transmission at %u\n",
806                 i);
807     GNUNET_CORE_notify_transmit_ready_cancel (peer->core_transmit[i]);
808     peer->core_transmit[i] = NULL;
809     /* TODO: notify that tranmission has failed */
810     switch (peer->types[i])
811     {
812       case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
813       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
814       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
815         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    type payload\n");
816         dd = peer->infos[i];
817         if (0 == --(*dd->copies))
818         {
819           GNUNET_free (dd->copies);
820           GNUNET_free (dd->data);
821         }
822         break;
823       case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
824         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    type create path\n");
825         path_info = peer->infos[i];
826         path_destroy(path_info->path);
827         break;
828     }
829     GNUNET_free (peer->infos[i]);
830   } 
831 }
832
833
834 /**
835  * 
836  */
837 static unsigned int
838 peer_info_transmit_slot (struct MeshPeerInfo *peer)
839 {
840   unsigned int i;
841
842   for (i = 0; peer->core_transmit[i]; i++)
843   {
844     if (i == (CORE_QUEUE_SIZE - 1))
845     {
846       /* All positions are taken! Overwriting! */
847       GNUNET_break (0);
848       peer_info_cancel_transmission(peer, 0);
849       return 0;
850     }
851   }
852   return i;
853 }
854
855
856 /**
857  * Retrieve the MeshPeerInfo stucture associated with the peer, create one
858  * and insert it in the appropiate structures if the peer is not known yet.
859  *
860  * @param peer Full identity of the peer.
861  *
862  * @return Existing or newly created peer info.
863  */
864 static struct MeshPeerInfo *
865 peer_info_get (const struct GNUNET_PeerIdentity *peer)
866 {
867   struct MeshPeerInfo *peer_info;
868
869   peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
870   if (NULL == peer_info)
871   {
872     peer_info =
873         (struct MeshPeerInfo *) GNUNET_malloc (sizeof (struct MeshPeerInfo));
874     GNUNET_CONTAINER_multihashmap_put (peers, &peer->hashPubKey, peer_info,
875                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
876     peer_info->id = GNUNET_PEER_intern (peer);
877   }
878
879   return peer_info;
880 }
881
882
883 /**
884  * Retrieve the MeshPeerInfo stucture associated with the peer, create one
885  * and insert it in the appropiate structures if the peer is not known yet.
886  *
887  * @param peer Short identity of the peer.
888  *
889  * @return Existing or newly created peer info.
890  */
891 static struct MeshPeerInfo *
892 peer_info_get_short (const GNUNET_PEER_Id peer)
893 {
894   struct GNUNET_PeerIdentity id;
895
896   GNUNET_PEER_resolve(peer, &id);
897   return peer_info_get(&id);
898 }
899
900
901 /**
902  * Iterator to remove the tunnel from the list of tunnels a peer participates
903  * in.
904  *
905  * @param cls Closure (tunnel info)
906  * @param key GNUNET_PeerIdentity of the peer (unused)
907  * @param value PeerInfo of the peer
908  *
909  * @return always GNUNET_YES, to keep iterating
910  */
911 static int
912 peer_info_delete_tunnel (void* cls, const GNUNET_HashCode* key, void* value)
913 {
914   struct MeshTunnel *t = cls;
915   struct MeshPeerInfo *peer = value;
916   unsigned int i;
917
918   for (i = 0; i < peer->ntunnels; i++)
919   {
920     if (0 == memcmp(&peer->tunnels[i]->id,
921                     &t->id,
922                     sizeof(struct MESH_TunnelID)))
923     {
924       peer->ntunnels--;
925       peer->tunnels[i] = peer->tunnels[peer->ntunnels];
926       peer->tunnels = GNUNET_realloc (peer->tunnels, peer->ntunnels);
927       return GNUNET_YES;
928     }
929   }
930   return GNUNET_YES;
931 }
932
933
934 /**
935  * Sends a CREATE PATH message for a path to a peer, properly registrating
936  * all used resources.
937  * 
938  * @param peer PeerInfo of the final peer for whom this path is being created.
939  * @param p Path itself.
940  * @param t Tunnel for which the path is created.
941  */
942 static void
943 send_create_path (struct MeshPeerInfo *peer,
944                   struct MeshPeerPath *p,
945                   struct MeshTunnel *t)
946 {
947   struct GNUNET_PeerIdentity id;
948   struct MeshPathInfo *path_info;
949   struct MeshPeerInfo *neighbor;
950   unsigned int i;
951
952   if (NULL == p)
953   {
954     p = tree_get_path_to_peer(t->tree, peer->id);
955     if (NULL == p)
956     {
957       GNUNET_break (0);
958       return;
959     }
960   }
961   for (i = 0; i < p->length; i++)
962   {
963     if (p->peers[i] == myid)
964       break;
965   }
966   if (i >= p->length - 1)
967   {
968     path_destroy(p);
969     GNUNET_break (0);
970     return;
971   }
972   GNUNET_PEER_resolve(p->peers[i + 1], &id);
973
974   path_info = GNUNET_malloc (sizeof (struct MeshPathInfo));
975   path_info->path = p;
976   path_info->peer = peer;
977   path_info->t = t;
978   neighbor = peer_info_get(&id);
979   path_info->pos = peer_info_transmit_slot(neighbor);
980   neighbor->types[path_info->pos] = GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE;
981   neighbor->infos[path_info->pos] = path_info;
982   neighbor->core_transmit[path_info->pos] = 
983       GNUNET_CORE_notify_transmit_ready (
984           core_handle, /* handle */
985           0, /* cork */
986           0, /* priority */
987           GNUNET_TIME_UNIT_FOREVER_REL, /* timeout */
988           &id, /* target */
989           sizeof (struct GNUNET_MESH_ManipulatePath)
990           + (p->length * sizeof (struct GNUNET_PeerIdentity)), /*size */
991           &send_core_create_path, /* callback */
992           path_info);        /* cls */
993 }
994
995
996 /**
997  * Try to establish a new connection to this peer.
998  * Use the best path for the given tunnel.
999  * If the peer doesn't have any path to it yet, try to get one. 
1000  * If the peer already has some path, send a CREATE PATH towards it.
1001  *
1002  * @param peer PeerInfo of the peer.
1003  * @param t Tunnel for which to create the path, if possible.
1004  */
1005 static void
1006 peer_info_connect (struct MeshPeerInfo *peer, struct MeshTunnel *t)
1007 {
1008   struct MeshPeerPath *p;
1009   struct MeshPathInfo *path_info;
1010
1011   if (NULL != peer->path_head)
1012   {
1013     p = tree_get_path_to_peer(t->tree, peer->id);
1014     if (p->length > 1)
1015     {
1016       send_create_path(peer, p, t);
1017     }
1018     else
1019     {
1020       path_destroy(p);
1021       send_client_peer_connected(t, myid);
1022     }
1023   }
1024   else if (NULL == peer->dhtget)
1025   {
1026     struct GNUNET_PeerIdentity id;
1027
1028     GNUNET_PEER_resolve(peer->id, &id);
1029     path_info = GNUNET_malloc(sizeof(struct MeshPathInfo));
1030     path_info->peer = peer;
1031     path_info->t = t;
1032     peer->dhtget =
1033         GNUNET_DHT_get_start(dht_handle,       /* handle */
1034                              GNUNET_TIME_UNIT_FOREVER_REL,     /* timeout */
1035                              GNUNET_BLOCK_TYPE_TEST,   /* type */
1036                              &id.hashPubKey,       /* key to search */
1037                              4,         /* replication level */
1038                              GNUNET_DHT_RO_RECORD_ROUTE |
1039                                GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
1040                              NULL,     /* xquery */
1041                              0,        /* xquery bits */
1042                              &dht_get_id_handler,
1043                              path_info);
1044   }
1045   /* Otherwise, there is no path but the DHT get is already started. */
1046 }
1047
1048
1049 #if LATER
1050 /**
1051  * Destroy the peer_info and free any allocated resources linked to it
1052  * @param t tunnel the path belongs to
1053  * @param pi the peer_info to destroy
1054  * @return GNUNET_OK on success
1055  */
1056 static int
1057 peer_info_destroy (struct MeshPeerInfo *pi)
1058 {
1059   GNUNET_HashCode hash;
1060   struct GNUNET_PeerIdentity id;
1061
1062   GNUNET_PEER_resolve (pi->id, &id);
1063   GNUNET_PEER_change_rc (pi->id, -1);
1064   GNUNET_CRYPTO_hash (&id, sizeof (struct GNUNET_PeerIdentity), &hash);
1065
1066   GNUNET_CONTAINER_multihashmap_remove (peers, &hash, pi);
1067   GNUNET_SCHEDULER_cancel (pi->path_refresh_task);
1068   GNUNET_free (pi);
1069   return GNUNET_OK;
1070 }
1071 #endif
1072
1073
1074 /**
1075  * Notify a tunnel that a connection has broken that affects at least
1076  * some of its peers.
1077  *
1078  * @param t Tunnel affected.
1079  * @param peer Peer that (at least) has been affected by the disconnection.
1080  * @param p1 Peer that got disconnected from p2.
1081  * @param p2 Peer that got disconnected from p1.
1082  *
1083  * @return Short ID of the peer disconnected (either p1 or p2).
1084  *         0 if the tunnel remained unaffected.
1085  */
1086 static GNUNET_PEER_Id
1087 tunnel_notify_connection_broken (struct MeshTunnel *t,
1088                                  struct MeshPeerInfo *peer, GNUNET_PEER_Id p1,
1089                                  GNUNET_PEER_Id p2);
1090
1091 /**
1092  * Remove all paths that rely on a direct connection between p1 and p2
1093  * from the peer itself and notify all tunnels about it.
1094  *
1095  * @param peer PeerInfo of affected peer.
1096  * @param p1 GNUNET_PEER_Id of one peer.
1097  * @param p2 GNUNET_PEER_Id of another peer that was connected to the first and
1098  *           no longer is.
1099  *
1100  * TODO: optimize (see below)
1101  */
1102 static void
1103 path_remove_from_peer (struct MeshPeerInfo *peer,
1104                        GNUNET_PEER_Id p1,
1105                        GNUNET_PEER_Id p2)
1106 {
1107   struct GNUNET_PeerIdentity id;
1108   struct MeshPeerPath *p;
1109   struct MeshPeerPath *aux;
1110   struct MeshPeerInfo *peer_d;
1111   GNUNET_PEER_Id d;
1112   unsigned int destroyed;
1113   unsigned int best;
1114   unsigned int cost;
1115   unsigned int i;
1116
1117   destroyed = 0;
1118   p = peer->path_head;
1119   while (NULL != p)
1120   {
1121     aux = p->next;
1122     for (i = 0; i < (p->length - 1); i++)
1123     {
1124       if ((p->peers[i] == p1 && p->peers[i + 1] == p2) ||
1125           (p->peers[i] == p2 && p->peers[i + 1] == p1))
1126       {
1127         path_destroy (p);
1128         destroyed++;
1129         break;
1130       }
1131     }
1132     p = aux;
1133   }
1134   if (0 == destroyed)
1135     return;
1136
1137   for (i = 0; i < peer->ntunnels; i++)
1138   {
1139     d = tunnel_notify_connection_broken (peer->tunnels[i], peer, p1, p2);
1140     /* TODO
1141      * Problem: one or more peers have been deleted from the tunnel tree.
1142      * We don't know who they are to try to add them again.
1143      * We need to try to find a new path for each of the disconnected peers.
1144      * Some of them might already have a path to reach them that does not
1145      * involve p1 and p2. Adding all anew might render in a better tree than
1146      * the trivial immediate fix.
1147      * 
1148      * Trivial immiediate fix: try to reconnect to the disconnected node. All
1149      * its children will be reachable trough him.
1150      */
1151     peer_d = peer_info_get_short(d);
1152     best = UINT_MAX;
1153     aux = NULL;
1154     for (p = peer_d->path_head; NULL != p; p = p->next)
1155     {
1156       if ((cost = path_get_cost(peer->tunnels[i]->tree, p)) < best)
1157       {
1158         best = cost;
1159         aux = p;
1160       }
1161     }
1162     if (NULL != aux)
1163     {
1164       /* No callback, as peer will be already disconnected */
1165       tree_add_path(peer->tunnels[i]->tree, aux, NULL);
1166     }
1167     else
1168     {
1169       struct MeshPathInfo *path_info;
1170
1171       if (NULL != peer_d->dhtget)
1172         return;
1173       path_info = GNUNET_malloc(sizeof(struct MeshPathInfo));
1174       path_info->path = p;
1175       path_info->peer = peer_d;
1176       path_info->t = peer->tunnels[i];
1177       peer_d->dhtget =
1178           GNUNET_DHT_get_start(dht_handle,       /* handle */
1179                                GNUNET_TIME_UNIT_FOREVER_REL, /* timeout */
1180                                GNUNET_BLOCK_TYPE_TEST,   /* type */
1181                                &id.hashPubKey,   /*key to search */
1182                                4,        /* replication level */
1183                                GNUNET_DHT_RO_RECORD_ROUTE |
1184                                  GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
1185                                NULL,     /* xquery */
1186                                0,        /* xquery bits */
1187                                &dht_get_id_handler,
1188                                (void *) path_info);
1189     }
1190   }
1191 }
1192
1193
1194 /**
1195  * Add the path to the peer and update the path used to reach it in case this
1196  * is the shortest.
1197  *
1198  * @param peer_info Destination peer to add the path to.
1199  * @param path New path to add. Last peer must be the peer in arg 1.
1200  *             Path will be either used of freed if already known.
1201  *
1202  * TODO: trim the part from origin to us? Add it as path to origin?
1203  */
1204 void
1205 path_add_to_peer (struct MeshPeerInfo *peer_info, struct MeshPeerPath *path)
1206 {
1207   struct MeshPeerPath *aux;
1208   unsigned int l;
1209   unsigned int l2;
1210
1211   if (NULL == peer_info || NULL == path)
1212   {
1213     GNUNET_break (0);
1214     return;
1215   }
1216
1217   l = path_get_length (path);
1218   if (0 == l)
1219   {
1220     GNUNET_free (path);
1221     return;
1222   }
1223
1224   for (aux = peer_info->path_head; aux != NULL; aux = aux->next)
1225   {
1226     l2 = path_get_length (aux);
1227     if (l2 > l)
1228     {
1229       GNUNET_CONTAINER_DLL_insert_before (peer_info->path_head,
1230                                           peer_info->path_tail, aux, path);
1231     }
1232     else
1233     {
1234       if (l2 == l && memcmp(path->peers, aux->peers, l) == 0)
1235       {
1236         path_destroy(path);
1237         return;
1238       }
1239     }
1240   }
1241   GNUNET_CONTAINER_DLL_insert_tail (peer_info->path_head, peer_info->path_tail,
1242                                     path);
1243   return;
1244 }
1245
1246
1247 /**
1248  * Add the path to the origin peer and update the path used to reach it in case
1249  * this is the shortest.
1250  * The path is given in peer_info -> destination, therefore we turn the path
1251  * upside down first.
1252  *
1253  * @param peer_info Peer to add the path to, being the origin of the path.
1254  * @param path New path to add after being inversed.
1255  */
1256 static void
1257 path_add_to_origin (struct MeshPeerInfo *peer_info, struct MeshPeerPath *path)
1258 {
1259   path_invert(path);
1260   path_add_to_peer (peer_info, path);
1261 }
1262
1263
1264 /**
1265  * Build a PeerPath from the paths returned from the DHT, reversing the paths
1266  * to obtain a local peer -> destination path and interning the peer ids.
1267  *
1268  * @return Newly allocated and created path
1269  */
1270 static struct MeshPeerPath *
1271 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
1272                      unsigned int get_path_length,
1273                      const struct GNUNET_PeerIdentity *put_path,
1274                      unsigned int put_path_length)
1275 {
1276   struct MeshPeerPath *p;
1277   GNUNET_PEER_Id id;
1278   int i;
1279
1280   p = path_new (1);
1281   p->peers[0] = myid;
1282   GNUNET_PEER_change_rc(myid, 1);
1283   i = get_path_length;
1284   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "MESH:    GET has %d hops.\n", i);
1285   for (i--; i >= 0; i--)
1286   {
1287     id = GNUNET_PEER_intern (&get_path[i]);
1288     if (p->length > 0 && id == p->peers[p->length - 1])
1289     {
1290       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "MESH:    Optimizing 1 hop out.\n");
1291       GNUNET_PEER_change_rc(id, -1);
1292     }
1293     else
1294     {
1295       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1296                  "MESH:    Adding from GET: %s.\n",
1297                  GNUNET_i2s(&get_path[i]));
1298       p->length++;
1299       p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
1300       p->peers[p->length - 1] = id;
1301     }
1302   }
1303   i = put_path_length;
1304   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "MESH:    PUT has %d hops.\n", i);
1305   for (i--; i >= 0; i--)
1306   {
1307     id = GNUNET_PEER_intern (&put_path[i]);
1308     if (id == myid)
1309     {
1310       /* PUT path went through us, so discard the path up until now and start
1311        * from here to get a much shorter (and loop-free) path.
1312        */
1313       path_destroy (p);
1314       p = path_new (0);
1315     }
1316     if (p->length > 0 && id == p->peers[p->length - 1])
1317     {
1318       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "MESH:    Optimizing 1 hop out.\n");
1319       GNUNET_PEER_change_rc(id, -1);
1320     }
1321     else
1322     {
1323       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1324             "MESH:    Adding from PUT: %s.\n",
1325             GNUNET_i2s(&put_path[i]));
1326       p->length++;
1327       p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
1328       p->peers[p->length - 1] = id;
1329     }
1330   }
1331 #if MESH_DEBUG
1332   if (get_path_length > 0)
1333     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1334                 "MESH:    (first of GET: %s)\n",
1335                 GNUNET_h2s_full(&get_path[0].hashPubKey));
1336   if (put_path_length > 0)
1337     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1338                 "MESH:    (first of PUT: %s)\n",
1339                 GNUNET_h2s_full(&put_path[0].hashPubKey));
1340   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1341               "MESH:    In total: %d hops\n",
1342               p->length);
1343   for (i = 0; i < p->length; i++)
1344   {
1345     struct GNUNET_PeerIdentity peer_id;
1346
1347     GNUNET_PEER_resolve(p->peers[i], &peer_id);
1348     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1349               "MESH:        %u: %s\n",
1350               p->peers[i],
1351               GNUNET_h2s_full(&peer_id.hashPubKey));
1352   }
1353 #endif
1354   return p;
1355 }
1356
1357
1358 /**
1359  * Send keepalive packets for a peer
1360  *
1361  * @param cls Closure (tunnel for which to send the keepalive).
1362  * @param tc Notification context.
1363  *
1364  * TODO: implement explicit multicast keepalive?
1365  */
1366 void
1367 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1368
1369
1370 /**
1371  * Search for a tunnel among the tunnels for a client
1372  *
1373  * @param c the client whose tunnels to search in
1374  * @param tid the local id of the tunnel
1375  *
1376  * @return tunnel handler, NULL if doesn't exist
1377  */
1378 static struct MeshTunnel *
1379 tunnel_get_by_local_id (struct MeshClient *c, MESH_TunnelNumber tid)
1380 {
1381   GNUNET_HashCode hash;
1382
1383   GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
1384   if (tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
1385   {
1386     return GNUNET_CONTAINER_multihashmap_get (incoming_tunnels, &hash);
1387   }
1388   return GNUNET_CONTAINER_multihashmap_get (c->tunnels, &hash);
1389 }
1390
1391
1392 /**
1393  * Search for a tunnel by global ID using PEER_ID
1394  *
1395  * @param pi owner of the tunnel
1396  * @param tid global tunnel number
1397  *
1398  * @return tunnel handler, NULL if doesn't exist
1399  */
1400 static struct MeshTunnel *
1401 tunnel_get_by_pi (GNUNET_PEER_Id pi, MESH_TunnelNumber tid)
1402 {
1403   struct MESH_TunnelID id;
1404   GNUNET_HashCode hash;
1405
1406   id.oid = pi;
1407   id.tid = tid;
1408
1409   GNUNET_CRYPTO_hash (&id, sizeof (struct MESH_TunnelID), &hash);
1410   return GNUNET_CONTAINER_multihashmap_get (tunnels, &hash);
1411 }
1412
1413
1414 /**
1415  * Search for a tunnel by global ID using full PeerIdentities
1416  *
1417  * @param oid owner of the tunnel
1418  * @param tid global tunnel number
1419  *
1420  * @return tunnel handler, NULL if doesn't exist
1421  */
1422 static struct MeshTunnel *
1423 tunnel_get (struct GNUNET_PeerIdentity *oid, MESH_TunnelNumber tid)
1424 {
1425   return tunnel_get_by_pi (GNUNET_PEER_search (oid), tid);
1426 }
1427
1428
1429 /**
1430  * Callback used to notify a client owner of a tunnel that a peer has
1431  * disconnected, most likely because of a path change.
1432  *
1433  * @param n Node in the tree representing the disconnected peer
1434  */
1435 void
1436 notify_peer_disconnected (const struct MeshTunnelTreeNode *n)
1437 {
1438   struct MeshPeerInfo *peer;
1439
1440   if (NULL != n->t->client && NULL != nc)
1441   {
1442     struct GNUNET_MESH_PeerControl msg;
1443     msg.header.size = htons (sizeof (msg));
1444     msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL);
1445     msg.tunnel_id = htonl (n->t->local_tid);
1446     GNUNET_PEER_resolve (n->peer, &msg.peer);
1447     GNUNET_SERVER_notification_context_unicast (nc, n->t->client->handle,
1448                                                 &msg.header, GNUNET_NO);
1449   }
1450   peer = peer_info_get_short(n->peer);
1451   peer_info_connect(peer, n->t);
1452 }
1453
1454
1455 /**
1456  * Add a peer to a tunnel, accomodating paths accordingly and initializing all
1457  * needed rescources.
1458  * If peer already exists, reevaluate shortest path and change if different.
1459  *
1460  * @param t Tunnel we want to add a new peer to
1461  * @param peer PeerInfo of the peer being added
1462  *
1463  */
1464 static void
1465 tunnel_add_peer (struct MeshTunnel *t, struct MeshPeerInfo *peer)
1466 {
1467   struct GNUNET_PeerIdentity id;
1468   struct MeshPeerPath *best_p;
1469   struct MeshPeerPath *p;
1470   unsigned int best_cost;
1471   unsigned int cost;
1472
1473   GNUNET_PEER_resolve(peer->id, &id);
1474   if (GNUNET_NO ==
1475       GNUNET_CONTAINER_multihashmap_contains(t->peers, &id.hashPubKey))
1476   {
1477     t->peers_total++;
1478     GNUNET_array_append (peer->tunnels, peer->ntunnels, t);
1479     GNUNET_CONTAINER_multihashmap_put(
1480       t->peers,
1481       &id.hashPubKey,
1482       peer,
1483       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1484   }
1485
1486   if (NULL != (p = peer->path_head))
1487   {
1488     best_p = p;
1489     best_cost = path_get_cost(t->tree, p);
1490     while (NULL != p)
1491     {
1492       if ((cost = path_get_cost (t->tree, p)) < best_cost)
1493       {
1494         best_cost = cost;
1495         best_p = p;
1496       }
1497       p = p->next;
1498     }
1499     tree_add_path (t->tree, best_p, &notify_peer_disconnected);
1500     if (GNUNET_SCHEDULER_NO_TASK == t->path_refresh_task)
1501       t->path_refresh_task =
1502           GNUNET_SCHEDULER_add_delayed (t->tree->refresh, &path_refresh, t);
1503   }
1504   else
1505   {
1506     /* Start a DHT get if necessary */
1507     peer_info_connect(peer, t);
1508   }
1509 }
1510
1511 /**
1512  * Add a path to a tunnel which we don't own, just to remember the next hop.
1513  * If destination node was already in the tunnel, the first hop information
1514  * will be replaced with the new path.
1515  *
1516  * @param t Tunnel we want to add a new peer to
1517  * @param p Path to add
1518  * @param own_pos Position of local node in path.
1519  *
1520  */
1521 static void
1522 tunnel_add_path (struct MeshTunnel *t,
1523                  struct MeshPeerPath *p,
1524                  unsigned int own_pos)
1525 {
1526   struct GNUNET_PeerIdentity id;
1527
1528   GNUNET_assert (0 != own_pos);
1529   tree_add_path(t->tree, p, NULL);
1530   if (NULL == t->tree->me)
1531     t->tree->me = tree_find_peer(t->tree->root, p->peers[own_pos]);
1532   if (own_pos < p->length - 1)
1533   {
1534     GNUNET_PEER_resolve (p->peers[own_pos + 1], &id);
1535     tree_update_first_hops(t->tree, t->tree->me, &id);
1536   }
1537 }
1538
1539
1540 /**
1541  * Notify a tunnel that a connection has broken that affects at least
1542  * some of its peers.
1543  *
1544  * @param t Tunnel affected.
1545  * @param peer Peer that (at least) has been affected by the disconnection.
1546  * @param p1 Peer that got disconnected from p2.
1547  * @param p2 Peer that got disconnected from p1.
1548  *
1549  * @return Short ID of the peer disconnected (either p1 or p2).
1550  *         0 if the tunnel remained unaffected.
1551  */
1552 static GNUNET_PEER_Id
1553 tunnel_notify_connection_broken (struct MeshTunnel *t,
1554                                  struct MeshPeerInfo *peer,
1555                                  GNUNET_PEER_Id p1,
1556                                  GNUNET_PEER_Id p2)
1557 {
1558   return tree_notify_connection_broken (t->tree, p1, p2,
1559                                         &notify_peer_disconnected);
1560 }
1561
1562
1563 /**
1564  * Destroy the tunnel and free any allocated resources linked to it
1565  *
1566  * @param t the tunnel to destroy
1567  *
1568  * @return GNUNET_OK on success
1569  */
1570 static int
1571 tunnel_destroy (struct MeshTunnel *t)
1572 {
1573   struct MeshClient *c;
1574   struct MeshQueue *q;
1575   struct MeshQueue *qn;
1576   GNUNET_HashCode hash;
1577   int r;
1578
1579   if (NULL == t)
1580     return GNUNET_OK;
1581
1582   c = t->client;
1583 #if MESH_DEBUG
1584   {
1585     struct GNUNET_PeerIdentity id;
1586
1587     GNUNET_PEER_resolve(t->id.oid, &id);
1588     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1589                 "MESH: destroying tunnel %s [%x]\n",
1590                 GNUNET_i2s (&id),
1591                 t->id.tid);
1592     if (NULL != c)
1593       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   by client %u\n", c->id);
1594   }
1595 #endif
1596
1597   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
1598   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &hash, t))
1599   {
1600     r = GNUNET_SYSERR;
1601   }
1602
1603   GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
1604   if (NULL != c && GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (c->tunnels, &hash, t))
1605   {
1606     r = GNUNET_SYSERR;
1607   }
1608   if (t->local_tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
1609   {
1610     GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
1611     GNUNET_break (GNUNET_YES ==
1612       GNUNET_CONTAINER_multihashmap_remove (incoming_tunnels, &hash, t));
1613   }
1614
1615   GNUNET_CONTAINER_multihashmap_iterate(t->peers, &peer_info_delete_tunnel, t);
1616   GNUNET_CONTAINER_multihashmap_destroy (t->peers);
1617   q = t->queue_head;
1618   while (NULL != q)
1619   {
1620     if (NULL != q->data)
1621       GNUNET_free (q->data);
1622     qn = q->next;
1623     GNUNET_free (q);
1624     q = qn;
1625     /* TODO cancel core transmit ready in case it was active */
1626   }
1627   tree_destroy(t->tree);
1628   if (NULL != t->dht_get_type)
1629     GNUNET_DHT_get_stop(t->dht_get_type);
1630   GNUNET_free (t);
1631   return r;
1632 }
1633
1634
1635 /**
1636  * tunnel_destroy_iterator: iterator for deleting each tunnel that belongs to a
1637  * client when the client disconnects.
1638  * 
1639  * @param cls closure (client that is disconnecting)
1640  * @param key the hash of the local tunnel id (used to access the hashmap)
1641  * @param value the value stored at the key (tunnel to destroy)
1642  * 
1643  * @return GNUNET_OK on success
1644  */
1645 static int
1646 tunnel_destroy_iterator (void *cls, const GNUNET_HashCode * key, void *value)
1647 {
1648   struct MeshTunnel *t = value;
1649   int r;
1650
1651   if (NULL != t->dht_get_type)
1652   {
1653     GNUNET_DHT_get_stop (t->dht_get_type);
1654   }
1655   r = tunnel_destroy (t);
1656   return r;
1657 }
1658
1659
1660 /******************************************************************************/
1661 /****************      MESH NETWORK HANDLER HELPERS     ***********************/
1662 /******************************************************************************/
1663
1664 /**
1665  * Function called to notify a client about the socket
1666  * being ready to queue more data.  "buf" will be
1667  * NULL and "size" zero if the socket was closed for
1668  * writing in the meantime.
1669  *
1670  * @param cls closure
1671  * @param size number of bytes available in buf
1672  * @param buf where the callee should write the message
1673  * @return number of bytes written to buf
1674  */
1675 static size_t
1676 send_core_create_path (void *cls, size_t size, void *buf)
1677 {
1678   struct MeshPathInfo *info = cls;
1679   struct GNUNET_MESH_ManipulatePath *msg;
1680   struct GNUNET_PeerIdentity *peer_ptr;
1681   struct MeshPeerInfo *peer = info->peer;
1682   struct MeshTunnel *t = info->t;
1683   struct MeshPeerPath *p = info->path;
1684   size_t size_needed;
1685   int i;
1686
1687   size_needed =
1688       sizeof (struct GNUNET_MESH_ManipulatePath) +
1689       p->length * sizeof (struct GNUNET_PeerIdentity);
1690
1691   if (size < size_needed || NULL == buf)
1692   {
1693     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: create path retransmit!\n");
1694     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   buf:  %p\n", buf);
1695     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   size: (%u/%u)\n",
1696                 size, size_needed);
1697     info->peer->core_transmit[info->pos] = 
1698       GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
1699                                         GNUNET_TIME_UNIT_FOREVER_REL,
1700                                         path_get_first_hop (t->tree, peer->id),
1701                                         size_needed,
1702                                         &send_core_create_path,
1703                                         info);
1704     return 0;
1705   }
1706   info->peer->core_transmit[info->pos] = NULL;
1707
1708   msg = (struct GNUNET_MESH_ManipulatePath *) buf;
1709   msg->header.size = htons (size_needed);
1710   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE);
1711   msg->tid = ntohl (t->id.tid);
1712
1713   peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
1714   for (i = 0; i < p->length; i++)
1715   {
1716     GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
1717   }
1718
1719   path_destroy (p);
1720   GNUNET_free (info);
1721
1722   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1723               "MESH: CREATE PATH (%u bytes long) sent!\n",
1724               size_needed);
1725   return size_needed;
1726 }
1727
1728
1729 #if LATER
1730 /**
1731  * Function called to notify a client about the socket
1732  * being ready to queue more data.  "buf" will be
1733  * NULL and "size" zero if the socket was closed for
1734  * writing in the meantime.
1735  *
1736  * @param cls closure (MeshDataDescriptor with all info to build packet)
1737  * @param size number of bytes available in buf
1738  * @param buf where the callee should write the message
1739  * @return number of bytes written to buf
1740  */
1741 static size_t
1742 send_core_data_to_origin (void *cls, size_t size, void *buf)
1743 {
1744   struct MeshDataDescriptor *info = cls;
1745   struct GNUNET_MESH_ToOrigin *msg = buf;
1746   size_t total_size;
1747
1748   GNUNET_assert (NULL != info);
1749   total_size = sizeof (struct GNUNET_MESH_ToOrigin) + info->size;
1750   GNUNET_assert (total_size < 65536);   /* UNIT16_MAX */
1751
1752   if (total_size > size)
1753   {
1754     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1755                 "not enough buffer to send data to origin\n");
1756     return 0;
1757   }
1758   msg->header.size = htons (total_size);
1759   msg->header.type = htons (GNUNET_MESSAGE_TYPE_DATA_MESSAGE_TO_ORIGIN);
1760   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
1761   msg->tid = htonl (info->origin->tid);
1762   if (0 != info->size)
1763   {
1764     memcpy (&msg[1], &info[1], info->size);
1765   }
1766   if (NULL != info->client)
1767   {
1768     GNUNET_SERVER_receive_done (info->client, GNUNET_OK);
1769   }
1770   GNUNET_free (info);
1771   return total_size;
1772 }
1773 #endif
1774
1775
1776 /**
1777  * Function called to notify a client about the socket
1778  * being ready to queue more data.  "buf" will be
1779  * NULL and "size" zero if the socket was closed for
1780  * writing in the meantime.
1781  *
1782  * @param cls closure (data itself)
1783  * @param size number of bytes available in buf
1784  * @param buf where the callee should write the message
1785  * 
1786  * @return number of bytes written to buf
1787  */
1788 static size_t
1789 send_core_data_multicast (void *cls, size_t size, void *buf)
1790 {
1791   struct MeshDataDescriptor *info = cls;
1792   struct GNUNET_MESH_Multicast *msg = buf;
1793   size_t total_size;
1794
1795   GNUNET_assert (NULL != info);
1796   GNUNET_assert (NULL != info->peer);
1797   total_size = info->size + sizeof (struct GNUNET_MESH_Multicast);
1798   GNUNET_assert (total_size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1799
1800   if (total_size > size)
1801   {
1802     /* Retry */
1803     struct GNUNET_PeerIdentity id;
1804
1805     GNUNET_PEER_resolve(info->peer->id, &id);
1806     info->peer->infos[info->handler_n] = info;
1807     info->peer->types[info->handler_n] = GNUNET_MESSAGE_TYPE_MESH_MULTICAST;
1808     info->peer->core_transmit[info->handler_n] =
1809       GNUNET_CORE_notify_transmit_ready (core_handle,
1810                                          0,
1811                                          0,
1812                                          GNUNET_TIME_UNIT_FOREVER_REL,
1813                                          &id,
1814                                          total_size,
1815                                          &send_core_data_multicast,
1816                                          info);
1817     return 0;
1818   }
1819   info->peer->core_transmit[info->handler_n] = NULL;
1820   info->peer->infos[info->handler_n] = NULL;
1821   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
1822   msg->header.size = htons (total_size);
1823   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
1824   msg->tid = htonl (info->origin->tid);
1825   memcpy (&msg[1], info->data, info->size);
1826   if (0 == --(*info->copies))
1827   {
1828     if (NULL != info->client)
1829     {
1830       /* FIXME One unresponsive neighbor (who doesn't "call" tmt_rdy) can lock
1831        *       the client from sending anything else to the service.
1832        *       - Call receive_done after certain timeout.
1833        *       - Here cancel the timeout.
1834        */
1835       GNUNET_SERVER_receive_done (info->client, GNUNET_OK);
1836     }
1837     GNUNET_free (info->data);
1838     GNUNET_free (info->copies);
1839   }
1840   GNUNET_free (info);
1841   return total_size;
1842 }
1843
1844
1845 /**
1846  * Function called to notify a client about the socket
1847  * being ready to queue more data.  "buf" will be
1848  * NULL and "size" zero if the socket was closed for
1849  * writing in the meantime.
1850  *
1851  * @param cls closure (MeshDataDescriptor)
1852  * @param size number of bytes available in buf
1853  * @param buf where the callee should write the message
1854  * @return number of bytes written to buf
1855  */
1856 static size_t
1857 send_core_path_ack (void *cls, size_t size, void *buf)
1858 {
1859   struct MeshDataDescriptor *info = cls;
1860   struct GNUNET_MESH_PathACK *msg = buf;
1861
1862   GNUNET_assert (NULL != info);
1863   if (info->peer)
1864   {
1865     info->peer->core_transmit[info->handler_n] = NULL;
1866   }
1867   if (sizeof (struct GNUNET_MESH_PathACK) > size)
1868   {
1869     GNUNET_break (0);
1870     return 0;
1871   }
1872   msg->header.size = htons (sizeof (struct GNUNET_MESH_PathACK));
1873   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_ACK);
1874   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
1875   msg->tid = htonl (info->origin->tid);
1876   msg->peer_id = my_full_id;
1877   GNUNET_free (info);
1878   /* TODO add signature */
1879
1880   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: PATH ACK sent!\n");
1881   return sizeof (struct GNUNET_MESH_PathACK);
1882 }
1883
1884
1885 /**
1886  * Function called to notify a client about the socket
1887  * being ready to queue more data.  "buf" will be
1888  * NULL and "size" zero if the socket was closed for
1889  * writing in the meantime.
1890  *
1891  * @param cls closure (data itself)
1892  * @param size number of bytes available in buf
1893  * @param buf where the callee should write the message
1894  * @return number of bytes written to buf
1895  */
1896 static size_t
1897 send_core_data_raw (void *cls, size_t size, void *buf)
1898 {
1899   struct GNUNET_MessageHeader *msg = cls;
1900   size_t total_size;
1901
1902   GNUNET_assert (NULL != msg);
1903   total_size = ntohs (msg->size);
1904
1905   if (total_size > size)
1906   {
1907     GNUNET_break (0);
1908     return 0;
1909   }
1910   memcpy (buf, msg, total_size);
1911   GNUNET_free (cls);
1912   return total_size;
1913 }
1914
1915
1916 #if LATER
1917 /**
1918  * Send another peer a notification to destroy a tunnel
1919  * @param cls The tunnel to destroy
1920  * @param size Size in the buffer
1921  * @param buf Memory where to put the data to transmit
1922  * @return Size of data put in buffer
1923  */
1924 static size_t
1925 send_p2p_tunnel_destroy (void *cls, size_t size, void *buf)
1926 {
1927   struct MeshTunnel *t = cls;
1928   struct MeshClient *c;
1929   struct GNUNET_MESH_TunnelMessage *msg;
1930
1931   c = t->client;
1932   msg = buf;
1933   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
1934    /*FIXME*/ msg->header.size =
1935       htons (sizeof (struct GNUNET_MESH_TunnelMessage));
1936   msg->tunnel_id = htonl (t->id.tid);
1937
1938   tunnel_destroy (c, t);
1939   return sizeof (struct GNUNET_MESH_TunnelMessage);
1940 }
1941 #endif
1942
1943
1944 /******************************************************************************/
1945 /********************      MESH NETWORK HANDLERS     **************************/
1946 /******************************************************************************/
1947
1948
1949 /**
1950  * Core handler for path creation
1951  * struct GNUNET_CORE_MessageHandler
1952  *
1953  * @param cls closure
1954  * @param message message
1955  * @param peer peer identity this notification is about
1956  * @param atsi performance data
1957  * @return GNUNET_OK to keep the connection open,
1958  *         GNUNET_SYSERR to close it (signal serious error)
1959  *
1960  */
1961 static int
1962 handle_mesh_path_create (void *cls, const struct GNUNET_PeerIdentity *peer,
1963                          const struct GNUNET_MessageHeader *message,
1964                          const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1965 {
1966   unsigned int own_pos;
1967   uint16_t size;
1968   uint16_t i;
1969   MESH_TunnelNumber tid;
1970   struct GNUNET_MESH_ManipulatePath *msg;
1971   struct GNUNET_PeerIdentity *pi;
1972   GNUNET_HashCode hash;
1973   struct MeshPeerPath *path;
1974   struct MeshPeerInfo *dest_peer_info;
1975   struct MeshPeerInfo *orig_peer_info;
1976   struct MeshTunnel *t;
1977
1978   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1979               "MESH: Received a path create msg [%s]\n",
1980               GNUNET_i2s(&my_full_id));
1981   size = ntohs (message->size);
1982   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
1983   {
1984     GNUNET_break_op (0);
1985     return GNUNET_OK;
1986   }
1987
1988   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
1989   if (size % sizeof (struct GNUNET_PeerIdentity))
1990   {
1991     GNUNET_break_op (0);
1992     return GNUNET_OK;
1993   }
1994   size /= sizeof (struct GNUNET_PeerIdentity);
1995   if (size < 2)
1996   {
1997     GNUNET_break_op (0);
1998     return GNUNET_OK;
1999   }
2000   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2001               "MESH:     path has %u hops.\n",
2002               size);
2003   msg = (struct GNUNET_MESH_ManipulatePath *) message;
2004
2005   tid = ntohl (msg->tid);
2006   pi = (struct GNUNET_PeerIdentity *) &msg[1];
2007   t = tunnel_get (pi, tid);
2008   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2009               "MESH:     path is for tunnel %s [%X].\n",
2010               GNUNET_i2s(pi),
2011               tid);
2012   if (NULL == t)
2013   {
2014     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   Creating tunnel\n");
2015     t = GNUNET_malloc (sizeof (struct MeshTunnel));
2016     t->id.oid = GNUNET_PEER_intern (pi);
2017     t->id.tid = tid;
2018     t->peers = GNUNET_CONTAINER_multihashmap_create (32);
2019     t->local_tid = next_local_tid++;
2020     /* FIXME test if taken */
2021     next_local_tid |= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
2022     t->tree = tree_new(t, t->id.oid);
2023
2024     GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
2025     if (GNUNET_OK !=
2026         GNUNET_CONTAINER_multihashmap_put (
2027             tunnels,
2028             &hash,
2029             t,
2030             GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2031     {
2032       tunnel_destroy(t);
2033       GNUNET_break (0);
2034       return GNUNET_OK;
2035     }
2036     GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
2037     if (GNUNET_OK !=
2038         GNUNET_CONTAINER_multihashmap_put (
2039             incoming_tunnels,
2040             &hash,
2041             t,
2042             GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2043     {
2044       tunnel_destroy(t);
2045       GNUNET_break (0);
2046       return GNUNET_OK;
2047     }
2048   }
2049   dest_peer_info =
2050       GNUNET_CONTAINER_multihashmap_get (peers, &pi[size - 1].hashPubKey);
2051   if (NULL == dest_peer_info)
2052   {
2053     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2054                 "MESH:   Creating PeerInfo for destination.\n");
2055     dest_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
2056     dest_peer_info->id = GNUNET_PEER_intern (&pi[size - 1]);
2057     GNUNET_CONTAINER_multihashmap_put (peers, &pi[size - 1].hashPubKey,
2058                                        dest_peer_info,
2059                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2060   }
2061   orig_peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &pi->hashPubKey);
2062   if (NULL == orig_peer_info)
2063   {
2064     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2065                 "MESH:   Creating PeerInfo for origin.\n");
2066     orig_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
2067     orig_peer_info->id = GNUNET_PEER_intern (pi);
2068     GNUNET_CONTAINER_multihashmap_put (peers, &pi->hashPubKey, orig_peer_info,
2069                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2070   }
2071   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   Creating path...\n");
2072   path = path_new (size);
2073   own_pos = 0;
2074   for (i = 0; i < size; i++)
2075   {
2076     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2077                 "MESH:   ... adding %s\n",
2078                 GNUNET_i2s(&pi[i]));
2079     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
2080     if (path->peers[i] == myid)
2081       own_pos = i;
2082   }
2083   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2084                 "MESH:   Own position: %u\n", own_pos);
2085   if (own_pos == 0)
2086   {
2087     /* cannot be self, must be 'not found' */
2088     /* create path: self not found in path through self */
2089     GNUNET_break_op (0);
2090     path_destroy (path);
2091     /* FIXME error. destroy tunnel? leave for timeout? */
2092     return 0;
2093   }
2094   tunnel_add_path (t, path, own_pos);
2095   t->tree->me = tree_find_peer(t->tree->root, myid);
2096   if (own_pos == size - 1)
2097   {
2098     /* It is for us! Send ack. */
2099     struct GNUNET_MESH_TunnelNotification cmsg;
2100     struct MeshDataDescriptor *info;
2101     unsigned int j;
2102
2103     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2104                 "MESH:   It's for us!\n");
2105     path_add_to_origin (orig_peer_info, path);
2106     info = GNUNET_malloc (sizeof (struct MeshDataDescriptor));
2107     info->origin = &t->id;
2108     info->peer = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
2109     GNUNET_assert (NULL != info->peer);
2110     j = peer_info_transmit_slot(info->peer);
2111     info->handler_n = j;
2112     info->peer->types[j] = GNUNET_MESSAGE_TYPE_MESH_PATH_ACK;
2113     info->peer->infos[j] = info;
2114     info->peer->core_transmit[j] =
2115         GNUNET_CORE_notify_transmit_ready (core_handle, 0, 100,
2116                                            GNUNET_TIME_UNIT_FOREVER_REL, peer,
2117                                            sizeof (struct GNUNET_MESH_PathACK),
2118                                            &send_core_path_ack, info);
2119     cmsg.header.size = htons(sizeof(cmsg));
2120     cmsg.header.type = htons(GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
2121     GNUNET_PEER_resolve(t->id.oid, &cmsg.peer);
2122     cmsg.tunnel_id = htonl(t->local_tid);
2123     GNUNET_SERVER_notification_context_broadcast(nc, &cmsg.header, GNUNET_NO);
2124   }
2125   else
2126   {
2127     struct MeshPeerPath *path2;
2128
2129     /* It's for somebody else! Retransmit. */
2130     path2 = path_duplicate(path);
2131     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2132                 "MESH:   Retransmitting.\n");
2133     path_add_to_peer(dest_peer_info, path);
2134     path = path_duplicate(path2);
2135     path_add_to_origin(orig_peer_info, path2);
2136     send_create_path(dest_peer_info, path, t);
2137   }
2138   return GNUNET_OK;
2139 }
2140
2141
2142 /**
2143  * Core handler for mesh network traffic going from the origin to a peer
2144  *
2145  * @param cls closure
2146  * @param peer peer identity this notification is about
2147  * @param message message
2148  * @param atsi performance data
2149  * @return GNUNET_OK to keep the connection open,
2150  *         GNUNET_SYSERR to close it (signal serious error)
2151  */
2152 static int
2153 handle_mesh_data_unicast (void *cls, const struct GNUNET_PeerIdentity *peer,
2154                           const struct GNUNET_MessageHeader *message,
2155                           const struct GNUNET_TRANSPORT_ATS_Information *atsi)
2156 {
2157   struct GNUNET_MESH_Unicast *msg;
2158   struct MeshTunnel *t;
2159   GNUNET_PEER_Id pid;
2160   size_t size;
2161
2162   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2163               "MESH: got a unicast packet from %s\n",
2164               GNUNET_i2s (peer));
2165   size = ntohs (message->size);
2166   if (size <
2167       sizeof (struct GNUNET_MESH_Unicast) +
2168       sizeof (struct GNUNET_MessageHeader))
2169   {
2170     GNUNET_break (0);
2171     return GNUNET_OK;
2172   }
2173   msg = (struct GNUNET_MESH_Unicast *) message;
2174   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2175               "MESH:  of type %u\n",
2176               ntohs (msg[1].header.type));
2177   t = tunnel_get (&msg->oid, ntohl (msg->tid));
2178   if (NULL == t)
2179   {
2180     /* TODO notify back: we don't know this tunnel */
2181     GNUNET_break_op (0);
2182     return GNUNET_OK;
2183   }
2184   pid = GNUNET_PEER_search(&msg->destination);
2185   if (pid == myid)
2186   {
2187     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2188                 "MESH:   it's for us! sending to clients...\n");
2189     send_subscribed_clients (message, (struct GNUNET_MessageHeader *) &msg[1]);
2190     return GNUNET_OK;
2191   }
2192   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2193               "MESH:   not for us, retransmitting...\n");
2194   msg = GNUNET_malloc (size);
2195   memcpy (msg, message, size);
2196   GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
2197                                      GNUNET_TIME_UNIT_FOREVER_REL,
2198                                      path_get_first_hop (t->tree, pid),
2199                                      size,
2200                                      &send_core_data_raw, msg);
2201   return GNUNET_OK;
2202 }
2203
2204
2205 /**
2206  * Core handler for mesh network traffic going from the origin to all peers
2207  *
2208  * @param cls closure
2209  * @param message message
2210  * @param peer peer identity this notification is about
2211  * @param atsi performance data
2212  * @return GNUNET_OK to keep the connection open,
2213  *         GNUNET_SYSERR to close it (signal serious error)
2214  *
2215  * TODO: Check who we got this from, to validate route.
2216  */
2217 static int
2218 handle_mesh_data_multicast (void *cls, const struct GNUNET_PeerIdentity *peer,
2219                             const struct GNUNET_MessageHeader *message,
2220                             const struct GNUNET_TRANSPORT_ATS_Information *atsi)
2221 {
2222   struct GNUNET_MESH_Multicast *msg;
2223   struct GNUNET_PeerIdentity *id;
2224   struct MeshDataDescriptor *info;
2225   struct MeshTunnelTreeNode *n;
2226   struct MeshTunnel *t;
2227   unsigned int *copies;
2228   unsigned int i;
2229   size_t size;
2230   void *data;
2231
2232   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_Multicast);
2233   if (size < sizeof (struct GNUNET_MessageHeader))
2234   {
2235     GNUNET_break_op (0);
2236     return GNUNET_OK;
2237   }
2238   msg = (struct GNUNET_MESH_Multicast *) message;
2239   t = tunnel_get (&msg->oid, ntohl (msg->tid));
2240
2241   if (NULL == t)
2242   {
2243     /* TODO notify that we dont know that tunnel */
2244     GNUNET_break_op (0);
2245     return GNUNET_OK;
2246   }
2247
2248   /* Transmit to locally interested clients */
2249   if (GNUNET_CONTAINER_multihashmap_contains (t->peers, &my_full_id.hashPubKey))
2250   {
2251     send_subscribed_clients (message, (struct GNUNET_MessageHeader *) &msg[1]);
2252   }
2253   n = t->tree->me->children_head;
2254   if (NULL == n)
2255     return GNUNET_OK;
2256   copies = GNUNET_malloc (sizeof (unsigned int));
2257   for (*copies = 0; NULL != n; n = n->next)
2258     (*copies)++;
2259   n = t->tree->me->children_head;
2260   data = GNUNET_malloc (size);
2261   memcpy (data, &msg[1], size);
2262   while (NULL != n)
2263   {
2264     info = GNUNET_malloc (sizeof (struct MeshDataDescriptor));
2265     info->origin = &t->id;
2266     info->data = data;
2267     info->size = size;
2268     info->copies = copies;
2269     info->client = t->client->handle;
2270     info->destination = n->peer;
2271     id = path_get_first_hop(t->tree, n->peer);
2272     info->peer = peer_info_get(id);
2273     GNUNET_assert (NULL != info->peer);
2274     for (i = 0; NULL != info->peer->core_transmit[i]; i++)
2275     {
2276       if (i == (CORE_QUEUE_SIZE - 1))
2277       {
2278         GNUNET_free (info);
2279         GNUNET_break (0);
2280         return GNUNET_OK;
2281       }
2282     }
2283     info->handler_n = i;
2284     info->peer->infos[i] = info;
2285     info->peer->types[i] = GNUNET_MESSAGE_TYPE_MESH_MULTICAST;
2286     info->peer->core_transmit[i] =
2287         GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
2288                                            GNUNET_TIME_UNIT_FOREVER_REL, id,
2289                                            ntohs (msg->header.size),
2290                                            &send_core_data_multicast, info);
2291   }
2292
2293   return GNUNET_OK;
2294 }
2295
2296
2297 /**
2298  * Core handler for mesh network traffic
2299  *
2300  * @param cls closure
2301  * @param message message
2302  * @param peer peer identity this notification is about
2303  * @param atsi performance data
2304  *
2305  * @return GNUNET_OK to keep the connection open,
2306  *         GNUNET_SYSERR to close it (signal serious error)
2307  */
2308 static int
2309 handle_mesh_data_to_orig (void *cls, const struct GNUNET_PeerIdentity *peer,
2310                           const struct GNUNET_MessageHeader *message,
2311                           const struct GNUNET_TRANSPORT_ATS_Information *atsi)
2312 {
2313   struct GNUNET_MESH_ToOrigin *msg;
2314   struct GNUNET_PeerIdentity id;
2315   struct MeshPeerInfo *peer_info;
2316   struct MeshTunnel *t;
2317   size_t size;
2318
2319   size = ntohs (message->size);
2320   if (size < sizeof (struct GNUNET_MESH_ToOrigin) +     /* Payload must be */
2321       sizeof (struct GNUNET_MessageHeader))     /* at least a header */
2322   {
2323     GNUNET_break_op (0);
2324     return GNUNET_OK;
2325   }
2326   msg = (struct GNUNET_MESH_ToOrigin *) message;
2327   t = tunnel_get (&msg->oid, ntohl (msg->tid));
2328
2329   if (NULL == t)
2330   {
2331     /* TODO notify that we dont know this tunnel (whom)? */
2332     return GNUNET_OK;
2333   }
2334
2335   if (t->id.oid == myid)
2336   {
2337     if (NULL == t->client)
2338     {
2339       /* got data packet for ownerless tunnel */
2340       GNUNET_break_op (0);
2341       return GNUNET_OK;
2342     }
2343     /* TODO signature verification */
2344     GNUNET_SERVER_notification_context_unicast (nc, t->client->handle, message,
2345                                                 GNUNET_YES);
2346     return GNUNET_OK;
2347   }
2348   peer_info = peer_info_get (&msg->oid);
2349   if (NULL == peer_info)
2350   {
2351     /* unknown origin of tunnel */
2352     GNUNET_break (0);
2353     return GNUNET_OK;
2354   }
2355   GNUNET_PEER_resolve (t->tree->me->parent->peer, &id);
2356   msg = GNUNET_malloc (size);
2357   memcpy (msg, message, size);
2358   GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
2359                                      GNUNET_TIME_UNIT_FOREVER_REL, &id, size,
2360                                      &send_core_data_raw, msg);
2361
2362   return GNUNET_OK;
2363 }
2364
2365
2366 /**
2367  * Core handler for path ACKs
2368  *
2369  * @param cls closure
2370  * @param message message
2371  * @param peer peer identity this notification is about
2372  * @param atsi performance data
2373  *
2374  * @return GNUNET_OK to keep the connection open,
2375  *         GNUNET_SYSERR to close it (signal serious error)
2376  */
2377 static int
2378 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
2379                       const struct GNUNET_MessageHeader *message,
2380                       const struct GNUNET_TRANSPORT_ATS_Information *atsi)
2381 {
2382   struct GNUNET_MESH_PathACK *msg;
2383   struct GNUNET_PeerIdentity id;
2384   struct MeshTunnelTreeNode *n;
2385   struct MeshPeerInfo *peer_info;
2386   struct MeshTunnel *t;
2387
2388   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2389               "MESH: Received a path ACK msg [%s]\n",
2390               GNUNET_i2s(&my_full_id));
2391   msg = (struct GNUNET_MESH_PathACK *) message;
2392   t = tunnel_get (&msg->oid, msg->tid);
2393   if (NULL == t)
2394   {
2395     /* TODO notify that we don't know the tunnel */
2396     return GNUNET_OK;
2397   }
2398
2399   /* Message for us? */
2400   if (0 == memcmp (&msg->oid, &my_full_id, sizeof (struct GNUNET_PeerIdentity)))
2401   {
2402     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2403                 "MESH:   It's for us!\n");
2404     if (NULL == t->client)
2405     {
2406       GNUNET_break_op (0);
2407       return GNUNET_OK;
2408     }
2409     peer_info = peer_info_get (&msg->peer_id);
2410     if (NULL == peer_info)
2411     {
2412       GNUNET_break_op (0);
2413       return GNUNET_OK;
2414     }
2415     n = tree_find_peer(t->tree->root, peer_info->id);
2416     if (NULL == n)
2417     {
2418       GNUNET_break_op (0);
2419       return GNUNET_OK;
2420     }
2421     n->status = MESH_PEER_READY;
2422     send_client_peer_connected(t, peer_info->id);
2423     return GNUNET_OK;
2424   }
2425   
2426   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2427               "MESH:   not for us, retransmitting...\n");
2428   GNUNET_PEER_resolve(t->tree->me->parent->peer, &id);
2429   peer_info = peer_info_get (&msg->oid);
2430   if (NULL == peer_info)
2431   {
2432     /* If we know the tunnel, we should DEFINITELY know the peer */
2433     GNUNET_break (0);
2434     return GNUNET_OK;
2435   }
2436   msg = GNUNET_malloc (sizeof (struct GNUNET_MESH_PathACK));
2437   memcpy (msg, message, sizeof (struct GNUNET_MESH_PathACK));
2438   GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
2439                                      GNUNET_TIME_UNIT_FOREVER_REL,
2440                                      &id,
2441                                      sizeof (struct GNUNET_MESH_PathACK),
2442                                      &send_core_data_raw, msg);
2443   return GNUNET_OK;
2444 }
2445
2446
2447 /**
2448  * Functions to handle messages from core
2449  */
2450 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
2451   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
2452   {&handle_mesh_data_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
2453   {&handle_mesh_data_multicast, GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
2454   {&handle_mesh_data_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
2455   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
2456    sizeof (struct GNUNET_MESH_PathACK)},
2457   {NULL, 0, 0}
2458 };
2459
2460
2461
2462 /******************************************************************************/
2463 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
2464 /******************************************************************************/
2465
2466 /**
2467  * deregister_app: iterator for removing each application registered by a client
2468  * 
2469  * @param cls closure
2470  * @param key the hash of the application id (used to access the hashmap)
2471  * @param value the value stored at the key (client)
2472  * 
2473  * @return GNUNET_OK on success
2474  */
2475 static int
2476 deregister_app (void *cls, const GNUNET_HashCode * key, void *value)
2477 {
2478   GNUNET_break (GNUNET_YES == 
2479       GNUNET_CONTAINER_multihashmap_remove (applications, key, value));
2480   return GNUNET_OK;
2481 }
2482
2483 #if LATER
2484 /**
2485  * notify_client_connection_failure: notify a client that the connection to the
2486  * requested remote peer is not possible (for instance, no route found)
2487  * Function called when the socket is ready to queue more data. "buf" will be
2488  * NULL and "size" zero if the socket was closed for writing in the meantime.
2489  *
2490  * @param cls closure
2491  * @param size number of bytes available in buf
2492  * @param buf where the callee should write the message
2493  * @return number of bytes written to buf
2494  */
2495 static size_t
2496 notify_client_connection_failure (void *cls, size_t size, void *buf)
2497 {
2498   int size_needed;
2499   struct MeshPeerInfo *peer_info;
2500   struct GNUNET_MESH_PeerControl *msg;
2501   struct GNUNET_PeerIdentity id;
2502
2503   if (0 == size && NULL == buf)
2504   {
2505     // TODO retry? cancel?
2506     return 0;
2507   }
2508
2509   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
2510   peer_info = (struct MeshPeerInfo *) cls;
2511   msg = (struct GNUNET_MESH_PeerControl *) buf;
2512   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
2513   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
2514 //     msg->tunnel_id = htonl(peer_info->t->tid);
2515   GNUNET_PEER_resolve (peer_info->id, &id);
2516   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
2517
2518   return size_needed;
2519 }
2520 #endif
2521
2522
2523 /**
2524  * Send keepalive packets for a peer
2525  *
2526  * @param cls Closure (tunnel for which to send the keepalive).
2527  * @param tc Notification context.
2528  *
2529  * TODO: implement explicit multicast keepalive?
2530  */
2531 void
2532 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2533 {
2534   struct MeshTunnel *t = cls;
2535   struct GNUNET_MessageHeader *payload;
2536   struct GNUNET_MESH_Multicast *msg;
2537   size_t size;
2538
2539   t->path_refresh_task = GNUNET_SCHEDULER_NO_TASK;
2540   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
2541   {
2542     return;
2543   }
2544
2545   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2546               "MESH: sending keepalive for tunnel %d\n",
2547               t->id.tid);
2548
2549   size = sizeof(struct GNUNET_MESH_Multicast) +
2550          sizeof(struct GNUNET_MessageHeader);
2551   msg = GNUNET_malloc (size);
2552   msg->header.size = htons (size);
2553   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
2554   msg->oid = my_full_id;
2555   msg->tid = htonl(t->id.tid);
2556   payload = (struct GNUNET_MessageHeader *) &msg[1];
2557   payload->size = htons (sizeof(struct GNUNET_MessageHeader));
2558   payload->type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE);
2559   handle_mesh_data_multicast (NULL, &my_full_id, &msg->header, NULL);
2560
2561   GNUNET_free (msg);
2562   t->path_refresh_task =
2563       GNUNET_SCHEDULER_add_delayed (t->tree->refresh, &path_refresh, t);
2564   return;
2565 }
2566
2567
2568 /**
2569  * Function to process paths received for a new peer addition. The recorded
2570  * paths form the initial tunnel, which can be optimized later.
2571  * Called on each result obtained for the DHT search.
2572  *
2573  * @param cls closure
2574  * @param exp when will this value expire
2575  * @param key key of the result
2576  * @param type type of the result
2577  * @param size number of bytes in data
2578  * @param data pointer to the result data
2579  *
2580  * TODO: re-issue the request after certain time? cancel after X results?
2581  */
2582 static void
2583 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
2584                     const GNUNET_HashCode * key,
2585                     const struct GNUNET_PeerIdentity *get_path,
2586                     unsigned int get_path_length,
2587                     const struct GNUNET_PeerIdentity *put_path,
2588                     unsigned int put_path_length,
2589                     enum GNUNET_BLOCK_Type type, size_t size, const void *data)
2590 {
2591   struct MeshPathInfo *path_info = cls;
2592   struct MeshPeerPath *p;
2593   struct GNUNET_PeerIdentity pi;
2594   int i;
2595
2596   GNUNET_PEER_resolve (path_info->peer->id, &pi);
2597   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2598              "MESH: Got results from DHT for %s\n",
2599              GNUNET_h2s_full(&pi.hashPubKey));
2600   GNUNET_DHT_get_stop(path_info->peer->dhtget);
2601   path_info->peer->dhtget = NULL;
2602
2603   p = path_build_from_dht (get_path, get_path_length,
2604                            put_path, put_path_length);
2605   path_add_to_peer (path_info->peer, p);
2606   for (i = 0; i < path_info->peer->ntunnels; i++)
2607   {
2608     tunnel_add_peer (path_info->peer->tunnels[i], path_info->peer);
2609     peer_info_connect(path_info->peer, path_info->t);
2610   }
2611   GNUNET_free (path_info);
2612
2613   return;
2614 }
2615
2616
2617 /**
2618  * Function to process paths received for a new peer addition. The recorded
2619  * paths form the initial tunnel, which can be optimized later.
2620  * Called on each result obtained for the DHT search.
2621  *
2622  * @param cls closure
2623  * @param exp when will this value expire
2624  * @param key key of the result
2625  * @param type type of the result
2626  * @param size number of bytes in data
2627  * @param data pointer to the result data
2628  */
2629 static void
2630 dht_get_type_handler (void *cls, struct GNUNET_TIME_Absolute exp,
2631                       const GNUNET_HashCode * key,
2632                       const struct GNUNET_PeerIdentity *get_path,
2633                       unsigned int get_path_length,
2634                       const struct GNUNET_PeerIdentity *put_path,
2635                       unsigned int put_path_length,
2636                       enum GNUNET_BLOCK_Type type, size_t size,
2637                       const void *data)
2638 {
2639   const struct GNUNET_PeerIdentity *pi = data;
2640   struct GNUNET_PeerIdentity id;
2641   struct MeshTunnel *t = cls;
2642   struct MeshPeerInfo *peer_info;
2643   struct MeshPathInfo *path_info;
2644   struct MeshPeerPath *p;
2645   int i;
2646
2647   if (size != sizeof (struct GNUNET_PeerIdentity))
2648   {
2649     GNUNET_break_op (0);
2650     return;
2651   }
2652   GNUNET_assert (NULL != t->client);
2653   GNUNET_DHT_get_stop (t->dht_get_type);
2654   t->dht_get_type = NULL;
2655   peer_info = peer_info_get (pi);
2656   GNUNET_CONTAINER_multihashmap_put (t->peers, &pi->hashPubKey, peer_info,
2657                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2658
2659   if ((NULL == get_path || NULL == put_path) && NULL == peer_info->path_head &&
2660       NULL == peer_info->dhtget)
2661   {
2662     path_info = GNUNET_malloc (sizeof (struct MeshPathInfo));
2663     path_info->peer = peer_info;
2664     path_info->t = t;
2665     /* we don't have a route to the peer, let's try a direct lookup */
2666     peer_info->dhtget =
2667         GNUNET_DHT_get_start (dht_handle, /* handle */
2668                               GNUNET_TIME_UNIT_FOREVER_REL, /* timeout */
2669                               GNUNET_BLOCK_TYPE_TEST, /* block type */
2670                               &pi->hashPubKey, /* key to look up */
2671                               10U, /* replication level */
2672                               GNUNET_DHT_RO_RECORD_ROUTE |
2673                                 GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
2674                               /* option to dht: record route */
2675                               NULL,     /* xquery */
2676                               0,        /* xquery bits */
2677                               dht_get_id_handler,  /* callback */
2678                               path_info);       /* closure */
2679     return;
2680   }
2681
2682   p = path_build_from_dht (get_path, get_path_length, put_path, put_path_length);
2683   path_add_to_peer (peer_info, p);
2684   tunnel_add_peer(t, peer_info);
2685   p = tree_get_path_to_peer(t->tree, peer_info->id);
2686 #if MESH_DEBUG
2687   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2688               "MESH: new route for tunnel 0x%x found, has %u hops\n",
2689               t->local_tid, p->length);
2690   for (i = 0; i < p->length; i++)
2691   {
2692     GNUNET_PEER_resolve (p->peers[0], &id);
2693     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:\t%d\t%s\n", i,
2694                 GNUNET_h2s_full (&id.hashPubKey));
2695   }
2696 #endif
2697
2698   if (p->length > 1)
2699   {
2700     send_create_path(peer_info, p, t);
2701     return;
2702   }
2703   path_destroy(p);
2704   send_client_peer_connected(t, myid);
2705 }
2706
2707
2708 /******************************************************************************/
2709 /*********************       MESH LOCAL HANDLES      **************************/
2710 /******************************************************************************/
2711
2712
2713 /**
2714  * Handler for client disconnection
2715  *
2716  * @param cls closure
2717  * @param client identification of the client; NULL
2718  *        for the last call when the server is destroyed
2719  */
2720 static void
2721 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
2722 {
2723   struct MeshClient *c;
2724   struct MeshClient *next;
2725
2726   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: client disconnected\n");
2727   if (client == NULL)
2728      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    (SERVER DOWN)\n");
2729   c = clients;
2730   while (NULL != c)
2731   {
2732     if (c->handle != client && NULL != client)
2733     {
2734       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    ... searching\n");
2735       c = c->next;
2736       continue;
2737     }
2738     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: matching client found\n");
2739     if (NULL != c->tunnels)
2740     {
2741       GNUNET_CONTAINER_multihashmap_iterate (c->tunnels,
2742                                              &tunnel_destroy_iterator,
2743                                              c);
2744       GNUNET_CONTAINER_multihashmap_destroy (c->tunnels);
2745     }
2746
2747     /* deregister clients applications */
2748     if (NULL != c->apps)
2749     {
2750       GNUNET_CONTAINER_multihashmap_iterate (c->apps, &deregister_app, NULL);
2751       GNUNET_CONTAINER_multihashmap_destroy (c->apps);
2752     }
2753     if (0 == GNUNET_CONTAINER_multihashmap_size (applications) &&
2754         GNUNET_SCHEDULER_NO_TASK != announce_applications_task)
2755     {
2756       GNUNET_SCHEDULER_cancel (announce_applications_task);
2757       announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
2758     }
2759     if (NULL != c->types)
2760       GNUNET_CONTAINER_multihashmap_destroy (c->types);
2761     GNUNET_CONTAINER_DLL_remove (clients, clients_tail, c);
2762     next = c->next;
2763     GNUNET_free (c);
2764     c = next;
2765   }
2766
2767   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    done!\n");
2768   return;
2769 }
2770
2771
2772 /**
2773  * Handler for new clients
2774  *
2775  * @param cls closure
2776  * @param client identification of the client
2777  * @param message the actual message, which includes messages the client wants
2778  */
2779 static void
2780 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
2781                          const struct GNUNET_MessageHeader *message)
2782 {
2783   struct GNUNET_MESH_ClientConnect *cc_msg;
2784   struct MeshClient *c;
2785   GNUNET_MESH_ApplicationType *a;
2786   unsigned int size;
2787   uint16_t ntypes;
2788   uint16_t *t;
2789   uint16_t napps;
2790   uint16_t i;
2791
2792   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new client connected\n");
2793   /* Check data sanity */
2794   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
2795   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
2796   ntypes = ntohs (cc_msg->types);
2797   napps = ntohs (cc_msg->applications);
2798   if (size !=
2799       ntypes * sizeof (uint16_t) + napps * sizeof (GNUNET_MESH_ApplicationType))
2800   {
2801     GNUNET_break (0);
2802     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2803     return;
2804   }
2805
2806   /* Create new client structure */
2807   c = GNUNET_malloc (sizeof (struct MeshClient));
2808 #if MESH_DEBUG
2809   c->id = next_client_id++;
2810 #endif
2811   c->handle = client;
2812   a = (GNUNET_MESH_ApplicationType *) &cc_msg[1];
2813   if (napps > 0)
2814   {
2815     GNUNET_MESH_ApplicationType at;
2816     GNUNET_HashCode hc;
2817
2818     c->apps = GNUNET_CONTAINER_multihashmap_create (napps);
2819     for (i = 0; i < napps; i++)
2820     {
2821       at = ntohl (a[i]);
2822       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   app type: %u\n", at);
2823       GNUNET_CRYPTO_hash (&at, sizeof (at), &hc);
2824       /* store in clients hashmap */
2825       GNUNET_CONTAINER_multihashmap_put (c->apps, &hc, c,
2826                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2827       /* store in global hashmap, for announcements */
2828       GNUNET_CONTAINER_multihashmap_put (applications, &hc, c,
2829                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2830     }
2831     if (GNUNET_SCHEDULER_NO_TASK == announce_applications_task)
2832       announce_applications_task =
2833           GNUNET_SCHEDULER_add_now (&announce_applications, NULL);
2834
2835   }
2836   if (ntypes > 0)
2837   {
2838     uint16_t u16;
2839     GNUNET_HashCode hc;
2840
2841     t = (uint16_t *) & a[napps];
2842     c->types = GNUNET_CONTAINER_multihashmap_create (ntypes);
2843     for (i = 0; i < ntypes; i++)
2844     {
2845       u16 = ntohs (t[i]);
2846       GNUNET_CRYPTO_hash (&u16, sizeof (u16), &hc);
2847
2848       /* store in clients hashmap */
2849       GNUNET_CONTAINER_multihashmap_put (c->types, &hc, c,
2850                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2851       /* store in global hashmap */
2852       GNUNET_CONTAINER_multihashmap_put (types, &hc, c,
2853                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2854     }
2855   }
2856   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2857               "MESH:  client has %u+%u subscriptions\n", napps, ntypes);
2858
2859   GNUNET_CONTAINER_DLL_insert (clients, clients_tail, c);
2860   c->tunnels = GNUNET_CONTAINER_multihashmap_create (32);
2861   GNUNET_SERVER_notification_context_add (nc, client);
2862
2863   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2864 #if MESH_DEBUG
2865   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new client processed\n");
2866 #endif
2867 }
2868
2869
2870 /**
2871  * Handler for requests of new tunnels
2872  *
2873  * @param cls closure
2874  * @param client identification of the client
2875  * @param message the actual message
2876  */
2877 static void
2878 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
2879                             const struct GNUNET_MessageHeader *message)
2880 {
2881   struct GNUNET_MESH_TunnelMessage *t_msg;
2882   struct MeshTunnel *t;
2883   struct MeshClient *c;
2884   GNUNET_HashCode hash;
2885
2886   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new tunnel requested\n");
2887
2888   /* Sanity check for client registration */
2889   if (NULL == (c = client_get (client)))
2890   {
2891     GNUNET_break (0);
2892     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2893     return;
2894   }
2895 #if MESH_DEBUG
2896   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   by client %u\n", c->id);
2897 #endif
2898
2899   /* Message sanity check */
2900   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
2901   {
2902     GNUNET_break (0);
2903     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2904     return;
2905   }
2906
2907   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
2908   /* Sanity check for tunnel numbering */
2909   if (0 == (ntohl (t_msg->tunnel_id) & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
2910   {
2911     GNUNET_break (0);
2912     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2913     return;
2914   }
2915   /* Sanity check for duplicate tunnel IDs */
2916   if (NULL != tunnel_get_by_local_id (c, ntohl (t_msg->tunnel_id)))
2917   {
2918     GNUNET_break (0);
2919     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2920     return;
2921   }
2922
2923   t = GNUNET_malloc (sizeof (struct MeshTunnel));
2924   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: CREATED TUNNEL at %p\n", t);
2925   while (NULL != tunnel_get_by_pi (myid, next_tid))
2926     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
2927   t->id.tid = next_tid++;
2928   t->id.oid = myid;
2929   t->local_tid = ntohl (t_msg->tunnel_id);
2930   t->client = c;
2931   t->peers = GNUNET_CONTAINER_multihashmap_create (32);
2932
2933   GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
2934   if (GNUNET_OK !=
2935       GNUNET_CONTAINER_multihashmap_put (c->tunnels, &hash, t,
2936                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2937   {
2938     GNUNET_break (0);
2939     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2940     return;
2941   }
2942
2943   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
2944   if (GNUNET_OK !=
2945       GNUNET_CONTAINER_multihashmap_put (tunnels, &hash, t,
2946                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2947   {
2948     GNUNET_break (0);
2949     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2950     return;
2951   }
2952   t->tree = tree_new (t, myid);
2953   t->tree->refresh = REFRESH_PATH_TIME;
2954   t->tree->root->status = MESH_PEER_READY;
2955   t->tree->me = t->tree->root;
2956
2957   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2958   return;
2959 }
2960
2961
2962 /**
2963  * Handler for requests of deleting tunnels
2964  *
2965  * @param cls closure
2966  * @param client identification of the client
2967  * @param message the actual message
2968  */
2969 static void
2970 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
2971                              const struct GNUNET_MessageHeader *message)
2972 {
2973   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
2974   struct MeshClient *c;
2975   struct MeshTunnel *t;
2976   MESH_TunnelNumber tid;
2977   GNUNET_HashCode hash;
2978
2979   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: destroying tunnel\n");
2980
2981   /* Sanity check for client registration */
2982   if (NULL == (c = client_get (client)))
2983   {
2984     GNUNET_break (0);
2985     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2986     return;
2987   }
2988   /* Message sanity check */
2989   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
2990   {
2991     GNUNET_break (0);
2992     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2993     return;
2994   }
2995 #if MESH_DEBUG
2996   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   by client %u\n", c->id);
2997 #endif
2998   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
2999
3000   /* Retrieve tunnel */
3001   tid = ntohl (tunnel_msg->tunnel_id);
3002
3003   /* Remove from local id hashmap */
3004   GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
3005   t = GNUNET_CONTAINER_multihashmap_get (c->tunnels, &hash);
3006   GNUNET_CONTAINER_multihashmap_remove (c->tunnels, &hash, t);
3007
3008 //     notify_tunnel_destroy(t); FIXME
3009   tunnel_destroy(t);
3010   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3011   return;
3012 }
3013
3014
3015 /**
3016  * Handler for connection requests to new peers
3017  *
3018  * @param cls closure
3019  * @param client identification of the client
3020  * @param message the actual message (PeerControl)
3021  */
3022 static void
3023 handle_local_connect_add (void *cls, struct GNUNET_SERVER_Client *client,
3024                           const struct GNUNET_MessageHeader *message)
3025 {
3026   struct GNUNET_MESH_PeerControl *peer_msg;
3027   struct MeshPeerInfo *peer_info;
3028   struct MeshClient *c;
3029   struct MeshTunnel *t;
3030   MESH_TunnelNumber tid;
3031
3032   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "MESH: Got connection request\n");
3033   /* Sanity check for client registration */
3034   if (NULL == (c = client_get (client)))
3035   {
3036     GNUNET_break (0);
3037     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3038     return;
3039   }
3040
3041   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
3042   /* Sanity check for message size */
3043   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
3044   {
3045     GNUNET_break (0);
3046     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3047     return;
3048   }
3049
3050   /* Tunnel exists? */
3051   tid = ntohl (peer_msg->tunnel_id);
3052   t = tunnel_get_by_local_id (c, tid);
3053   if (NULL == t)
3054   {
3055     GNUNET_break (0);
3056     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3057     return;
3058   }
3059
3060   /* Does client own tunnel? */
3061   if (t->client->handle != client)
3062   {
3063     GNUNET_break (0);
3064     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3065     return;
3066   }
3067   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "MESH:      for %s\n",
3068              GNUNET_h2s_full(&peer_msg->peer.hashPubKey));
3069   peer_info = peer_info_get (&peer_msg->peer);
3070
3071   tunnel_add_peer(t, peer_info);
3072   peer_info_connect(peer_info, t);
3073
3074   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3075   return;
3076 }
3077
3078
3079 /**
3080  * Handler for disconnection requests of peers in a tunnel
3081  *
3082  * @param cls closure
3083  * @param client identification of the client
3084  * @param message the actual message (PeerControl)
3085  */
3086 static void
3087 handle_local_connect_del (void *cls, struct GNUNET_SERVER_Client *client,
3088                           const struct GNUNET_MessageHeader *message)
3089 {
3090   struct GNUNET_MESH_PeerControl *peer_msg;
3091   struct MeshClient *c;
3092   struct MeshTunnel *t;
3093   MESH_TunnelNumber tid;
3094
3095   /* Sanity check for client registration */
3096   if (NULL == (c = client_get (client)))
3097   {
3098     GNUNET_break (0);
3099     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3100     return;
3101   }
3102   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
3103   /* Sanity check for message size */
3104   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
3105   {
3106     GNUNET_break (0);
3107     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3108     return;
3109   }
3110
3111   /* Tunnel exists? */
3112   tid = ntohl (peer_msg->tunnel_id);
3113   t = tunnel_get_by_local_id (c, tid);
3114   if (NULL == t)
3115   {
3116     GNUNET_break (0);
3117     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3118     return;
3119   }
3120
3121   /* Does client own tunnel? */
3122   if (t->client->handle != client)
3123   {
3124     GNUNET_break (0);
3125     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3126     return;
3127   }
3128
3129   /* Ok, delete peer from tunnel */
3130   GNUNET_CONTAINER_multihashmap_remove_all (t->peers,
3131                                             &peer_msg->peer.hashPubKey);
3132
3133   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3134   return;
3135 }
3136
3137
3138 /**
3139  * Handler for connection requests to new peers by type
3140  *
3141  * @param cls closure
3142  * @param client identification of the client
3143  * @param message the actual message (ConnectPeerByType)
3144  */
3145 static void
3146 handle_local_connect_by_type (void *cls, struct GNUNET_SERVER_Client *client,
3147                               const struct GNUNET_MessageHeader *message)
3148 {
3149   struct GNUNET_MESH_ConnectPeerByType *connect_msg;
3150   struct MeshClient *c;
3151   struct MeshTunnel *t;
3152   GNUNET_HashCode hash;
3153   MESH_TunnelNumber tid;
3154
3155   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: got connect by type request\n");
3156   /* Sanity check for client registration */
3157   if (NULL == (c = client_get (client)))
3158   {
3159     GNUNET_break (0);
3160     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3161     return;
3162   }
3163
3164   connect_msg = (struct GNUNET_MESH_ConnectPeerByType *) message;
3165   /* Sanity check for message size */
3166   if (sizeof (struct GNUNET_MESH_ConnectPeerByType) !=
3167       ntohs (connect_msg->header.size))
3168   {
3169     GNUNET_break (0);
3170     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3171     return;
3172   }
3173
3174   /* Tunnel exists? */
3175   tid = ntohl (connect_msg->tunnel_id);
3176   t = tunnel_get_by_local_id (c, tid);
3177   if (NULL == t)
3178   {
3179     GNUNET_break (0);
3180     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3181     return;
3182   }
3183
3184   /* Does client own tunnel? */
3185   if (t->client->handle != client)
3186   {
3187     GNUNET_break (0);
3188     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3189     return;
3190   }
3191
3192   /* Do WE have the service? */
3193   t->type = ntohl (connect_msg->type);
3194   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  type requested: %u\n", t->type);
3195   GNUNET_CRYPTO_hash (&t->type, sizeof (GNUNET_MESH_ApplicationType), &hash);
3196   if (GNUNET_CONTAINER_multihashmap_contains (applications, &hash) ==
3197       GNUNET_YES)
3198   {
3199     /* Yes! Fast forward, add ourselves to the tunnel and send the
3200      * good news to the client
3201      */
3202     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  available locally\n");
3203     GNUNET_CONTAINER_multihashmap_put (t->peers, &my_full_id.hashPubKey,
3204                                        peer_info_get (&my_full_id),
3205                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3206
3207     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  notifying client\n");
3208     send_client_peer_connected(t, myid);
3209     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  Done\n");
3210     GNUNET_SERVER_receive_done (client, GNUNET_OK);
3211     return;
3212   }
3213   /* Ok, lets find a peer offering the service */
3214   if (NULL != t->dht_get_type)
3215   {
3216     GNUNET_DHT_get_stop (t->dht_get_type);
3217   }
3218   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  looking in DHT for %s\n",
3219               GNUNET_h2s_full (&hash));
3220   t->dht_get_type =
3221       GNUNET_DHT_get_start (dht_handle,
3222                             GNUNET_TIME_UNIT_FOREVER_REL,
3223                             GNUNET_BLOCK_TYPE_TEST,
3224                             &hash,
3225                             10U,
3226                             GNUNET_DHT_RO_RECORD_ROUTE |
3227                               GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
3228                             NULL, 0,
3229                             &dht_get_type_handler, t);
3230
3231   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3232   return;
3233 }
3234
3235
3236 /**
3237  * Handler for client traffic directed to one peer
3238  *
3239  * @param cls closure
3240  * @param client identification of the client
3241  * @param message the actual message
3242  */
3243 static void
3244 handle_local_unicast (void *cls, struct GNUNET_SERVER_Client *client,
3245                       const struct GNUNET_MessageHeader *message)
3246 {
3247   struct MeshClient *c;
3248   struct MeshTunnel *t;
3249   struct MeshPeerInfo *pi;
3250   struct GNUNET_MESH_Unicast *data_msg;
3251   MESH_TunnelNumber tid;
3252   size_t size;
3253
3254   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3255               "MESH: Got a unicast request from a client!\n");
3256
3257   /* Sanity check for client registration */
3258   if (NULL == (c = client_get (client)))
3259   {
3260     GNUNET_break (0);
3261     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3262     return;
3263   }
3264   data_msg = (struct GNUNET_MESH_Unicast *) message;
3265   /* Sanity check for message size */
3266   size = ntohs (message->size);
3267   if (sizeof (struct GNUNET_MESH_Unicast) +
3268       sizeof (struct GNUNET_MessageHeader) > size)
3269   {
3270     GNUNET_break (0);
3271     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3272     return;
3273   }
3274
3275   /* Tunnel exists? */
3276   tid = ntohl (data_msg->tid);
3277   t = tunnel_get_by_local_id (c, tid);
3278   if (NULL == t)
3279   {
3280     GNUNET_break (0);
3281     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3282     return;
3283   }
3284
3285   /*  Is it a local tunnel? Then, does client own the tunnel? */
3286   if (NULL != t->client &&
3287       NULL != t->client->handle &&
3288       t->client->handle != client)
3289   {
3290     GNUNET_break (0);
3291     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3292     return;
3293   }
3294
3295   pi = GNUNET_CONTAINER_multihashmap_get (t->peers,
3296                                           &data_msg->destination.hashPubKey);
3297   /* Is the selected peer in the tunnel? */
3298   if (NULL == pi)
3299   {
3300     GNUNET_break (0);
3301     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3302     return;
3303   }
3304
3305   /* Ok, everything is correct, send the message
3306    * (pretend we got it from a mesh peer)
3307    */
3308   {
3309     char buf[ntohs (message->size)];
3310     struct GNUNET_MESH_Unicast *copy;
3311
3312     /* Work around const limitation */
3313     copy = (struct GNUNET_MESH_Unicast *) buf;
3314     memcpy (buf, data_msg, size);
3315     copy->oid = my_full_id;
3316     copy->tid = htonl (t->id.tid);
3317     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3318                 "MESH:   calling generic handler...\n");
3319     handle_mesh_data_unicast (NULL, &my_full_id, &copy->header, NULL);
3320   }
3321   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3322   return;
3323 }
3324
3325 /**
3326  * Handler for client traffic directed to all peers in a tunnel
3327  *
3328  * @param cls closure
3329  * @param client identification of the client
3330  * @param message the actual message
3331  */
3332 static void
3333 handle_local_multicast (void *cls, struct GNUNET_SERVER_Client *client,
3334                         const struct GNUNET_MessageHeader *message)
3335 {
3336   struct MeshClient *c;
3337   struct MeshTunnel *t;
3338   struct GNUNET_MESH_Multicast *data_msg;
3339   MESH_TunnelNumber tid;
3340
3341   /* Sanity check for client registration */
3342   if (NULL == (c = client_get (client)))
3343   {
3344     GNUNET_break (0);
3345     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3346     return;
3347   }
3348   data_msg = (struct GNUNET_MESH_Multicast *) message;
3349   /* Sanity check for message size */
3350   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (data_msg->header.size))
3351   {
3352     GNUNET_break (0);
3353     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3354     return;
3355   }
3356
3357   /* Tunnel exists? */
3358   tid = ntohl (data_msg->tid);
3359   t = tunnel_get_by_local_id (c, tid);
3360   if (NULL == t)
3361   {
3362     GNUNET_break (0);
3363     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3364     return;
3365   }
3366
3367   /* Does client own tunnel? */
3368   if (t->client->handle != client)
3369   {
3370     GNUNET_break (0);
3371     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3372     return;
3373   }
3374
3375   {
3376     char buf[ntohs(message->size)];
3377     struct GNUNET_MESH_Multicast *copy;
3378
3379     copy = (struct GNUNET_MESH_Multicast *)buf;
3380     memcpy(buf, message, ntohs(message->size));
3381     copy->oid = my_full_id;
3382     copy->tid = htonl(t->id.tid);
3383     handle_mesh_data_multicast(client, &my_full_id, &copy->header, NULL);
3384   }
3385
3386   /* receive done gets called when last copy is sent */
3387   return;
3388 }
3389
3390 /**
3391  * Functions to handle messages from clients
3392  */
3393 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
3394   {&handle_local_new_client, NULL, GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
3395   {&handle_local_tunnel_create, NULL,
3396    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
3397    sizeof (struct GNUNET_MESH_TunnelMessage)},
3398   {&handle_local_tunnel_destroy, NULL,
3399    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
3400    sizeof (struct GNUNET_MESH_TunnelMessage)},
3401   {&handle_local_connect_add, NULL,
3402    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD,
3403    sizeof (struct GNUNET_MESH_PeerControl)},
3404   {&handle_local_connect_del, NULL,
3405    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL,
3406    sizeof (struct GNUNET_MESH_PeerControl)},
3407   {&handle_local_connect_by_type, NULL,
3408    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE,
3409    sizeof (struct GNUNET_MESH_ConnectPeerByType)},
3410   {&handle_local_unicast, NULL,
3411    GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
3412   {&handle_local_unicast, NULL,
3413    GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
3414   {&handle_local_multicast, NULL,
3415    GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
3416   {NULL, NULL, 0, 0}
3417 };
3418
3419
3420 /**
3421  * To be called on core init/fail.
3422  *
3423  * @param cls service closure
3424  * @param server handle to the server for this service
3425  * @param identity the public identity of this peer
3426  */
3427 static void
3428 core_init (void *cls, struct GNUNET_CORE_Handle *server,
3429            const struct GNUNET_PeerIdentity *identity)
3430 {
3431   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Core init\n");
3432   core_handle = server;
3433   if (0 != memcmp(identity, &my_full_id, sizeof(my_full_id)) || NULL == server)
3434   {
3435     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("MESH: Wrong CORE service\n"));
3436     GNUNET_SCHEDULER_shutdown();   
3437   }
3438   return;
3439 }
3440
3441 /**
3442  * Method called whenever a given peer connects.
3443  *
3444  * @param cls closure
3445  * @param peer peer identity this notification is about
3446  * @param atsi performance data for the connection
3447  */
3448 static void
3449 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
3450               const struct GNUNET_TRANSPORT_ATS_Information *atsi)
3451 {
3452   struct MeshPeerInfo *peer_info;
3453   struct MeshPeerPath *path;
3454
3455 #if MESH_DEBUG_CONNECTION
3456   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Peer connected\n");
3457   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      %s\n",
3458               GNUNET_h2s(&my_full_id.hashPubKey));
3459 #endif
3460   peer_info = peer_info_get (peer);
3461   if (myid == peer_info->id)
3462   {
3463 #if MESH_DEBUG_CONNECTION
3464     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      (self)\n");
3465 #endif
3466     return;
3467   }
3468 #if MESH_DEBUG_CONNECTION
3469   else
3470   {
3471     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      %s\n",
3472                 GNUNET_h2s(&peer->hashPubKey));
3473   }
3474 #endif
3475   path = path_new (2);
3476   path->peers[0] = myid;
3477   path->peers[1] = peer_info->id;
3478   GNUNET_PEER_change_rc(myid, 1);
3479   GNUNET_PEER_change_rc(peer_info->id, 1);
3480   path_add_to_peer (peer_info, path);
3481   return;
3482 }
3483
3484 /**
3485  * Method called whenever a peer disconnects.
3486  *
3487  * @param cls closure
3488  * @param peer peer identity this notification is about
3489  */
3490 static void
3491 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
3492 {
3493   struct MeshPeerInfo *pi;
3494   unsigned int i;
3495
3496 #if MESH_DEBUG_CONNECTION
3497   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Peer disconnected\n");
3498 #endif
3499   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
3500   if (NULL == pi)
3501   {
3502     GNUNET_break (0);
3503     return;
3504   }
3505   for (i = 0; i < CORE_QUEUE_SIZE; i++)
3506   {
3507     peer_info_cancel_transmission(pi, i);
3508   }
3509   path_remove_from_peer (pi, pi->id, myid);
3510 #if MESH_DEBUG_CONNECTION
3511   if (myid == pi->id)
3512   {
3513     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      (self)\n");
3514   }
3515 #endif
3516   return;
3517 }
3518
3519
3520 /******************************************************************************/
3521 /************************      MAIN FUNCTIONS      ****************************/
3522 /******************************************************************************/
3523
3524 /**
3525  * Iterator over hash map entries.
3526  *
3527  * @param cls closure
3528  * @param key current key code
3529  * @param value value in the hash map
3530  * @return GNUNET_YES if we should continue to
3531  *         iterate,
3532  *         GNUNET_NO if not.
3533  */
3534 int
3535 shutdown_tunnel (void *cls, const GNUNET_HashCode * key, void *value)
3536 {
3537   struct MeshTunnel *t = value;
3538   tunnel_destroy(t);
3539   return GNUNET_YES;
3540 }
3541
3542 /**
3543  * Task run during shutdown.
3544  *
3545  * @param cls unused
3546  * @param tc unused
3547  */
3548 static void
3549 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3550 {
3551   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: shutting down\n");
3552   /* TODO: destroy tunnels? */
3553   if (core_handle != NULL)
3554   {
3555     GNUNET_CORE_disconnect (core_handle);
3556     core_handle = NULL;
3557   }
3558   GNUNET_CONTAINER_multihashmap_iterate(tunnels, &shutdown_tunnel, NULL);
3559   if (dht_handle != NULL)
3560   {
3561     GNUNET_DHT_disconnect (dht_handle);
3562     dht_handle = NULL;
3563   }
3564   if (nc != NULL)
3565   {
3566     GNUNET_SERVER_notification_context_destroy (nc);
3567     nc = NULL;
3568   }
3569   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
3570   {
3571     GNUNET_SCHEDULER_cancel (announce_id_task);
3572     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
3573   }
3574   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: shut down\n");
3575 }
3576
3577 /**
3578  * Process mesh requests.
3579  *
3580  * @param cls closure
3581  * @param server the initialized server
3582  * @param c configuration to use
3583  */
3584 static void
3585 run (void *cls, struct GNUNET_SERVER_Handle *server,
3586      const struct GNUNET_CONFIGURATION_Handle *c)
3587 {
3588   struct MeshPeerInfo *peer;
3589   struct MeshPeerPath *p;
3590   char *keyfile;
3591
3592   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: starting to run\n");
3593   server_handle = server;
3594   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
3595                                      CORE_QUEUE_SIZE,   /* queue size */
3596                                      NULL,      /* Closure passed to MESH functions */
3597                                      &core_init,        /* Call core_init once connected */
3598                                      &core_connect,     /* Handle connects */
3599                                      &core_disconnect,  /* remove peers on disconnects */
3600                                      NULL,      /* Don't notify about all incoming messages */
3601                                      GNUNET_NO, /* For header only in notification */
3602                                      NULL,      /* Don't notify about all outbound messages */
3603                                      GNUNET_NO, /* For header-only out notification */
3604                                      core_handlers);    /* Register these handlers */
3605   if (core_handle == NULL)
3606   {
3607     GNUNET_break (0);
3608     GNUNET_SCHEDULER_shutdown ();
3609     return;
3610   }
3611
3612   if (GNUNET_OK !=
3613        GNUNET_CONFIGURATION_get_value_filename (c, "GNUNETD", "HOSTKEY",
3614                                                 &keyfile))
3615   {
3616     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3617                 _
3618                 ("Mesh service is lacking key configuration settings.  Exiting.\n"));
3619     GNUNET_SCHEDULER_shutdown ();
3620     return;
3621   }
3622   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3623   GNUNET_free (keyfile);
3624   if (my_private_key == NULL)
3625   {
3626     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3627                 _("Mesh service could not access hostkey.  Exiting.\n"));
3628     GNUNET_SCHEDULER_shutdown ();
3629     return;
3630   }
3631   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3632   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
3633                       &my_full_id.hashPubKey);
3634   myid = GNUNET_PEER_intern (&my_full_id);
3635
3636   dht_handle = GNUNET_DHT_connect (c, 64);
3637   if (dht_handle == NULL)
3638   {
3639     GNUNET_break (0);
3640   }
3641
3642   next_tid = 0;
3643   next_local_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
3644
3645   tunnels = GNUNET_CONTAINER_multihashmap_create (32);
3646   incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
3647   peers = GNUNET_CONTAINER_multihashmap_create (32);
3648   applications = GNUNET_CONTAINER_multihashmap_create (32);
3649   types = GNUNET_CONTAINER_multihashmap_create (32);
3650
3651   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
3652   nc = GNUNET_SERVER_notification_context_create (server_handle,
3653                                                   LOCAL_QUEUE_SIZE);
3654   GNUNET_SERVER_disconnect_notify (server_handle,
3655                                    &handle_local_client_disconnect,
3656                                    NULL);
3657
3658
3659   clients = NULL;
3660   clients_tail = NULL;
3661 #if MESH_DEBUG
3662   next_client_id = 0;
3663 #endif
3664
3665   announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
3666   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
3667
3668   /* Create a peer_info for the local peer */
3669   peer = peer_info_get(&my_full_id);
3670   p = path_new (1);
3671   p->peers[0] = myid;
3672   path_add_to_peer(peer, p);
3673
3674   /* Scheduled the task to clean up when shutdown is called */
3675   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
3676                                 NULL);
3677
3678   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: end of run()\n");
3679 }
3680
3681 /**
3682  * The main function for the mesh service.
3683  *
3684  * @param argc number of arguments from the command line
3685  * @param argv command line arguments
3686  * @return 0 ok, 1 on error
3687  */
3688 int
3689 main (int argc, char *const *argv)
3690 {
3691   int ret;
3692
3693 #if MESH_DEBUG
3694 //   fprintf (stderr, "main ()\n");
3695 #endif
3696   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: main()\n");
3697   ret =
3698       (GNUNET_OK ==
3699        GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
3700                            NULL)) ? 0 : 1;
3701   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: main() END\n");
3702 #if MESH_DEBUG
3703 //   fprintf (stderr, "main () END\n");
3704 #endif
3705   return ret;
3706 }