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