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