Expanded test to include traffic to origin, fixed bugs, separated unicast traffic...
[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 toward the owner of a tunnel
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   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2320               "MESH: got a ToOrigin packet from %s\n",
2321               GNUNET_i2s (peer));
2322   size = ntohs (message->size);
2323   if (size < sizeof (struct GNUNET_MESH_ToOrigin) +     /* Payload must be */
2324       sizeof (struct GNUNET_MessageHeader))     /* at least a header */
2325   {
2326     GNUNET_break_op (0);
2327     return GNUNET_OK;
2328   }
2329   msg = (struct GNUNET_MESH_ToOrigin *) message;
2330   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2331               "MESH:  of type %u\n",
2332               ntohs (msg[1].header.type));
2333   t = tunnel_get (&msg->oid, ntohl (msg->tid));
2334
2335   if (NULL == t)
2336   {
2337     /* TODO notify that we dont know this tunnel (whom)? */
2338     GNUNET_break_op (0);
2339     return GNUNET_OK;
2340   }
2341
2342   if (t->id.oid == myid)
2343   {
2344     char cbuf[size];
2345     struct GNUNET_MESH_ToOrigin *copy;
2346
2347     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2348                 "MESH:   it's for us! sending to clients...\n");
2349     if (NULL == t->client)
2350     {
2351       /* got data packet for ownerless tunnel */
2352       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2353                 "MESH:   no clients!\n");
2354       GNUNET_break_op (0);
2355       return GNUNET_OK;
2356     }
2357     /* TODO signature verification */
2358     memcpy (cbuf, message, size);
2359     copy = (struct GNUNET_MESH_ToOrigin *) cbuf;
2360     copy->tid = htonl (t->local_tid);
2361     GNUNET_SERVER_notification_context_unicast (nc,
2362                                                 t->client->handle,
2363                                                 &copy->header,
2364                                                 GNUNET_YES);
2365     return GNUNET_OK;
2366   }
2367   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2368               "MESH:   not for us, retransmitting...\n");
2369
2370   peer_info = peer_info_get (&msg->oid);
2371   if (NULL == peer_info)
2372   {
2373     /* unknown origin of tunnel */
2374     GNUNET_break (0);
2375     return GNUNET_OK;
2376   }
2377   GNUNET_PEER_resolve (t->tree->me->parent->peer, &id);
2378   msg = GNUNET_malloc (size);
2379   memcpy (msg, message, size);
2380   GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
2381                                      GNUNET_TIME_UNIT_FOREVER_REL, &id, size,
2382                                      &send_core_data_raw, msg);
2383
2384   return GNUNET_OK;
2385 }
2386
2387
2388 /**
2389  * Core handler for path ACKs
2390  *
2391  * @param cls closure
2392  * @param message message
2393  * @param peer peer identity this notification is about
2394  * @param atsi performance data
2395  *
2396  * @return GNUNET_OK to keep the connection open,
2397  *         GNUNET_SYSERR to close it (signal serious error)
2398  */
2399 static int
2400 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
2401                       const struct GNUNET_MessageHeader *message,
2402                       const struct GNUNET_TRANSPORT_ATS_Information *atsi)
2403 {
2404   struct GNUNET_MESH_PathACK *msg;
2405   struct GNUNET_PeerIdentity id;
2406   struct MeshTunnelTreeNode *n;
2407   struct MeshPeerInfo *peer_info;
2408   struct MeshTunnel *t;
2409
2410   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2411               "MESH: Received a path ACK msg [%s]\n",
2412               GNUNET_i2s(&my_full_id));
2413   msg = (struct GNUNET_MESH_PathACK *) message;
2414   t = tunnel_get (&msg->oid, msg->tid);
2415   if (NULL == t)
2416   {
2417     /* TODO notify that we don't know the tunnel */
2418     return GNUNET_OK;
2419   }
2420
2421   /* Message for us? */
2422   if (0 == memcmp (&msg->oid, &my_full_id, sizeof (struct GNUNET_PeerIdentity)))
2423   {
2424     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2425                 "MESH:   It's for us!\n");
2426     if (NULL == t->client)
2427     {
2428       GNUNET_break_op (0);
2429       return GNUNET_OK;
2430     }
2431     peer_info = peer_info_get (&msg->peer_id);
2432     if (NULL == peer_info)
2433     {
2434       GNUNET_break_op (0);
2435       return GNUNET_OK;
2436     }
2437     n = tree_find_peer(t->tree->root, peer_info->id);
2438     if (NULL == n)
2439     {
2440       GNUNET_break_op (0);
2441       return GNUNET_OK;
2442     }
2443     n->status = MESH_PEER_READY;
2444     send_client_peer_connected(t, peer_info->id);
2445     return GNUNET_OK;
2446   }
2447   
2448   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2449               "MESH:   not for us, retransmitting...\n");
2450   GNUNET_PEER_resolve(t->tree->me->parent->peer, &id);
2451   peer_info = peer_info_get (&msg->oid);
2452   if (NULL == peer_info)
2453   {
2454     /* If we know the tunnel, we should DEFINITELY know the peer */
2455     GNUNET_break (0);
2456     return GNUNET_OK;
2457   }
2458   msg = GNUNET_malloc (sizeof (struct GNUNET_MESH_PathACK));
2459   memcpy (msg, message, sizeof (struct GNUNET_MESH_PathACK));
2460   GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
2461                                      GNUNET_TIME_UNIT_FOREVER_REL,
2462                                      &id,
2463                                      sizeof (struct GNUNET_MESH_PathACK),
2464                                      &send_core_data_raw, msg);
2465   return GNUNET_OK;
2466 }
2467
2468
2469 /**
2470  * Functions to handle messages from core
2471  */
2472 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
2473   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
2474   {&handle_mesh_data_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
2475   {&handle_mesh_data_multicast, GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
2476   {&handle_mesh_data_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
2477   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
2478    sizeof (struct GNUNET_MESH_PathACK)},
2479   {NULL, 0, 0}
2480 };
2481
2482
2483
2484 /******************************************************************************/
2485 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
2486 /******************************************************************************/
2487
2488 /**
2489  * deregister_app: iterator for removing each application registered by a client
2490  * 
2491  * @param cls closure
2492  * @param key the hash of the application id (used to access the hashmap)
2493  * @param value the value stored at the key (client)
2494  * 
2495  * @return GNUNET_OK on success
2496  */
2497 static int
2498 deregister_app (void *cls, const GNUNET_HashCode * key, void *value)
2499 {
2500   GNUNET_break (GNUNET_YES == 
2501       GNUNET_CONTAINER_multihashmap_remove (applications, key, value));
2502   return GNUNET_OK;
2503 }
2504
2505 #if LATER
2506 /**
2507  * notify_client_connection_failure: notify a client that the connection to the
2508  * requested remote peer is not possible (for instance, no route found)
2509  * Function called when the socket is ready to queue more data. "buf" will be
2510  * NULL and "size" zero if the socket was closed for writing in the meantime.
2511  *
2512  * @param cls closure
2513  * @param size number of bytes available in buf
2514  * @param buf where the callee should write the message
2515  * @return number of bytes written to buf
2516  */
2517 static size_t
2518 notify_client_connection_failure (void *cls, size_t size, void *buf)
2519 {
2520   int size_needed;
2521   struct MeshPeerInfo *peer_info;
2522   struct GNUNET_MESH_PeerControl *msg;
2523   struct GNUNET_PeerIdentity id;
2524
2525   if (0 == size && NULL == buf)
2526   {
2527     // TODO retry? cancel?
2528     return 0;
2529   }
2530
2531   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
2532   peer_info = (struct MeshPeerInfo *) cls;
2533   msg = (struct GNUNET_MESH_PeerControl *) buf;
2534   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
2535   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
2536 //     msg->tunnel_id = htonl(peer_info->t->tid);
2537   GNUNET_PEER_resolve (peer_info->id, &id);
2538   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
2539
2540   return size_needed;
2541 }
2542 #endif
2543
2544
2545 /**
2546  * Send keepalive packets for a peer
2547  *
2548  * @param cls Closure (tunnel for which to send the keepalive).
2549  * @param tc Notification context.
2550  *
2551  * TODO: implement explicit multicast keepalive?
2552  */
2553 void
2554 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2555 {
2556   struct MeshTunnel *t = cls;
2557   struct GNUNET_MessageHeader *payload;
2558   struct GNUNET_MESH_Multicast *msg;
2559   size_t size;
2560
2561   t->path_refresh_task = GNUNET_SCHEDULER_NO_TASK;
2562   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
2563   {
2564     return;
2565   }
2566
2567   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2568               "MESH: sending keepalive for tunnel %d\n",
2569               t->id.tid);
2570
2571   size = sizeof(struct GNUNET_MESH_Multicast) +
2572          sizeof(struct GNUNET_MessageHeader);
2573   msg = GNUNET_malloc (size);
2574   msg->header.size = htons (size);
2575   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
2576   msg->oid = my_full_id;
2577   msg->tid = htonl(t->id.tid);
2578   payload = (struct GNUNET_MessageHeader *) &msg[1];
2579   payload->size = htons (sizeof(struct GNUNET_MessageHeader));
2580   payload->type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE);
2581   handle_mesh_data_multicast (NULL, &my_full_id, &msg->header, NULL);
2582
2583   GNUNET_free (msg);
2584   t->path_refresh_task =
2585       GNUNET_SCHEDULER_add_delayed (t->tree->refresh, &path_refresh, t);
2586   return;
2587 }
2588
2589
2590 /**
2591  * Function to process paths received for a new peer addition. The recorded
2592  * paths form the initial tunnel, which can be optimized later.
2593  * Called on each result obtained for the DHT search.
2594  *
2595  * @param cls closure
2596  * @param exp when will this value expire
2597  * @param key key of the result
2598  * @param type type of the result
2599  * @param size number of bytes in data
2600  * @param data pointer to the result data
2601  *
2602  * TODO: re-issue the request after certain time? cancel after X results?
2603  */
2604 static void
2605 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
2606                     const GNUNET_HashCode * key,
2607                     const struct GNUNET_PeerIdentity *get_path,
2608                     unsigned int get_path_length,
2609                     const struct GNUNET_PeerIdentity *put_path,
2610                     unsigned int put_path_length,
2611                     enum GNUNET_BLOCK_Type type, size_t size, const void *data)
2612 {
2613   struct MeshPathInfo *path_info = cls;
2614   struct MeshPeerPath *p;
2615   struct GNUNET_PeerIdentity pi;
2616   int i;
2617
2618   GNUNET_PEER_resolve (path_info->peer->id, &pi);
2619   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2620              "MESH: Got results from DHT for %s\n",
2621              GNUNET_h2s_full(&pi.hashPubKey));
2622   GNUNET_DHT_get_stop(path_info->peer->dhtget);
2623   path_info->peer->dhtget = NULL;
2624
2625   p = path_build_from_dht (get_path, get_path_length,
2626                            put_path, put_path_length);
2627   path_add_to_peer (path_info->peer, p);
2628   for (i = 0; i < path_info->peer->ntunnels; i++)
2629   {
2630     tunnel_add_peer (path_info->peer->tunnels[i], path_info->peer);
2631     peer_info_connect(path_info->peer, path_info->t);
2632   }
2633   GNUNET_free (path_info);
2634
2635   return;
2636 }
2637
2638
2639 /**
2640  * Function to process paths received for a new peer addition. The recorded
2641  * paths form the initial tunnel, which can be optimized later.
2642  * Called on each result obtained for the DHT search.
2643  *
2644  * @param cls closure
2645  * @param exp when will this value expire
2646  * @param key key of the result
2647  * @param type type of the result
2648  * @param size number of bytes in data
2649  * @param data pointer to the result data
2650  */
2651 static void
2652 dht_get_type_handler (void *cls, struct GNUNET_TIME_Absolute exp,
2653                       const GNUNET_HashCode * key,
2654                       const struct GNUNET_PeerIdentity *get_path,
2655                       unsigned int get_path_length,
2656                       const struct GNUNET_PeerIdentity *put_path,
2657                       unsigned int put_path_length,
2658                       enum GNUNET_BLOCK_Type type, size_t size,
2659                       const void *data)
2660 {
2661   const struct GNUNET_PeerIdentity *pi = data;
2662   struct GNUNET_PeerIdentity id;
2663   struct MeshTunnel *t = cls;
2664   struct MeshPeerInfo *peer_info;
2665   struct MeshPathInfo *path_info;
2666   struct MeshPeerPath *p;
2667   int i;
2668
2669   if (size != sizeof (struct GNUNET_PeerIdentity))
2670   {
2671     GNUNET_break_op (0);
2672     return;
2673   }
2674   GNUNET_assert (NULL != t->client);
2675   GNUNET_DHT_get_stop (t->dht_get_type);
2676   t->dht_get_type = NULL;
2677   peer_info = peer_info_get (pi);
2678   GNUNET_CONTAINER_multihashmap_put (t->peers, &pi->hashPubKey, peer_info,
2679                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2680
2681   if ((NULL == get_path || NULL == put_path) && NULL == peer_info->path_head &&
2682       NULL == peer_info->dhtget)
2683   {
2684     path_info = GNUNET_malloc (sizeof (struct MeshPathInfo));
2685     path_info->peer = peer_info;
2686     path_info->t = t;
2687     /* we don't have a route to the peer, let's try a direct lookup */
2688     peer_info->dhtget =
2689         GNUNET_DHT_get_start (dht_handle, /* handle */
2690                               GNUNET_TIME_UNIT_FOREVER_REL, /* timeout */
2691                               GNUNET_BLOCK_TYPE_TEST, /* block type */
2692                               &pi->hashPubKey, /* key to look up */
2693                               10U, /* replication level */
2694                               GNUNET_DHT_RO_RECORD_ROUTE |
2695                                 GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
2696                               /* option to dht: record route */
2697                               NULL,     /* xquery */
2698                               0,        /* xquery bits */
2699                               dht_get_id_handler,  /* callback */
2700                               path_info);       /* closure */
2701     return;
2702   }
2703
2704   p = path_build_from_dht (get_path, get_path_length, put_path, put_path_length);
2705   path_add_to_peer (peer_info, p);
2706   tunnel_add_peer(t, peer_info);
2707   p = tree_get_path_to_peer(t->tree, peer_info->id);
2708 #if MESH_DEBUG
2709   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2710               "MESH: new route for tunnel 0x%x found, has %u hops\n",
2711               t->local_tid, p->length);
2712   for (i = 0; i < p->length; i++)
2713   {
2714     GNUNET_PEER_resolve (p->peers[0], &id);
2715     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:\t%d\t%s\n", i,
2716                 GNUNET_h2s_full (&id.hashPubKey));
2717   }
2718 #endif
2719
2720   if (p->length > 1)
2721   {
2722     send_create_path(peer_info, p, t);
2723     return;
2724   }
2725   path_destroy(p);
2726   send_client_peer_connected(t, myid);
2727 }
2728
2729
2730 /******************************************************************************/
2731 /*********************       MESH LOCAL HANDLES      **************************/
2732 /******************************************************************************/
2733
2734
2735 /**
2736  * Handler for client disconnection
2737  *
2738  * @param cls closure
2739  * @param client identification of the client; NULL
2740  *        for the last call when the server is destroyed
2741  */
2742 static void
2743 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
2744 {
2745   struct MeshClient *c;
2746   struct MeshClient *next;
2747
2748   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: client disconnected\n");
2749   if (client == NULL)
2750      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    (SERVER DOWN)\n");
2751   c = clients;
2752   while (NULL != c)
2753   {
2754     if (c->handle != client && NULL != client)
2755     {
2756       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    ... searching\n");
2757       c = c->next;
2758       continue;
2759     }
2760     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: matching client found\n");
2761     if (NULL != c->tunnels)
2762     {
2763       GNUNET_CONTAINER_multihashmap_iterate (c->tunnels,
2764                                              &tunnel_destroy_iterator,
2765                                              c);
2766       GNUNET_CONTAINER_multihashmap_destroy (c->tunnels);
2767     }
2768
2769     /* deregister clients applications */
2770     if (NULL != c->apps)
2771     {
2772       GNUNET_CONTAINER_multihashmap_iterate (c->apps, &deregister_app, NULL);
2773       GNUNET_CONTAINER_multihashmap_destroy (c->apps);
2774     }
2775     if (0 == GNUNET_CONTAINER_multihashmap_size (applications) &&
2776         GNUNET_SCHEDULER_NO_TASK != announce_applications_task)
2777     {
2778       GNUNET_SCHEDULER_cancel (announce_applications_task);
2779       announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
2780     }
2781     if (NULL != c->types)
2782       GNUNET_CONTAINER_multihashmap_destroy (c->types);
2783     GNUNET_CONTAINER_DLL_remove (clients, clients_tail, c);
2784     next = c->next;
2785     GNUNET_free (c);
2786     c = next;
2787   }
2788
2789   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    done!\n");
2790   return;
2791 }
2792
2793
2794 /**
2795  * Handler for new clients
2796  *
2797  * @param cls closure
2798  * @param client identification of the client
2799  * @param message the actual message, which includes messages the client wants
2800  */
2801 static void
2802 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
2803                          const struct GNUNET_MessageHeader *message)
2804 {
2805   struct GNUNET_MESH_ClientConnect *cc_msg;
2806   struct MeshClient *c;
2807   GNUNET_MESH_ApplicationType *a;
2808   unsigned int size;
2809   uint16_t ntypes;
2810   uint16_t *t;
2811   uint16_t napps;
2812   uint16_t i;
2813
2814   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new client connected\n");
2815   /* Check data sanity */
2816   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
2817   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
2818   ntypes = ntohs (cc_msg->types);
2819   napps = ntohs (cc_msg->applications);
2820   if (size !=
2821       ntypes * sizeof (uint16_t) + napps * sizeof (GNUNET_MESH_ApplicationType))
2822   {
2823     GNUNET_break (0);
2824     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2825     return;
2826   }
2827
2828   /* Create new client structure */
2829   c = GNUNET_malloc (sizeof (struct MeshClient));
2830 #if MESH_DEBUG
2831   c->id = next_client_id++;
2832 #endif
2833   c->handle = client;
2834   a = (GNUNET_MESH_ApplicationType *) &cc_msg[1];
2835   if (napps > 0)
2836   {
2837     GNUNET_MESH_ApplicationType at;
2838     GNUNET_HashCode hc;
2839
2840     c->apps = GNUNET_CONTAINER_multihashmap_create (napps);
2841     for (i = 0; i < napps; i++)
2842     {
2843       at = ntohl (a[i]);
2844       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   app type: %u\n", at);
2845       GNUNET_CRYPTO_hash (&at, sizeof (at), &hc);
2846       /* store in clients hashmap */
2847       GNUNET_CONTAINER_multihashmap_put (c->apps, &hc, c,
2848                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2849       /* store in global hashmap, for announcements */
2850       GNUNET_CONTAINER_multihashmap_put (applications, &hc, c,
2851                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2852     }
2853     if (GNUNET_SCHEDULER_NO_TASK == announce_applications_task)
2854       announce_applications_task =
2855           GNUNET_SCHEDULER_add_now (&announce_applications, NULL);
2856
2857   }
2858   if (ntypes > 0)
2859   {
2860     uint16_t u16;
2861     GNUNET_HashCode hc;
2862
2863     t = (uint16_t *) & a[napps];
2864     c->types = GNUNET_CONTAINER_multihashmap_create (ntypes);
2865     for (i = 0; i < ntypes; i++)
2866     {
2867       u16 = ntohs (t[i]);
2868       GNUNET_CRYPTO_hash (&u16, sizeof (u16), &hc);
2869
2870       /* store in clients hashmap */
2871       GNUNET_CONTAINER_multihashmap_put (c->types, &hc, c,
2872                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2873       /* store in global hashmap */
2874       GNUNET_CONTAINER_multihashmap_put (types, &hc, c,
2875                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2876     }
2877   }
2878   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2879               "MESH:  client has %u+%u subscriptions\n", napps, ntypes);
2880
2881   GNUNET_CONTAINER_DLL_insert (clients, clients_tail, c);
2882   c->tunnels = GNUNET_CONTAINER_multihashmap_create (32);
2883   GNUNET_SERVER_notification_context_add (nc, client);
2884
2885   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2886 #if MESH_DEBUG
2887   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new client processed\n");
2888 #endif
2889 }
2890
2891
2892 /**
2893  * Handler for requests of new tunnels
2894  *
2895  * @param cls closure
2896  * @param client identification of the client
2897  * @param message the actual message
2898  */
2899 static void
2900 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
2901                             const struct GNUNET_MessageHeader *message)
2902 {
2903   struct GNUNET_MESH_TunnelMessage *t_msg;
2904   struct MeshTunnel *t;
2905   struct MeshClient *c;
2906   GNUNET_HashCode hash;
2907
2908   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new tunnel requested\n");
2909
2910   /* Sanity check for client registration */
2911   if (NULL == (c = client_get (client)))
2912   {
2913     GNUNET_break (0);
2914     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2915     return;
2916   }
2917 #if MESH_DEBUG
2918   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   by client %u\n", c->id);
2919 #endif
2920
2921   /* Message sanity check */
2922   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
2923   {
2924     GNUNET_break (0);
2925     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2926     return;
2927   }
2928
2929   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
2930   /* Sanity check for tunnel numbering */
2931   if (0 == (ntohl (t_msg->tunnel_id) & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
2932   {
2933     GNUNET_break (0);
2934     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2935     return;
2936   }
2937   /* Sanity check for duplicate tunnel IDs */
2938   if (NULL != tunnel_get_by_local_id (c, ntohl (t_msg->tunnel_id)))
2939   {
2940     GNUNET_break (0);
2941     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2942     return;
2943   }
2944
2945   t = GNUNET_malloc (sizeof (struct MeshTunnel));
2946   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: CREATED TUNNEL at %p\n", t);
2947   while (NULL != tunnel_get_by_pi (myid, next_tid))
2948     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
2949   t->id.tid = next_tid++;
2950   t->id.oid = myid;
2951   t->local_tid = ntohl (t_msg->tunnel_id);
2952   t->client = c;
2953   t->peers = GNUNET_CONTAINER_multihashmap_create (32);
2954
2955   GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
2956   if (GNUNET_OK !=
2957       GNUNET_CONTAINER_multihashmap_put (c->tunnels, &hash, t,
2958                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2959   {
2960     GNUNET_break (0);
2961     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2962     return;
2963   }
2964
2965   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
2966   if (GNUNET_OK !=
2967       GNUNET_CONTAINER_multihashmap_put (tunnels, &hash, t,
2968                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2969   {
2970     GNUNET_break (0);
2971     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2972     return;
2973   }
2974   t->tree = tree_new (t, myid);
2975   t->tree->refresh = REFRESH_PATH_TIME;
2976   t->tree->root->status = MESH_PEER_READY;
2977   t->tree->me = t->tree->root;
2978
2979   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2980   return;
2981 }
2982
2983
2984 /**
2985  * Handler for requests of deleting tunnels
2986  *
2987  * @param cls closure
2988  * @param client identification of the client
2989  * @param message the actual message
2990  */
2991 static void
2992 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
2993                              const struct GNUNET_MessageHeader *message)
2994 {
2995   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
2996   struct MeshClient *c;
2997   struct MeshTunnel *t;
2998   MESH_TunnelNumber tid;
2999   GNUNET_HashCode hash;
3000
3001   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: destroying tunnel\n");
3002
3003   /* Sanity check for client registration */
3004   if (NULL == (c = client_get (client)))
3005   {
3006     GNUNET_break (0);
3007     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3008     return;
3009   }
3010   /* Message sanity check */
3011   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
3012   {
3013     GNUNET_break (0);
3014     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3015     return;
3016   }
3017 #if MESH_DEBUG
3018   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   by client %u\n", c->id);
3019 #endif
3020   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
3021
3022   /* Retrieve tunnel */
3023   tid = ntohl (tunnel_msg->tunnel_id);
3024
3025   /* Remove from local id hashmap */
3026   GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
3027   t = GNUNET_CONTAINER_multihashmap_get (c->tunnels, &hash);
3028   GNUNET_CONTAINER_multihashmap_remove (c->tunnels, &hash, t);
3029
3030 //     notify_tunnel_destroy(t); FIXME
3031   tunnel_destroy(t);
3032   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3033   return;
3034 }
3035
3036
3037 /**
3038  * Handler for connection requests to new peers
3039  *
3040  * @param cls closure
3041  * @param client identification of the client
3042  * @param message the actual message (PeerControl)
3043  */
3044 static void
3045 handle_local_connect_add (void *cls, struct GNUNET_SERVER_Client *client,
3046                           const struct GNUNET_MessageHeader *message)
3047 {
3048   struct GNUNET_MESH_PeerControl *peer_msg;
3049   struct MeshPeerInfo *peer_info;
3050   struct MeshClient *c;
3051   struct MeshTunnel *t;
3052   MESH_TunnelNumber tid;
3053
3054   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "MESH: Got connection request\n");
3055   /* Sanity check for client registration */
3056   if (NULL == (c = client_get (client)))
3057   {
3058     GNUNET_break (0);
3059     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3060     return;
3061   }
3062
3063   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
3064   /* Sanity check for message size */
3065   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
3066   {
3067     GNUNET_break (0);
3068     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3069     return;
3070   }
3071
3072   /* Tunnel exists? */
3073   tid = ntohl (peer_msg->tunnel_id);
3074   t = tunnel_get_by_local_id (c, tid);
3075   if (NULL == t)
3076   {
3077     GNUNET_break (0);
3078     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3079     return;
3080   }
3081
3082   /* Does client own tunnel? */
3083   if (t->client->handle != client)
3084   {
3085     GNUNET_break (0);
3086     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3087     return;
3088   }
3089   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "MESH:      for %s\n",
3090              GNUNET_h2s_full(&peer_msg->peer.hashPubKey));
3091   peer_info = peer_info_get (&peer_msg->peer);
3092
3093   tunnel_add_peer(t, peer_info);
3094   peer_info_connect(peer_info, t);
3095
3096   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3097   return;
3098 }
3099
3100
3101 /**
3102  * Handler for disconnection requests of peers in a tunnel
3103  *
3104  * @param cls closure
3105  * @param client identification of the client
3106  * @param message the actual message (PeerControl)
3107  */
3108 static void
3109 handle_local_connect_del (void *cls, struct GNUNET_SERVER_Client *client,
3110                           const struct GNUNET_MessageHeader *message)
3111 {
3112   struct GNUNET_MESH_PeerControl *peer_msg;
3113   struct MeshClient *c;
3114   struct MeshTunnel *t;
3115   MESH_TunnelNumber tid;
3116
3117   /* Sanity check for client registration */
3118   if (NULL == (c = client_get (client)))
3119   {
3120     GNUNET_break (0);
3121     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3122     return;
3123   }
3124   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
3125   /* Sanity check for message size */
3126   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
3127   {
3128     GNUNET_break (0);
3129     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3130     return;
3131   }
3132
3133   /* Tunnel exists? */
3134   tid = ntohl (peer_msg->tunnel_id);
3135   t = tunnel_get_by_local_id (c, tid);
3136   if (NULL == t)
3137   {
3138     GNUNET_break (0);
3139     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3140     return;
3141   }
3142
3143   /* Does client own tunnel? */
3144   if (t->client->handle != client)
3145   {
3146     GNUNET_break (0);
3147     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3148     return;
3149   }
3150
3151   /* Ok, delete peer from tunnel */
3152   GNUNET_CONTAINER_multihashmap_remove_all (t->peers,
3153                                             &peer_msg->peer.hashPubKey);
3154
3155   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3156   return;
3157 }
3158
3159
3160 /**
3161  * Handler for connection requests to new peers by type
3162  *
3163  * @param cls closure
3164  * @param client identification of the client
3165  * @param message the actual message (ConnectPeerByType)
3166  */
3167 static void
3168 handle_local_connect_by_type (void *cls, struct GNUNET_SERVER_Client *client,
3169                               const struct GNUNET_MessageHeader *message)
3170 {
3171   struct GNUNET_MESH_ConnectPeerByType *connect_msg;
3172   struct MeshClient *c;
3173   struct MeshTunnel *t;
3174   GNUNET_HashCode hash;
3175   MESH_TunnelNumber tid;
3176
3177   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: got connect by type request\n");
3178   /* Sanity check for client registration */
3179   if (NULL == (c = client_get (client)))
3180   {
3181     GNUNET_break (0);
3182     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3183     return;
3184   }
3185
3186   connect_msg = (struct GNUNET_MESH_ConnectPeerByType *) message;
3187   /* Sanity check for message size */
3188   if (sizeof (struct GNUNET_MESH_ConnectPeerByType) !=
3189       ntohs (connect_msg->header.size))
3190   {
3191     GNUNET_break (0);
3192     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3193     return;
3194   }
3195
3196   /* Tunnel exists? */
3197   tid = ntohl (connect_msg->tunnel_id);
3198   t = tunnel_get_by_local_id (c, tid);
3199   if (NULL == t)
3200   {
3201     GNUNET_break (0);
3202     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3203     return;
3204   }
3205
3206   /* Does client own tunnel? */
3207   if (t->client->handle != client)
3208   {
3209     GNUNET_break (0);
3210     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3211     return;
3212   }
3213
3214   /* Do WE have the service? */
3215   t->type = ntohl (connect_msg->type);
3216   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  type requested: %u\n", t->type);
3217   GNUNET_CRYPTO_hash (&t->type, sizeof (GNUNET_MESH_ApplicationType), &hash);
3218   if (GNUNET_CONTAINER_multihashmap_contains (applications, &hash) ==
3219       GNUNET_YES)
3220   {
3221     /* Yes! Fast forward, add ourselves to the tunnel and send the
3222      * good news to the client
3223      */
3224     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  available locally\n");
3225     GNUNET_CONTAINER_multihashmap_put (t->peers, &my_full_id.hashPubKey,
3226                                        peer_info_get (&my_full_id),
3227                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3228
3229     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  notifying client\n");
3230     send_client_peer_connected(t, myid);
3231     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  Done\n");
3232     GNUNET_SERVER_receive_done (client, GNUNET_OK);
3233     return;
3234   }
3235   /* Ok, lets find a peer offering the service */
3236   if (NULL != t->dht_get_type)
3237   {
3238     GNUNET_DHT_get_stop (t->dht_get_type);
3239   }
3240   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  looking in DHT for %s\n",
3241               GNUNET_h2s_full (&hash));
3242   t->dht_get_type =
3243       GNUNET_DHT_get_start (dht_handle,
3244                             GNUNET_TIME_UNIT_FOREVER_REL,
3245                             GNUNET_BLOCK_TYPE_TEST,
3246                             &hash,
3247                             10U,
3248                             GNUNET_DHT_RO_RECORD_ROUTE |
3249                               GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
3250                             NULL, 0,
3251                             &dht_get_type_handler, t);
3252
3253   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3254   return;
3255 }
3256
3257
3258 /**
3259  * Handler for client traffic directed to one peer
3260  *
3261  * @param cls closure
3262  * @param client identification of the client
3263  * @param message the actual message
3264  */
3265 static void
3266 handle_local_unicast (void *cls, struct GNUNET_SERVER_Client *client,
3267                       const struct GNUNET_MessageHeader *message)
3268 {
3269   struct MeshClient *c;
3270   struct MeshTunnel *t;
3271   struct MeshPeerInfo *pi;
3272   struct GNUNET_MESH_Unicast *data_msg;
3273   MESH_TunnelNumber tid;
3274   size_t size;
3275
3276   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3277               "MESH: Got a unicast request from a client!\n");
3278
3279   /* Sanity check for client registration */
3280   if (NULL == (c = client_get (client)))
3281   {
3282     GNUNET_break (0);
3283     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3284     return;
3285   }
3286   data_msg = (struct GNUNET_MESH_Unicast *) message;
3287   /* Sanity check for message size */
3288   size = ntohs (message->size);
3289   if (sizeof (struct GNUNET_MESH_Unicast) +
3290       sizeof (struct GNUNET_MessageHeader) > size)
3291   {
3292     GNUNET_break (0);
3293     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3294     return;
3295   }
3296
3297   /* Tunnel exists? */
3298   tid = ntohl (data_msg->tid);
3299   t = tunnel_get_by_local_id (c, tid);
3300   if (NULL == t)
3301   {
3302     GNUNET_break (0);
3303     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3304     return;
3305   }
3306
3307   /*  Is it a local tunnel? Then, does client own the tunnel? */
3308   if (NULL != t->client &&
3309       NULL != t->client->handle &&
3310       t->client->handle != client)
3311   {
3312     GNUNET_break (0);
3313     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3314     return;
3315   }
3316
3317   pi = GNUNET_CONTAINER_multihashmap_get (t->peers,
3318                                           &data_msg->destination.hashPubKey);
3319   /* Is the selected peer in the tunnel? */
3320   if (NULL == pi)
3321   {
3322     GNUNET_break (0);
3323     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3324     return;
3325   }
3326
3327   /* Ok, everything is correct, send the message
3328    * (pretend we got it from a mesh peer)
3329    */
3330   {
3331     char buf[ntohs (message->size)];
3332     struct GNUNET_MESH_Unicast *copy;
3333
3334     /* Work around const limitation */
3335     copy = (struct GNUNET_MESH_Unicast *) buf;
3336     memcpy (buf, data_msg, size);
3337     copy->oid = my_full_id;
3338     copy->tid = htonl (t->id.tid);
3339     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3340                 "MESH:   calling generic handler...\n");
3341     handle_mesh_data_unicast (NULL, &my_full_id, &copy->header, NULL);
3342   }
3343   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3344   return;
3345 }
3346
3347
3348 /**
3349  * Handler for client traffic directed to the origin
3350  *
3351  * @param cls closure
3352  * @param client identification of the client
3353  * @param message the actual message
3354  */
3355 static void
3356 handle_local_to_origin (void *cls, struct GNUNET_SERVER_Client *client,
3357                         const struct GNUNET_MessageHeader *message)
3358 {
3359   struct GNUNET_MESH_ToOrigin *data_msg;
3360   struct GNUNET_PeerIdentity id;
3361   struct MeshClient *c;
3362   struct MeshTunnel *t;
3363   MESH_TunnelNumber tid;
3364   size_t size;
3365
3366   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3367               "MESH: Got a ToOrigin request from a client!\n");
3368
3369   /* Sanity check for client registration */
3370   if (NULL == (c = client_get (client)))
3371   {
3372     GNUNET_break (0);
3373     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3374     return;
3375   }
3376   data_msg = (struct GNUNET_MESH_ToOrigin *) message;
3377   /* Sanity check for message size */
3378   size = ntohs (message->size);
3379   if (sizeof (struct GNUNET_MESH_ToOrigin) +
3380       sizeof (struct GNUNET_MessageHeader) > size)
3381   {
3382     GNUNET_break (0);
3383     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3384     return;
3385   }
3386
3387   /* Tunnel exists? */
3388   tid = ntohl (data_msg->tid);
3389   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
3390   {
3391     GNUNET_break (0);
3392     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3393     return;
3394   }
3395   t = tunnel_get_by_local_id (c, tid);
3396   if (NULL == t)
3397   {
3398     GNUNET_break (0);
3399     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3400     return;
3401   }
3402
3403   /*  It shouldn't be a local tunnel.  */
3404   if (NULL != t->client)
3405   {
3406     GNUNET_break (0);
3407     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3408     return;
3409   }
3410   GNUNET_PEER_resolve(t->id.oid, &id);
3411
3412   /* Ok, everything is correct, send the message
3413    * (pretend we got it from a mesh peer)
3414    */
3415   {
3416     char buf[ntohs (message->size)];
3417     struct GNUNET_MESH_ToOrigin *copy;
3418
3419     /* Work around const limitation */
3420     copy = (struct GNUNET_MESH_ToOrigin *) buf;
3421     memcpy (buf, data_msg, size);
3422     copy->oid = id;
3423     copy->tid = htonl (t->id.tid);
3424     copy->sender = my_full_id;
3425     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3426                 "MESH:   calling generic handler...\n");
3427     handle_mesh_data_to_orig (NULL, &my_full_id, &copy->header, NULL);
3428   }
3429   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3430   return;
3431 }
3432
3433
3434 /**
3435  * Handler for client traffic directed to all peers in a tunnel
3436  *
3437  * @param cls closure
3438  * @param client identification of the client
3439  * @param message the actual message
3440  */
3441 static void
3442 handle_local_multicast (void *cls, struct GNUNET_SERVER_Client *client,
3443                         const struct GNUNET_MessageHeader *message)
3444 {
3445   struct MeshClient *c;
3446   struct MeshTunnel *t;
3447   struct GNUNET_MESH_Multicast *data_msg;
3448   MESH_TunnelNumber tid;
3449
3450   /* Sanity check for client registration */
3451   if (NULL == (c = client_get (client)))
3452   {
3453     GNUNET_break (0);
3454     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3455     return;
3456   }
3457   data_msg = (struct GNUNET_MESH_Multicast *) message;
3458   /* Sanity check for message size */
3459   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (data_msg->header.size))
3460   {
3461     GNUNET_break (0);
3462     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3463     return;
3464   }
3465
3466   /* Tunnel exists? */
3467   tid = ntohl (data_msg->tid);
3468   t = tunnel_get_by_local_id (c, tid);
3469   if (NULL == t)
3470   {
3471     GNUNET_break (0);
3472     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3473     return;
3474   }
3475
3476   /* Does client own tunnel? */
3477   if (t->client->handle != client)
3478   {
3479     GNUNET_break (0);
3480     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3481     return;
3482   }
3483
3484   {
3485     char buf[ntohs(message->size)];
3486     struct GNUNET_MESH_Multicast *copy;
3487
3488     copy = (struct GNUNET_MESH_Multicast *)buf;
3489     memcpy(buf, message, ntohs(message->size));
3490     copy->oid = my_full_id;
3491     copy->tid = htonl(t->id.tid);
3492     handle_mesh_data_multicast(client, &my_full_id, &copy->header, NULL);
3493   }
3494
3495   /* receive done gets called when last copy is sent */
3496   return;
3497 }
3498
3499 /**
3500  * Functions to handle messages from clients
3501  */
3502 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
3503   {&handle_local_new_client, NULL, GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
3504   {&handle_local_tunnel_create, NULL,
3505    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
3506    sizeof (struct GNUNET_MESH_TunnelMessage)},
3507   {&handle_local_tunnel_destroy, NULL,
3508    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
3509    sizeof (struct GNUNET_MESH_TunnelMessage)},
3510   {&handle_local_connect_add, NULL,
3511    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD,
3512    sizeof (struct GNUNET_MESH_PeerControl)},
3513   {&handle_local_connect_del, NULL,
3514    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL,
3515    sizeof (struct GNUNET_MESH_PeerControl)},
3516   {&handle_local_connect_by_type, NULL,
3517    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE,
3518    sizeof (struct GNUNET_MESH_ConnectPeerByType)},
3519   {&handle_local_unicast, NULL,
3520    GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
3521   {&handle_local_to_origin, NULL,
3522    GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
3523   {&handle_local_multicast, NULL,
3524    GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
3525   {NULL, NULL, 0, 0}
3526 };
3527
3528
3529 /**
3530  * To be called on core init/fail.
3531  *
3532  * @param cls service closure
3533  * @param server handle to the server for this service
3534  * @param identity the public identity of this peer
3535  */
3536 static void
3537 core_init (void *cls, struct GNUNET_CORE_Handle *server,
3538            const struct GNUNET_PeerIdentity *identity)
3539 {
3540   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Core init\n");
3541   core_handle = server;
3542   if (0 != memcmp(identity, &my_full_id, sizeof(my_full_id)) || NULL == server)
3543   {
3544     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("MESH: Wrong CORE service\n"));
3545     GNUNET_SCHEDULER_shutdown();   
3546   }
3547   return;
3548 }
3549
3550 /**
3551  * Method called whenever a given peer connects.
3552  *
3553  * @param cls closure
3554  * @param peer peer identity this notification is about
3555  * @param atsi performance data for the connection
3556  */
3557 static void
3558 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
3559               const struct GNUNET_TRANSPORT_ATS_Information *atsi)
3560 {
3561   struct MeshPeerInfo *peer_info;
3562   struct MeshPeerPath *path;
3563
3564 #if MESH_DEBUG_CONNECTION
3565   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Peer connected\n");
3566   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      %s\n",
3567               GNUNET_h2s(&my_full_id.hashPubKey));
3568 #endif
3569   peer_info = peer_info_get (peer);
3570   if (myid == peer_info->id)
3571   {
3572 #if MESH_DEBUG_CONNECTION
3573     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      (self)\n");
3574 #endif
3575     return;
3576   }
3577 #if MESH_DEBUG_CONNECTION
3578   else
3579   {
3580     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      %s\n",
3581                 GNUNET_h2s(&peer->hashPubKey));
3582   }
3583 #endif
3584   path = path_new (2);
3585   path->peers[0] = myid;
3586   path->peers[1] = peer_info->id;
3587   GNUNET_PEER_change_rc(myid, 1);
3588   GNUNET_PEER_change_rc(peer_info->id, 1);
3589   path_add_to_peer (peer_info, path);
3590   return;
3591 }
3592
3593 /**
3594  * Method called whenever a peer disconnects.
3595  *
3596  * @param cls closure
3597  * @param peer peer identity this notification is about
3598  */
3599 static void
3600 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
3601 {
3602   struct MeshPeerInfo *pi;
3603   unsigned int i;
3604
3605 #if MESH_DEBUG_CONNECTION
3606   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Peer disconnected\n");
3607 #endif
3608   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
3609   if (NULL == pi)
3610   {
3611     GNUNET_break (0);
3612     return;
3613   }
3614   for (i = 0; i < CORE_QUEUE_SIZE; i++)
3615   {
3616     peer_info_cancel_transmission(pi, i);
3617   }
3618   path_remove_from_peer (pi, pi->id, myid);
3619 #if MESH_DEBUG_CONNECTION
3620   if (myid == pi->id)
3621   {
3622     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      (self)\n");
3623   }
3624 #endif
3625   return;
3626 }
3627
3628
3629 /******************************************************************************/
3630 /************************      MAIN FUNCTIONS      ****************************/
3631 /******************************************************************************/
3632
3633 /**
3634  * Iterator over hash map entries.
3635  *
3636  * @param cls closure
3637  * @param key current key code
3638  * @param value value in the hash map
3639  * @return GNUNET_YES if we should continue to
3640  *         iterate,
3641  *         GNUNET_NO if not.
3642  */
3643 int
3644 shutdown_tunnel (void *cls, const GNUNET_HashCode * key, void *value)
3645 {
3646   struct MeshTunnel *t = value;
3647   tunnel_destroy(t);
3648   return GNUNET_YES;
3649 }
3650
3651 /**
3652  * Task run during shutdown.
3653  *
3654  * @param cls unused
3655  * @param tc unused
3656  */
3657 static void
3658 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3659 {
3660   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: shutting down\n");
3661   /* TODO: destroy tunnels? */
3662   if (core_handle != NULL)
3663   {
3664     GNUNET_CORE_disconnect (core_handle);
3665     core_handle = NULL;
3666   }
3667   GNUNET_CONTAINER_multihashmap_iterate(tunnels, &shutdown_tunnel, NULL);
3668   if (dht_handle != NULL)
3669   {
3670     GNUNET_DHT_disconnect (dht_handle);
3671     dht_handle = NULL;
3672   }
3673   if (nc != NULL)
3674   {
3675     GNUNET_SERVER_notification_context_destroy (nc);
3676     nc = NULL;
3677   }
3678   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
3679   {
3680     GNUNET_SCHEDULER_cancel (announce_id_task);
3681     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
3682   }
3683   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: shut down\n");
3684 }
3685
3686 /**
3687  * Process mesh requests.
3688  *
3689  * @param cls closure
3690  * @param server the initialized server
3691  * @param c configuration to use
3692  */
3693 static void
3694 run (void *cls, struct GNUNET_SERVER_Handle *server,
3695      const struct GNUNET_CONFIGURATION_Handle *c)
3696 {
3697   struct MeshPeerInfo *peer;
3698   struct MeshPeerPath *p;
3699   char *keyfile;
3700
3701   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: starting to run\n");
3702   server_handle = server;
3703   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
3704                                      CORE_QUEUE_SIZE,   /* queue size */
3705                                      NULL,      /* Closure passed to MESH functions */
3706                                      &core_init,        /* Call core_init once connected */
3707                                      &core_connect,     /* Handle connects */
3708                                      &core_disconnect,  /* remove peers on disconnects */
3709                                      NULL,      /* Don't notify about all incoming messages */
3710                                      GNUNET_NO, /* For header only in notification */
3711                                      NULL,      /* Don't notify about all outbound messages */
3712                                      GNUNET_NO, /* For header-only out notification */
3713                                      core_handlers);    /* Register these handlers */
3714   if (core_handle == NULL)
3715   {
3716     GNUNET_break (0);
3717     GNUNET_SCHEDULER_shutdown ();
3718     return;
3719   }
3720
3721   if (GNUNET_OK !=
3722        GNUNET_CONFIGURATION_get_value_filename (c, "GNUNETD", "HOSTKEY",
3723                                                 &keyfile))
3724   {
3725     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3726                 _
3727                 ("Mesh service is lacking key configuration settings.  Exiting.\n"));
3728     GNUNET_SCHEDULER_shutdown ();
3729     return;
3730   }
3731   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
3732   GNUNET_free (keyfile);
3733   if (my_private_key == NULL)
3734   {
3735     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3736                 _("Mesh service could not access hostkey.  Exiting.\n"));
3737     GNUNET_SCHEDULER_shutdown ();
3738     return;
3739   }
3740   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
3741   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
3742                       &my_full_id.hashPubKey);
3743   myid = GNUNET_PEER_intern (&my_full_id);
3744
3745   dht_handle = GNUNET_DHT_connect (c, 64);
3746   if (dht_handle == NULL)
3747   {
3748     GNUNET_break (0);
3749   }
3750
3751   next_tid = 0;
3752   next_local_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
3753
3754   tunnels = GNUNET_CONTAINER_multihashmap_create (32);
3755   incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
3756   peers = GNUNET_CONTAINER_multihashmap_create (32);
3757   applications = GNUNET_CONTAINER_multihashmap_create (32);
3758   types = GNUNET_CONTAINER_multihashmap_create (32);
3759
3760   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
3761   nc = GNUNET_SERVER_notification_context_create (server_handle,
3762                                                   LOCAL_QUEUE_SIZE);
3763   GNUNET_SERVER_disconnect_notify (server_handle,
3764                                    &handle_local_client_disconnect,
3765                                    NULL);
3766
3767
3768   clients = NULL;
3769   clients_tail = NULL;
3770 #if MESH_DEBUG
3771   next_client_id = 0;
3772 #endif
3773
3774   announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
3775   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
3776
3777   /* Create a peer_info for the local peer */
3778   peer = peer_info_get(&my_full_id);
3779   p = path_new (1);
3780   p->peers[0] = myid;
3781   path_add_to_peer(peer, p);
3782
3783   /* Scheduled the task to clean up when shutdown is called */
3784   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
3785                                 NULL);
3786
3787   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: end of run()\n");
3788 }
3789
3790 /**
3791  * The main function for the mesh service.
3792  *
3793  * @param argc number of arguments from the command line
3794  * @param argv command line arguments
3795  * @return 0 ok, 1 on error
3796  */
3797 int
3798 main (int argc, char *const *argv)
3799 {
3800   int ret;
3801
3802 #if MESH_DEBUG
3803 //   fprintf (stderr, "main ()\n");
3804 #endif
3805   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: main()\n");
3806   ret =
3807       (GNUNET_OK ==
3808        GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
3809                            NULL)) ? 0 : 1;
3810   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: main() END\n");
3811 #if MESH_DEBUG
3812 //   fprintf (stderr, "main () END\n");
3813 #endif
3814   return ret;
3815 }