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