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