Dont add whole path to peer, just the relevant part
[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 (NULL == p)
1290     {
1291       GNUNET_break (0);
1292       return;
1293     }
1294
1295     if (p->length > 1)
1296     {
1297       send_create_path(peer, p, t);
1298     }
1299     else
1300     {
1301       path_destroy(p);
1302       send_client_peer_connected(t, myid);
1303     }
1304   }
1305   else if (NULL == peer->dhtget)
1306   {
1307     struct GNUNET_PeerIdentity id;
1308
1309     GNUNET_PEER_resolve(peer->id, &id);
1310     path_info = GNUNET_malloc(sizeof(struct MeshPathInfo));
1311     path_info->peer = peer;
1312     path_info->t = t;
1313     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1314                 "MESH:   Starting DHT GET for peer %s\n",
1315                 GNUNET_i2s (&id));
1316     peer->dhtgetcls = path_info;
1317     peer->dhtget =
1318         GNUNET_DHT_get_start(dht_handle,       /* handle */
1319                              GNUNET_TIME_UNIT_FOREVER_REL,     /* timeout */
1320                              GNUNET_BLOCK_TYPE_TEST,   /* type */
1321                              &id.hashPubKey,       /* key to search */
1322                              4,         /* replication level */
1323                              GNUNET_DHT_RO_RECORD_ROUTE |
1324                                GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
1325                              NULL,     /* xquery */
1326                              0,        /* xquery bits */
1327                              &dht_get_id_handler,
1328                              path_info);
1329   }
1330   /* Otherwise, there is no path but the DHT get is already started. */
1331 }
1332
1333
1334 /**
1335  * Task to delay the connection of a peer
1336  *
1337  * @param cls Closure (path info with tunnel and peer to connect).
1338  *            Will be free'd on exection.
1339  * @param tc TaskContext
1340  */
1341 static void
1342 peer_info_connect_task (void *cls,
1343                         const struct GNUNET_SCHEDULER_TaskContext *tc)
1344 {
1345   struct MeshPathInfo *path_info = cls;
1346
1347   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1348   {
1349     GNUNET_free (cls);
1350     return;
1351   }
1352   peer_info_connect (path_info->peer, path_info->t);
1353   GNUNET_free (cls);
1354 }
1355
1356
1357 /**
1358  * Destroy the peer_info and free any allocated resources linked to it
1359  * 
1360  * @param pi The peer_info to destroy.
1361  * 
1362  * @return GNUNET_OK on success
1363  */
1364 static int
1365 peer_info_destroy (struct MeshPeerInfo *pi)
1366 {
1367   struct GNUNET_PeerIdentity id;
1368   struct MeshPeerPath *p;
1369   struct MeshPeerPath *nextp;
1370   unsigned int i;
1371
1372   GNUNET_PEER_resolve (pi->id, &id);
1373   GNUNET_PEER_change_rc (pi->id, -1);
1374
1375   if (GNUNET_YES !=
1376       GNUNET_CONTAINER_multihashmap_remove (peers,&id.hashPubKey, pi))
1377   {
1378     GNUNET_break (0);
1379     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1380                 "MESH: removing peer %s, not in hashmap\n",
1381                 GNUNET_i2s (&id));
1382   }
1383   if (NULL != pi->dhtget)
1384   {
1385     GNUNET_DHT_get_stop(pi->dhtget);
1386     GNUNET_free (pi->dhtgetcls);
1387   }
1388   for (i = 0; i < CORE_QUEUE_SIZE; i++)
1389   {
1390     peer_info_cancel_transmission(pi, i);
1391   }
1392   p = pi->path_head;
1393   while (NULL != p)
1394   {
1395     nextp = p->next;
1396     GNUNET_CONTAINER_DLL_remove (pi->path_head, pi->path_tail, p);
1397     path_destroy (p);
1398     p = nextp;
1399   }
1400   GNUNET_free (pi);
1401   return GNUNET_OK;
1402 }
1403
1404
1405 /**
1406  * Remove all paths that rely on a direct connection between p1 and p2
1407  * from the peer itself and notify all tunnels about it.
1408  *
1409  * @param peer PeerInfo of affected peer.
1410  * @param p1 GNUNET_PEER_Id of one peer.
1411  * @param p2 GNUNET_PEER_Id of another peer that was connected to the first and
1412  *           no longer is.
1413  *
1414  * TODO: optimize (see below)
1415  */
1416 static void
1417 path_remove_from_peer (struct MeshPeerInfo *peer,
1418                        GNUNET_PEER_Id p1,
1419                        GNUNET_PEER_Id p2)
1420 {
1421   struct MeshPeerPath *p;
1422   struct MeshPeerPath *aux;
1423   struct MeshPeerInfo *peer_d;
1424   GNUNET_PEER_Id d;
1425   unsigned int destroyed;
1426   unsigned int best;
1427   unsigned int cost;
1428   unsigned int i;
1429
1430   destroyed = 0;
1431   p = peer->path_head;
1432   while (NULL != p)
1433   {
1434     aux = p->next;
1435     for (i = 0; i < (p->length - 1); i++)
1436     {
1437       if ((p->peers[i] == p1 && p->peers[i + 1] == p2) ||
1438           (p->peers[i] == p2 && p->peers[i + 1] == p1))
1439       {
1440         GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, p);
1441         path_destroy (p);
1442         destroyed++;
1443         break;
1444       }
1445     }
1446     p = aux;
1447   }
1448   if (0 == destroyed)
1449     return;
1450
1451   for (i = 0; i < peer->ntunnels; i++)
1452   {
1453     d = tunnel_notify_connection_broken (peer->tunnels[i], p1, p2);
1454     /* TODO
1455      * Problem: one or more peers have been deleted from the tunnel tree.
1456      * We don't know who they are to try to add them again.
1457      * We need to try to find a new path for each of the disconnected peers.
1458      * Some of them might already have a path to reach them that does not
1459      * involve p1 and p2. Adding all anew might render in a better tree than
1460      * the trivial immediate fix.
1461      * 
1462      * Trivial immiediate fix: try to reconnect to the disconnected node. All
1463      * its children will be reachable trough him.
1464      */
1465     peer_d = peer_info_get_short(d);
1466     best = UINT_MAX;
1467     aux = NULL;
1468     for (p = peer_d->path_head; NULL != p; p = p->next)
1469     {
1470       if ((cost = path_get_cost(peer->tunnels[i]->tree, p)) < best)
1471       {
1472         best = cost;
1473         aux = p;
1474       }
1475     }
1476     if (NULL != aux)
1477     {
1478       /* No callback, as peer will be already disconnected */
1479       tree_add_path(peer->tunnels[i]->tree, aux, NULL);
1480     }
1481     else
1482     {
1483       peer_info_connect (peer_d, peer->tunnels[i]);
1484     }
1485   }
1486 }
1487
1488
1489 /**
1490  * Add the path to the peer and update the path used to reach it in case this
1491  * is the shortest.
1492  *
1493  * @param peer_info Destination peer to add the path to.
1494  * @param path New path to add. Last peer must be the peer in arg 1.
1495  *             Path will be either used of freed if already known.
1496  *
1497  * TODO: trim the part from origin to us? Add it as path to origin?
1498  */
1499 void
1500 path_add_to_peer (struct MeshPeerInfo *peer_info, struct MeshPeerPath *path)
1501 {
1502   struct MeshPeerPath *aux;
1503   unsigned int l;
1504   unsigned int l2;
1505
1506   if ((NULL == peer_info) || (NULL == path))
1507   {
1508     GNUNET_break (0);
1509     path_destroy (path);
1510     return;
1511   }
1512   for (l = 1; l < path->length; l++)
1513   {
1514     if (path->peers[l] == myid)
1515     {
1516       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1517                   "MESH: shortening path by %u\n",
1518                   l);
1519       for (l2 = 0; l2 < path->length - l - 1 ; l2++)
1520       {
1521         path->peers[l2] = path->peers[l + l2];
1522       }
1523       path->length -= l;
1524       l = 0;
1525       path->peers = GNUNET_realloc (path->peers,
1526                                     path->length * sizeof (GNUNET_PEER_Id));
1527     }
1528   }
1529 #if MESH_DEBUG
1530   { 
1531     struct GNUNET_PeerIdentity id;
1532
1533     GNUNET_PEER_resolve (peer_info->id, &id);
1534     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1535                 "MESH: adding path [%u] to peer %s\n",
1536                 path->length,
1537                 GNUNET_i2s (&id));
1538   }
1539 #endif
1540   l = path_get_length (path);
1541   if (0 == l)
1542   {
1543     GNUNET_free (path);
1544     return;
1545   }
1546
1547   for (aux = peer_info->path_head; aux != NULL; aux = aux->next)
1548   {
1549     l2 = path_get_length (aux);
1550     if (l2 > l)
1551     {
1552       GNUNET_CONTAINER_DLL_insert_before (peer_info->path_head,
1553                                           peer_info->path_tail,
1554                                           aux,
1555                                           path);
1556       return;
1557     }
1558     else
1559     {
1560       if (l2 == l && memcmp(path->peers, aux->peers, l) == 0)
1561       {
1562         path_destroy(path);
1563         return;
1564       }
1565     }
1566   }
1567   GNUNET_CONTAINER_DLL_insert_tail (peer_info->path_head,
1568                                     peer_info->path_tail,
1569                                     path);
1570   return;
1571 }
1572
1573
1574 /**
1575  * Add the path to the origin peer and update the path used to reach it in case
1576  * this is the shortest.
1577  * The path is given in peer_info -> destination, therefore we turn the path
1578  * upside down first.
1579  *
1580  * @param peer_info Peer to add the path to, being the origin of the path.
1581  * @param path New path to add after being inversed.
1582  */
1583 static void
1584 path_add_to_origin (struct MeshPeerInfo *peer_info, struct MeshPeerPath *path)
1585 {
1586   path_invert(path);
1587   path_add_to_peer (peer_info, path);
1588 }
1589
1590
1591 /**
1592  * Build a PeerPath from the paths returned from the DHT, reversing the paths
1593  * to obtain a local peer -> destination path and interning the peer ids.
1594  *
1595  * @return Newly allocated and created path
1596  */
1597 static struct MeshPeerPath *
1598 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
1599                      unsigned int get_path_length,
1600                      const struct GNUNET_PeerIdentity *put_path,
1601                      unsigned int put_path_length)
1602 {
1603   struct MeshPeerPath *p;
1604   GNUNET_PEER_Id id;
1605   int i;
1606
1607   p = path_new (1);
1608   p->peers[0] = myid;
1609   GNUNET_PEER_change_rc(myid, 1);
1610   i = get_path_length;
1611   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "MESH:    GET has %d hops.\n", i);
1612   for (i--; i >= 0; i--)
1613   {
1614     id = GNUNET_PEER_intern (&get_path[i]);
1615     if (p->length > 0 && id == p->peers[p->length - 1])
1616     {
1617       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "MESH:    Optimizing 1 hop out.\n");
1618       GNUNET_PEER_change_rc(id, -1);
1619     }
1620     else
1621     {
1622       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1623                  "MESH:    Adding from GET: %s.\n",
1624                  GNUNET_i2s(&get_path[i]));
1625       p->length++;
1626       p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
1627       p->peers[p->length - 1] = id;
1628     }
1629   }
1630   i = put_path_length;
1631   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "MESH:    PUT has %d hops.\n", i);
1632   for (i--; i >= 0; i--)
1633   {
1634     id = GNUNET_PEER_intern (&put_path[i]);
1635     if (id == myid)
1636     {
1637       /* PUT path went through us, so discard the path up until now and start
1638        * from here to get a much shorter (and loop-free) path.
1639        */
1640       path_destroy (p);
1641       p = path_new (0);
1642     }
1643     if (p->length > 0 && id == p->peers[p->length - 1])
1644     {
1645       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "MESH:    Optimizing 1 hop out.\n");
1646       GNUNET_PEER_change_rc(id, -1);
1647     }
1648     else
1649     {
1650       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1651             "MESH:    Adding from PUT: %s.\n",
1652             GNUNET_i2s(&put_path[i]));
1653       p->length++;
1654       p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
1655       p->peers[p->length - 1] = id;
1656     }
1657   }
1658 #if MESH_DEBUG
1659   if (get_path_length > 0)
1660     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1661                 "MESH:    (first of GET: %s)\n",
1662                 GNUNET_i2s(&get_path[0]));
1663   if (put_path_length > 0)
1664     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1665                 "MESH:    (first of PUT: %s)\n",
1666                 GNUNET_i2s(&put_path[0]));
1667   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1668               "MESH:    In total: %d hops\n",
1669               p->length);
1670   for (i = 0; i < p->length; i++)
1671   {
1672     struct GNUNET_PeerIdentity peer_id;
1673
1674     GNUNET_PEER_resolve(p->peers[i], &peer_id);
1675     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1676               "MESH:        %u: %s\n",
1677               p->peers[i],
1678               GNUNET_i2s(&peer_id));
1679   }
1680 #endif
1681   return p;
1682 }
1683
1684
1685 /**
1686  * Send keepalive packets for a peer
1687  *
1688  * @param cls Closure (tunnel for which to send the keepalive).
1689  * @param tc Notification context.
1690  *
1691  * TODO: implement explicit multicast keepalive?
1692  */
1693 static void
1694 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1695
1696
1697 /**
1698  * Search for a tunnel among the tunnels for a client
1699  *
1700  * @param c the client whose tunnels to search in
1701  * @param tid the local id of the tunnel
1702  *
1703  * @return tunnel handler, NULL if doesn't exist
1704  */
1705 static struct MeshTunnel *
1706 tunnel_get_by_local_id (struct MeshClient *c, MESH_TunnelNumber tid)
1707 {
1708   GNUNET_HashCode hash;
1709
1710   GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
1711   if (tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
1712   {
1713     return GNUNET_CONTAINER_multihashmap_get (incoming_tunnels, &hash);
1714   }
1715   return GNUNET_CONTAINER_multihashmap_get (c->tunnels, &hash);
1716 }
1717
1718
1719 /**
1720  * Search for a tunnel by global ID using PEER_ID
1721  *
1722  * @param pi owner of the tunnel
1723  * @param tid global tunnel number
1724  *
1725  * @return tunnel handler, NULL if doesn't exist
1726  */
1727 static struct MeshTunnel *
1728 tunnel_get_by_pi (GNUNET_PEER_Id pi, MESH_TunnelNumber tid)
1729 {
1730   struct MESH_TunnelID id;
1731   GNUNET_HashCode hash;
1732
1733   id.oid = pi;
1734   id.tid = tid;
1735
1736   GNUNET_CRYPTO_hash (&id, sizeof (struct MESH_TunnelID), &hash);
1737   return GNUNET_CONTAINER_multihashmap_get (tunnels, &hash);
1738 }
1739
1740
1741 /**
1742  * Search for a tunnel by global ID using full PeerIdentities
1743  *
1744  * @param oid owner of the tunnel
1745  * @param tid global tunnel number
1746  *
1747  * @return tunnel handler, NULL if doesn't exist
1748  */
1749 static struct MeshTunnel *
1750 tunnel_get (struct GNUNET_PeerIdentity *oid, MESH_TunnelNumber tid)
1751 {
1752   return tunnel_get_by_pi (GNUNET_PEER_search (oid), tid);
1753 }
1754
1755
1756 /**
1757  * Callback used to notify a client owner of a tunnel that a peer has
1758  * disconnected, most likely because of a path change.
1759  *
1760  * @param n Node in the tree representing the disconnected peer
1761  * 
1762  * FIXME: pass tunnel via cls, make param just a peer identity
1763  */
1764 void
1765 notify_peer_disconnected (const struct MeshTunnelTreeNode *n)
1766 {
1767   struct MeshPeerInfo *peer;
1768   struct MeshPathInfo *path_info;
1769
1770   if (NULL != n->t->client && NULL != nc)
1771   {
1772     struct GNUNET_MESH_PeerControl msg;
1773     msg.header.size = htons (sizeof (msg));
1774     msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL);
1775     msg.tunnel_id = htonl (n->t->local_tid);
1776     GNUNET_PEER_resolve (n->peer, &msg.peer);
1777     GNUNET_SERVER_notification_context_unicast (nc, n->t->client->handle,
1778                                                 &msg.header, GNUNET_NO);
1779   }
1780   peer = peer_info_get_short(n->peer);
1781   path_info = GNUNET_malloc (sizeof (struct MeshPathInfo));
1782   path_info->peer = peer;
1783   path_info->t = n->t;
1784   GNUNET_SCHEDULER_add_now(&peer_info_connect_task, path_info);
1785 }
1786
1787
1788 /**
1789  * Add a peer to a tunnel, accomodating paths accordingly and initializing all
1790  * needed rescources.
1791  * If peer already exists, reevaluate shortest path and change if different.
1792  *
1793  * @param t Tunnel we want to add a new peer to
1794  * @param peer PeerInfo of the peer being added
1795  *
1796  */
1797 static void
1798 tunnel_add_peer (struct MeshTunnel *t, struct MeshPeerInfo *peer)
1799 {
1800   struct GNUNET_PeerIdentity id;
1801   struct MeshPeerPath *best_p;
1802   struct MeshPeerPath *p;
1803   unsigned int best_cost;
1804   unsigned int cost;
1805
1806   GNUNET_PEER_resolve(peer->id, &id);
1807   if (GNUNET_NO ==
1808       GNUNET_CONTAINER_multihashmap_contains(t->peers, &id.hashPubKey))
1809   {
1810     t->peers_total++;
1811     GNUNET_array_append (peer->tunnels, peer->ntunnels, t);
1812     GNUNET_CONTAINER_multihashmap_put(
1813       t->peers,
1814       &id.hashPubKey,
1815       peer,
1816       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1817   }
1818
1819   if (NULL != (p = peer->path_head))
1820   {
1821     best_p = p;
1822     best_cost = path_get_cost(t->tree, p);
1823     while (NULL != p)
1824     {
1825       if ((cost = path_get_cost (t->tree, p)) < best_cost)
1826       {
1827         best_cost = cost;
1828         best_p = p;
1829       }
1830       p = p->next;
1831     }
1832     tree_add_path (t->tree, best_p, &notify_peer_disconnected);
1833     if (GNUNET_SCHEDULER_NO_TASK == t->path_refresh_task)
1834       t->path_refresh_task =
1835           GNUNET_SCHEDULER_add_delayed (t->tree->refresh, &path_refresh, t);
1836   }
1837   else
1838   {
1839     /* Start a DHT get if necessary */
1840     peer_info_connect(peer, t);
1841   }
1842 }
1843
1844 /**
1845  * Add a path to a tunnel which we don't own, just to remember the next hop.
1846  * If destination node was already in the tunnel, the first hop information
1847  * will be replaced with the new path.
1848  *
1849  * @param t Tunnel we want to add a new peer to
1850  * @param p Path to add
1851  * @param own_pos Position of local node in path.
1852  *
1853  */
1854 static void
1855 tunnel_add_path (struct MeshTunnel *t,
1856                  struct MeshPeerPath *p,
1857                  unsigned int own_pos)
1858 {
1859   struct GNUNET_PeerIdentity id;
1860
1861   GNUNET_assert (0 != own_pos);
1862   tree_add_path(t->tree, p, NULL);
1863   if (NULL == t->tree->me)
1864     t->tree->me = tree_find_peer(t->tree->root, p->peers[own_pos]);
1865   if (own_pos < p->length - 1)
1866   {
1867     GNUNET_PEER_resolve (p->peers[own_pos + 1], &id);
1868     tree_update_first_hops(t->tree, t->tree->me, &id);
1869   }
1870 }
1871
1872
1873 /**
1874  * Notifies a tunnel that a connection has broken that affects at least
1875  * some of its peers. Sends a notification towards the root of the tree.
1876  * In case the peer is the owner of the tree, notifies the client that owns
1877  * the tunnel and tries to reconnect.
1878  *
1879  * @param t Tunnel affected.
1880  * @param p1 Peer that got disconnected from p2.
1881  * @param p2 Peer that got disconnected from p1.
1882  *
1883  * @return Short ID of the peer disconnected (either p1 or p2).
1884  *         0 if the tunnel remained unaffected.
1885  */
1886 static GNUNET_PEER_Id
1887 tunnel_notify_connection_broken (struct MeshTunnel *t,
1888                                  GNUNET_PEER_Id p1,
1889                                  GNUNET_PEER_Id p2)
1890 {
1891   GNUNET_PEER_Id pid;
1892
1893   pid = tree_notify_connection_broken (t->tree,
1894                                        p1,
1895                                        p2,
1896                                        &notify_peer_disconnected);
1897   if (myid != p1 && myid != p2)
1898   {
1899     return pid;
1900   }
1901   if (pid != myid)
1902   {
1903     if (NULL != t->tree->me->parent)
1904     {
1905       /* We are the peer still connected, notify owner of the disconnection. */
1906       struct GNUNET_MESH_PathBroken msg;
1907       struct GNUNET_PeerIdentity neighbor;
1908
1909       msg.header.size = htons (sizeof (msg));
1910       msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN);
1911       GNUNET_PEER_resolve (t->id.oid, &msg.oid);
1912       msg.tid = htonl (t->id.tid);
1913       msg.peer1 = my_full_id;
1914       GNUNET_PEER_resolve (pid, &msg.peer2);
1915       GNUNET_PEER_resolve (t->tree->me->parent->peer, &neighbor);
1916       send_message (&msg.header, &neighbor);
1917     }
1918   }
1919   return pid;
1920 }
1921
1922
1923 /**
1924  * Send a message in a tunnel in multicast, sending a copy to each child node
1925  * down the local one in the tunnel tree.
1926  *
1927  * @param t Tunnel in which to send the data.
1928  * @param msg Message to be sent
1929  *
1930  * @return Number of copies sent.
1931  * 
1932  * TODO: unifiy shared resources and reference counter management
1933  */
1934 static int
1935 tunnel_send_multicast (struct MeshTunnel *t,
1936                        const struct GNUNET_MessageHeader *msg)
1937 {
1938   struct GNUNET_PeerIdentity neighbor;
1939   struct MeshDataDescriptor *info;
1940   struct MeshTunnelTreeNode *n;
1941   struct MeshTunnelTreeNode *counter;
1942   GNUNET_SCHEDULER_TaskIdentifier *task;
1943   unsigned int *copies;
1944   unsigned int i;
1945   size_t size;
1946   void *data;
1947
1948   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1949               "MESH:  sending a multicast packet...\n");
1950   size = ntohs (msg->size);
1951   GNUNET_assert (NULL != t->tree->me);
1952   n = t->tree->me->children_head;
1953   if (NULL == n)
1954   {
1955     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1956               "MESH:  no children in the tree, no one to send.\n");
1957     return 0;
1958   }
1959   copies = GNUNET_malloc (sizeof (unsigned int));
1960   for (counter = n; NULL != counter; counter = counter->next)
1961     (*copies)++;
1962   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  (%u copies)\n", *copies);
1963   data = GNUNET_malloc (size);
1964   memcpy (data, msg, size);
1965   if (NULL != t->client)
1966   {
1967     task = GNUNET_malloc (sizeof (GNUNET_SCHEDULER_TaskIdentifier));
1968     *task = GNUNET_SCHEDULER_add_delayed (UNACKNOWLEDGED_WAIT,
1969                                          &client_allow_send,
1970                                          t->client->handle);
1971   }
1972   else
1973     task = NULL; // So GCC shuts up about task being potentially uninitialized
1974   while (NULL != n)
1975   {
1976     info = GNUNET_malloc (sizeof (struct MeshDataDescriptor));
1977     info->data = data;
1978     info->size = size;
1979     info->copies = copies;
1980     if (NULL != t->client)
1981     {
1982       info->client = t->client->handle;
1983       info->timeout_task = task;
1984     }
1985     info->destination = n->peer;
1986     GNUNET_PEER_resolve (n->peer, &neighbor);
1987     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1988               "MESH:  sending to %s...\n",
1989               GNUNET_i2s (&neighbor));
1990     info->peer = peer_info_get(&neighbor);
1991     GNUNET_assert (NULL != info->peer);
1992     i = peer_info_transmit_slot(info->peer);
1993     info->handler_n = i;
1994     info->peer->infos[i] = info;
1995     info->peer->types[i] = GNUNET_MESSAGE_TYPE_MESH_MULTICAST;
1996     info->peer->core_transmit[i] =
1997         GNUNET_CORE_notify_transmit_ready (core_handle,
1998                                            0,
1999                                            0,
2000                                            GNUNET_TIME_UNIT_FOREVER_REL,
2001                                            &neighbor,
2002                                            size,
2003                                            &send_core_data_multicast, info);
2004     n = n->next;
2005   }
2006   return *copies;
2007 }
2008
2009
2010 /**
2011  * Send a message to all peers in this tunnel that the tunnel is no longer
2012  * valid.
2013  *
2014  * @param t The tunnel whose peers to notify.
2015  */
2016 static void
2017 tunnel_send_destroy (struct MeshTunnel *t)
2018 {
2019   struct GNUNET_MESH_TunnelDestroy msg;
2020
2021   msg.header.size = htons (sizeof (msg));
2022   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY);
2023   GNUNET_PEER_resolve (t->id.oid, &msg.oid);
2024   msg.tid = htonl (t->id.tid);
2025   tunnel_send_multicast (t, &msg.header);
2026 }
2027
2028
2029
2030 /**
2031  * Destroy the tunnel and free any allocated resources linked to it
2032  *
2033  * @param t the tunnel to destroy
2034  *
2035  * @return GNUNET_OK on success
2036  */
2037 static int
2038 tunnel_destroy (struct MeshTunnel *t)
2039 {
2040   struct MeshClient *c;
2041   struct MeshQueue *q;
2042   struct MeshQueue *qn;
2043   GNUNET_HashCode hash;
2044   int r;
2045
2046   if (NULL == t)
2047     return GNUNET_OK;
2048
2049   c = t->client;
2050 #if MESH_DEBUG
2051   {
2052     struct GNUNET_PeerIdentity id;
2053
2054     GNUNET_PEER_resolve(t->id.oid, &id);
2055     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2056                 "MESH: destroying tunnel %s [%x]\n",
2057                 GNUNET_i2s (&id),
2058                 t->id.tid);
2059     if (NULL != c)
2060       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   by client %u\n", c->id);
2061   }
2062 #endif
2063
2064   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
2065   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &hash, t))
2066   {
2067     r = GNUNET_SYSERR;
2068   }
2069
2070   GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
2071   if (NULL != c &&
2072       GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (c->tunnels, &hash, t))
2073   {
2074     r = GNUNET_SYSERR;
2075   }
2076   if (t->local_tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
2077   {
2078     GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
2079     GNUNET_break (GNUNET_YES ==
2080       GNUNET_CONTAINER_multihashmap_remove (incoming_tunnels, &hash, t));
2081   }
2082
2083   if (NULL != t->peers)
2084   {
2085     GNUNET_CONTAINER_multihashmap_iterate(t->peers,
2086                                           &peer_info_delete_tunnel, t);
2087     GNUNET_CONTAINER_multihashmap_destroy (t->peers);
2088   }
2089   q = t->queue_head;
2090   while (NULL != q)
2091   {
2092     if (NULL != q->data)
2093       GNUNET_free (q->data);
2094     qn = q->next;
2095     GNUNET_free (q);
2096     q = qn;
2097     /* TODO cancel core transmit ready in case it was active */
2098   }
2099   tree_destroy(t->tree);
2100   if (NULL != t->dht_get_type)
2101     GNUNET_DHT_get_stop(t->dht_get_type);
2102   if (GNUNET_SCHEDULER_NO_TASK != t->timeout_task)
2103     GNUNET_SCHEDULER_cancel(t->timeout_task);
2104   if (GNUNET_SCHEDULER_NO_TASK != t->path_refresh_task)
2105     GNUNET_SCHEDULER_cancel(t->path_refresh_task);
2106   GNUNET_free (t);
2107   return r;
2108 }
2109
2110
2111 /**
2112  * Removes an explicit path from a tunnel, freeing all intermediate nodes
2113  * that are no longer needed, as well as nodes of no longer reachable peers.
2114  * The tunnel itself is also destoyed if results in a remote empty tunnel.
2115  *
2116  * @param t Tunnel from which to remove the path.
2117  * @param p Peer which should be removed.
2118  */
2119 static void
2120 tunnel_delete_peer (struct MeshTunnel *t,
2121                     GNUNET_PEER_Id peer)
2122 {
2123   GNUNET_break (GNUNET_OK == tree_del_peer (t->tree, peer, NULL));
2124   if (NULL == t->tree->root)
2125     tunnel_destroy (t);
2126 }
2127
2128
2129 /**
2130  * tunnel_destroy_iterator: iterator for deleting each tunnel that belongs to a
2131  * client when the client disconnects.
2132  * 
2133  * @param cls closure (client that is disconnecting)
2134  * @param key the hash of the local tunnel id (used to access the hashmap)
2135  * @param value the value stored at the key (tunnel to destroy)
2136  * 
2137  * @return GNUNET_OK on success
2138  */
2139 static int
2140 tunnel_destroy_iterator (void *cls, const GNUNET_HashCode * key, void *value)
2141 {
2142   struct MeshTunnel *t = value;
2143   int r;
2144
2145   if (NULL != t->dht_get_type)
2146   {
2147     GNUNET_DHT_get_stop (t->dht_get_type);
2148   }
2149   r = tunnel_destroy (t);
2150   return r;
2151 }
2152
2153
2154 /**
2155  * Timeout function, destroys tunnel if called
2156  *
2157  * @param cls Closure (tunnel to destroy).
2158  * @param tc TaskContext
2159  */
2160 static void
2161 tunnel_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2162 {
2163   struct MeshTunnel *t = cls;
2164
2165   if (GNUNET_SCHEDULER_REASON_SHUTDOWN == tc->reason)
2166     return;
2167   t->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2168   tunnel_destroy (t);
2169 }
2170
2171 /**
2172  * Resets the tunnel timeout. Starts it if no timeout was running.
2173  *
2174  * @param t Tunnel whose timeout to reset.
2175  */
2176 static void
2177 tunnel_reset_timeout (struct MeshTunnel *t)
2178 {
2179   if (GNUNET_SCHEDULER_NO_TASK != t->timeout_task)
2180     GNUNET_SCHEDULER_cancel (t->timeout_task);
2181   t->timeout_task = GNUNET_SCHEDULER_add_delayed (
2182       GNUNET_TIME_relative_multiply(REFRESH_PATH_TIME, 4),
2183       &tunnel_timeout,
2184       t);
2185 }
2186
2187
2188 /******************************************************************************/
2189 /****************      MESH NETWORK HANDLER HELPERS     ***********************/
2190 /******************************************************************************/
2191
2192 /**
2193  * Function called to notify a client about the socket
2194  * being ready to queue more data.  "buf" will be
2195  * NULL and "size" zero if the socket was closed for
2196  * writing in the meantime.
2197  *
2198  * @param cls closure
2199  * @param size number of bytes available in buf
2200  * @param buf where the callee should write the message
2201  * @return number of bytes written to buf
2202  */
2203 static size_t
2204 send_core_create_path (void *cls, size_t size, void *buf)
2205 {
2206   struct MeshPathInfo *info = cls;
2207   struct GNUNET_MESH_ManipulatePath *msg;
2208   struct GNUNET_PeerIdentity *peer_ptr;
2209   struct MeshPeerInfo *peer = info->peer;
2210   struct MeshTunnel *t = info->t;
2211   struct MeshPeerPath *p = info->path;
2212   size_t size_needed;
2213   int i;
2214
2215   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2216               "MESH: CREATE PATH sending...\n");
2217   size_needed =
2218       sizeof (struct GNUNET_MESH_ManipulatePath) +
2219       p->length * sizeof (struct GNUNET_PeerIdentity);
2220
2221   if (size < size_needed || NULL == buf)
2222   {
2223     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: create path retransmit!\n");
2224     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   buf:  %p\n", buf);
2225     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   size: (%u/%u)\n",
2226                 size, size_needed);
2227     info->peer->core_transmit[info->pos] = 
2228       GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
2229                                         GNUNET_TIME_UNIT_FOREVER_REL,
2230                                         path_get_first_hop (t->tree, peer->id),
2231                                         size_needed,
2232                                         &send_core_create_path,
2233                                         info);
2234     return 0;
2235   }
2236   info->peer->core_transmit[info->pos] = NULL;
2237 #if MESH_DEBUG
2238   {
2239     struct GNUNET_PeerIdentity id;
2240
2241     GNUNET_PEER_resolve (peer->id, &id);
2242     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2243                 "MESH:   setting core_transmit %s [%u] to NULL\n",
2244                 GNUNET_i2s (&id),
2245                 info->pos);
2246   }
2247 #endif
2248   msg = (struct GNUNET_MESH_ManipulatePath *) buf;
2249   msg->header.size = htons (size_needed);
2250   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE);
2251   msg->tid = ntohl (t->id.tid);
2252
2253   peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
2254   for (i = 0; i < p->length; i++)
2255   {
2256     GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
2257   }
2258
2259   path_destroy (p);
2260   GNUNET_free (info);
2261
2262   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2263               "MESH: CREATE PATH (%u bytes long) sent!\n",
2264               size_needed);
2265   return size_needed;
2266 }
2267
2268
2269 /**
2270  * Function called to notify a client about the socket
2271  * being ready to queue more data.  "buf" will be
2272  * NULL and "size" zero if the socket was closed for
2273  * writing in the meantime.
2274  *
2275  * @param cls closure (data itself)
2276  * @param size number of bytes available in buf
2277  * @param buf where the callee should write the message
2278  * 
2279  * @return number of bytes written to buf
2280  */
2281 static size_t
2282 send_core_data_multicast (void *cls, size_t size, void *buf)
2283 {
2284   struct MeshDataDescriptor *info = cls;
2285   size_t total_size;
2286
2287   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Multicast callback.\n");
2288   GNUNET_assert (NULL != info);
2289   GNUNET_assert (NULL != info->peer);
2290   total_size = info->size;
2291   GNUNET_assert (total_size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
2292
2293   if (total_size > size)
2294   {
2295     /* Retry */
2296     struct GNUNET_PeerIdentity id;
2297
2298     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2299                 "MESH: Multicast: retransmitting... (%u/%u)\n",
2300                 size, total_size);
2301     GNUNET_PEER_resolve(info->peer->id, &id);
2302     info->peer->core_transmit[info->handler_n] =
2303       GNUNET_CORE_notify_transmit_ready (core_handle,
2304                                          0,
2305                                          0,
2306                                          GNUNET_TIME_UNIT_FOREVER_REL,
2307                                          &id,
2308                                          total_size,
2309                                          &send_core_data_multicast,
2310                                          info);
2311     return 0;
2312   }
2313   info->peer->core_transmit[info->handler_n] = NULL;
2314   info->peer->infos[info->handler_n] = NULL;
2315   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  copying data...\n");
2316   memcpy (buf, info->data, total_size);
2317 #if MESH_DEBUG
2318   {
2319     struct GNUNET_MESH_Multicast *mc;
2320     struct GNUNET_MessageHeader *mh;
2321
2322     mh = buf;
2323     if (ntohs (mh->type) == GNUNET_MESSAGE_TYPE_MESH_MULTICAST)
2324     {
2325       mc = (struct GNUNET_MESH_Multicast *) mh;
2326       mh = (struct GNUNET_MessageHeader *) &mc[1];
2327       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2328                   "MESH:  multicast, payload type %u\n",
2329                   ntohs (mh->type));
2330       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2331                   "MESH:  multicast, payload size %u\n",
2332                   ntohs (mh->size));
2333     }
2334     else
2335     {
2336       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2337                   "MESH:  type %u\n",
2338                   ntohs (mh->type));
2339     }
2340   }
2341 #endif
2342   data_descriptor_decrement_multicast (info);
2343   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: freeing info...\n");
2344   GNUNET_free (info);
2345   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: return %u\n", total_size);
2346   return total_size;
2347 }
2348
2349
2350 /**
2351  * Function called to notify a client about the socket
2352  * being ready to queue more data.  "buf" will be
2353  * NULL and "size" zero if the socket was closed for
2354  * writing in the meantime.
2355  *
2356  * @param cls closure (MeshDataDescriptor)
2357  * @param size number of bytes available in buf
2358  * @param buf where the callee should write the message
2359  * @return number of bytes written to buf
2360  */
2361 static size_t
2362 send_core_path_ack (void *cls, size_t size, void *buf)
2363 {
2364   struct MeshDataDescriptor *info = cls;
2365   struct GNUNET_MESH_PathACK *msg = buf;
2366
2367   GNUNET_assert (NULL != info);
2368   if (info->peer)
2369   {
2370     info->peer->core_transmit[info->handler_n] = NULL;
2371   }
2372   if (sizeof (struct GNUNET_MESH_PathACK) > size)
2373   {
2374     GNUNET_break (0);
2375     return 0;
2376   }
2377   msg->header.size = htons (sizeof (struct GNUNET_MESH_PathACK));
2378   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_ACK);
2379   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
2380   msg->tid = htonl (info->origin->tid);
2381   msg->peer_id = my_full_id;
2382   GNUNET_free (info);
2383   /* TODO add signature */
2384
2385   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: PATH ACK sent!\n");
2386   return sizeof (struct GNUNET_MESH_PathACK);
2387 }
2388
2389
2390 /******************************************************************************/
2391 /********************      MESH NETWORK HANDLERS     **************************/
2392 /******************************************************************************/
2393
2394
2395 /**
2396  * Core handler for path creation
2397  *
2398  * @param cls closure
2399  * @param message message
2400  * @param peer peer identity this notification is about
2401  * @param atsi performance data
2402  * @param atsi_count number of records in 'atsi'
2403  * 
2404  * @return GNUNET_OK to keep the connection open,
2405  *         GNUNET_SYSERR to close it (signal serious error)
2406  */
2407 static int
2408 handle_mesh_path_create (void *cls, const struct GNUNET_PeerIdentity *peer,
2409                          const struct GNUNET_MessageHeader *message,
2410                          const struct GNUNET_ATS_Information *atsi,
2411                          unsigned int atsi_count)
2412 {
2413   unsigned int own_pos;
2414   uint16_t size;
2415   uint16_t i;
2416   MESH_TunnelNumber tid;
2417   struct GNUNET_MESH_ManipulatePath *msg;
2418   struct GNUNET_PeerIdentity *pi;
2419   GNUNET_HashCode hash;
2420   struct MeshPeerPath *path;
2421   struct MeshPeerInfo *dest_peer_info;
2422   struct MeshPeerInfo *orig_peer_info;
2423   struct MeshTunnel *t;
2424
2425   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2426               "MESH: Received a path create msg [%s]\n",
2427               GNUNET_i2s(&my_full_id));
2428   size = ntohs (message->size);
2429   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
2430   {
2431     GNUNET_break_op (0);
2432     return GNUNET_OK;
2433   }
2434
2435   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
2436   if (size % sizeof (struct GNUNET_PeerIdentity))
2437   {
2438     GNUNET_break_op (0);
2439     return GNUNET_OK;
2440   }
2441   size /= sizeof (struct GNUNET_PeerIdentity);
2442   if (size < 2)
2443   {
2444     GNUNET_break_op (0);
2445     return GNUNET_OK;
2446   }
2447   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2448               "MESH:     path has %u hops.\n",
2449               size);
2450   msg = (struct GNUNET_MESH_ManipulatePath *) message;
2451
2452   tid = ntohl (msg->tid);
2453   pi = (struct GNUNET_PeerIdentity *) &msg[1];
2454   t = tunnel_get (pi, tid);
2455   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2456               "MESH:     path is for tunnel %s [%X].\n",
2457               GNUNET_i2s(pi),
2458               tid);
2459   if (NULL == t)
2460   {
2461     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   Creating tunnel\n");
2462     t = GNUNET_malloc (sizeof (struct MeshTunnel));
2463     t->id.oid = GNUNET_PEER_intern (pi);
2464     t->id.tid = tid;
2465     t->local_tid = next_local_tid++;
2466     /* FIXME test if taken */
2467     next_local_tid |= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
2468     t->tree = tree_new(t, t->id.oid);
2469
2470     GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
2471     if (GNUNET_OK !=
2472         GNUNET_CONTAINER_multihashmap_put (
2473             tunnels,
2474             &hash,
2475             t,
2476             GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2477     {
2478       tunnel_destroy (t);
2479       GNUNET_break (0);
2480       return GNUNET_OK;
2481     }
2482     tunnel_reset_timeout (t);
2483     GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
2484     if (GNUNET_OK !=
2485         GNUNET_CONTAINER_multihashmap_put (
2486             incoming_tunnels,
2487             &hash,
2488             t,
2489             GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2490     {
2491       tunnel_destroy (t);
2492       GNUNET_break (0);
2493       return GNUNET_OK;
2494     }
2495   }
2496   dest_peer_info =
2497       GNUNET_CONTAINER_multihashmap_get (peers, &pi[size - 1].hashPubKey);
2498   if (NULL == dest_peer_info)
2499   {
2500     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2501                 "MESH:   Creating PeerInfo for destination.\n");
2502     dest_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
2503     dest_peer_info->id = GNUNET_PEER_intern (&pi[size - 1]);
2504     GNUNET_CONTAINER_multihashmap_put (peers, &pi[size - 1].hashPubKey,
2505                                        dest_peer_info,
2506                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2507   }
2508   orig_peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &pi->hashPubKey);
2509   if (NULL == orig_peer_info)
2510   {
2511     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2512                 "MESH:   Creating PeerInfo for origin.\n");
2513     orig_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
2514     orig_peer_info->id = GNUNET_PEER_intern (pi);
2515     GNUNET_CONTAINER_multihashmap_put (peers, &pi->hashPubKey, orig_peer_info,
2516                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2517   }
2518   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   Creating path...\n");
2519   path = path_new (size);
2520   own_pos = 0;
2521   for (i = 0; i < size; i++)
2522   {
2523     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2524                 "MESH:   ... adding %s\n",
2525                 GNUNET_i2s(&pi[i]));
2526     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
2527     if (path->peers[i] == myid)
2528       own_pos = i;
2529   }
2530   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2531                 "MESH:   Own position: %u\n", own_pos);
2532   if (own_pos == 0)
2533   {
2534     /* cannot be self, must be 'not found' */
2535     /* create path: self not found in path through self */
2536     GNUNET_break_op (0);
2537     path_destroy (path);
2538     /* FIXME error. destroy tunnel? leave for timeout? */
2539     return 0;
2540   }
2541   tunnel_add_path (t, path, own_pos);
2542   if (own_pos == size - 1)
2543   {
2544     /* It is for us! Send ack. */
2545     struct GNUNET_MESH_TunnelNotification cmsg;
2546     struct MeshDataDescriptor *info;
2547     unsigned int j;
2548
2549     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2550                 "MESH:   It's for us!\n");
2551     path_add_to_origin (orig_peer_info, path);
2552     if (NULL == t->peers)
2553       t->peers = GNUNET_CONTAINER_multihashmap_create(4);
2554     GNUNET_break (GNUNET_OK == GNUNET_CONTAINER_multihashmap_put (
2555         t->peers,
2556         &my_full_id.hashPubKey,
2557         peer_info_get(&my_full_id),
2558         GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
2559     info = GNUNET_malloc (sizeof (struct MeshDataDescriptor));
2560     info->origin = &t->id;
2561     info->peer = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
2562     GNUNET_assert (NULL != info->peer);
2563     j = peer_info_transmit_slot(info->peer);
2564     info->handler_n = j;
2565     info->peer->types[j] = GNUNET_MESSAGE_TYPE_MESH_PATH_ACK;
2566     info->peer->infos[j] = info;
2567     info->peer->core_transmit[j] =
2568         GNUNET_CORE_notify_transmit_ready (core_handle, 0, 100,
2569                                            GNUNET_TIME_UNIT_FOREVER_REL, peer,
2570                                            sizeof (struct GNUNET_MESH_PathACK),
2571                                            &send_core_path_ack, info);
2572     cmsg.header.size = htons(sizeof(cmsg));
2573     cmsg.header.type = htons(GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
2574     GNUNET_PEER_resolve(t->id.oid, &cmsg.peer);
2575     cmsg.tunnel_id = htonl(t->local_tid);
2576     GNUNET_SERVER_notification_context_broadcast(nc, &cmsg.header, GNUNET_NO);
2577   }
2578   else
2579   {
2580     struct MeshPeerPath *path2;
2581
2582     /* It's for somebody else! Retransmit. */
2583     path2 = path_duplicate(path);
2584     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2585                 "MESH:   Retransmitting.\n");
2586     path_add_to_peer(dest_peer_info, path);
2587     path = path_duplicate(path2);
2588     path_add_to_origin(orig_peer_info, path2);
2589     send_create_path(dest_peer_info, path, t);
2590   }
2591   return GNUNET_OK;
2592 }
2593
2594
2595 /**
2596  * Core handler for path destruction
2597  *
2598  * @param cls closure
2599  * @param message message
2600  * @param peer peer identity this notification is about
2601  * @param atsi performance data
2602  * @param atsi_count number of records in 'atsi'
2603  *
2604  * @return GNUNET_OK to keep the connection open,
2605  *         GNUNET_SYSERR to close it (signal serious error)
2606  */
2607 static int
2608 handle_mesh_path_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
2609                           const struct GNUNET_MessageHeader *message,
2610                           const struct GNUNET_ATS_Information *atsi,
2611                           unsigned int atsi_count)
2612 {
2613   struct GNUNET_MESH_ManipulatePath *msg;
2614   struct GNUNET_PeerIdentity *pi;
2615   struct MeshPeerPath *path;
2616   struct MeshTunnel *t;
2617   unsigned int own_pos;
2618   unsigned int i;
2619   size_t size;
2620
2621   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2622               "MESH: Received a PATH DESTROY msg from %s\n",
2623               GNUNET_i2s(peer));
2624   size = ntohs (message->size);
2625   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
2626   {
2627     GNUNET_break_op (0);
2628     return GNUNET_OK;
2629   }
2630
2631   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
2632   if (size % sizeof (struct GNUNET_PeerIdentity))
2633   {
2634     GNUNET_break_op (0);
2635     return GNUNET_OK;
2636   }
2637   size /= sizeof (struct GNUNET_PeerIdentity);
2638   if (size < 2)
2639   {
2640     GNUNET_break_op (0);
2641     return GNUNET_OK;
2642   }
2643   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2644               "MESH:     path has %u hops.\n",
2645               size);
2646
2647   msg = (struct GNUNET_MESH_ManipulatePath *) message;
2648   pi = (struct GNUNET_PeerIdentity *) &msg[1];
2649   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2650               "MESH:     path is for tunnel %s [%X].\n",
2651               GNUNET_i2s(pi),
2652               msg->tid);
2653   t = tunnel_get (pi, ntohl (msg->tid));
2654   if (NULL == t)
2655   {
2656     /* TODO notify back: we don't know this tunnel */
2657     GNUNET_break_op (0);
2658     return GNUNET_OK;
2659   }
2660   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   Creating path...\n");
2661   path = path_new (size);
2662   own_pos = 0;
2663   for (i = 0; i < size; i++)
2664   {
2665     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2666                 "MESH:   ... adding %s\n",
2667                 GNUNET_i2s(&pi[i]));
2668     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
2669     if (path->peers[i] == myid)
2670       own_pos = i;
2671   }
2672   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2673                 "MESH:   Own position: %u\n", own_pos);
2674   if (own_pos < path->length - 1)
2675     send_message (message, &pi[own_pos + 1]);
2676   tunnel_delete_peer (t, path->peers[path->length - 1]);
2677   path_destroy (path);
2678   return GNUNET_OK;
2679 }
2680
2681
2682 /**
2683  * Core handler for notifications of broken paths
2684  *
2685  * @param cls closure
2686  * @param message message
2687  * @param peer peer identity this notification is about
2688  * @param atsi performance data
2689  * @param atsi_count number of records in 'atsi'
2690  *
2691  * @return GNUNET_OK to keep the connection open,
2692  *         GNUNET_SYSERR to close it (signal serious error)
2693  */
2694 static int
2695 handle_mesh_path_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
2696                           const struct GNUNET_MessageHeader *message,
2697                           const struct GNUNET_ATS_Information *atsi,
2698                           unsigned int atsi_count)
2699 {
2700   struct GNUNET_MESH_PathBroken *msg;
2701   struct MeshTunnel *t;
2702
2703   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2704               "MESH: Received a PATH BROKEN msg from %s\n",
2705               GNUNET_i2s(peer));
2706   msg = (struct GNUNET_MESH_PathBroken *) message;
2707   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2708               "MESH:   regarding %s\n",
2709               GNUNET_i2s(&msg->peer1));
2710   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2711               "MESH:   regarding %s\n",
2712               GNUNET_i2s(&msg->peer2));
2713   t = tunnel_get(&msg->oid, ntohl (msg->tid));
2714   if (NULL == t)
2715   {
2716     GNUNET_break_op (0);
2717     return GNUNET_OK;
2718   }
2719   tunnel_notify_connection_broken(t,
2720                                   GNUNET_PEER_search(&msg->peer1),
2721                                   GNUNET_PEER_search(&msg->peer2));
2722   return GNUNET_OK;
2723
2724 }
2725
2726
2727 /**
2728  * Core handler for tunnel destruction
2729  *
2730  * @param cls closure
2731  * @param message message
2732  * @param peer peer identity this notification is about
2733  * @param atsi performance data
2734  * @param atsi_count number of records in 'atsi'
2735  *
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_tunnel_destroy (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_TunnelDestroy *msg;
2746   struct MeshTunnel *t;
2747
2748   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2749               "MESH: Got a TUNNEL DESTROY packet from %s\n",
2750               GNUNET_i2s (peer));
2751   msg = (struct GNUNET_MESH_TunnelDestroy *) message;
2752   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2753               "MESH:   for tunnel %s [%u]\n",
2754               GNUNET_i2s (&msg->oid),
2755               ntohl (msg->tid));
2756   t = tunnel_get (&msg->oid, ntohl (msg->tid));
2757   if (NULL == t)
2758   {
2759     /* Probably already got the message from another path,
2760      * destroyed the tunnel and retransmitted to children.
2761      * Safe to ignore.
2762      */
2763     return GNUNET_OK;
2764   }
2765   if (t->id.oid == myid)
2766   {
2767     GNUNET_break_op (0);
2768     return GNUNET_OK;
2769   }
2770   if (t->local_tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
2771   {
2772     /* Tunnel was incoming, notify clients */
2773     send_clients_tunnel_destroy (t);
2774   }
2775   tunnel_send_destroy (t);
2776   tunnel_destroy (t);
2777   return GNUNET_OK;
2778 }
2779
2780
2781 /**
2782  * Core handler for mesh network traffic going from the origin to a peer
2783  *
2784  * @param cls closure
2785  * @param peer peer identity this notification is about
2786  * @param message message
2787  * @param atsi performance data
2788  * @param atsi_count number of records in 'atsi'
2789  * @return GNUNET_OK to keep the connection open,
2790  *         GNUNET_SYSERR to close it (signal serious error)
2791  */
2792 static int
2793 handle_mesh_data_unicast (void *cls, const struct GNUNET_PeerIdentity *peer,
2794                           const struct GNUNET_MessageHeader *message,
2795                           const struct GNUNET_ATS_Information *atsi,
2796                           unsigned int atsi_count)
2797 {
2798   struct GNUNET_MESH_Unicast *msg;
2799   struct MeshTunnel *t;
2800   GNUNET_PEER_Id pid;
2801   size_t size;
2802
2803   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2804               "MESH: got a unicast packet from %s\n",
2805               GNUNET_i2s (peer));
2806   size = ntohs (message->size);
2807   if (size <
2808       sizeof (struct GNUNET_MESH_Unicast) +
2809       sizeof (struct GNUNET_MessageHeader))
2810   {
2811     GNUNET_break (0);
2812     return GNUNET_OK;
2813   }
2814   msg = (struct GNUNET_MESH_Unicast *) message;
2815   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2816               "MESH:  of type %u\n",
2817               ntohs (msg[1].header.type));
2818   t = tunnel_get (&msg->oid, ntohl (msg->tid));
2819   if (NULL == t)
2820   {
2821     /* TODO notify back: we don't know this tunnel */
2822     GNUNET_break_op (0);
2823     return GNUNET_OK;
2824   }
2825   tunnel_reset_timeout (t);
2826   pid = GNUNET_PEER_search(&msg->destination);
2827   if (pid == myid)
2828   {
2829     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2830                 "MESH:   it's for us! sending to clients...\n");
2831     send_subscribed_clients (message, (struct GNUNET_MessageHeader *) &msg[1]);
2832     return GNUNET_OK;
2833   }
2834   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2835               "MESH:   not for us, retransmitting...\n");
2836   send_message (message, path_get_first_hop(t->tree, pid));
2837   return GNUNET_OK;
2838 }
2839
2840
2841 /**
2842  * Core handler for mesh network traffic going from the origin to all peers
2843  *
2844  * @param cls closure
2845  * @param message message
2846  * @param peer peer identity this notification is about
2847  * @param atsi performance data
2848  * @param atsi_count number of records in 'atsi'
2849  * @return GNUNET_OK to keep the connection open,
2850  *         GNUNET_SYSERR to close it (signal serious error)
2851  *
2852  * TODO: Check who we got this from, to validate route.
2853  */
2854 static int
2855 handle_mesh_data_multicast (void *cls, const struct GNUNET_PeerIdentity *peer,
2856                             const struct GNUNET_MessageHeader *message,
2857                             const struct GNUNET_ATS_Information *atsi,
2858                             unsigned int atsi_count)
2859 {
2860   struct GNUNET_MESH_Multicast *msg;
2861   struct MeshTunnel *t;
2862   size_t size;
2863
2864   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2865               "MESH: got a multicast packet from %s\n",
2866               GNUNET_i2s (peer));
2867   size = ntohs (message->size);
2868   if (sizeof (struct GNUNET_MESH_Multicast) +
2869       sizeof (struct GNUNET_MessageHeader) > size)
2870   {
2871     GNUNET_break_op (0);
2872     return GNUNET_OK;
2873   }
2874   msg = (struct GNUNET_MESH_Multicast *) message;
2875   t = tunnel_get (&msg->oid, ntohl (msg->tid));
2876
2877   if (NULL == t)
2878   {
2879     /* TODO notify that we dont know that tunnel */
2880     GNUNET_break_op (0);
2881     return GNUNET_OK;
2882   }
2883   tunnel_reset_timeout (t);
2884
2885   /* Transmit to locally interested clients */
2886   if (NULL != t->peers &&
2887       GNUNET_CONTAINER_multihashmap_contains (t->peers, &my_full_id.hashPubKey))
2888   {
2889     send_subscribed_clients (message, &msg[1].header);
2890   }
2891   tunnel_send_multicast(t, message);
2892   return GNUNET_OK;
2893 }
2894
2895
2896 /**
2897  * Core handler for mesh network traffic toward the owner of a tunnel
2898  *
2899  * @param cls closure
2900  * @param message message
2901  * @param peer peer identity this notification is about
2902  * @param atsi performance data
2903  * @param atsi_count number of records in 'atsi'
2904  *
2905  * @return GNUNET_OK to keep the connection open,
2906  *         GNUNET_SYSERR to close it (signal serious error)
2907  */
2908 static int
2909 handle_mesh_data_to_orig (void *cls, const struct GNUNET_PeerIdentity *peer,
2910                           const struct GNUNET_MessageHeader *message,
2911                           const struct GNUNET_ATS_Information *atsi,
2912                           unsigned int atsi_count)
2913 {
2914   struct GNUNET_MESH_ToOrigin *msg;
2915   struct GNUNET_PeerIdentity id;
2916   struct MeshPeerInfo *peer_info;
2917   struct MeshTunnel *t;
2918   size_t size;
2919
2920   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2921               "MESH: got a ToOrigin packet from %s\n",
2922               GNUNET_i2s (peer));
2923   size = ntohs (message->size);
2924   if (size < sizeof (struct GNUNET_MESH_ToOrigin) +     /* Payload must be */
2925       sizeof (struct GNUNET_MessageHeader))     /* at least a header */
2926   {
2927     GNUNET_break_op (0);
2928     return GNUNET_OK;
2929   }
2930   msg = (struct GNUNET_MESH_ToOrigin *) message;
2931   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2932               "MESH:  of type %u\n",
2933               ntohs (msg[1].header.type));
2934   t = tunnel_get (&msg->oid, ntohl (msg->tid));
2935
2936   if (NULL == t)
2937   {
2938     /* TODO notify that we dont know this tunnel (whom)? */
2939     GNUNET_break_op (0);
2940     return GNUNET_OK;
2941   }
2942
2943   if (t->id.oid == myid)
2944   {
2945     char cbuf[size];
2946     struct GNUNET_MESH_ToOrigin *copy;
2947
2948     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2949                 "MESH:   it's for us! sending to clients...\n");
2950     if (NULL == t->client)
2951     {
2952       /* got data packet for ownerless tunnel */
2953       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2954                 "MESH:   no clients!\n");
2955       GNUNET_break_op (0);
2956       return GNUNET_OK;
2957     }
2958     /* TODO signature verification */
2959     memcpy (cbuf, message, size);
2960     copy = (struct GNUNET_MESH_ToOrigin *) cbuf;
2961     copy->tid = htonl (t->local_tid);
2962     GNUNET_SERVER_notification_context_unicast (nc,
2963                                                 t->client->handle,
2964                                                 &copy->header,
2965                                                 GNUNET_YES);
2966     return GNUNET_OK;
2967   }
2968   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2969               "MESH:   not for us, retransmitting...\n");
2970
2971   peer_info = peer_info_get (&msg->oid);
2972   if (NULL == peer_info)
2973   {
2974     /* unknown origin of tunnel */
2975     GNUNET_break (0);
2976     return GNUNET_OK;
2977   }
2978   GNUNET_PEER_resolve (t->tree->me->parent->peer, &id);
2979   send_message (message, &id);
2980
2981   return GNUNET_OK;
2982 }
2983
2984
2985 /**
2986  * Core handler for path ACKs
2987  *
2988  * @param cls closure
2989  * @param message message
2990  * @param peer peer identity this notification is about
2991  * @param atsi performance data
2992  * @param atsi_count number of records in 'atsi'
2993  *
2994  * @return GNUNET_OK to keep the connection open,
2995  *         GNUNET_SYSERR to close it (signal serious error)
2996  */
2997 static int
2998 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
2999                       const struct GNUNET_MessageHeader *message,
3000                       const struct GNUNET_ATS_Information *atsi,
3001                       unsigned int atsi_count)
3002 {
3003   struct GNUNET_MESH_PathACK *msg;
3004   struct GNUNET_PeerIdentity id;
3005   struct MeshTunnelTreeNode *n;
3006   struct MeshPeerInfo *peer_info;
3007   struct MeshTunnel *t;
3008
3009   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3010               "MESH: Received a path ACK msg [%s]\n",
3011               GNUNET_i2s(&my_full_id));
3012   msg = (struct GNUNET_MESH_PathACK *) message;
3013   t = tunnel_get (&msg->oid, msg->tid);
3014   if (NULL == t)
3015   {
3016     /* TODO notify that we don't know the tunnel */
3017     return GNUNET_OK;
3018   }
3019
3020   /* Message for us? */
3021   if (0 == memcmp (&msg->oid, &my_full_id, sizeof (struct GNUNET_PeerIdentity)))
3022   {
3023     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   It's for us!\n");
3024     if (NULL == t->client)
3025     {
3026       GNUNET_break_op (0);
3027       return GNUNET_OK;
3028     }
3029     if (NULL != t->dht_get_type)
3030     {
3031       GNUNET_DHT_get_stop (t->dht_get_type);
3032       t->dht_get_type = NULL;
3033     }
3034     peer_info = peer_info_get (&msg->peer_id);
3035     n = tree_find_peer(t->tree->root, peer_info->id);
3036     if (NULL == n)
3037     {
3038       GNUNET_break_op (0);
3039       return GNUNET_OK;
3040     }
3041     n->status = MESH_PEER_READY;
3042     send_client_peer_connected(t, peer_info->id);
3043     return GNUNET_OK;
3044   }
3045   
3046   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3047               "MESH:   not for us, retransmitting...\n");
3048   GNUNET_PEER_resolve(t->tree->me->parent->peer, &id);
3049   peer_info = peer_info_get (&msg->oid);
3050   if (NULL == peer_info)
3051   {
3052     /* If we know the tunnel, we should DEFINITELY know the peer */
3053     GNUNET_break (0);
3054     return GNUNET_OK;
3055   }
3056   send_message (message, &id);
3057   return GNUNET_OK;
3058 }
3059
3060
3061 /**
3062  * Functions to handle messages from core
3063  */
3064 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
3065   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
3066   {&handle_mesh_path_destroy, GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY, 0},
3067   {&handle_mesh_path_broken, GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN,
3068     sizeof (struct GNUNET_MESH_PathBroken)},
3069   {&handle_mesh_tunnel_destroy, GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY, 0},
3070   {&handle_mesh_data_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
3071   {&handle_mesh_data_multicast, GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
3072   {&handle_mesh_data_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
3073   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
3074     sizeof (struct GNUNET_MESH_PathACK)},
3075   {NULL, 0, 0}
3076 };
3077
3078
3079
3080 /******************************************************************************/
3081 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
3082 /******************************************************************************/
3083
3084 /**
3085  * deregister_app: iterator for removing each application registered by a client
3086  * 
3087  * @param cls closure
3088  * @param key the hash of the application id (used to access the hashmap)
3089  * @param value the value stored at the key (client)
3090  * 
3091  * @return GNUNET_OK on success
3092  */
3093 static int
3094 deregister_app (void *cls, const GNUNET_HashCode * key, void *value)
3095 {
3096   GNUNET_break (GNUNET_YES == 
3097       GNUNET_CONTAINER_multihashmap_remove (applications, key, value));
3098   return GNUNET_OK;
3099 }
3100
3101 #if LATER
3102 /**
3103  * notify_client_connection_failure: notify a client that the connection to the
3104  * requested remote peer is not possible (for instance, no route found)
3105  * Function called when the socket is ready to queue more data. "buf" will be
3106  * NULL and "size" zero if the socket was closed for writing in the meantime.
3107  *
3108  * @param cls closure
3109  * @param size number of bytes available in buf
3110  * @param buf where the callee should write the message
3111  * @return number of bytes written to buf
3112  */
3113 static size_t
3114 notify_client_connection_failure (void *cls, size_t size, void *buf)
3115 {
3116   int size_needed;
3117   struct MeshPeerInfo *peer_info;
3118   struct GNUNET_MESH_PeerControl *msg;
3119   struct GNUNET_PeerIdentity id;
3120
3121   if (0 == size && NULL == buf)
3122   {
3123     // TODO retry? cancel?
3124     return 0;
3125   }
3126
3127   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
3128   peer_info = (struct MeshPeerInfo *) cls;
3129   msg = (struct GNUNET_MESH_PeerControl *) buf;
3130   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
3131   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
3132 //     msg->tunnel_id = htonl(peer_info->t->tid);
3133   GNUNET_PEER_resolve (peer_info->id, &id);
3134   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
3135
3136   return size_needed;
3137 }
3138 #endif
3139
3140
3141 /**
3142  * Send keepalive packets for a peer
3143  *
3144  * @param cls Closure (tunnel for which to send the keepalive).
3145  * @param tc Notification context.
3146  *
3147  * TODO: implement explicit multicast keepalive?
3148  */
3149 static void
3150 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3151 {
3152   struct MeshTunnel *t = cls;
3153   struct GNUNET_MessageHeader *payload;
3154   struct GNUNET_MESH_Multicast *msg;
3155   size_t size = sizeof(struct GNUNET_MESH_Multicast) +
3156                 sizeof(struct GNUNET_MessageHeader);
3157   char cbuf[size];
3158
3159   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3160   {
3161     return;
3162   }
3163   t->path_refresh_task = GNUNET_SCHEDULER_NO_TASK;
3164
3165   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3166               "MESH: sending keepalive for tunnel %d\n",
3167               t->id.tid);
3168
3169   msg = (struct GNUNET_MESH_Multicast *) cbuf;
3170   msg->header.size = htons (size);
3171   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
3172   msg->oid = my_full_id;
3173   msg->tid = htonl(t->id.tid);
3174   payload = (struct GNUNET_MessageHeader *) &msg[1];
3175   payload->size = htons (sizeof(struct GNUNET_MessageHeader));
3176   payload->type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE);
3177   tunnel_send_multicast (t, &msg->header);
3178
3179   t->path_refresh_task =
3180       GNUNET_SCHEDULER_add_delayed (t->tree->refresh, &path_refresh, t);
3181   return;
3182 }
3183
3184
3185 /**
3186  * Function to process paths received for a new peer addition. The recorded
3187  * paths form the initial tunnel, which can be optimized later.
3188  * Called on each result obtained for the DHT search.
3189  *
3190  * @param cls closure
3191  * @param exp when will this value expire
3192  * @param key key of the result
3193  * @param type type of the result
3194  * @param size number of bytes in data
3195  * @param data pointer to the result data
3196  *
3197  * TODO: re-issue the request after certain time? cancel after X results?
3198  */
3199 static void
3200 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
3201                     const GNUNET_HashCode * key,
3202                     const struct GNUNET_PeerIdentity *get_path,
3203                     unsigned int get_path_length,
3204                     const struct GNUNET_PeerIdentity *put_path,
3205                     unsigned int put_path_length,
3206                     enum GNUNET_BLOCK_Type type, size_t size, const void *data)
3207 {
3208   struct MeshPathInfo *path_info = cls;
3209   struct MeshPeerPath *p;
3210   struct GNUNET_PeerIdentity pi;
3211   int i;
3212
3213   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3214              "MESH: Got results from DHT!\n");
3215   GNUNET_PEER_resolve (path_info->peer->id, &pi);
3216   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3217              "MESH:   for %s\n",
3218              GNUNET_i2s(&pi));
3219 //   GNUNET_DHT_get_stop(path_info->peer->dhtget);
3220 //   path_info->peer->dhtget = NULL;
3221
3222   p = path_build_from_dht (get_path, get_path_length,
3223                            put_path, put_path_length);
3224   path_add_to_peer (path_info->peer, p);
3225   for (i = 0; i < path_info->peer->ntunnels; i++)
3226   {
3227     tunnel_add_peer (path_info->peer->tunnels[i], path_info->peer);
3228     peer_info_connect(path_info->peer, path_info->t);
3229   }
3230 //   GNUNET_free (path_info);
3231
3232   return;
3233 }
3234
3235
3236 /**
3237  * Function to process paths received for a new peer addition. The recorded
3238  * paths form the initial tunnel, which can be optimized later.
3239  * Called on each result obtained for the DHT search.
3240  *
3241  * @param cls closure
3242  * @param exp when will this value expire
3243  * @param key key of the result
3244  * @param type type of the result
3245  * @param size number of bytes in data
3246  * @param data pointer to the result data
3247  */
3248 static void
3249 dht_get_type_handler (void *cls, struct GNUNET_TIME_Absolute exp,
3250                       const GNUNET_HashCode * key,
3251                       const struct GNUNET_PeerIdentity *get_path,
3252                       unsigned int get_path_length,
3253                       const struct GNUNET_PeerIdentity *put_path,
3254                       unsigned int put_path_length,
3255                       enum GNUNET_BLOCK_Type type, size_t size,
3256                       const void *data)
3257 {
3258   const struct GNUNET_PeerIdentity *pi = data;
3259   struct MeshTunnel *t = cls;
3260   struct MeshPeerInfo *peer_info;
3261   struct MeshPeerPath *p;
3262
3263   if (size != sizeof (struct GNUNET_PeerIdentity))
3264   {
3265     GNUNET_break_op (0);
3266     return;
3267   }
3268   GNUNET_assert (NULL != t->client);
3269   peer_info = peer_info_get (pi);
3270   (void) GNUNET_CONTAINER_multihashmap_put (
3271       t->peers,
3272       &pi->hashPubKey,
3273       peer_info,
3274       GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
3275
3276   p = path_build_from_dht (get_path, get_path_length,
3277                            put_path, put_path_length);
3278   path_add_to_peer (peer_info, p);
3279   tunnel_add_peer(t, peer_info);
3280   peer_info_connect (peer_info, t);
3281 }
3282
3283
3284 /******************************************************************************/
3285 /*********************       MESH LOCAL HANDLES      **************************/
3286 /******************************************************************************/
3287
3288
3289 /**
3290  * Handler for client disconnection
3291  *
3292  * @param cls closure
3293  * @param client identification of the client; NULL
3294  *        for the last call when the server is destroyed
3295  */
3296 static void
3297 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
3298 {
3299   struct MeshClient *c;
3300   struct MeshClient *next;
3301
3302   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: client disconnected\n");
3303   if (client == NULL)
3304   {
3305     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    (SERVER DOWN)\n");
3306     return;
3307   }
3308   c = clients;
3309   while (NULL != c)
3310   {
3311     if (c->handle != client && NULL != client)
3312     {
3313       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    ... searching\n");
3314       c = c->next;
3315       continue;
3316     }
3317     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: matching client found\n");
3318     GNUNET_SERVER_client_drop (c->handle);
3319     if (NULL != c->tunnels)
3320     {
3321       GNUNET_CONTAINER_multihashmap_iterate (c->tunnels,
3322                                              &tunnel_destroy_iterator,
3323                                              c);
3324       GNUNET_CONTAINER_multihashmap_destroy (c->tunnels);
3325     }
3326
3327     /* deregister clients applications */
3328     if (NULL != c->apps)
3329     {
3330       GNUNET_CONTAINER_multihashmap_iterate (c->apps, &deregister_app, NULL);
3331       GNUNET_CONTAINER_multihashmap_destroy (c->apps);
3332     }
3333     if (0 == GNUNET_CONTAINER_multihashmap_size (applications) &&
3334         GNUNET_SCHEDULER_NO_TASK != announce_applications_task)
3335     {
3336       GNUNET_SCHEDULER_cancel (announce_applications_task);
3337       announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
3338     }
3339     if (NULL != c->types)
3340       GNUNET_CONTAINER_multihashmap_destroy (c->types);
3341     next = c->next;
3342     GNUNET_CONTAINER_DLL_remove (clients, clients_tail, c);
3343     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   CLIENT FREE at %p\n", c);
3344     GNUNET_free (c);
3345     c = next;
3346   }
3347
3348   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    done!\n");
3349   return;
3350 }
3351
3352
3353 /**
3354  * Handler for new clients
3355  *
3356  * @param cls closure
3357  * @param client identification of the client
3358  * @param message the actual message, which includes messages the client wants
3359  */
3360 static void
3361 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
3362                          const struct GNUNET_MessageHeader *message)
3363 {
3364   struct GNUNET_MESH_ClientConnect *cc_msg;
3365   struct MeshClient *c;
3366   GNUNET_MESH_ApplicationType *a;
3367   unsigned int size;
3368   uint16_t ntypes;
3369   uint16_t *t;
3370   uint16_t napps;
3371   uint16_t i;
3372
3373   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new client connected\n");
3374   /* Check data sanity */
3375   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
3376   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
3377   ntypes = ntohs (cc_msg->types);
3378   napps = ntohs (cc_msg->applications);
3379   if (size !=
3380       ntypes * sizeof (uint16_t) + napps * sizeof (GNUNET_MESH_ApplicationType))
3381   {
3382     GNUNET_break (0);
3383     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3384     return;
3385   }
3386
3387   /* Create new client structure */
3388   c = GNUNET_malloc (sizeof (struct MeshClient));
3389 #if MESH_DEBUG
3390   c->id = next_client_id++;
3391 #endif
3392   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   CLIENT NEW %u at %p\n", c->id, c);
3393   c->handle = client;
3394   GNUNET_SERVER_client_keep (client);
3395   a = (GNUNET_MESH_ApplicationType *) &cc_msg[1];
3396   if (napps > 0)
3397   {
3398     GNUNET_MESH_ApplicationType at;
3399     GNUNET_HashCode hc;
3400
3401     c->apps = GNUNET_CONTAINER_multihashmap_create (napps);
3402     for (i = 0; i < napps; i++)
3403     {
3404       at = ntohl (a[i]);
3405       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   app type: %u\n", at);
3406       GNUNET_CRYPTO_hash (&at, sizeof (at), &hc);
3407       /* store in clients hashmap */
3408       GNUNET_CONTAINER_multihashmap_put (c->apps, &hc, c,
3409                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3410       /* store in global hashmap, for announcements */
3411       GNUNET_CONTAINER_multihashmap_put (applications, &hc, c,
3412                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3413     }
3414     if (GNUNET_SCHEDULER_NO_TASK == announce_applications_task)
3415       announce_applications_task =
3416           GNUNET_SCHEDULER_add_now (&announce_applications, NULL);
3417
3418   }
3419   if (ntypes > 0)
3420   {
3421     uint16_t u16;
3422     GNUNET_HashCode hc;
3423
3424     t = (uint16_t *) & a[napps];
3425     c->types = GNUNET_CONTAINER_multihashmap_create (ntypes);
3426     for (i = 0; i < ntypes; i++)
3427     {
3428       u16 = ntohs (t[i]);
3429       GNUNET_CRYPTO_hash (&u16, sizeof (u16), &hc);
3430
3431       /* store in clients hashmap */
3432       GNUNET_CONTAINER_multihashmap_put (c->types, &hc, c,
3433                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3434       /* store in global hashmap */
3435       GNUNET_CONTAINER_multihashmap_put (types, &hc, c,
3436                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3437     }
3438   }
3439   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3440               "MESH:  client has %u+%u subscriptions\n", napps, ntypes);
3441
3442   GNUNET_CONTAINER_DLL_insert (clients, clients_tail, c);
3443   c->tunnels = GNUNET_CONTAINER_multihashmap_create (32);
3444   GNUNET_SERVER_notification_context_add (nc, client);
3445
3446   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3447 #if MESH_DEBUG
3448   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new client processed\n");
3449 #endif
3450 }
3451
3452
3453 /**
3454  * Handler for requests of new tunnels
3455  *
3456  * @param cls closure
3457  * @param client identification of the client
3458  * @param message the actual message
3459  */
3460 static void
3461 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
3462                             const struct GNUNET_MessageHeader *message)
3463 {
3464   struct GNUNET_MESH_TunnelMessage *t_msg;
3465   struct MeshTunnel *t;
3466   struct MeshClient *c;
3467   GNUNET_HashCode hash;
3468
3469   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new tunnel requested\n");
3470
3471   /* Sanity check for client registration */
3472   if (NULL == (c = client_get (client)))
3473   {
3474     GNUNET_break (0);
3475     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3476     return;
3477   }
3478 #if MESH_DEBUG
3479   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   by client %u\n", c->id);
3480 #endif
3481
3482   /* Message sanity check */
3483   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
3484   {
3485     GNUNET_break (0);
3486     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3487     return;
3488   }
3489
3490   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
3491   /* Sanity check for tunnel numbering */
3492   if (0 == (ntohl (t_msg->tunnel_id) & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
3493   {
3494     GNUNET_break (0);
3495     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3496     return;
3497   }
3498   /* Sanity check for duplicate tunnel IDs */
3499   if (NULL != tunnel_get_by_local_id (c, ntohl (t_msg->tunnel_id)))
3500   {
3501     GNUNET_break (0);
3502     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3503     return;
3504   }
3505
3506   t = GNUNET_malloc (sizeof (struct MeshTunnel));
3507   while (NULL != tunnel_get_by_pi (myid, next_tid))
3508     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
3509   t->id.tid = next_tid++;
3510   t->id.oid = myid;
3511   t->local_tid = ntohl (t_msg->tunnel_id);
3512 #if MESH_DEBUG
3513   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3514               "MESH: CREATED TUNNEL %s [%x] (%x)\n",
3515               GNUNET_i2s (&my_full_id),
3516               t->id.tid,
3517               t->local_tid);
3518 #endif
3519   t->client = c;
3520   t->peers = GNUNET_CONTAINER_multihashmap_create (32);
3521
3522   GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
3523   if (GNUNET_OK !=
3524       GNUNET_CONTAINER_multihashmap_put (
3525         c->tunnels, &hash, t,
3526         GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
3527   {
3528     GNUNET_break (0);
3529     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3530     return;
3531   }
3532
3533   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
3534   if (GNUNET_OK !=
3535       GNUNET_CONTAINER_multihashmap_put (
3536         tunnels, &hash, t,
3537         GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
3538   {
3539     GNUNET_break (0);
3540     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3541     return;
3542   }
3543   t->tree = tree_new (t, myid);
3544   t->tree->refresh = REFRESH_PATH_TIME;
3545   t->tree->root->status = MESH_PEER_READY;
3546   t->tree->me = t->tree->root;
3547
3548   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3549   return;
3550 }
3551
3552
3553 /**
3554  * Handler for requests of deleting tunnels
3555  *
3556  * @param cls closure
3557  * @param client identification of the client
3558  * @param message the actual message
3559  */
3560 static void
3561 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
3562                              const struct GNUNET_MessageHeader *message)
3563 {
3564   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
3565   struct MeshClient *c;
3566   struct MeshTunnel *t;
3567   MESH_TunnelNumber tid;
3568   GNUNET_HashCode hash;
3569
3570   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3571               "MESH: Got a DESTROY TUNNEL from client!\n");
3572
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   /* Message sanity check */
3581   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
3582   {
3583     GNUNET_break (0);
3584     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3585     return;
3586   }
3587 #if MESH_DEBUG
3588   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   by client %u\n", c->id);
3589 #endif
3590   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
3591
3592   /* Retrieve tunnel */
3593   tid = ntohl (tunnel_msg->tunnel_id);
3594
3595   /* Remove from local id hashmap */
3596   GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
3597   t = GNUNET_CONTAINER_multihashmap_get (c->tunnels, &hash);
3598   GNUNET_assert (GNUNET_YES ==
3599                  GNUNET_CONTAINER_multihashmap_remove (c->tunnels, &hash, t));
3600
3601   t->client = NULL;
3602   tunnel_send_destroy (t);
3603   tunnel_destroy(t);
3604   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3605   return;
3606 }
3607
3608
3609 /**
3610  * Handler for connection requests to new peers
3611  *
3612  * @param cls closure
3613  * @param client identification of the client
3614  * @param message the actual message (PeerControl)
3615  */
3616 static void
3617 handle_local_connect_add (void *cls, struct GNUNET_SERVER_Client *client,
3618                           const struct GNUNET_MessageHeader *message)
3619 {
3620   struct GNUNET_MESH_PeerControl *peer_msg;
3621   struct MeshPeerInfo *peer_info;
3622   struct MeshClient *c;
3623   struct MeshTunnel *t;
3624   MESH_TunnelNumber tid;
3625
3626   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "MESH: Got connection request\n");
3627   /* Sanity check for client registration */
3628   if (NULL == (c = client_get (client)))
3629   {
3630     GNUNET_break (0);
3631     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3632     return;
3633   }
3634
3635   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
3636   /* Sanity check for message size */
3637   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
3638   {
3639     GNUNET_break (0);
3640     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3641     return;
3642   }
3643
3644   /* Tunnel exists? */
3645   tid = ntohl (peer_msg->tunnel_id);
3646   t = tunnel_get_by_local_id (c, tid);
3647   if (NULL == t)
3648   {
3649     GNUNET_break (0);
3650     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3651     return;
3652   }
3653
3654   /* Does client own tunnel? */
3655   if (t->client->handle != client)
3656   {
3657     GNUNET_break (0);
3658     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3659     return;
3660   }
3661   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "MESH:      for %s\n",
3662              GNUNET_i2s(&peer_msg->peer));
3663   peer_info = peer_info_get (&peer_msg->peer);
3664
3665   tunnel_add_peer(t, peer_info);
3666   peer_info_connect(peer_info, t);
3667
3668   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3669   return;
3670 }
3671
3672
3673 /**
3674  * Handler for disconnection requests of peers in a tunnel
3675  *
3676  * @param cls closure
3677  * @param client identification of the client
3678  * @param message the actual message (PeerControl)
3679  */
3680 static void
3681 handle_local_connect_del (void *cls, struct GNUNET_SERVER_Client *client,
3682                           const struct GNUNET_MessageHeader *message)
3683 {
3684   struct GNUNET_MESH_PeerControl *peer_msg;
3685   struct MeshPeerInfo *peer_info;
3686   struct MeshClient *c;
3687   struct MeshTunnel *t;
3688   MESH_TunnelNumber tid;
3689
3690   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Got a PEER DEL request\n");
3691   /* Sanity check for client registration */
3692   if (NULL == (c = client_get (client)))
3693   {
3694     GNUNET_break (0);
3695     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3696     return;
3697   }
3698   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
3699   /* Sanity check for message size */
3700   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
3701   {
3702     GNUNET_break (0);
3703     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3704     return;
3705   }
3706
3707   /* Tunnel exists? */
3708   tid = ntohl (peer_msg->tunnel_id);
3709   t = tunnel_get_by_local_id (c, tid);
3710   if (NULL == t)
3711   {
3712     GNUNET_break (0);
3713     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3714     return;
3715   }
3716   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   on tunnel %X\n", t->id.tid);
3717
3718   /* Does client own tunnel? */
3719   if (t->client->handle != client)
3720   {
3721     GNUNET_break (0);
3722     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3723     return;
3724   }
3725
3726   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3727               "MESH:   for peer %s\n",
3728               GNUNET_i2s(&peer_msg->peer));
3729   /* Is the peer in the tunnel? */
3730   peer_info = GNUNET_CONTAINER_multihashmap_get(t->peers,
3731                                                 &peer_msg->peer.hashPubKey);
3732   if (NULL == peer_info)
3733   {
3734     GNUNET_break (0);
3735     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3736     return;
3737   }
3738
3739   /* Ok, delete peer from tunnel */
3740   GNUNET_CONTAINER_multihashmap_remove_all (t->peers,
3741                                             &peer_msg->peer.hashPubKey);
3742
3743   send_destroy_path (t, peer_info->id);
3744   tunnel_delete_peer(t, peer_info->id);
3745   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3746   return;
3747 }
3748
3749
3750 /**
3751  * Handler for connection requests to new peers by type
3752  *
3753  * @param cls closure
3754  * @param client identification of the client
3755  * @param message the actual message (ConnectPeerByType)
3756  */
3757 static void
3758 handle_local_connect_by_type (void *cls, struct GNUNET_SERVER_Client *client,
3759                               const struct GNUNET_MessageHeader *message)
3760 {
3761   struct GNUNET_MESH_ConnectPeerByType *connect_msg;
3762   struct MeshClient *c;
3763   struct MeshTunnel *t;
3764   GNUNET_HashCode hash;
3765   MESH_TunnelNumber tid;
3766
3767   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: got connect by type request\n");
3768   /* Sanity check for client registration */
3769   if (NULL == (c = client_get (client)))
3770   {
3771     GNUNET_break (0);
3772     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3773     return;
3774   }
3775
3776   connect_msg = (struct GNUNET_MESH_ConnectPeerByType *) message;
3777   /* Sanity check for message size */
3778   if (sizeof (struct GNUNET_MESH_ConnectPeerByType) !=
3779       ntohs (connect_msg->header.size))
3780   {
3781     GNUNET_break (0);
3782     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3783     return;
3784   }
3785
3786   /* Tunnel exists? */
3787   tid = ntohl (connect_msg->tunnel_id);
3788   t = tunnel_get_by_local_id (c, tid);
3789   if (NULL == t)
3790   {
3791     GNUNET_break (0);
3792     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3793     return;
3794   }
3795
3796   /* Does client own tunnel? */
3797   if (t->client->handle != client)
3798   {
3799     GNUNET_break (0);
3800     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3801     return;
3802   }
3803
3804   /* Do WE have the service? */
3805   t->type = ntohl (connect_msg->type);
3806   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  type requested: %u\n", t->type);
3807   GNUNET_CRYPTO_hash (&t->type, sizeof (GNUNET_MESH_ApplicationType), &hash);
3808   if (GNUNET_CONTAINER_multihashmap_contains (applications, &hash) ==
3809       GNUNET_YES)
3810   {
3811     /* Yes! Fast forward, add ourselves to the tunnel and send the
3812      * good news to the client
3813      */
3814     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  available locally\n");
3815     GNUNET_CONTAINER_multihashmap_put (t->peers, &my_full_id.hashPubKey,
3816                                        peer_info_get (&my_full_id),
3817                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3818
3819     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  notifying client\n");
3820     send_client_peer_connected(t, myid);
3821     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  Done\n");
3822     GNUNET_SERVER_receive_done (client, GNUNET_OK);
3823     return;
3824   }
3825   /* Ok, lets find a peer offering the service */
3826   if (NULL != t->dht_get_type)
3827   {
3828     GNUNET_DHT_get_stop (t->dht_get_type);
3829   }
3830   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  looking in DHT for %s\n",
3831               GNUNET_h2s (&hash));
3832   t->dht_get_type =
3833       GNUNET_DHT_get_start (dht_handle,
3834                             GNUNET_TIME_UNIT_FOREVER_REL,
3835                             GNUNET_BLOCK_TYPE_TEST,
3836                             &hash,
3837                             10U,
3838                             GNUNET_DHT_RO_RECORD_ROUTE |
3839                               GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
3840                             NULL, 0,
3841                             &dht_get_type_handler, t);
3842
3843   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3844   return;
3845 }
3846
3847
3848 /**
3849  * Handler for client traffic directed to one peer
3850  *
3851  * @param cls closure
3852  * @param client identification of the client
3853  * @param message the actual message
3854  */
3855 static void
3856 handle_local_unicast (void *cls, struct GNUNET_SERVER_Client *client,
3857                       const struct GNUNET_MessageHeader *message)
3858 {
3859   struct MeshClient *c;
3860   struct MeshTunnel *t;
3861   struct MeshPeerInfo *pi;
3862   struct GNUNET_MESH_Unicast *data_msg;
3863   MESH_TunnelNumber tid;
3864   size_t size;
3865
3866   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3867               "MESH: Got a unicast request from a client!\n");
3868
3869   /* Sanity check for client registration */
3870   if (NULL == (c = client_get (client)))
3871   {
3872     GNUNET_break (0);
3873     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3874     return;
3875   }
3876   data_msg = (struct GNUNET_MESH_Unicast *) message;
3877   /* Sanity check for message size */
3878   size = ntohs (message->size);
3879   if (sizeof (struct GNUNET_MESH_Unicast) +
3880       sizeof (struct GNUNET_MessageHeader) > size)
3881   {
3882     GNUNET_break (0);
3883     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3884     return;
3885   }
3886
3887   /* Tunnel exists? */
3888   tid = ntohl (data_msg->tid);
3889   t = tunnel_get_by_local_id (c, tid);
3890   if (NULL == t)
3891   {
3892     GNUNET_break (0);
3893     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3894     return;
3895   }
3896
3897   /*  Is it a local tunnel? Then, does client own the tunnel? */
3898   if (NULL != t->client &&
3899       NULL != t->client->handle &&
3900       t->client->handle != client)
3901   {
3902     GNUNET_break (0);
3903     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3904     return;
3905   }
3906
3907   pi = GNUNET_CONTAINER_multihashmap_get (t->peers,
3908                                           &data_msg->destination.hashPubKey);
3909   /* Is the selected peer in the tunnel? */
3910   if (NULL == pi)
3911   {
3912     GNUNET_break (0);
3913     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3914     return;
3915   }
3916
3917   /* Ok, everything is correct, send the message
3918    * (pretend we got it from a mesh peer)
3919    */
3920   {
3921     char buf[ntohs (message->size)];
3922     struct GNUNET_MESH_Unicast *copy;
3923
3924     /* Work around const limitation */
3925     copy = (struct GNUNET_MESH_Unicast *) buf;
3926     memcpy (buf, data_msg, size);
3927     copy->oid = my_full_id;
3928     copy->tid = htonl (t->id.tid);
3929     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3930                 "MESH:   calling generic handler...\n");
3931     handle_mesh_data_unicast (NULL, &my_full_id, &copy->header, NULL, 0);
3932   }
3933   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3934   return;
3935 }
3936
3937
3938 /**
3939  * Handler for client traffic directed to the origin
3940  *
3941  * @param cls closure
3942  * @param client identification of the client
3943  * @param message the actual message
3944  */
3945 static void
3946 handle_local_to_origin (void *cls, struct GNUNET_SERVER_Client *client,
3947                         const struct GNUNET_MessageHeader *message)
3948 {
3949   struct GNUNET_MESH_ToOrigin *data_msg;
3950   struct GNUNET_PeerIdentity id;
3951   struct MeshClient *c;
3952   struct MeshTunnel *t;
3953   MESH_TunnelNumber tid;
3954   size_t size;
3955
3956   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3957               "MESH: Got a ToOrigin request from a client!\n");
3958
3959   /* Sanity check for client registration */
3960   if (NULL == (c = client_get (client)))
3961   {
3962     GNUNET_break (0);
3963     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3964     return;
3965   }
3966   data_msg = (struct GNUNET_MESH_ToOrigin *) message;
3967   /* Sanity check for message size */
3968   size = ntohs (message->size);
3969   if (sizeof (struct GNUNET_MESH_ToOrigin) +
3970       sizeof (struct GNUNET_MessageHeader) > size)
3971   {
3972     GNUNET_break (0);
3973     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3974     return;
3975   }
3976
3977   /* Tunnel exists? */
3978   tid = ntohl (data_msg->tid);
3979   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
3980   {
3981     GNUNET_break (0);
3982     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3983     return;
3984   }
3985   t = tunnel_get_by_local_id (c, tid);
3986   if (NULL == t)
3987   {
3988     GNUNET_break (0);
3989     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3990     return;
3991   }
3992
3993   /*  It shouldn't be a local tunnel.  */
3994   if (NULL != t->client)
3995   {
3996     GNUNET_break (0);
3997     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3998     return;
3999   }
4000   GNUNET_PEER_resolve(t->id.oid, &id);
4001
4002   /* Ok, everything is correct, send the message
4003    * (pretend we got it from a mesh peer)
4004    */
4005   {
4006     char buf[ntohs (message->size)];
4007     struct GNUNET_MESH_ToOrigin *copy;
4008
4009     /* Work around const limitation */
4010     copy = (struct GNUNET_MESH_ToOrigin *) buf;
4011     memcpy (buf, data_msg, size);
4012     copy->oid = id;
4013     copy->tid = htonl (t->id.tid);
4014     copy->sender = my_full_id;
4015     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4016                 "MESH:   calling generic handler...\n");
4017     handle_mesh_data_to_orig (NULL, &my_full_id, &copy->header, NULL, 0);
4018   }
4019   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4020   return;
4021 }
4022
4023
4024 /**
4025  * Handler for client traffic directed to all peers in a tunnel
4026  *
4027  * @param cls closure
4028  * @param client identification of the client
4029  * @param message the actual message
4030  */
4031 static void
4032 handle_local_multicast (void *cls, struct GNUNET_SERVER_Client *client,
4033                         const struct GNUNET_MessageHeader *message)
4034 {
4035   struct MeshClient *c;
4036   struct MeshTunnel *t;
4037   struct GNUNET_MESH_Multicast *data_msg;
4038   MESH_TunnelNumber tid;
4039
4040   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4041               "MESH: Got a multicast request from a client!\n");
4042
4043   /* Sanity check for client registration */
4044   if (NULL == (c = client_get (client)))
4045   {
4046     GNUNET_break (0);
4047     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4048     return;
4049   }
4050   data_msg = (struct GNUNET_MESH_Multicast *) message;
4051   /* Sanity check for message size */
4052   if (sizeof (struct GNUNET_MESH_Multicast) +
4053       sizeof (struct GNUNET_MessageHeader) > ntohs (data_msg->header.size))
4054   {
4055     GNUNET_break (0);
4056     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4057     return;
4058   }
4059
4060   /* Tunnel exists? */
4061   tid = ntohl (data_msg->tid);
4062   t = tunnel_get_by_local_id (c, tid);
4063   if (NULL == t)
4064   {
4065     GNUNET_break (0);
4066     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4067     return;
4068   }
4069
4070   /* Does client own tunnel? */
4071   if (t->client->handle != client)
4072   {
4073     GNUNET_break (0);
4074     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4075     return;
4076   }
4077
4078   {
4079     char buf[ntohs(message->size)];
4080     struct GNUNET_MESH_Multicast *copy;
4081
4082     copy = (struct GNUNET_MESH_Multicast *)buf;
4083     memcpy(buf, message, ntohs(message->size));
4084     copy->oid = my_full_id;
4085     copy->tid = htonl(t->id.tid);
4086     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4087                 "MESH:   calling generic handler...\n");
4088     handle_mesh_data_multicast(client, &my_full_id, &copy->header, NULL, 0);
4089   }
4090
4091   /* receive done gets called when last copy is sent to a neighbor */
4092   return;
4093 }
4094
4095 /**
4096  * Functions to handle messages from clients
4097  */
4098 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
4099   {&handle_local_new_client, NULL,
4100    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
4101   {&handle_local_tunnel_create, NULL,
4102    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
4103    sizeof (struct GNUNET_MESH_TunnelMessage)},
4104   {&handle_local_tunnel_destroy, NULL,
4105    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
4106    sizeof (struct GNUNET_MESH_TunnelMessage)},
4107   {&handle_local_connect_add, NULL,
4108    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD,
4109    sizeof (struct GNUNET_MESH_PeerControl)},
4110   {&handle_local_connect_del, NULL,
4111    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL,
4112    sizeof (struct GNUNET_MESH_PeerControl)},
4113   {&handle_local_connect_by_type, NULL,
4114    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE,
4115    sizeof (struct GNUNET_MESH_ConnectPeerByType)},
4116   {&handle_local_unicast, NULL,
4117    GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
4118   {&handle_local_to_origin, NULL,
4119    GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
4120   {&handle_local_multicast, NULL,
4121    GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
4122   {NULL, NULL, 0, 0}
4123 };
4124
4125
4126 /**
4127  * To be called on core init/fail.
4128  *
4129  * @param cls service closure
4130  * @param server handle to the server for this service
4131  * @param identity the public identity of this peer
4132  */
4133 static void
4134 core_init (void *cls, struct GNUNET_CORE_Handle *server,
4135            const struct GNUNET_PeerIdentity *identity)
4136 {
4137   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Core init\n");
4138   core_handle = server;
4139   if (0 != memcmp(identity, &my_full_id, sizeof(my_full_id)) || NULL == server)
4140   {
4141     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("MESH: Wrong CORE service\n"));
4142     GNUNET_SCHEDULER_shutdown();   
4143   }
4144   return;
4145 }
4146
4147 /**
4148  * Method called whenever a given peer connects.
4149  *
4150  * @param cls closure
4151  * @param peer peer identity this notification is about
4152  * @param atsi performance data for the connection
4153  * @param atsi_count number of records in 'atsi'
4154  */
4155 static void
4156 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
4157               const struct GNUNET_ATS_Information *atsi,
4158               unsigned int atsi_count)
4159 {
4160   struct MeshPeerInfo *peer_info;
4161   struct MeshPeerPath *path;
4162
4163 #if MESH_DEBUG_CONNECTION
4164   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Peer connected\n");
4165   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      %s\n",
4166               GNUNET_i2s(&my_full_id));
4167 #endif
4168   peer_info = peer_info_get (peer);
4169   if (myid == peer_info->id)
4170   {
4171 #if MESH_DEBUG_CONNECTION
4172     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      (self)\n");
4173 #endif
4174     return;
4175   }
4176 #if MESH_DEBUG_CONNECTION
4177   else
4178   {
4179     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      %s\n",
4180                 GNUNET_i2s(peer));
4181   }
4182 #endif
4183   path = path_new (2);
4184   path->peers[0] = myid;
4185   path->peers[1] = peer_info->id;
4186   GNUNET_PEER_change_rc(myid, 1);
4187   GNUNET_PEER_change_rc(peer_info->id, 1);
4188   path_add_to_peer (peer_info, path);
4189   return;
4190 }
4191
4192 /**
4193  * Method called whenever a peer disconnects.
4194  *
4195  * @param cls closure
4196  * @param peer peer identity this notification is about
4197  */
4198 static void
4199 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
4200 {
4201   struct MeshPeerInfo *pi;
4202   unsigned int i;
4203
4204 #if MESH_DEBUG_CONNECTION
4205   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Peer disconnected\n");
4206 #endif
4207   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
4208   if (NULL == pi)
4209   {
4210     GNUNET_break (0);
4211     return;
4212   }
4213   for (i = 0; i < CORE_QUEUE_SIZE; i++)
4214   {
4215     /* TODO: notify that the transmission failed */
4216     peer_info_cancel_transmission(pi, i);
4217   }
4218   path_remove_from_peer (pi, pi->id, myid);
4219 #if MESH_DEBUG_CONNECTION
4220   if (myid == pi->id)
4221   {
4222     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      (self)\n");
4223   }
4224 #endif
4225   return;
4226 }
4227
4228
4229 /******************************************************************************/
4230 /************************      MAIN FUNCTIONS      ****************************/
4231 /******************************************************************************/
4232
4233 /**
4234  * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
4235  *
4236  * @param cls closure
4237  * @param key current key code
4238  * @param value value in the hash map
4239  * @return GNUNET_YES if we should continue to iterate,
4240  *         GNUNET_NO if not.
4241  */
4242 static int
4243 shutdown_tunnel (void *cls, const GNUNET_HashCode * key, void *value)
4244 {
4245   struct MeshTunnel *t = value;
4246   tunnel_destroy(t);
4247   return GNUNET_YES;
4248 }
4249
4250 /**
4251  * Iterator over peer hash map entries to destroy the tunnel during shutdown.
4252  *
4253  * @param cls closure
4254  * @param key current key code
4255  * @param value value in the hash map
4256  * @return GNUNET_YES if we should continue to iterate,
4257  *         GNUNET_NO if not.
4258  */
4259 static int
4260 shutdown_peer (void *cls, const GNUNET_HashCode * key, void *value)
4261 {
4262   struct MeshPeerInfo *p = value;
4263   peer_info_destroy (p);
4264   return GNUNET_YES;
4265 }
4266
4267 /**
4268  * Task run during shutdown.
4269  *
4270  * @param cls unused
4271  * @param tc unused
4272  */
4273 static void
4274 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4275 {
4276   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: shutting down\n");
4277   /* TODO: destroy tunnels? */
4278   if (core_handle != NULL)
4279   {
4280     GNUNET_CORE_disconnect (core_handle);
4281     core_handle = NULL;
4282   }
4283   GNUNET_CONTAINER_multihashmap_iterate(tunnels, &shutdown_tunnel, NULL);
4284   GNUNET_CONTAINER_multihashmap_iterate(peers, &shutdown_peer, NULL);
4285   if (dht_handle != NULL)
4286   {
4287     GNUNET_DHT_disconnect (dht_handle);
4288     dht_handle = NULL;
4289   }
4290   if (nc != NULL)
4291   {
4292     GNUNET_SERVER_notification_context_destroy (nc);
4293     nc = NULL;
4294   }
4295   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
4296   {
4297     GNUNET_SCHEDULER_cancel (announce_id_task);
4298     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
4299   }
4300   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: shut down\n");
4301 }
4302
4303 /**
4304  * Process mesh requests.
4305  *
4306  * @param cls closure
4307  * @param server the initialized server
4308  * @param c configuration to use
4309  */
4310 static void
4311 run (void *cls, struct GNUNET_SERVER_Handle *server,
4312      const struct GNUNET_CONFIGURATION_Handle *c)
4313 {
4314   struct MeshPeerInfo *peer;
4315   struct MeshPeerPath *p;
4316   char *keyfile;
4317
4318   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: starting to run\n");
4319   server_handle = server;
4320   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
4321                                      CORE_QUEUE_SIZE,   /* queue size */
4322                                      NULL,      /* Closure passed to MESH functions */
4323                                      &core_init,        /* Call core_init once connected */
4324                                      &core_connect,     /* Handle connects */
4325                                      &core_disconnect,  /* remove peers on disconnects */
4326                                      NULL,      /* Don't notify about all incoming messages */
4327                                      GNUNET_NO, /* For header only in notification */
4328                                      NULL,      /* Don't notify about all outbound messages */
4329                                      GNUNET_NO, /* For header-only out notification */
4330                                      core_handlers);    /* Register these handlers */
4331   if (core_handle == NULL)
4332   {
4333     GNUNET_break (0);
4334     GNUNET_SCHEDULER_shutdown ();
4335     return;
4336   }
4337
4338   if (GNUNET_OK !=
4339        GNUNET_CONFIGURATION_get_value_filename (c, "GNUNETD", "HOSTKEY",
4340                                                 &keyfile))
4341   {
4342     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4343                 _
4344                 ("Mesh service is lacking key configuration settings.  Exiting.\n"));
4345     GNUNET_SCHEDULER_shutdown ();
4346     return;
4347   }
4348   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
4349   GNUNET_free (keyfile);
4350   if (my_private_key == NULL)
4351   {
4352     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4353                 _("Mesh service could not access hostkey.  Exiting.\n"));
4354     GNUNET_SCHEDULER_shutdown ();
4355     return;
4356   }
4357   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
4358   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
4359                       &my_full_id.hashPubKey);
4360   myid = GNUNET_PEER_intern (&my_full_id);
4361
4362   dht_handle = GNUNET_DHT_connect (c, 64);
4363   if (dht_handle == NULL)
4364   {
4365     GNUNET_break (0);
4366   }
4367
4368   next_tid = 0;
4369   next_local_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
4370
4371   tunnels = GNUNET_CONTAINER_multihashmap_create (32);
4372   incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
4373   peers = GNUNET_CONTAINER_multihashmap_create (32);
4374   applications = GNUNET_CONTAINER_multihashmap_create (32);
4375   types = GNUNET_CONTAINER_multihashmap_create (32);
4376
4377   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
4378   nc = GNUNET_SERVER_notification_context_create (server_handle,
4379                                                   LOCAL_QUEUE_SIZE);
4380   GNUNET_SERVER_disconnect_notify (server_handle,
4381                                    &handle_local_client_disconnect,
4382                                    NULL);
4383
4384
4385   clients = NULL;
4386   clients_tail = NULL;
4387 #if MESH_DEBUG
4388   next_client_id = 0;
4389 #endif
4390
4391   announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
4392   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
4393
4394   /* Create a peer_info for the local peer */
4395   peer = peer_info_get(&my_full_id);
4396   p = path_new (1);
4397   p->peers[0] = myid;
4398   path_add_to_peer(peer, p);
4399
4400   /* Scheduled the task to clean up when shutdown is called */
4401   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
4402                                 NULL);
4403
4404   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: end of run()\n");
4405 }
4406
4407 /**
4408  * The main function for the mesh service.
4409  *
4410  * @param argc number of arguments from the command line
4411  * @param argv command line arguments
4412  * @return 0 ok, 1 on error
4413  */
4414 int
4415 main (int argc, char *const *argv)
4416 {
4417   int ret;
4418
4419   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: main()\n");
4420   ret =
4421       (GNUNET_OK ==
4422        GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
4423                            NULL)) ? 0 : 1;
4424   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: main() END\n");
4425
4426   return ret;
4427 }