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