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