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