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