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