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