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