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