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