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