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