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