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