Removed core queue requirements from mesh (backporting mesh_new)
[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 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 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   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   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   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           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 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       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   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     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   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   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 id Tunnel Number of the tunnel.
2423  * 
2424  */
2425 static struct MeshTunnel *
2426 tunnel_new (GNUNET_PEER_Id owner,
2427             MESH_TunnelNumber tid,
2428             struct MeshClient *client,
2429             MESH_TunnelNumber local)
2430 {
2431   struct MeshTunnel *t;
2432   struct GNUNET_HashCode hash;
2433
2434   t = GNUNET_malloc (sizeof (struct MeshTunnel));
2435   t->id.oid = owner;
2436   t->id.tid = tid;
2437   t->queue_max = 1000; // FIXME API parameter
2438   t->tree = tree_new (owner);
2439   t->owner = client;
2440   t->local_tid = local;
2441
2442   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
2443   if (GNUNET_OK !=
2444       GNUNET_CONTAINER_multihashmap_put (tunnels, &hash, t,
2445                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2446   {
2447     GNUNET_break (0);
2448     tunnel_destroy (t);
2449     if (NULL != client)
2450       GNUNET_SERVER_receive_done (client->handle, GNUNET_SYSERR);
2451     return NULL;
2452   }
2453
2454   if (NULL != client)
2455   {
2456     GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
2457     if (GNUNET_OK !=
2458         GNUNET_CONTAINER_multihashmap_put (client->own_tunnels, &hash, t,
2459                                           GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2460     {
2461       GNUNET_break (0);
2462       tunnel_destroy (t);
2463       GNUNET_SERVER_receive_done (client->handle, GNUNET_SYSERR);
2464       return NULL;
2465     }
2466   }
2467
2468   return t;
2469 }
2470
2471
2472 /**
2473  * Removes an explicit path from a tunnel, freeing all intermediate nodes
2474  * that are no longer needed, as well as nodes of no longer reachable peers.
2475  * The tunnel itself is also destoyed if results in a remote empty tunnel.
2476  *
2477  * @param t Tunnel from which to remove the path.
2478  * @param peer Short id of the peer which should be removed.
2479  */
2480 static void
2481 tunnel_delete_peer (struct MeshTunnel *t, GNUNET_PEER_Id peer)
2482 {
2483   if (GNUNET_NO == tree_del_peer (t->tree, peer, NULL, NULL))
2484     tunnel_destroy (t);
2485 }
2486
2487
2488 /**
2489  * tunnel_destroy_iterator: iterator for deleting each tunnel that belongs to a
2490  * client when the client disconnects. If the client is not the owner, the
2491  * owner will get notified if no more clients are in the tunnel and the client
2492  * get removed from the tunnel's list.
2493  *
2494  * @param cls closure (client that is disconnecting)
2495  * @param key the hash of the local tunnel id (used to access the hashmap)
2496  * @param value the value stored at the key (tunnel to destroy)
2497  *
2498  * @return GNUNET_OK on success
2499  */
2500 static int
2501 tunnel_destroy_iterator (void *cls, const GNUNET_HashCode * key, void *value)
2502 {
2503   struct MeshTunnel *t = value;
2504   struct MeshClient *c = cls;
2505   int r;
2506
2507   send_client_tunnel_disconnect(t, c);
2508   if (c != t->owner)
2509   {
2510     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2511                 "Client %u is destination, keeping the tunnel alive.\n", c->id);
2512     tunnel_delete_client(t, c);
2513     client_delete_tunnel(c, t);
2514     return GNUNET_OK;
2515   }
2516   tunnel_send_destroy(t);
2517   r = tunnel_destroy (t);
2518   return r;
2519 }
2520
2521
2522 /**
2523  * Timeout function, destroys tunnel if called
2524  *
2525  * @param cls Closure (tunnel to destroy).
2526  * @param tc TaskContext
2527  */
2528 static void
2529 tunnel_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2530 {
2531   struct MeshTunnel *t = cls;
2532
2533   if (GNUNET_SCHEDULER_REASON_SHUTDOWN == tc->reason)
2534     return;
2535   t->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2536   tunnel_destroy (t);
2537 }
2538
2539 /**
2540  * Resets the tunnel timeout. Starts it if no timeout was running.
2541  *
2542  * @param t Tunnel whose timeout to reset.
2543  */
2544 static void
2545 tunnel_reset_timeout (struct MeshTunnel *t)
2546 {
2547   if (GNUNET_SCHEDULER_NO_TASK != t->timeout_task)
2548     GNUNET_SCHEDULER_cancel (t->timeout_task);
2549   t->timeout_task =
2550       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
2551                                     (REFRESH_PATH_TIME, 4), &tunnel_timeout, t);
2552 }
2553
2554
2555 /******************************************************************************/
2556 /****************      MESH NETWORK HANDLER HELPERS     ***********************/
2557 /******************************************************************************/
2558
2559 /**
2560  * Function to send a create path packet to a peer.
2561  *
2562  * @param cls closure
2563  * @param size number of bytes available in buf
2564  * @param buf where the callee should write the message
2565  * @return number of bytes written to buf
2566  */
2567 static size_t
2568 send_core_path_create (void *cls, size_t size, void *buf)
2569 {
2570   struct MeshPathInfo *info = cls;
2571   struct GNUNET_MESH_ManipulatePath *msg;
2572   struct GNUNET_PeerIdentity *peer_ptr;
2573   struct MeshTunnel *t = info->t;
2574   struct MeshPeerPath *p = info->path;
2575   size_t size_needed;
2576   int i;
2577
2578   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATE PATH sending...\n");
2579   size_needed =
2580       sizeof (struct GNUNET_MESH_ManipulatePath) +
2581       p->length * sizeof (struct GNUNET_PeerIdentity);
2582
2583   if (size < size_needed || NULL == buf)
2584   {
2585     GNUNET_break (0);
2586     return 0;
2587   }
2588   msg = (struct GNUNET_MESH_ManipulatePath *) buf;
2589   msg->header.size = htons (size_needed);
2590   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE);
2591   msg->tid = ntohl (t->id.tid);
2592
2593   peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
2594   for (i = 0; i < p->length; i++)
2595   {
2596     GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
2597   }
2598
2599   path_destroy (p);
2600   GNUNET_free (info);
2601
2602   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2603               "CREATE PATH (%u bytes long) sent!\n", size_needed);
2604   return size_needed;
2605 }
2606
2607
2608 /**
2609  * Fill the core buffer 
2610  *
2611  * @param cls closure (data itself)
2612  * @param size number of bytes available in buf
2613  * @param buf where the callee should write the message
2614  *
2615  * @return number of bytes written to buf
2616  */
2617 static size_t
2618 send_core_data_multicast (void *cls, size_t size, void *buf)
2619 {
2620   struct MeshTransmissionDescriptor *info = cls;
2621   size_t total_size;
2622
2623   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Multicast callback.\n");
2624   GNUNET_assert (NULL != info);
2625   GNUNET_assert (NULL != info->peer);
2626   total_size = info->mesh_data->data_len;
2627   GNUNET_assert (total_size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
2628
2629   if (total_size > size)
2630   {
2631     GNUNET_break (0);
2632     return 0;
2633   }
2634   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " copying data...\n");
2635   memcpy (buf, info->mesh_data->data, total_size);
2636 #if MESH_DEBUG
2637   {
2638     struct GNUNET_MESH_Multicast *mc;
2639     struct GNUNET_MessageHeader *mh;
2640
2641     mh = buf;
2642     if (ntohs (mh->type) == GNUNET_MESSAGE_TYPE_MESH_MULTICAST)
2643     {
2644       mc = (struct GNUNET_MESH_Multicast *) mh;
2645       mh = (struct GNUNET_MessageHeader *) &mc[1];
2646       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2647                   " multicast, payload type %u\n", ntohs (mh->type));
2648       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2649                   " multicast, payload size %u\n", ntohs (mh->size));
2650     }
2651     else
2652     {
2653       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " type %u\n",
2654                   ntohs (mh->type));
2655     }
2656   }
2657 #endif
2658   data_descriptor_decrement_multicast (info->mesh_data);
2659   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "freeing info...\n");
2660   GNUNET_free (info);
2661   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "return %u\n", total_size);
2662   return total_size;
2663 }
2664
2665
2666 /**
2667  * Creates a path ack message in buf and frees all unused resources.
2668  *
2669  * @param cls closure (MeshTransmissionDescriptor)
2670  * @param size number of bytes available in buf
2671  * @param buf where the callee should write the message
2672  * @return number of bytes written to buf
2673  */
2674 static size_t
2675 send_core_path_ack (void *cls, size_t size, void *buf)
2676 {
2677   struct MeshTransmissionDescriptor *info = cls;
2678   struct GNUNET_MESH_PathACK *msg = buf;
2679
2680   GNUNET_assert (NULL != info);
2681   if (sizeof (struct GNUNET_MESH_PathACK) > size)
2682   {
2683     GNUNET_break (0);
2684     return 0;
2685   }
2686   msg->header.size = htons (sizeof (struct GNUNET_MESH_PathACK));
2687   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_ACK);
2688   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
2689   msg->tid = htonl (info->origin->tid);
2690   msg->peer_id = my_full_id;
2691
2692   GNUNET_free (info);
2693   /* TODO add signature */
2694
2695   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "PATH ACK sent!\n");
2696   return sizeof (struct GNUNET_MESH_PathACK);
2697 }
2698
2699
2700 /**
2701  * Free a transmission that was already queued with all resources
2702  * associated to the request.
2703  *
2704  * @param queue Queue handler to cancel.
2705  * @param clear_cls Is it necessary to free associated cls?
2706  */
2707 static void
2708 queue_destroy (struct MeshPeerQueue *queue, int clear_cls)
2709 {
2710   struct MeshTransmissionDescriptor *dd;
2711   struct MeshPathInfo *path_info;
2712
2713   if (GNUNET_YES == clear_cls)
2714   {
2715     switch (queue->type)
2716     {
2717     case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
2718     case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
2719         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   type payload\n");
2720         dd = queue->cls;
2721         data_descriptor_decrement_multicast (dd->mesh_data);
2722         break;
2723     case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
2724         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   type create path\n");
2725         path_info = queue->cls;
2726         path_destroy (path_info->path);
2727         break;
2728     default:
2729         GNUNET_break (0);
2730         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   type unknown!\n");
2731     }
2732     GNUNET_free_non_null (queue->cls);
2733   }
2734   GNUNET_CONTAINER_DLL_remove (queue->peer->queue_head,
2735                                queue->peer->queue_tail,
2736                                queue);
2737   GNUNET_free (queue);
2738 }
2739
2740
2741 /**
2742   * Core callback to write a queued packet to core buffer
2743   *
2744   * @param cls Closure (peer info).
2745   * @param size Number of bytes available in buf.
2746   * @param buf Where the to write the message.
2747   *
2748   * @return number of bytes written to buf
2749   */
2750 static size_t
2751 queue_send (void *cls, size_t size, void *buf)
2752 {
2753     struct MeshPeerInfo *peer = cls;
2754     struct MeshPeerQueue *queue;
2755     size_t data_size;
2756
2757     peer->core_transmit = NULL;
2758     queue = peer->queue_head;
2759
2760     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "********* Queue send\n");
2761
2762
2763     /* If queue is empty, send should have been cancelled */
2764     if (NULL == queue)
2765     {
2766         GNUNET_break(0);
2767         return 0;
2768     }
2769     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   not empty\n");
2770
2771     /* Check if buffer size is enough for the message */
2772     if (queue->size > size)
2773     {
2774         struct GNUNET_PeerIdentity id;
2775
2776         GNUNET_PEER_resolve (peer->id, &id);
2777         peer->core_transmit =
2778             GNUNET_CORE_notify_transmit_ready(core_handle,
2779                                               0,
2780                                               0,
2781                                               GNUNET_TIME_UNIT_FOREVER_REL,
2782                                               &id,
2783                                               queue->size,
2784                                               &queue_send,
2785                                               peer);
2786         return 0;
2787     }
2788     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   size ok\n");
2789
2790     /* Fill buf */
2791     switch (queue->type)
2792     {
2793         case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
2794             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   unicast\n");
2795             data_size = send_core_data_raw (queue->cls, size, buf);
2796             break;
2797         case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
2798             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   multicast\n");
2799             data_size = send_core_data_multicast(queue->cls, size, buf);
2800             break;
2801         case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
2802             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path create\n");
2803             data_size = send_core_path_create(queue->cls, size, buf);
2804             break;
2805         case GNUNET_MESSAGE_TYPE_MESH_PATH_ACK:
2806             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path ack\n");
2807             data_size = send_core_path_ack(queue->cls, size, buf);
2808             break;
2809         default:
2810             GNUNET_break (0);
2811             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   type unknown\n");
2812             data_size = 0;
2813     }
2814     queue->tunnel->queue_n--;
2815
2816     /* Free queue, but cls was freed by send_core_* */
2817     queue_destroy(queue, GNUNET_NO);
2818
2819     /* If more data in queue, send next */
2820     if (NULL != peer->queue_head)
2821     {
2822         struct GNUNET_PeerIdentity id;
2823
2824         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   more data!\n");
2825         GNUNET_PEER_resolve (peer->id, &id);
2826         peer->core_transmit =
2827             GNUNET_CORE_notify_transmit_ready(core_handle,
2828                                               0,
2829                                               0,
2830                                               GNUNET_TIME_UNIT_FOREVER_REL,
2831                                               &id,
2832                                               peer->queue_head->size,
2833                                               &queue_send,
2834                                               peer);
2835     }
2836     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   return %d\n", data_size);
2837     return data_size;
2838 }
2839
2840
2841 /**
2842  * Queue and pass message to core when possible.
2843  *
2844  * @param cls Closure (type dependant).
2845  * @param type Type of the message.
2846  * @param size Size of the message.
2847  * @param dst Neighbor to send message to.
2848  * @param t Tunnel this message belongs to.
2849  */
2850 static void
2851 queue_add (void *cls, uint16_t type, size_t size,
2852            struct MeshPeerInfo *dst, struct MeshTunnel *t)
2853 {
2854     struct MeshPeerQueue *queue;
2855
2856     if (t->queue_n >= t->queue_max)
2857     {
2858       if (NULL == t->owner)
2859         GNUNET_break_op(0);       // TODO: kill connection?
2860       else
2861         GNUNET_break(0);
2862       return;                       // Drop message
2863     }
2864     t->queue_n++;
2865     queue = GNUNET_malloc (sizeof (struct MeshPeerQueue));
2866     queue->cls = cls;
2867     queue->type = type;
2868     queue->size = size;
2869     queue->peer = dst;
2870     queue->tunnel = t;
2871     GNUNET_CONTAINER_DLL_insert_tail (dst->queue_head, dst->queue_tail, queue);
2872     if (NULL == dst->core_transmit)
2873     {
2874         struct GNUNET_PeerIdentity id;
2875
2876         GNUNET_PEER_resolve (dst->id, &id);
2877         dst->core_transmit =
2878             GNUNET_CORE_notify_transmit_ready(core_handle,
2879                                               0,
2880                                               0,
2881                                               GNUNET_TIME_UNIT_FOREVER_REL,
2882                                               &id,
2883                                               size,
2884                                               &queue_send,
2885                                               dst);
2886     }
2887 }
2888
2889
2890 /******************************************************************************/
2891 /********************      MESH NETWORK HANDLERS     **************************/
2892 /******************************************************************************/
2893
2894
2895 /**
2896  * Core handler for path creation
2897  *
2898  * @param cls closure
2899  * @param message message
2900  * @param peer peer identity this notification is about
2901  * @param atsi performance data
2902  * @param atsi_count number of records in 'atsi'
2903  *
2904  * @return GNUNET_OK to keep the connection open,
2905  *         GNUNET_SYSERR to close it (signal serious error)
2906  */
2907 static int
2908 handle_mesh_path_create (void *cls, const struct GNUNET_PeerIdentity *peer,
2909                          const struct GNUNET_MessageHeader *message,
2910                          const struct GNUNET_ATS_Information *atsi,
2911                          unsigned int atsi_count)
2912 {
2913   unsigned int own_pos;
2914   uint16_t size;
2915   uint16_t i;
2916   MESH_TunnelNumber tid;
2917   struct GNUNET_MESH_ManipulatePath *msg;
2918   struct GNUNET_PeerIdentity *pi;
2919   GNUNET_HashCode hash;
2920   struct MeshPeerPath *path;
2921   struct MeshPeerInfo *dest_peer_info;
2922   struct MeshPeerInfo *orig_peer_info;
2923   struct MeshTunnel *t;
2924
2925   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2926               "Received a path create msg [%s]\n",
2927               GNUNET_i2s (&my_full_id));
2928   size = ntohs (message->size);
2929   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
2930   {
2931     GNUNET_break_op (0);
2932     return GNUNET_OK;
2933   }
2934
2935   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
2936   if (size % sizeof (struct GNUNET_PeerIdentity))
2937   {
2938     GNUNET_break_op (0);
2939     return GNUNET_OK;
2940   }
2941   size /= sizeof (struct GNUNET_PeerIdentity);
2942   if (size < 2)
2943   {
2944     GNUNET_break_op (0);
2945     return GNUNET_OK;
2946   }
2947   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
2948   msg = (struct GNUNET_MESH_ManipulatePath *) message;
2949
2950   tid = ntohl (msg->tid);
2951   pi = (struct GNUNET_PeerIdentity *) &msg[1];
2952   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2953               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi), tid);
2954   t = tunnel_get (pi, tid);
2955   if (NULL == t) // FIXME only for INCOMING tunnels?
2956   {
2957     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating tunnel\n");
2958     t = tunnel_new (GNUNET_PEER_intern (pi), tid, NULL, 0);
2959
2960     while (NULL != tunnel_get_incoming (next_local_tid))
2961       next_local_tid = (next_local_tid + 1) | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
2962     t->local_tid_dest = next_local_tid++;
2963     next_local_tid = next_local_tid | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
2964
2965     tunnel_reset_timeout (t);
2966     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
2967     if (GNUNET_OK !=
2968         GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
2969                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2970     {
2971       tunnel_destroy (t);
2972       GNUNET_break (0);
2973       return GNUNET_OK;
2974     }
2975   }
2976   dest_peer_info =
2977       GNUNET_CONTAINER_multihashmap_get (peers, &pi[size - 1].hashPubKey);
2978   if (NULL == dest_peer_info)
2979   {
2980     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2981                 "  Creating PeerInfo for destination.\n");
2982     dest_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
2983     dest_peer_info->id = GNUNET_PEER_intern (&pi[size - 1]);
2984     GNUNET_CONTAINER_multihashmap_put (peers, &pi[size - 1].hashPubKey,
2985                                        dest_peer_info,
2986                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2987   }
2988   orig_peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &pi->hashPubKey);
2989   if (NULL == orig_peer_info)
2990   {
2991     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2992                 "  Creating PeerInfo for origin.\n");
2993     orig_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
2994     orig_peer_info->id = GNUNET_PEER_intern (pi);
2995     GNUNET_CONTAINER_multihashmap_put (peers, &pi->hashPubKey, orig_peer_info,
2996                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2997   }
2998   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
2999   path = path_new (size);
3000   own_pos = 0;
3001   for (i = 0; i < size; i++)
3002   {
3003     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
3004                 GNUNET_i2s (&pi[i]));
3005     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
3006     if (path->peers[i] == myid)
3007       own_pos = i;
3008   }
3009   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
3010   if (own_pos == 0)
3011   {
3012     /* cannot be self, must be 'not found' */
3013     /* create path: self not found in path through self */
3014     GNUNET_break_op (0);
3015     path_destroy (path);
3016     /* FIXME error. destroy tunnel? leave for timeout? */
3017     return 0;
3018   }
3019   path_add_to_peers (path, GNUNET_NO);
3020   tunnel_add_path (t, path, own_pos);
3021   if (own_pos == size - 1)
3022   {
3023     /* It is for us! Send ack. */
3024     struct MeshTransmissionDescriptor *info;
3025
3026     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
3027     peer_info_add_path_to_origin (orig_peer_info, path, GNUNET_NO);
3028     if (NULL == t->peers)
3029     {
3030       /* New tunnel! Notify clients on data. */
3031       t->peers = GNUNET_CONTAINER_multihashmap_create (4);
3032     }
3033     GNUNET_break (GNUNET_OK ==
3034                   GNUNET_CONTAINER_multihashmap_put (t->peers,
3035                                                      &my_full_id.hashPubKey,
3036                                                      peer_info_get
3037                                                      (&my_full_id),
3038                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE));
3039     info = GNUNET_malloc (sizeof (struct MeshTransmissionDescriptor));
3040     info->origin = &t->id;
3041     info->peer = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
3042     GNUNET_assert (NULL != info->peer);
3043     queue_add(info,
3044               GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
3045               sizeof (struct GNUNET_MESH_PathACK),
3046               info->peer,
3047               t);
3048   }
3049   else
3050   {
3051     struct MeshPeerPath *path2;
3052
3053     /* It's for somebody else! Retransmit. */
3054     path2 = path_duplicate (path);
3055     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Retransmitting.\n");
3056     peer_info_add_path (dest_peer_info, path2, GNUNET_NO);
3057     path2 = path_duplicate (path);
3058     peer_info_add_path_to_origin (orig_peer_info, path2, GNUNET_NO);
3059     send_create_path (dest_peer_info, path, t);
3060   }
3061   return GNUNET_OK;
3062 }
3063
3064
3065 /**
3066  * Core handler for path destruction
3067  *
3068  * @param cls closure
3069  * @param message message
3070  * @param peer peer identity this notification is about
3071  * @param atsi performance data
3072  * @param atsi_count number of records in 'atsi'
3073  *
3074  * @return GNUNET_OK to keep the connection open,
3075  *         GNUNET_SYSERR to close it (signal serious error)
3076  */
3077 static int
3078 handle_mesh_path_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
3079                           const struct GNUNET_MessageHeader *message,
3080                           const struct GNUNET_ATS_Information *atsi,
3081                           unsigned int atsi_count)
3082 {
3083   struct GNUNET_MESH_ManipulatePath *msg;
3084   struct GNUNET_PeerIdentity *pi;
3085   struct MeshPeerPath *path;
3086   struct MeshTunnel *t;
3087   unsigned int own_pos;
3088   unsigned int i;
3089   size_t size;
3090
3091   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3092               "Received a PATH DESTROY msg from %s\n", GNUNET_i2s (peer));
3093   size = ntohs (message->size);
3094   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
3095   {
3096     GNUNET_break_op (0);
3097     return GNUNET_OK;
3098   }
3099
3100   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
3101   if (size % sizeof (struct GNUNET_PeerIdentity))
3102   {
3103     GNUNET_break_op (0);
3104     return GNUNET_OK;
3105   }
3106   size /= sizeof (struct GNUNET_PeerIdentity);
3107   if (size < 2)
3108   {
3109     GNUNET_break_op (0);
3110     return GNUNET_OK;
3111   }
3112   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
3113
3114   msg = (struct GNUNET_MESH_ManipulatePath *) message;
3115   pi = (struct GNUNET_PeerIdentity *) &msg[1];
3116   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3117               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi),
3118               msg->tid);
3119   t = tunnel_get (pi, ntohl (msg->tid));
3120   if (NULL == t)
3121   {
3122     /* TODO notify back: we don't know this tunnel */
3123     GNUNET_break_op (0);
3124     return GNUNET_OK;
3125   }
3126   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
3127   path = path_new (size);
3128   own_pos = 0;
3129   for (i = 0; i < size; i++)
3130   {
3131     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
3132                 GNUNET_i2s (&pi[i]));
3133     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
3134     if (path->peers[i] == myid)
3135       own_pos = i;
3136   }
3137   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
3138   if (own_pos < path->length - 1)
3139     send_message (message, &pi[own_pos + 1], t);
3140   else
3141     send_client_tunnel_disconnect(t, NULL);
3142
3143   tunnel_delete_peer (t, path->peers[path->length - 1]);
3144   path_destroy (path);
3145   return GNUNET_OK;
3146 }
3147
3148
3149 /**
3150  * Core handler for notifications of broken paths
3151  *
3152  * @param cls closure
3153  * @param message message
3154  * @param peer peer identity this notification is about
3155  * @param atsi performance data
3156  * @param atsi_count number of records in 'atsi'
3157  *
3158  * @return GNUNET_OK to keep the connection open,
3159  *         GNUNET_SYSERR to close it (signal serious error)
3160  */
3161 static int
3162 handle_mesh_path_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
3163                          const struct GNUNET_MessageHeader *message,
3164                          const struct GNUNET_ATS_Information *atsi,
3165                          unsigned int atsi_count)
3166 {
3167   struct GNUNET_MESH_PathBroken *msg;
3168   struct MeshTunnel *t;
3169
3170   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3171               "Received a PATH BROKEN msg from %s\n", GNUNET_i2s (peer));
3172   msg = (struct GNUNET_MESH_PathBroken *) message;
3173   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
3174               GNUNET_i2s (&msg->peer1));
3175   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
3176               GNUNET_i2s (&msg->peer2));
3177   t = tunnel_get (&msg->oid, ntohl (msg->tid));
3178   if (NULL == t)
3179   {
3180     GNUNET_break_op (0);
3181     return GNUNET_OK;
3182   }
3183   tunnel_notify_connection_broken (t, GNUNET_PEER_search (&msg->peer1),
3184                                    GNUNET_PEER_search (&msg->peer2));
3185   return GNUNET_OK;
3186
3187 }
3188
3189
3190 /**
3191  * Core handler for tunnel destruction
3192  *
3193  * @param cls closure
3194  * @param message message
3195  * @param peer peer identity this notification is about
3196  * @param atsi performance data
3197  * @param atsi_count number of records in 'atsi'
3198  *
3199  * @return GNUNET_OK to keep the connection open,
3200  *         GNUNET_SYSERR to close it (signal serious error)
3201  */
3202 static int
3203 handle_mesh_tunnel_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
3204                             const struct GNUNET_MessageHeader *message,
3205                             const struct GNUNET_ATS_Information *atsi,
3206                             unsigned int atsi_count)
3207 {
3208   struct GNUNET_MESH_TunnelDestroy *msg;
3209   struct MeshTunnel *t;
3210
3211   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3212               "Got a TUNNEL DESTROY packet from %s\n", GNUNET_i2s (peer));
3213   msg = (struct GNUNET_MESH_TunnelDestroy *) message;
3214   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for tunnel %s [%u]\n",
3215               GNUNET_i2s (&msg->oid), ntohl (msg->tid));
3216   t = tunnel_get (&msg->oid, ntohl (msg->tid));
3217   if (NULL == t)
3218   {
3219     /* Probably already got the message from another path,
3220      * destroyed the tunnel and retransmitted to children.
3221      * Safe to ignore.
3222      */
3223     return GNUNET_OK;
3224   }
3225   if (t->id.oid == myid)
3226   {
3227     GNUNET_break_op (0);
3228     return GNUNET_OK;
3229   }
3230   if (t->local_tid_dest >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
3231   {
3232     /* Tunnel was incoming, notify clients */
3233     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "INCOMING TUNNEL %X %X\n",
3234                 t->local_tid, t->local_tid_dest);
3235     send_clients_tunnel_destroy (t);
3236   }
3237   tunnel_send_destroy (t);
3238   tunnel_destroy (t);
3239   return GNUNET_OK;
3240 }
3241
3242
3243 /**
3244  * Core handler for mesh network traffic going from the origin to a peer
3245  *
3246  * @param cls closure
3247  * @param peer peer identity this notification is about
3248  * @param message message
3249  * @param atsi performance data
3250  * @param atsi_count number of records in 'atsi'
3251  * @return GNUNET_OK to keep the connection open,
3252  *         GNUNET_SYSERR to close it (signal serious error)
3253  */
3254 static int
3255 handle_mesh_data_unicast (void *cls, const struct GNUNET_PeerIdentity *peer,
3256                           const struct GNUNET_MessageHeader *message,
3257                           const struct GNUNET_ATS_Information *atsi,
3258                           unsigned int atsi_count)
3259 {
3260   struct GNUNET_MESH_Unicast *msg;
3261   struct MeshTunnel *t;
3262   GNUNET_PEER_Id pid;
3263   size_t size;
3264
3265   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a unicast packet from %s\n",
3266               GNUNET_i2s (peer));
3267   size = ntohs (message->size);
3268   if (size <
3269       sizeof (struct GNUNET_MESH_Unicast) +
3270       sizeof (struct GNUNET_MessageHeader))
3271   {
3272     GNUNET_break (0);
3273     return GNUNET_OK;
3274   }
3275   msg = (struct GNUNET_MESH_Unicast *) message;
3276   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %u\n",
3277               ntohs (msg[1].header.type));
3278   t = tunnel_get (&msg->oid, ntohl (msg->tid));
3279   if (NULL == t)
3280   {
3281     /* TODO notify back: we don't know this tunnel */
3282     GNUNET_break_op (0);
3283     return GNUNET_OK;
3284   }
3285   tunnel_reset_timeout (t);
3286   pid = GNUNET_PEER_search (&msg->destination);
3287   if (pid == myid)
3288   {
3289     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3290                 "  it's for us! sending to clients...\n");
3291     send_subscribed_clients (message, (struct GNUNET_MessageHeader *) &msg[1]);
3292     return GNUNET_OK;
3293   }
3294   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3295               "  not for us, retransmitting...\n");
3296   send_message (message, tree_get_first_hop (t->tree, pid), t);
3297   return GNUNET_OK;
3298 }
3299
3300
3301 /**
3302  * Core handler for mesh network traffic going from the origin to all peers
3303  *
3304  * @param cls closure
3305  * @param message message
3306  * @param peer peer identity this notification is about
3307  * @param atsi performance data
3308  * @param atsi_count number of records in 'atsi'
3309  * @return GNUNET_OK to keep the connection open,
3310  *         GNUNET_SYSERR to close it (signal serious error)
3311  *
3312  * TODO: Check who we got this from, to validate route.
3313  */
3314 static int
3315 handle_mesh_data_multicast (void *cls, const struct GNUNET_PeerIdentity *peer,
3316                             const struct GNUNET_MessageHeader *message,
3317                             const struct GNUNET_ATS_Information *atsi,
3318                             unsigned int atsi_count)
3319 {
3320   struct GNUNET_MESH_Multicast *msg;
3321   struct MeshTunnel *t;
3322   size_t size;
3323
3324   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a multicast packet from %s\n",
3325               GNUNET_i2s (peer));
3326   size = ntohs (message->size);
3327   if (sizeof (struct GNUNET_MESH_Multicast) +
3328       sizeof (struct GNUNET_MessageHeader) > size)
3329   {
3330     GNUNET_break_op (0);
3331     return GNUNET_OK;
3332   }
3333   msg = (struct GNUNET_MESH_Multicast *) message;
3334   t = tunnel_get (&msg->oid, ntohl (msg->tid));
3335
3336   if (NULL == t)
3337   {
3338     /* TODO notify that we dont know that tunnel */
3339     GNUNET_break_op (0);
3340     return GNUNET_OK;
3341   }
3342   if (t->mid == ntohl (msg->mid))
3343   {
3344     /* FIXME: already seen this packet, log dropping */
3345     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3346                 " Already seen mid %u, DROPPING!\n", t->mid);
3347     return GNUNET_OK;
3348   }
3349   else
3350   {
3351     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3352                 " mid %u not seen yet, forwarding\n", ntohl (msg->mid));
3353   }
3354   t->mid = ntohl (msg->mid);
3355   tunnel_reset_timeout (t);
3356
3357   /* Transmit to locally interested clients */
3358   if (NULL != t->peers &&
3359       GNUNET_CONTAINER_multihashmap_contains (t->peers, &my_full_id.hashPubKey))
3360   {
3361     send_subscribed_clients (message, &msg[1].header);
3362   }
3363   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ntohl (msg->ttl));
3364   if (ntohl (msg->ttl) == 0)
3365   {
3366     /* FIXME: ttl is 0, log dropping */
3367     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
3368     return GNUNET_OK;
3369   }
3370   tunnel_send_multicast (t, message, GNUNET_NO);
3371   return GNUNET_OK;
3372 }
3373
3374
3375 /**
3376  * Core handler for mesh network traffic toward the owner of a tunnel
3377  *
3378  * @param cls closure
3379  * @param message message
3380  * @param peer peer identity this notification is about
3381  * @param atsi performance data
3382  * @param atsi_count number of records in 'atsi'
3383  *
3384  * @return GNUNET_OK to keep the connection open,
3385  *         GNUNET_SYSERR to close it (signal serious error)
3386  */
3387 static int
3388 handle_mesh_data_to_orig (void *cls, const struct GNUNET_PeerIdentity *peer,
3389                           const struct GNUNET_MessageHeader *message,
3390                           const struct GNUNET_ATS_Information *atsi,
3391                           unsigned int atsi_count)
3392 {
3393   struct GNUNET_MESH_ToOrigin *msg;
3394   struct GNUNET_PeerIdentity id;
3395   struct MeshPeerInfo *peer_info;
3396   struct MeshTunnel *t;
3397   size_t size;
3398
3399   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a ToOrigin packet from %s\n",
3400               GNUNET_i2s (peer));
3401   size = ntohs (message->size);
3402   if (size < sizeof (struct GNUNET_MESH_ToOrigin) +     /* Payload must be */
3403       sizeof (struct GNUNET_MessageHeader))     /* at least a header */
3404   {
3405     GNUNET_break_op (0);
3406     return GNUNET_OK;
3407   }
3408   msg = (struct GNUNET_MESH_ToOrigin *) message;
3409   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %u\n",
3410               ntohs (msg[1].header.type));
3411   t = tunnel_get (&msg->oid, ntohl (msg->tid));
3412
3413   if (NULL == t)
3414   {
3415     /* TODO notify that we dont know this tunnel (whom)? */
3416     GNUNET_break_op (0);
3417     return GNUNET_OK;
3418   }
3419
3420   if (t->id.oid == myid)
3421   {
3422     char cbuf[size];
3423     struct GNUNET_MESH_ToOrigin *copy;
3424
3425     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3426                 "  it's for us! sending to clients...\n");
3427     if (NULL == t->owner)
3428     {
3429       /* got data packet for ownerless tunnel */
3430       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  no clients!\n");
3431       GNUNET_break_op (0);
3432       return GNUNET_OK;
3433     }
3434     /* TODO signature verification */
3435     memcpy (cbuf, message, size);
3436     copy = (struct GNUNET_MESH_ToOrigin *) cbuf;
3437     copy->tid = htonl (t->local_tid);
3438     GNUNET_SERVER_notification_context_unicast (nc, t->owner->handle,
3439                                                 &copy->header, GNUNET_YES);
3440     return GNUNET_OK;
3441   }
3442   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3443               "  not for us, retransmitting...\n");
3444
3445   peer_info = peer_info_get (&msg->oid);
3446   if (NULL == peer_info)
3447   {
3448     /* unknown origin of tunnel */
3449     GNUNET_break (0);
3450     return GNUNET_OK;
3451   }
3452   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
3453   send_message (message, &id, t);
3454
3455   return GNUNET_OK;
3456 }
3457
3458
3459 /**
3460  * Core handler for path ACKs
3461  *
3462  * @param cls closure
3463  * @param message message
3464  * @param peer peer identity this notification is about
3465  * @param atsi performance data
3466  * @param atsi_count number of records in 'atsi'
3467  *
3468  * @return GNUNET_OK to keep the connection open,
3469  *         GNUNET_SYSERR to close it (signal serious error)
3470  */
3471 static int
3472 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
3473                       const struct GNUNET_MessageHeader *message,
3474                       const struct GNUNET_ATS_Information *atsi,
3475                       unsigned int atsi_count)
3476 {
3477   struct GNUNET_MESH_PathACK *msg;
3478   struct GNUNET_PeerIdentity id;
3479   struct MeshPeerInfo *peer_info;
3480   struct MeshPeerPath *p;
3481   struct MeshTunnel *t;
3482
3483   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a path ACK msg [%s]\n",
3484               GNUNET_i2s (&my_full_id));
3485   msg = (struct GNUNET_MESH_PathACK *) message;
3486   t = tunnel_get (&msg->oid, msg->tid);
3487   if (NULL == t)
3488   {
3489     /* TODO notify that we don't know the tunnel */
3490     return GNUNET_OK;
3491   }
3492
3493   peer_info = peer_info_get (&msg->peer_id);
3494
3495   /* Add paths to peers? */
3496   p = tree_get_path_to_peer (t->tree, peer_info->id);
3497   if (NULL != p)
3498   {
3499     path_add_to_peers (p, GNUNET_YES);
3500     path_destroy (p);
3501   }
3502   else
3503   {
3504     GNUNET_break (0);
3505   }
3506
3507   /* Message for us? */
3508   if (0 == memcmp (&msg->oid, &my_full_id, sizeof (struct GNUNET_PeerIdentity)))
3509   {
3510     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
3511     if (NULL == t->owner)
3512     {
3513       GNUNET_break_op (0);
3514       return GNUNET_OK;
3515     }
3516     if (NULL != t->dht_get_type)
3517     {
3518       GNUNET_DHT_get_stop (t->dht_get_type);
3519       t->dht_get_type = NULL;
3520     }
3521     if (tree_get_status (t->tree, peer_info->id) != MESH_PEER_READY)
3522     {
3523       tree_set_status (t->tree, peer_info->id, MESH_PEER_READY);
3524       send_client_peer_connected (t, peer_info->id);
3525     }
3526     return GNUNET_OK;
3527   }
3528
3529   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3530               "  not for us, retransmitting...\n");
3531   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
3532   peer_info = peer_info_get (&msg->oid);
3533   if (NULL == peer_info)
3534   {
3535     /* If we know the tunnel, we should DEFINITELY know the peer */
3536     GNUNET_break (0);
3537     return GNUNET_OK;
3538   }
3539   send_message (message, &id, t);
3540   return GNUNET_OK;
3541 }
3542
3543
3544 /**
3545  * Functions to handle messages from core
3546  */
3547 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
3548   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
3549   {&handle_mesh_path_destroy, GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY, 0},
3550   {&handle_mesh_path_broken, GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN,
3551    sizeof (struct GNUNET_MESH_PathBroken)},
3552   {&handle_mesh_tunnel_destroy, GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY, 0},
3553   {&handle_mesh_data_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
3554   {&handle_mesh_data_multicast, GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
3555   {&handle_mesh_data_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
3556   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
3557    sizeof (struct GNUNET_MESH_PathACK)},
3558   {NULL, 0, 0}
3559 };
3560
3561
3562
3563 /******************************************************************************/
3564 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
3565 /******************************************************************************/
3566
3567 /**
3568  * deregister_app: iterator for removing each application registered by a client
3569  *
3570  * @param cls closure
3571  * @param key the hash of the application id (used to access the hashmap)
3572  * @param value the value stored at the key (client)
3573  *
3574  * @return GNUNET_OK on success
3575  */
3576 static int
3577 deregister_app (void *cls, const GNUNET_HashCode * key, void *value)
3578 {
3579   GNUNET_break (GNUNET_YES ==
3580                 GNUNET_CONTAINER_multihashmap_remove (applications, key,
3581                                                       value));
3582   return GNUNET_OK;
3583 }
3584
3585 #if LATER
3586 /**
3587  * notify_client_connection_failure: notify a client that the connection to the
3588  * requested remote peer is not possible (for instance, no route found)
3589  * Function called when the socket is ready to queue more data. "buf" will be
3590  * NULL and "size" zero if the socket was closed for writing in the meantime.
3591  *
3592  * @param cls closure
3593  * @param size number of bytes available in buf
3594  * @param buf where the callee should write the message
3595  * @return number of bytes written to buf
3596  */
3597 static size_t
3598 notify_client_connection_failure (void *cls, size_t size, void *buf)
3599 {
3600   int size_needed;
3601   struct MeshPeerInfo *peer_info;
3602   struct GNUNET_MESH_PeerControl *msg;
3603   struct GNUNET_PeerIdentity id;
3604
3605   if (0 == size && NULL == buf)
3606   {
3607     // TODO retry? cancel?
3608     return 0;
3609   }
3610
3611   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
3612   peer_info = (struct MeshPeerInfo *) cls;
3613   msg = (struct GNUNET_MESH_PeerControl *) buf;
3614   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
3615   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
3616 //     msg->tunnel_id = htonl(peer_info->t->tid);
3617   GNUNET_PEER_resolve (peer_info->id, &id);
3618   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
3619
3620   return size_needed;
3621 }
3622 #endif
3623
3624
3625 /**
3626  * Send keepalive packets for a peer
3627  *
3628  * @param cls Closure (tunnel for which to send the keepalive).
3629  * @param tc Notification context.
3630  *
3631  * TODO: implement explicit multicast keepalive?
3632  */
3633 static void
3634 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3635 {
3636   struct MeshTunnel *t = cls;
3637   struct GNUNET_MessageHeader *payload;
3638   struct GNUNET_MESH_Multicast *msg;
3639   size_t size =
3640       sizeof (struct GNUNET_MESH_Multicast) +
3641       sizeof (struct GNUNET_MessageHeader);
3642   char cbuf[size];
3643
3644   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3645   {
3646     return;
3647   }
3648   t->path_refresh_task = GNUNET_SCHEDULER_NO_TASK;
3649
3650   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3651               "sending keepalive for tunnel %d\n", t->id.tid);
3652
3653   msg = (struct GNUNET_MESH_Multicast *) cbuf;
3654   msg->header.size = htons (size);
3655   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
3656   msg->oid = my_full_id;
3657   msg->tid = htonl (t->id.tid);
3658   msg->ttl = htonl (DEFAULT_TTL);
3659   msg->mid = htonl (t->mid + 1);
3660   t->mid++;
3661   payload = (struct GNUNET_MessageHeader *) &msg[1];
3662   payload->size = htons (sizeof (struct GNUNET_MessageHeader));
3663   payload->type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE);
3664   tunnel_send_multicast (t, &msg->header, GNUNET_YES);
3665
3666   t->path_refresh_task =
3667       GNUNET_SCHEDULER_add_delayed (REFRESH_PATH_TIME, &path_refresh, t);
3668   return;
3669 }
3670
3671
3672 /**
3673  * Function to process paths received for a new peer addition. The recorded
3674  * paths form the initial tunnel, which can be optimized later.
3675  * Called on each result obtained for the DHT search.
3676  *
3677  * @param cls closure
3678  * @param exp when will this value expire
3679  * @param key key of the result
3680  * @param get_path path of the get request
3681  * @param get_path_length lenght of get_path
3682  * @param put_path path of the put request
3683  * @param put_path_length length of the put_path
3684  * @param type type of the result
3685  * @param size number of bytes in data
3686  * @param data pointer to the result data
3687  *
3688  * TODO: re-issue the request after certain time? cancel after X results?
3689  */
3690 static void
3691 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
3692                     const GNUNET_HashCode * key,
3693                     const struct GNUNET_PeerIdentity *get_path,
3694                     unsigned int get_path_length,
3695                     const struct GNUNET_PeerIdentity *put_path,
3696                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
3697                     size_t size, const void *data)
3698 {
3699   struct MeshPathInfo *path_info = cls;
3700   struct MeshPeerPath *p;
3701   struct GNUNET_PeerIdentity pi;
3702   int i;
3703
3704   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
3705   GNUNET_PEER_resolve (path_info->peer->id, &pi);
3706   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", GNUNET_i2s (&pi));
3707
3708   p = path_build_from_dht (get_path, get_path_length, put_path,
3709                            put_path_length);
3710   path_add_to_peers (p, GNUNET_NO);
3711   path_destroy(p);
3712   for (i = 0; i < path_info->peer->ntunnels; i++)
3713   {
3714     tunnel_add_peer (path_info->peer->tunnels[i], path_info->peer);
3715     peer_info_connect (path_info->peer, path_info->t);
3716   }
3717
3718   return;
3719 }
3720
3721
3722 /**
3723  * Function to process paths received for a new peer addition. The recorded
3724  * paths form the initial tunnel, which can be optimized later.
3725  * Called on each result obtained for the DHT search.
3726  *
3727  * @param cls closure
3728  * @param exp when will this value expire
3729  * @param key key of the result
3730  * @param get_path path of the get request
3731  * @param get_path_length lenght of get_path
3732  * @param put_path path of the put request
3733  * @param put_path_length length of the put_path
3734  * @param type type of the result
3735  * @param size number of bytes in data
3736  * @param data pointer to the result data
3737  */
3738 static void
3739 dht_get_type_handler (void *cls, struct GNUNET_TIME_Absolute exp,
3740                       const GNUNET_HashCode * key,
3741                       const struct GNUNET_PeerIdentity *get_path,
3742                       unsigned int get_path_length,
3743                       const struct GNUNET_PeerIdentity *put_path,
3744                       unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
3745                       size_t size, const void *data)
3746 {
3747   const struct GNUNET_PeerIdentity *pi = data;
3748   struct MeshTunnel *t = cls;
3749   struct MeshPeerInfo *peer_info;
3750   struct MeshPeerPath *p;
3751
3752   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got type DHT result!\n");
3753   if (size != sizeof (struct GNUNET_PeerIdentity))
3754   {
3755     GNUNET_break_op (0);
3756     return;
3757   }
3758   GNUNET_assert (NULL != t->owner);
3759   peer_info = peer_info_get (pi);
3760   (void) GNUNET_CONTAINER_multihashmap_put (t->peers, &pi->hashPubKey,
3761                                             peer_info,
3762                                             GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
3763
3764   p = path_build_from_dht (get_path, get_path_length, put_path,
3765                            put_path_length);
3766   path_add_to_peers (p, GNUNET_NO);
3767   path_destroy(p);
3768   tunnel_add_peer (t, peer_info);
3769   peer_info_connect (peer_info, t);
3770 }
3771
3772
3773 /******************************************************************************/
3774 /*********************       MESH LOCAL HANDLES      **************************/
3775 /******************************************************************************/
3776
3777
3778 /**
3779  * Handler for client disconnection
3780  *
3781  * @param cls closure
3782  * @param client identification of the client; NULL
3783  *        for the last call when the server is destroyed
3784  */
3785 static void
3786 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
3787 {
3788   struct MeshClient *c;
3789   struct MeshClient *next;
3790
3791   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected\n");
3792   if (client == NULL)
3793   {
3794     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (SERVER DOWN)\n");
3795     return;
3796   }
3797   c = clients;
3798   while (NULL != c)
3799   {
3800     if (c->handle != client)
3801     {
3802       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ... searching\n");
3803       c = c->next;
3804       continue;
3805     }
3806     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u)\n",
3807                 c->id);
3808     GNUNET_SERVER_client_drop (c->handle);
3809     c->shutting_down = GNUNET_YES;
3810     GNUNET_assert (NULL != c->own_tunnels);
3811     GNUNET_assert (NULL != c->incoming_tunnels);
3812     GNUNET_CONTAINER_multihashmap_iterate (c->own_tunnels,
3813                                            &tunnel_destroy_iterator, c);
3814     GNUNET_CONTAINER_multihashmap_iterate (c->incoming_tunnels,
3815                                            &tunnel_destroy_iterator, c);
3816     GNUNET_CONTAINER_multihashmap_iterate (c->ignore_tunnels,
3817                                            &tunnel_destroy_iterator, c);
3818     GNUNET_CONTAINER_multihashmap_destroy (c->own_tunnels);
3819     GNUNET_CONTAINER_multihashmap_destroy (c->incoming_tunnels);
3820     GNUNET_CONTAINER_multihashmap_destroy (c->ignore_tunnels);
3821
3822     /* deregister clients applications */
3823     if (NULL != c->apps)
3824     {
3825       GNUNET_CONTAINER_multihashmap_iterate (c->apps, &deregister_app, NULL);
3826       GNUNET_CONTAINER_multihashmap_destroy (c->apps);
3827     }
3828     if (0 == GNUNET_CONTAINER_multihashmap_size (applications) &&
3829         GNUNET_SCHEDULER_NO_TASK != announce_applications_task)
3830     {
3831       GNUNET_SCHEDULER_cancel (announce_applications_task);
3832       announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
3833     }
3834     if (NULL != c->types)
3835       GNUNET_CONTAINER_multihashmap_destroy (c->types);
3836     next = c->next;
3837     GNUNET_CONTAINER_DLL_remove (clients, clients_tail, c);
3838     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT FREE at %p\n", c);
3839     GNUNET_free (c);
3840     c = next;
3841   }
3842   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   done!\n");
3843   return;
3844 }
3845
3846
3847 /**
3848  * Handler for new clients
3849  *
3850  * @param cls closure
3851  * @param client identification of the client
3852  * @param message the actual message, which includes messages the client wants
3853  */
3854 static void
3855 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
3856                          const struct GNUNET_MessageHeader *message)
3857 {
3858   struct GNUNET_MESH_ClientConnect *cc_msg;
3859   struct MeshClient *c;
3860   GNUNET_MESH_ApplicationType *a;
3861   unsigned int size;
3862   uint16_t ntypes;
3863   uint16_t *t;
3864   uint16_t napps;
3865   uint16_t i;
3866
3867   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected\n");
3868   /* Check data sanity */
3869   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
3870   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
3871   ntypes = ntohs (cc_msg->types);
3872   napps = ntohs (cc_msg->applications);
3873   if (size !=
3874       ntypes * sizeof (uint16_t) + napps * sizeof (GNUNET_MESH_ApplicationType))
3875   {
3876     GNUNET_break (0);
3877     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3878     return;
3879   }
3880
3881   /* Create new client structure */
3882   c = GNUNET_malloc (sizeof (struct MeshClient));
3883   c->id = next_client_id++;
3884   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT NEW %u\n", c->id);
3885   c->handle = client;
3886   GNUNET_SERVER_client_keep (client);
3887   a = (GNUNET_MESH_ApplicationType *) &cc_msg[1];
3888   if (napps > 0)
3889   {
3890     GNUNET_MESH_ApplicationType at;
3891     GNUNET_HashCode hc;
3892
3893     c->apps = GNUNET_CONTAINER_multihashmap_create (napps);
3894     for (i = 0; i < napps; i++)
3895     {
3896       at = ntohl (a[i]);
3897       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  app type: %u\n", at);
3898       GNUNET_CRYPTO_hash (&at, sizeof (at), &hc);
3899       /* store in clients hashmap */
3900       GNUNET_CONTAINER_multihashmap_put (c->apps, &hc, c,
3901                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3902       /* store in global hashmap, for announcements */
3903       GNUNET_CONTAINER_multihashmap_put (applications, &hc, c,
3904                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3905     }
3906     if (GNUNET_SCHEDULER_NO_TASK == announce_applications_task)
3907       announce_applications_task =
3908           GNUNET_SCHEDULER_add_now (&announce_applications, NULL);
3909
3910   }
3911   if (ntypes > 0)
3912   {
3913     uint16_t u16;
3914     GNUNET_HashCode hc;
3915
3916     t = (uint16_t *) & a[napps];
3917     c->types = GNUNET_CONTAINER_multihashmap_create (ntypes);
3918     for (i = 0; i < ntypes; i++)
3919     {
3920       u16 = ntohs (t[i]);
3921       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  msg type: %u\n", u16);
3922       GNUNET_CRYPTO_hash (&u16, sizeof (u16), &hc);
3923
3924       /* store in clients hashmap */
3925       GNUNET_CONTAINER_multihashmap_put (c->types, &hc, c,
3926                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3927       /* store in global hashmap */
3928       GNUNET_CONTAINER_multihashmap_put (types, &hc, c,
3929                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3930     }
3931   }
3932   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3933               " client has %u+%u subscriptions\n", napps, ntypes);
3934
3935   GNUNET_CONTAINER_DLL_insert (clients, clients_tail, c);
3936   c->own_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
3937   c->incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
3938   c->ignore_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
3939   GNUNET_SERVER_notification_context_add (nc, client);
3940
3941   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3942   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
3943 }
3944
3945
3946 /**
3947  * Handler for requests of new tunnels
3948  *
3949  * @param cls closure
3950  * @param client identification of the client
3951  * @param message the actual message
3952  */
3953 static void
3954 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
3955                             const struct GNUNET_MessageHeader *message)
3956 {
3957   struct GNUNET_MESH_TunnelMessage *t_msg;
3958   struct MeshTunnel *t;
3959   struct MeshClient *c;
3960
3961   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel requested\n");
3962
3963   /* Sanity check for client registration */
3964   if (NULL == (c = client_get (client)))
3965   {
3966     GNUNET_break (0);
3967     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3968     return;
3969   }
3970   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
3971
3972   /* Message sanity check */
3973   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
3974   {
3975     GNUNET_break (0);
3976     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3977     return;
3978   }
3979
3980   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
3981   /* Sanity check for tunnel numbering */
3982   if (0 == (ntohl (t_msg->tunnel_id) & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
3983   {
3984     GNUNET_break (0);
3985     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3986     return;
3987   }
3988   /* Sanity check for duplicate tunnel IDs */
3989   if (NULL != tunnel_get_by_local_id (c, ntohl (t_msg->tunnel_id)))
3990   {
3991     GNUNET_break (0);
3992     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3993     return;
3994   }
3995
3996   while (NULL != tunnel_get_by_pi (myid, next_tid))
3997     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
3998   t = tunnel_new (myid, next_tid++, c, ntohl (t_msg->tunnel_id));
3999   next_tid = next_tid & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
4000   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED TUNNEL %s [%x] (%x)\n",
4001               GNUNET_i2s (&my_full_id), t->id.tid, t->local_tid);
4002   t->peers = GNUNET_CONTAINER_multihashmap_create (32);
4003
4004   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel created\n");
4005   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4006   return;
4007 }
4008
4009
4010 /**
4011  * Handler for requests of deleting tunnels
4012  *
4013  * @param cls closure
4014  * @param client identification of the client
4015  * @param message the actual message
4016  */
4017 static void
4018 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
4019                              const struct GNUNET_MessageHeader *message)
4020 {
4021   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
4022   struct MeshClient *c;
4023   struct MeshTunnel *t;
4024   MESH_TunnelNumber tid;
4025
4026   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4027               "Got a DESTROY TUNNEL from client!\n");
4028
4029   /* Sanity check for client registration */
4030   if (NULL == (c = client_get (client)))
4031   {
4032     GNUNET_break (0);
4033     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4034     return;
4035   }
4036   /* Message sanity check */
4037   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
4038   {
4039     GNUNET_break (0);
4040     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4041     return;
4042   }
4043   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
4044   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
4045
4046   /* Retrieve tunnel */
4047   tid = ntohl (tunnel_msg->tunnel_id);
4048   t = tunnel_get_by_local_id(c, tid);
4049   if (NULL == t)
4050   {
4051     GNUNET_break (0);
4052     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
4053     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4054     return;
4055   }
4056   if (c != t->owner || tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
4057   {
4058     client_ignore_tunnel (c, t);
4059 #if 0
4060     // TODO: when to destroy incoming tunnel?
4061     if (t->nclients == 0)
4062     {
4063       GNUNET_assert (GNUNET_YES ==
4064                      GNUNET_CONTAINER_multihashmap_remove (incoming_tunnels,
4065                                                            &hash, t));
4066       GNUNET_assert (GNUNET_YES ==
4067                      GNUNET_CONTAINER_multihashmap_remove (t->peers,
4068                                                            &my_full_id.hashPubKey,
4069                                                            t));
4070     }
4071 #endif
4072     GNUNET_SERVER_receive_done (client, GNUNET_OK);
4073     return;
4074   }
4075   send_client_tunnel_disconnect(t, c);
4076   client_delete_tunnel(c, t);
4077
4078   /* Don't try to ACK the client about the tunnel_destroy multicast packet */
4079   t->owner = NULL;
4080   tunnel_send_destroy (t);
4081   tunnel_destroy (t);
4082   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4083   return;
4084 }
4085
4086
4087 /**
4088  * Handler for connection requests to new peers
4089  *
4090  * @param cls closure
4091  * @param client identification of the client
4092  * @param message the actual message (PeerControl)
4093  */
4094 static void
4095 handle_local_connect_add (void *cls, struct GNUNET_SERVER_Client *client,
4096                           const struct GNUNET_MessageHeader *message)
4097 {
4098   struct GNUNET_MESH_PeerControl *peer_msg;
4099   struct MeshPeerInfo *peer_info;
4100   struct MeshClient *c;
4101   struct MeshTunnel *t;
4102   MESH_TunnelNumber tid;
4103
4104   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got connection request\n");
4105   /* Sanity check for client registration */
4106   if (NULL == (c = client_get (client)))
4107   {
4108     GNUNET_break (0);
4109     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4110     return;
4111   }
4112
4113   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
4114   /* Sanity check for message size */
4115   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
4116   {
4117     GNUNET_break (0);
4118     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4119     return;
4120   }
4121
4122   /* Tunnel exists? */
4123   tid = ntohl (peer_msg->tunnel_id);
4124   t = tunnel_get_by_local_id (c, tid);
4125   if (NULL == t)
4126   {
4127     GNUNET_break (0);
4128     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4129     return;
4130   }
4131
4132   /* Does client own tunnel? */
4133   if (t->owner->handle != client)
4134   {
4135     GNUNET_break (0);
4136     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4137     return;
4138   }
4139   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "     for %s\n",
4140               GNUNET_i2s (&peer_msg->peer));
4141   peer_info = peer_info_get (&peer_msg->peer);
4142
4143   tunnel_add_peer (t, peer_info);
4144   peer_info_connect (peer_info, t);
4145
4146   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4147   return;
4148 }
4149
4150
4151 /**
4152  * Handler for disconnection requests of peers in a tunnel
4153  *
4154  * @param cls closure
4155  * @param client identification of the client
4156  * @param message the actual message (PeerControl)
4157  */
4158 static void
4159 handle_local_connect_del (void *cls, struct GNUNET_SERVER_Client *client,
4160                           const struct GNUNET_MessageHeader *message)
4161 {
4162   struct GNUNET_MESH_PeerControl *peer_msg;
4163   struct MeshPeerInfo *peer_info;
4164   struct MeshClient *c;
4165   struct MeshTunnel *t;
4166   MESH_TunnelNumber tid;
4167
4168   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER DEL request\n");
4169   /* Sanity check for client registration */
4170   if (NULL == (c = client_get (client)))
4171   {
4172     GNUNET_break (0);
4173     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4174     return;
4175   }
4176   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
4177   /* Sanity check for message size */
4178   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
4179   {
4180     GNUNET_break (0);
4181     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4182     return;
4183   }
4184
4185   /* Tunnel exists? */
4186   tid = ntohl (peer_msg->tunnel_id);
4187   t = tunnel_get_by_local_id (c, tid);
4188   if (NULL == t)
4189   {
4190     GNUNET_break (0);
4191     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4192     return;
4193   }
4194   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
4195
4196   /* Does client own tunnel? */
4197   if (t->owner->handle != client)
4198   {
4199     GNUNET_break (0);
4200     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4201     return;
4202   }
4203
4204   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for peer %s\n",
4205               GNUNET_i2s (&peer_msg->peer));
4206   /* Is the peer in the tunnel? */
4207   peer_info =
4208       GNUNET_CONTAINER_multihashmap_get (t->peers, &peer_msg->peer.hashPubKey);
4209   if (NULL == peer_info)
4210   {
4211     GNUNET_break (0);
4212     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4213     return;
4214   }
4215
4216   /* Ok, delete peer from tunnel */
4217   GNUNET_CONTAINER_multihashmap_remove_all (t->peers,
4218                                             &peer_msg->peer.hashPubKey);
4219
4220   send_destroy_path (t, peer_info->id);
4221   tunnel_delete_peer (t, peer_info->id);
4222   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4223   return;
4224 }
4225
4226
4227 /**
4228  * Handler for connection requests to new peers by type
4229  *
4230  * @param cls closure
4231  * @param client identification of the client
4232  * @param message the actual message (ConnectPeerByType)
4233  */
4234 static void
4235 handle_local_connect_by_type (void *cls, struct GNUNET_SERVER_Client *client,
4236                               const struct GNUNET_MessageHeader *message)
4237 {
4238   struct GNUNET_MESH_ConnectPeerByType *connect_msg;
4239   struct MeshClient *c;
4240   struct MeshTunnel *t;
4241   GNUNET_HashCode hash;
4242   MESH_TunnelNumber tid;
4243
4244   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got connect by type request\n");
4245   /* Sanity check for client registration */
4246   if (NULL == (c = client_get (client)))
4247   {
4248     GNUNET_break (0);
4249     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4250     return;
4251   }
4252
4253   connect_msg = (struct GNUNET_MESH_ConnectPeerByType *) message;
4254   /* Sanity check for message size */
4255   if (sizeof (struct GNUNET_MESH_ConnectPeerByType) !=
4256       ntohs (connect_msg->header.size))
4257   {
4258     GNUNET_break (0);
4259     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4260     return;
4261   }
4262
4263   /* Tunnel exists? */
4264   tid = ntohl (connect_msg->tunnel_id);
4265   t = tunnel_get_by_local_id (c, tid);
4266   if (NULL == t)
4267   {
4268     GNUNET_break (0);
4269     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4270     return;
4271   }
4272
4273   /* Does client own tunnel? */
4274   if (t->owner->handle != client)
4275   {
4276     GNUNET_break (0);
4277     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4278     return;
4279   }
4280
4281   /* Do WE have the service? */
4282   t->type = ntohl (connect_msg->type);
4283   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " type requested: %u\n", t->type);
4284   GNUNET_CRYPTO_hash (&t->type, sizeof (GNUNET_MESH_ApplicationType), &hash);
4285   if (GNUNET_CONTAINER_multihashmap_contains (applications, &hash) ==
4286       GNUNET_YES)
4287   {
4288     /* Yes! Fast forward, add ourselves to the tunnel and send the
4289      * good news to the client, and alert the destination client of
4290      * an incoming tunnel.
4291      *
4292      * FIXME send a path create to self, avoid code duplication
4293      */
4294     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " available locally\n");
4295     GNUNET_CONTAINER_multihashmap_put (t->peers, &my_full_id.hashPubKey,
4296                                        peer_info_get (&my_full_id),
4297                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
4298
4299     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " notifying client\n");
4300     send_client_peer_connected (t, myid);
4301     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Done\n");
4302     GNUNET_SERVER_receive_done (client, GNUNET_OK);
4303
4304     t->local_tid_dest = next_local_tid++;
4305     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
4306     GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
4307                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
4308
4309     return;
4310   }
4311   /* Ok, lets find a peer offering the service */
4312   if (NULL != t->dht_get_type)
4313   {
4314     GNUNET_DHT_get_stop (t->dht_get_type);
4315   }
4316   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " looking in DHT for %s\n",
4317               GNUNET_h2s (&hash));
4318   t->dht_get_type =
4319       GNUNET_DHT_get_start (dht_handle, 
4320                             GNUNET_BLOCK_TYPE_TEST, &hash, 10,
4321                             GNUNET_DHT_RO_RECORD_ROUTE |
4322                             GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE, NULL, 0,
4323                             &dht_get_type_handler, t);
4324
4325   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4326   return;
4327 }
4328
4329
4330 /**
4331  * Handler for client traffic directed to one peer
4332  *
4333  * @param cls closure
4334  * @param client identification of the client
4335  * @param message the actual message
4336  */
4337 static void
4338 handle_local_unicast (void *cls, struct GNUNET_SERVER_Client *client,
4339                       const struct GNUNET_MessageHeader *message)
4340 {
4341   struct MeshClient *c;
4342   struct MeshTunnel *t;
4343   struct MeshPeerInfo *pi;
4344   struct GNUNET_MESH_Unicast *data_msg;
4345   MESH_TunnelNumber tid;
4346   size_t size;
4347
4348   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4349               "Got a unicast request from a client!\n");
4350
4351   /* Sanity check for client registration */
4352   if (NULL == (c = client_get (client)))
4353   {
4354     GNUNET_break (0);
4355     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4356     return;
4357   }
4358   data_msg = (struct GNUNET_MESH_Unicast *) message;
4359   /* Sanity check for message size */
4360   size = ntohs (message->size);
4361   if (sizeof (struct GNUNET_MESH_Unicast) +
4362       sizeof (struct GNUNET_MessageHeader) > size)
4363   {
4364     GNUNET_break (0);
4365     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4366     return;
4367   }
4368
4369   /* Tunnel exists? */
4370   tid = ntohl (data_msg->tid);
4371   t = tunnel_get_by_local_id (c, tid);
4372   if (NULL == t)
4373   {
4374     GNUNET_break (0);
4375     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4376     return;
4377   }
4378
4379   /*  Is it a local tunnel? Then, does client own the tunnel? */
4380   if (t->owner->handle != client)
4381   {
4382     GNUNET_break (0);
4383     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4384     return;
4385   }
4386
4387   pi = GNUNET_CONTAINER_multihashmap_get (t->peers,
4388                                           &data_msg->destination.hashPubKey);
4389   /* Is the selected peer in the tunnel? */
4390   if (NULL == pi)
4391   {
4392     GNUNET_break (0);
4393     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4394     return;
4395   }
4396
4397   /* Ok, everything is correct, send the message
4398    * (pretend we got it from a mesh peer)
4399    */
4400   {
4401     char buf[ntohs (message->size)] GNUNET_ALIGN;
4402     struct GNUNET_MESH_Unicast *copy;
4403
4404     /* Work around const limitation */
4405     copy = (struct GNUNET_MESH_Unicast *) buf;
4406     memcpy (buf, data_msg, size);
4407     copy->oid = my_full_id;
4408     copy->tid = htonl (t->id.tid);
4409     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4410                 "  calling generic handler...\n");
4411     handle_mesh_data_unicast (NULL, &my_full_id, &copy->header, NULL, 0);
4412   }
4413   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4414   return;
4415 }
4416
4417
4418 /**
4419  * Handler for client traffic directed to the origin
4420  *
4421  * @param cls closure
4422  * @param client identification of the client
4423  * @param message the actual message
4424  */
4425 static void
4426 handle_local_to_origin (void *cls, struct GNUNET_SERVER_Client *client,
4427                         const struct GNUNET_MessageHeader *message)
4428 {
4429   struct GNUNET_MESH_ToOrigin *data_msg;
4430   struct GNUNET_PeerIdentity id;
4431   struct MeshClient *c;
4432   struct MeshTunnel *t;
4433   MESH_TunnelNumber tid;
4434   size_t size;
4435
4436   /* Sanity check for client registration */
4437   if (NULL == (c = client_get (client)))
4438   {
4439     GNUNET_break (0);
4440     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4441     return;
4442   }
4443   data_msg = (struct GNUNET_MESH_ToOrigin *) message;
4444   /* Sanity check for message size */
4445   size = ntohs (message->size);
4446   if (sizeof (struct GNUNET_MESH_ToOrigin) +
4447       sizeof (struct GNUNET_MessageHeader) > size)
4448   {
4449     GNUNET_break (0);
4450     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4451     return;
4452   }
4453
4454   /* Tunnel exists? */
4455   tid = ntohl (data_msg->tid);
4456   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4457               "Got a ToOrigin request from a client! Tunnel %X\n", tid);
4458   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
4459   {
4460     GNUNET_break (0);
4461     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4462     return;
4463   }
4464   t = tunnel_get_by_local_id (c, tid);
4465   if (NULL == t)
4466   {
4467     GNUNET_break (0);
4468     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4469     return;
4470   }
4471
4472   /*  It should be sent by someone who has this as incoming tunnel. */
4473   if (-1 == client_knows_tunnel (c, t))
4474   {
4475     GNUNET_break (0);
4476     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4477     return;
4478   }
4479   GNUNET_PEER_resolve (t->id.oid, &id);
4480
4481   /* Ok, everything is correct, send the message
4482    * (pretend we got it from a mesh peer)
4483    */
4484   {
4485     char buf[ntohs (message->size)] GNUNET_ALIGN;
4486     struct GNUNET_MESH_ToOrigin *copy;
4487
4488     /* Work around const limitation */
4489     copy = (struct GNUNET_MESH_ToOrigin *) buf;
4490     memcpy (buf, data_msg, size);
4491     copy->oid = id;
4492     copy->tid = htonl (t->id.tid);
4493     copy->sender = my_full_id;
4494     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4495                 "  calling generic handler...\n");
4496     handle_mesh_data_to_orig (NULL, &my_full_id, &copy->header, NULL, 0);
4497   }
4498   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4499   return;
4500 }
4501
4502
4503 /**
4504  * Handler for client traffic directed to all peers in a tunnel
4505  *
4506  * @param cls closure
4507  * @param client identification of the client
4508  * @param message the actual message
4509  */
4510 static void
4511 handle_local_multicast (void *cls, struct GNUNET_SERVER_Client *client,
4512                         const struct GNUNET_MessageHeader *message)
4513 {
4514   struct MeshClient *c;
4515   struct MeshTunnel *t;
4516   struct GNUNET_MESH_Multicast *data_msg;
4517   MESH_TunnelNumber tid;
4518
4519   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4520               "Got a multicast request from a client!\n");
4521
4522   /* Sanity check for client registration */
4523   if (NULL == (c = client_get (client)))
4524   {
4525     GNUNET_break (0);
4526     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4527     return;
4528   }
4529   data_msg = (struct GNUNET_MESH_Multicast *) message;
4530   /* Sanity check for message size */
4531   if (sizeof (struct GNUNET_MESH_Multicast) +
4532       sizeof (struct GNUNET_MessageHeader) > ntohs (data_msg->header.size))
4533   {
4534     GNUNET_break (0);
4535     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4536     return;
4537   }
4538
4539   /* Tunnel exists? */
4540   tid = ntohl (data_msg->tid);
4541   t = tunnel_get_by_local_id (c, tid);
4542   if (NULL == t)
4543   {
4544     GNUNET_break (0);
4545     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4546     return;
4547   }
4548
4549   /* Does client own tunnel? */
4550   if (t->owner->handle != client)
4551   {
4552     GNUNET_break (0);
4553     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4554     return;
4555   }
4556
4557   {
4558     char buf[ntohs (message->size)] GNUNET_ALIGN;
4559     struct GNUNET_MESH_Multicast *copy;
4560
4561     copy = (struct GNUNET_MESH_Multicast *) buf;
4562     memcpy (buf, message, ntohs (message->size));
4563     copy->oid = my_full_id;
4564     copy->tid = htonl (t->id.tid);
4565     copy->ttl = htonl (DEFAULT_TTL);
4566     copy->mid = htonl (t->mid + 1);
4567     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4568                 "  calling generic handler...\n");
4569     handle_mesh_data_multicast (client, &my_full_id, &copy->header, NULL, 0);
4570   }
4571
4572   /* receive done gets called when last copy is sent to a neighbor */
4573   return;
4574 }
4575
4576 /**
4577  * Functions to handle messages from clients
4578  */
4579 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
4580   {&handle_local_new_client, NULL,
4581    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
4582   {&handle_local_tunnel_create, NULL,
4583    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
4584    sizeof (struct GNUNET_MESH_TunnelMessage)},
4585   {&handle_local_tunnel_destroy, NULL,
4586    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
4587    sizeof (struct GNUNET_MESH_TunnelMessage)},
4588   {&handle_local_connect_add, NULL,
4589    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD,
4590    sizeof (struct GNUNET_MESH_PeerControl)},
4591   {&handle_local_connect_del, NULL,
4592    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL,
4593    sizeof (struct GNUNET_MESH_PeerControl)},
4594   {&handle_local_connect_by_type, NULL,
4595    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE,
4596    sizeof (struct GNUNET_MESH_ConnectPeerByType)},
4597   {&handle_local_unicast, NULL,
4598    GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
4599   {&handle_local_to_origin, NULL,
4600    GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
4601   {&handle_local_multicast, NULL,
4602    GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
4603   {NULL, NULL, 0, 0}
4604 };
4605
4606
4607 /**
4608  * To be called on core init/fail.
4609  *
4610  * @param cls service closure
4611  * @param server handle to the server for this service
4612  * @param identity the public identity of this peer
4613  */
4614 static void
4615 core_init (void *cls, struct GNUNET_CORE_Handle *server,
4616            const struct GNUNET_PeerIdentity *identity)
4617 {
4618   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
4619   core_handle = server;
4620   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)) ||
4621       NULL == server)
4622   {
4623     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
4624     GNUNET_SCHEDULER_shutdown ();
4625   }
4626   return;
4627 }
4628
4629 /**
4630  * Method called whenever a given peer connects.
4631  *
4632  * @param cls closure
4633  * @param peer peer identity this notification is about
4634  * @param atsi performance data for the connection
4635  * @param atsi_count number of records in 'atsi'
4636  */
4637 static void
4638 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
4639               const struct GNUNET_ATS_Information *atsi,
4640               unsigned int atsi_count)
4641 {
4642   struct MeshPeerInfo *peer_info;
4643   struct MeshPeerPath *path;
4644
4645   DEBUG_CONN ("Peer connected\n");
4646   DEBUG_CONN ("     %s\n", GNUNET_i2s (&my_full_id));
4647   peer_info = peer_info_get (peer);
4648   if (myid == peer_info->id)
4649   {
4650     DEBUG_CONN ("     (self)\n");
4651     return;
4652   }
4653   else
4654   {
4655     DEBUG_CONN ("     %s\n", GNUNET_i2s (peer));
4656   }
4657   path = path_new (2);
4658   path->peers[0] = myid;
4659   path->peers[1] = peer_info->id;
4660   GNUNET_PEER_change_rc (myid, 1);
4661   GNUNET_PEER_change_rc (peer_info->id, 1);
4662   peer_info_add_path (peer_info, path, GNUNET_YES);
4663   return;
4664 }
4665
4666 /**
4667  * Method called whenever a peer disconnects.
4668  *
4669  * @param cls closure
4670  * @param peer peer identity this notification is about
4671  */
4672 static void
4673 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
4674 {
4675   struct MeshPeerInfo *pi;
4676   struct MeshPeerQueue *q;
4677   struct MeshPeerQueue *n;
4678
4679   DEBUG_CONN ("Peer disconnected\n");
4680   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
4681   if (NULL == pi)
4682   {
4683     GNUNET_break (0);
4684     return;
4685   }
4686   q = pi->queue_head;
4687   while (NULL != q)
4688   {
4689       n = q->next;
4690       if (q->peer == pi)
4691       {
4692         /* try to reroute this traffic instead */
4693         queue_destroy(q, GNUNET_YES);
4694       }
4695       q = n;
4696   }
4697   peer_info_remove_path (pi, pi->id, myid);
4698   if (myid == pi->id)
4699   {
4700     DEBUG_CONN ("     (self)\n");
4701   }
4702   return;
4703 }
4704
4705
4706 /******************************************************************************/
4707 /************************      MAIN FUNCTIONS      ****************************/
4708 /******************************************************************************/
4709
4710 /**
4711  * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
4712  *
4713  * @param cls closure
4714  * @param key current key code
4715  * @param value value in the hash map
4716  * @return GNUNET_YES if we should continue to iterate,
4717  *         GNUNET_NO if not.
4718  */
4719 static int
4720 shutdown_tunnel (void *cls, const GNUNET_HashCode * key, void *value)
4721 {
4722   struct MeshTunnel *t = value;
4723
4724   tunnel_destroy (t);
4725   return GNUNET_YES;
4726 }
4727
4728 /**
4729  * Iterator over peer hash map entries to destroy the tunnel during shutdown.
4730  *
4731  * @param cls closure
4732  * @param key current key code
4733  * @param value value in the hash map
4734  * @return GNUNET_YES if we should continue to iterate,
4735  *         GNUNET_NO if not.
4736  */
4737 static int
4738 shutdown_peer (void *cls, const GNUNET_HashCode * key, void *value)
4739 {
4740   struct MeshPeerInfo *p = value;
4741   struct MeshPeerQueue *q;
4742   struct MeshPeerQueue *n;
4743
4744   q = p->queue_head;
4745   while (NULL != q)
4746   {
4747       n = q->next;
4748       if (q->peer == p)
4749       {
4750         queue_destroy(q, GNUNET_YES);
4751       }
4752       q = n;
4753   }
4754   peer_info_destroy (p);
4755   return GNUNET_YES;
4756 }
4757
4758 /**
4759  * Task run during shutdown.
4760  *
4761  * @param cls unused
4762  * @param tc unused
4763  */
4764 static void
4765 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4766 {
4767   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
4768
4769   if (core_handle != NULL)
4770   {
4771     GNUNET_CORE_disconnect (core_handle);
4772     core_handle = NULL;
4773   }
4774   GNUNET_CONTAINER_multihashmap_iterate (tunnels, &shutdown_tunnel, NULL);
4775   GNUNET_CONTAINER_multihashmap_iterate (peers, &shutdown_peer, NULL);
4776   if (dht_handle != NULL)
4777   {
4778     GNUNET_DHT_disconnect (dht_handle);
4779     dht_handle = NULL;
4780   }
4781   if (nc != NULL)
4782   {
4783     GNUNET_SERVER_notification_context_destroy (nc);
4784     nc = NULL;
4785   }
4786   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
4787   {
4788     GNUNET_SCHEDULER_cancel (announce_id_task);
4789     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
4790   }
4791   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
4792 }
4793
4794 /**
4795  * Process mesh requests.
4796  *
4797  * @param cls closure
4798  * @param server the initialized server
4799  * @param c configuration to use
4800  */
4801 static void
4802 run (void *cls, struct GNUNET_SERVER_Handle *server,
4803      const struct GNUNET_CONFIGURATION_Handle *c)
4804 {
4805   struct MeshPeerInfo *peer;
4806   struct MeshPeerPath *p;
4807   char *keyfile;
4808
4809   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
4810   server_handle = server;
4811   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
4812                                      NULL,      /* Closure passed to MESH functions */
4813                                      &core_init,        /* Call core_init once connected */
4814                                      &core_connect,     /* Handle connects */
4815                                      &core_disconnect,  /* remove peers on disconnects */
4816                                      NULL,      /* Don't notify about all incoming messages */
4817                                      GNUNET_NO, /* For header only in notification */
4818                                      NULL,      /* Don't notify about all outbound messages */
4819                                      GNUNET_NO, /* For header-only out notification */
4820                                      core_handlers);    /* Register these handlers */
4821
4822   if (core_handle == NULL)
4823   {
4824     GNUNET_break (0);
4825     GNUNET_SCHEDULER_shutdown ();
4826     return;
4827   }
4828
4829   if (GNUNET_OK !=
4830       GNUNET_CONFIGURATION_get_value_filename (c, "GNUNETD", "HOSTKEY",
4831                                                &keyfile))
4832   {
4833     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4834                 _
4835                 ("Mesh service is lacking key configuration settings.  Exiting.\n"));
4836     GNUNET_SCHEDULER_shutdown ();
4837     return;
4838   }
4839   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
4840   GNUNET_free (keyfile);
4841   if (my_private_key == NULL)
4842   {
4843     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4844                 _("Mesh service could not access hostkey.  Exiting.\n"));
4845     GNUNET_SCHEDULER_shutdown ();
4846     return;
4847   }
4848   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
4849   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
4850                       &my_full_id.hashPubKey);
4851   myid = GNUNET_PEER_intern (&my_full_id);
4852
4853 //   transport_handle = GNUNET_TRANSPORT_connect(c,
4854 //                                               &my_full_id,
4855 //                                               NULL,
4856 //                                               NULL,
4857 //                                               NULL,
4858 //                                               NULL);
4859
4860   dht_handle = GNUNET_DHT_connect (c, 64);
4861   if (dht_handle == NULL)
4862   {
4863     GNUNET_break (0);
4864   }
4865
4866   next_tid = 0;
4867   next_local_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
4868
4869   tunnels = GNUNET_CONTAINER_multihashmap_create (32);
4870   incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
4871   peers = GNUNET_CONTAINER_multihashmap_create (32);
4872   applications = GNUNET_CONTAINER_multihashmap_create (32);
4873   types = GNUNET_CONTAINER_multihashmap_create (32);
4874
4875   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
4876   nc = GNUNET_SERVER_notification_context_create (server_handle,
4877                                                   LOCAL_QUEUE_SIZE);
4878   GNUNET_SERVER_disconnect_notify (server_handle,
4879                                    &handle_local_client_disconnect, NULL);
4880
4881
4882   clients = NULL;
4883   clients_tail = NULL;
4884   next_client_id = 0;
4885
4886   announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
4887   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
4888
4889   /* Create a peer_info for the local peer */
4890   peer = peer_info_get (&my_full_id);
4891   p = path_new (1);
4892   p->peers[0] = myid;
4893   GNUNET_PEER_change_rc (myid, 1);
4894   peer_info_add_path (peer, p, GNUNET_YES);
4895
4896   /* Scheduled the task to clean up when shutdown is called */
4897   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
4898                                 NULL);
4899
4900   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "end of run()\n");
4901 }
4902
4903 /**
4904  * The main function for the mesh service.
4905  *
4906  * @param argc number of arguments from the command line
4907  * @param argv command line arguments
4908  * @return 0 ok, 1 on error
4909  */
4910 int
4911 main (int argc, char *const *argv)
4912 {
4913   int ret;
4914
4915   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
4916   ret =
4917       (GNUNET_OK ==
4918        GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
4919                            NULL)) ? 0 : 1;
4920   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");
4921
4922   return ret;
4923 }