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