68162284a9e6f3c552b06b350e358bba02575df5
[oweals/gnunet.git] / src / mesh / gnunet-service-mesh.c
1 /*
2      This file is part of GNUnet.
3      (C) 2001 - 2011 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file mesh/gnunet-service-mesh.c
23  * @brief GNUnet MESH service
24  * @author Bartlomiej Polot
25  *
26  * STRUCTURE:
27  * - DATA STRUCTURES
28  * - GLOBAL VARIABLES
29  * - GENERAL HELPERS
30  * - PERIODIC FUNCTIONS
31  * - MESH NETWORK HANDLER HELPERS
32  * - MESH NETWORK HANDLES
33  * - MESH LOCAL HANDLER HELPERS
34  * - MESH LOCAL HANDLES
35  * - MAIN FUNCTIONS (main & run)
36  *
37  * TODO:
38  * - error reporting (CREATE/CHANGE/ADD/DEL?) -- new message!
39  * - partial disconnect reporting -- same as error reporting?
40  * - add vs create? change vs. keep-alive? same msg or different ones? -- thinking...
41  * - add ping message
42  * - relay corking down to core
43  * - set ttl relative to tree depth
44  * - Add data ACK count in path ACK
45  * TODO END
46  */
47
48 #include "platform.h"
49 #include "mesh.h"
50 #include "mesh_protocol.h"
51 #include "mesh_tunnel_tree.h"
52 #include "block_mesh.h"
53 #include "mesh_block_lib.h"
54 #include "gnunet_dht_service.h"
55 #include "gnunet_statistics_service.h"
56 #include "gnunet_regex_lib.h"
57
58 #define MESH_BLOOM_SIZE         128
59
60 #define MESH_DEBUG_DHT          GNUNET_YES
61 #define MESH_DEBUG_CONNECTION   GNUNET_NO
62
63 #define INITIAL_WINDOW_SIZE     2
64 #define ACK_THRESHOLD           INITIAL_WINDOW_SIZE / 2
65
66 #if MESH_DEBUG_CONNECTION
67 #define DEBUG_CONN(...) GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
68 #else
69 #define DEBUG_CONN(...)
70 #endif
71
72 #if MESH_DEBUG_DHT
73 #define DEBUG_DHT(...) GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
74 #else
75 #define DEBUG_DHT(...)
76 #endif
77
78 /******************************************************************************/
79 /************************      DATA STRUCTURES     ****************************/
80 /******************************************************************************/
81
82 /** FWD declaration */
83 struct MeshPeerInfo;
84 struct MeshClient;
85
86
87 /**
88  * Struct representing a piece of data being sent to other peers
89  */
90 struct MeshData
91 {
92   /** Tunnel it belongs to. */
93   struct MeshTunnel *t;
94
95   /** In case of a multicast, task to allow a client to send more data if
96    * some neighbor is too slow. */
97   GNUNET_SCHEDULER_TaskIdentifier *task;
98
99   /** How many remaining neighbors we need to send this to. */
100   unsigned int *reference_counter;
101
102   /** Size of the data. */
103   size_t data_len;
104
105   /** Data itself */
106   void *data;
107 };
108
109
110 /**
111  * Struct containing info about a queued transmission to this peer
112  */
113 struct MeshPeerQueue
114 {
115     /**
116       * DLL next
117       */
118   struct MeshPeerQueue *next;
119
120     /**
121       * DLL previous
122       */
123   struct MeshPeerQueue *prev;
124
125     /**
126      * Peer this transmission is directed to.
127      */
128   struct MeshPeerInfo *peer;
129
130     /**
131      * Tunnel this message belongs to.
132      */
133   struct MeshTunnel *tunnel;
134
135     /**
136      * Pointer to info stucture used as cls.
137      */
138   void *cls;
139
140     /**
141      * Type of message
142      */
143   uint16_t type;
144
145     /**
146      * Size of the message
147      */
148   size_t size;
149 };
150
151
152 /**
153  * Struct containing all info possibly needed to build a package when called
154  * back by core.
155  */
156 struct MeshTransmissionDescriptor
157 {
158     /** ID of the tunnel this packet travels in */
159   struct MESH_TunnelID *origin;
160
161     /** Who was this message being sent to */
162   struct MeshPeerInfo *peer;
163
164     /** Ultimate destination of the packet */
165   GNUNET_PEER_Id destination;
166
167     /** Data descriptor */
168   struct MeshData* mesh_data;
169 };
170
171
172 /**
173  * Struct containing all information regarding a given peer
174  */
175 struct MeshPeerInfo
176 {
177     /**
178      * ID of the peer
179      */
180   GNUNET_PEER_Id id;
181
182     /**
183      * Last time we heard from this peer
184      */
185   struct GNUNET_TIME_Absolute last_contact;
186
187     /**
188      * Number of attempts to reconnect so far
189      */
190   int n_reconnect_attempts;
191
192     /**
193      * Paths to reach the peer, ordered by ascending hop count
194      */
195   struct MeshPeerPath *path_head;
196
197     /**
198      * Paths to reach the peer, ordered by ascending hop count
199      */
200   struct MeshPeerPath *path_tail;
201
202     /**
203      * Handle to stop the DHT search for a path to this peer
204      */
205   struct GNUNET_DHT_GetHandle *dhtget;
206
207     /**
208      * Closure given to the DHT GET
209      */
210   struct MeshPathInfo *dhtgetcls;
211
212     /**
213      * Array of tunnels this peer participates in
214      * (most probably a small amount, therefore not a hashmap)
215      * When the path to the peer changes, notify these tunnels to let them
216      * re-adjust their path trees.
217      */
218   struct MeshTunnel **tunnels;
219
220     /**
221      * Number of tunnels this peers participates in
222      */
223   unsigned int ntunnels;
224
225    /**
226     * Transmission queue to core DLL head
227     */
228   struct MeshPeerQueue *queue_head;
229
230    /**
231     * Transmission queue to core DLL tail
232     */
233    struct MeshPeerQueue *queue_tail;
234
235    /**
236     * How many messages are in the queue to this peer.
237     */
238    unsigned int queue_n;
239
240    /**
241     * Handle to for queued transmissions
242     */
243   struct GNUNET_CORE_TransmitHandle *core_transmit;
244 };
245
246
247 /**
248  * Globally unique tunnel identification (owner + number)
249  * DO NOT USE OVER THE NETWORK
250  */
251 struct MESH_TunnelID
252 {
253     /**
254      * Node that owns the tunnel
255      */
256   GNUNET_PEER_Id oid;
257
258     /**
259      * Tunnel number to differentiate all the tunnels owned by the node oid
260      * ( tid < GNUNET_MESH_LOCAL_TUNNEL_ID_CLI )
261      */
262   MESH_TunnelNumber tid;
263 };
264
265
266 /**
267  * Struct containing all information regarding a tunnel
268  * For an intermediate node the improtant info used will be:
269  * - id        Tunnel unique identification
270  * - paths[0]  To know where to send it next
271  * - metainfo: ready, speeds, accounting
272  */
273 struct MeshTunnel
274 {
275     /**
276      * Tunnel ID
277      */
278   struct MESH_TunnelID id;
279
280     /**
281      * Local tunnel number ( >= GNUNET_MESH_LOCAL_TUNNEL_ID_CLI or 0 )
282      */
283   MESH_TunnelNumber local_tid;
284
285     /**
286      * Local tunnel number for local destination clients (incoming number)
287      * ( >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV or 0). All clients share the same
288      * number.
289      */
290   MESH_TunnelNumber local_tid_dest;
291
292     /**
293      * Is the speed on the tunnel limited to the slowest peer?
294      */
295   int speed_min;
296
297     /**
298      * Is the tunnel bufferless (minimum latency)?
299      */
300   int nobuffer;
301
302     /**
303      * Packet ID of the last fwd packet seen (sent/retransmitted/received).
304      */
305   uint32_t fwd_pid;
306
307     /**
308      * Packet ID of the last bck packet sent (unique counter per hop).
309      */
310   uint32_t bck_pid;
311
312   /**
313      * SKIP value for this tunnel.
314      */
315   uint32_t skip;
316
317     /**
318      * MeshTunnelChildInfo of all children, indexed by GNUNET_PEER_Id.
319      * Contains the Flow Control info: FWD ACK value received,
320      * last BCK ACK sent, PID and SKIP values.
321      */
322   struct GNUNET_CONTAINER_MultiHashMap *children_fc;
323
324     /**
325      * Last ACK sent towards the origin (for traffic towards leaf node).
326      */
327   uint32_t last_fwd_ack;
328
329   /**
330    * BCK ACK value received from the hop towards the owner of the tunnel,
331    * (previous node / owner): up to what message PID can we sent back to him.
332    */
333   uint32_t bck_ack;
334
335     /**
336      * How many messages are in the forward queue (towards leaves).
337      */
338   unsigned int fwd_queue_n;
339
340     /**
341      * How many messages do we accept in the forward queue.
342      */
343   unsigned int fwd_queue_max;
344
345     /**
346      * How many messages are in the backward queue (towards origin).
347      */
348   unsigned int bck_queue_n;
349
350     /**
351      * How many messages do we accept in the backward queue.
352     */
353    unsigned int bck_queue_max;
354
355     /**
356      * Last time the tunnel was used
357      */
358   struct GNUNET_TIME_Absolute timestamp;
359
360     /**
361      * Peers in the tunnel, indexed by PeerIdentity -> (MeshPeerInfo)
362      * containing peers added by id or by type, not intermediate peers.
363      */
364   struct GNUNET_CONTAINER_MultiHashMap *peers;
365
366     /**
367      * Number of peers that are connected and potentially ready to receive data
368      */
369   unsigned int peers_ready;
370
371     /**
372      * Number of peers that have been added to the tunnel
373      */
374   unsigned int peers_total;
375
376     /**
377      * Client owner of the tunnel, if any
378      */
379   struct MeshClient *owner;
380
381     /**
382      * Clients that have been informed about and want to stay in the tunnel.
383      */
384   struct MeshClient **clients;
385
386     /**
387      * Flow control info for each client.
388      */
389   struct MeshTunnelClientInfo *clients_fc;
390
391   /**
392      * Number of elements in clients/clients_fc
393      */
394   unsigned int nclients;
395
396     /**
397      * Clients that have been informed but requested to leave the tunnel.
398      */
399   struct MeshClient **ignore;
400
401     /**
402      * Number of elements in clients
403      */
404   unsigned int nignore;
405
406     /**
407      * Blacklisted peers
408      */
409   GNUNET_PEER_Id *blacklisted;
410
411     /**
412      * Number of elements in blacklisted
413      */
414   unsigned int nblacklisted;
415
416   /**
417    * Bloomfilter (for peer identities) to stop circular routes
418    */
419   char bloomfilter[MESH_BLOOM_SIZE];
420
421   /**
422    * Tunnel paths
423    */
424   struct MeshTunnelTree *tree;
425
426   /**
427    * Application type we are looking for in this tunnel
428    */
429   GNUNET_MESH_ApplicationType type;
430
431     /**
432      * Used to search peers offering a service
433      */
434   struct GNUNET_DHT_GetHandle *dht_get_type;
435
436     /**
437      * Initial context of the regex search for a connect_by_string
438      */
439   struct MeshRegexSearchContext *regex_ctx;
440
441     /**
442      * Task to keep the used paths alive
443      */
444   GNUNET_SCHEDULER_TaskIdentifier path_refresh_task;
445
446     /**
447      * Task to destroy the tunnel after timeout
448      *
449      * FIXME: merge the two? a tunnel will have either
450      * a path refresh OR a timeout, never both!
451      */
452   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
453
454     /**
455      * Flag to signal the destruction of the tunnel.
456      * If this is set GNUNET_YES the tunnel will be destroyed
457      * when the queue is empty.
458      */
459   int destroy;
460 };
461
462
463 /**
464  * Info about a child node in a tunnel, needed to perform flow control.
465  */
466 struct MeshTunnelChildInfo
467 {
468     /**
469      * ID of the child node.
470      */
471   GNUNET_PEER_Id id;
472
473     /**
474      * SKIP value.
475      */
476   uint32_t skip;
477
478     /**
479      * Last sent PID.
480      */
481   uint32_t pid;
482
483     /**
484      * Maximum PID allowed (FWD ACK received).
485      */
486   uint32_t fwd_ack;
487
488     /**
489      * Last ACK sent to that child (BCK ACK).
490      */
491   uint32_t bck_ack;
492 };
493
494
495 /**
496  * Info about a leaf client of a tunnel, needed to perform flow control.
497  */
498 struct MeshTunnelClientInfo
499 {
500   /**
501    * PID of the last packet sent to the client (FWD).
502    */
503   uint32_t fwd_pid;
504
505   /**
506    * PID of the last packet received from the client (BCK).
507    */
508   uint32_t bck_pid;
509
510   /**
511    * Maximum PID allowed (FWD ACK received).
512    */
513   uint32_t fwd_ack;
514   
515   /**
516    * Last ACK sent to that child (BCK ACK).
517    */
518   uint32_t bck_ack;
519 };
520
521
522
523 /**
524  * Info collected during iteration of child nodes in order to get the ACK value
525  * for a tunnel.
526  */
527 struct MeshTunnelChildIteratorContext
528 {
529     /**
530      * Tunnel whose info is being collected.
531      */
532   struct MeshTunnel *t;
533
534     /**
535      * Is this context initialized? Is the value in max_child_ack valid?
536      */
537   int init;
538
539     /**
540      * Maximum child ACK so far.
541      */
542   uint32_t max_child_ack;
543
544     /**
545      * Number of children nodes
546      */
547   unsigned int nchildren;
548 };
549
550
551 /**
552  * Info needed to work with tunnel paths and peers
553  */
554 struct MeshPathInfo
555 {
556   /**
557    * Tunnel
558    */
559   struct MeshTunnel *t;
560
561   /**
562    * Neighbouring peer to whom we send the packet to
563    */
564   struct MeshPeerInfo *peer;
565
566   /**
567    * Path itself
568    */
569   struct MeshPeerPath *path;
570 };
571
572
573 /**
574  * Struct containing information about a client of the service
575  */
576 struct MeshClient
577 {
578     /**
579      * Linked list next
580      */
581   struct MeshClient *next;
582
583     /**
584      * Linked list prev
585      */
586   struct MeshClient *prev;
587
588     /**
589      * Tunnels that belong to this client, indexed by local id
590      */
591   struct GNUNET_CONTAINER_MultiHashMap *own_tunnels;
592
593    /**
594      * Tunnels this client has accepted, indexed by incoming local id
595      */
596   struct GNUNET_CONTAINER_MultiHashMap *incoming_tunnels;
597
598    /**
599      * Tunnels this client has rejected, indexed by incoming local id
600      */
601   struct GNUNET_CONTAINER_MultiHashMap *ignore_tunnels;
602     /**
603      * Handle to communicate with the client
604      */
605   struct GNUNET_SERVER_Client *handle;
606
607     /**
608      * Applications that this client has claimed to provide
609      */
610   struct GNUNET_CONTAINER_MultiHashMap *apps;
611
612     /**
613      * Messages that this client has declared interest in
614      */
615   struct GNUNET_CONTAINER_MultiHashMap *types;
616
617     /**
618      * Whether the client is active or shutting down (don't send confirmations
619      * to a client that is shutting down.
620      */
621   int shutting_down;
622
623     /**
624      * ID of the client, mainly for debug messages
625      */
626   unsigned int id;
627   
628     /**
629      * Regular expressions describing the services offered by this client.
630      */
631   char **regexes; // FIXME add timeout? API to remove a regex?
632
633     /**
634      * Number of regular expressions in regexes.
635      */
636   unsigned int n_regex;
637
638     /**
639      * Task to refresh all regular expresions in the DHT.
640      */
641   GNUNET_SCHEDULER_TaskIdentifier regex_announce_task;
642
643 };
644
645
646 /**
647  * Struct to keep information of searches of services described by a regex
648  * using a user-provided string service description.
649  */
650 struct MeshRegexSearchInfo
651 {
652     /**
653      * Which tunnel is this for
654      */
655   struct MeshTunnel *t;
656
657     /**
658      * User provided description of the searched service.
659      */
660   char *description;
661
662     /**
663      * Part of the description already consumed by the search.
664      */
665   size_t position;
666
667     /**
668      * Running DHT GETs.
669      */
670   struct GNUNET_CONTAINER_MultiHashMap *dht_get_handles;
671
672     /**
673      * Results from running DHT GETs.
674      */
675   struct GNUNET_CONTAINER_MultiHashMap *dht_get_results;
676
677     /**
678      * Contexts, for each running DHT GET. Free all on end of search.
679      */
680   struct MeshRegexSearchContext **contexts;
681
682     /**
683      * Number of contexts (branches/steps in search).
684      */
685   unsigned int n_contexts;
686
687     /**
688      * Peer that is connecting via connect_by_string. When connected, free ctx.
689      */
690   GNUNET_PEER_Id peer;
691
692     /**
693      * Other peers that are found but not yet being connected to.
694      */
695   GNUNET_PEER_Id *peers;
696
697     /**
698      * Number of elements in peers.
699      */
700   unsigned int n_peers;
701
702     /**
703      * Next peer to try to connect to.
704      */
705   unsigned int i_peer;
706
707     /**
708      * Timeout for a connect attempt.
709      * When reached, try to connect to a different peer, if any. If not,
710      * try the same peer again.
711      */
712   GNUNET_SCHEDULER_TaskIdentifier timeout;
713
714 };
715
716 /**
717  * Struct to keep state of running searches that have consumed a part of
718  * the inital string.
719  */
720 struct MeshRegexSearchContext
721 {
722     /**
723      * Part of the description already consumed by
724      * this particular search branch.
725      */
726   size_t position;
727
728     /**
729      * Information about the search.
730      */
731   struct MeshRegexSearchInfo *info;
732
733 };
734
735 /******************************************************************************/
736 /************************      DEBUG FUNCTIONS     ****************************/
737 /******************************************************************************/
738
739 #if MESH_DEBUG
740 /**
741  * GNUNET_SCHEDULER_Task for printing a message after some operation is done
742  * @param cls string to print
743  * @param success  GNUNET_OK if the PUT was transmitted,
744  *                GNUNET_NO on timeout,
745  *                GNUNET_SYSERR on disconnect from service
746  *                after the PUT message was transmitted
747  *                (so we don't know if it was received or not)
748  */
749
750 #if 0
751 static void
752 mesh_debug (void *cls, int success)
753 {
754   char *s = cls;
755
756   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s (%d)\n", s, success);
757 }
758 #endif
759
760 #endif
761
762 /******************************************************************************/
763 /***********************      GLOBAL VARIABLES     ****************************/
764 /******************************************************************************/
765
766
767 /**
768  * Configuration parameters
769  */
770 static struct GNUNET_TIME_Relative refresh_path_time;
771 static struct GNUNET_TIME_Relative app_announce_time;
772 static struct GNUNET_TIME_Relative id_announce_time;
773 static struct GNUNET_TIME_Relative unacknowledged_wait_time;
774 static struct GNUNET_TIME_Relative connect_timeout;
775 static long long unsigned int default_ttl;
776 static long long unsigned int dht_replication_level;
777 static long long unsigned int max_tunnels;
778 static long long unsigned int max_msgs_queue;
779
780 /**
781  * DLL with all the clients, head.
782  */
783 static struct MeshClient *clients;
784
785 /**
786  * DLL with all the clients, tail.
787  */
788 static struct MeshClient *clients_tail;
789
790 /**
791  * Tunnels known, indexed by MESH_TunnelID (MeshTunnel).
792  */
793 static struct GNUNET_CONTAINER_MultiHashMap *tunnels;
794
795 /**
796  * Number of tunnels known.
797  */
798 static unsigned long long n_tunnels;
799
800 /**
801  * Tunnels incoming, indexed by MESH_TunnelNumber
802  * (which is greater than GNUNET_MESH_LOCAL_TUNNEL_ID_SERV).
803  */
804 static struct GNUNET_CONTAINER_MultiHashMap *incoming_tunnels;
805
806 /**
807  * Peers known, indexed by PeerIdentity (MeshPeerInfo).
808  */
809 static struct GNUNET_CONTAINER_MultiHashMap *peers;
810
811 /*
812  * Handle to communicate with transport
813  */
814 // static struct GNUNET_TRANSPORT_Handle *transport_handle;
815
816 /**
817  * Handle to communicate with core.
818  */
819 static struct GNUNET_CORE_Handle *core_handle;
820
821 /**
822  * Handle to use DHT.
823  */
824 static struct GNUNET_DHT_Handle *dht_handle;
825
826 /**
827  * Handle to server.
828  */
829 static struct GNUNET_SERVER_Handle *server_handle;
830
831 /**
832  * Handle to the statistics service.
833  */
834 static struct GNUNET_STATISTICS_Handle *stats;
835
836 /**
837  * Notification context, to send messages to local clients.
838  */
839 static struct GNUNET_SERVER_NotificationContext *nc;
840
841 /**
842  * Local peer own ID (memory efficient handle).
843  */
844 static GNUNET_PEER_Id myid;
845
846 /**
847  * Local peer own ID (full value).
848  */
849 static struct GNUNET_PeerIdentity my_full_id;
850
851 /**
852  * Own private key.
853  */
854 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
855
856 /**
857  * Own public key.
858  */
859 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
860
861 /**
862  * Tunnel ID for the next created tunnel (global tunnel number).
863  */
864 static MESH_TunnelNumber next_tid;
865
866 /**
867  * Tunnel ID for the next incoming tunnel (local tunnel number).
868  */
869 static MESH_TunnelNumber next_local_tid;
870
871 /**
872  * All application types provided by this peer.
873  */
874 static struct GNUNET_CONTAINER_MultiHashMap *applications;
875
876 /**
877  * All message types clients of this peer are interested in.
878  */
879 static struct GNUNET_CONTAINER_MultiHashMap *types;
880
881 /**
882  * Task to periodically announce provided applications.
883  */
884 GNUNET_SCHEDULER_TaskIdentifier announce_applications_task;
885
886 /**
887  * Task to periodically announce itself in the network.
888  */
889 GNUNET_SCHEDULER_TaskIdentifier announce_id_task;
890
891 /**
892  * Next ID to assign to a client.
893  */
894 unsigned int next_client_id;
895
896
897 /******************************************************************************/
898 /***********************         DECLARATIONS        **************************/
899 /******************************************************************************/
900
901 /* FIXME move declarations here */
902
903 /**
904  * Function to process paths received for a new peer addition. The recorded
905  * paths form the initial tunnel, which can be optimized later.
906  * Called on each result obtained for the DHT search.
907  *
908  * @param cls closure
909  * @param exp when will this value expire
910  * @param key key of the result
911  * @param type type of the result
912  * @param size number of bytes in data
913  * @param data pointer to the result data
914  */
915 static void
916 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
917                     const struct GNUNET_HashCode * key,
918                     const struct GNUNET_PeerIdentity *get_path,
919                     unsigned int get_path_length,
920                     const struct GNUNET_PeerIdentity *put_path,
921                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
922                     size_t size, const void *data);
923
924
925 /**
926  * Function to process DHT string to regex matching.
927  * Called on each result obtained for the DHT search.
928  *
929  * @param cls closure (search context)
930  * @param exp when will this value expire
931  * @param key key of the result
932  * @param get_path path of the get request (not used)
933  * @param get_path_length lenght of get_path (not used)
934  * @param put_path path of the put request (not used)
935  * @param put_path_length length of the put_path (not used)
936  * @param type type of the result
937  * @param size number of bytes in data
938  * @param data pointer to the result data
939  *
940  * TODO: re-issue the request after certain time? cancel after X results?
941  */
942 static void
943 dht_get_string_handler (void *cls, struct GNUNET_TIME_Absolute exp,
944                         const struct GNUNET_HashCode * key,
945                         const struct GNUNET_PeerIdentity *get_path,
946                         unsigned int get_path_length,
947                         const struct GNUNET_PeerIdentity *put_path,
948                         unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
949                         size_t size, const void *data);
950
951
952 /**
953  * Function to process DHT string to regex matching.
954  * Called on each result obtained for the DHT search.
955  *
956  * @param cls closure (search context)
957  * @param exp when will this value expire
958  * @param key key of the result
959  * @param get_path path of the get request (not used)
960  * @param get_path_length lenght of get_path (not used)
961  * @param put_path path of the put request (not used)
962  * @param put_path_length length of the put_path (not used)
963  * @param type type of the result
964  * @param size number of bytes in data
965  * @param data pointer to the result data
966  */
967 static void
968 dht_get_string_accept_handler (void *cls, struct GNUNET_TIME_Absolute exp,
969                                const struct GNUNET_HashCode * key,
970                                const struct GNUNET_PeerIdentity *get_path,
971                                unsigned int get_path_length,
972                                const struct GNUNET_PeerIdentity *put_path,
973                                unsigned int put_path_length,
974                                enum GNUNET_BLOCK_Type type,
975                                size_t size, const void *data);
976
977
978 /**
979  * Retrieve the MeshPeerInfo stucture associated with the peer, create one
980  * and insert it in the appropiate structures if the peer is not known yet.
981  *
982  * @param peer Short identity of the peer.
983  *
984  * @return Existing or newly created peer info.
985  */
986 static struct MeshPeerInfo *
987 peer_info_get_short (const GNUNET_PEER_Id peer);
988
989
990 /**
991  * Try to establish a new connection to this peer.
992  * Use the best path for the given tunnel.
993  * If the peer doesn't have any path to it yet, try to get one.
994  * If the peer already has some path, send a CREATE PATH towards it.
995  *
996  * @param peer PeerInfo of the peer.
997  * @param t Tunnel for which to create the path, if possible.
998  */
999 static void
1000 peer_info_connect (struct MeshPeerInfo *peer, struct MeshTunnel *t);
1001
1002
1003 /**
1004  * Add a peer to a tunnel, accomodating paths accordingly and initializing all
1005  * needed rescources.
1006  * If peer already exists, reevaluate shortest path and change if different.
1007  *
1008  * @param t Tunnel we want to add a new peer to
1009  * @param peer PeerInfo of the peer being added
1010  *
1011  */
1012 static void
1013 tunnel_add_peer (struct MeshTunnel *t, struct MeshPeerInfo *peer);
1014
1015
1016 /**
1017  * Removes an explicit path from a tunnel, freeing all intermediate nodes
1018  * that are no longer needed, as well as nodes of no longer reachable peers.
1019  * The tunnel itself is also destoyed if results in a remote empty tunnel.
1020  *
1021  * @param t Tunnel from which to remove the path.
1022  * @param peer Short id of the peer which should be removed.
1023  */
1024 static void
1025 tunnel_delete_peer (struct MeshTunnel *t, GNUNET_PEER_Id peer);
1026
1027
1028 /**
1029  * Search for a tunnel by global ID using full PeerIdentities.
1030  *
1031  * @param oid owner of the tunnel.
1032  * @param tid global tunnel number.
1033  *
1034  * @return tunnel handler, NULL if doesn't exist.
1035  */
1036 static struct MeshTunnel *
1037 tunnel_get (struct GNUNET_PeerIdentity *oid, MESH_TunnelNumber tid);
1038
1039
1040 /**
1041  * Delete an active client from the tunnel.
1042  *
1043  * @param t Tunnel.
1044  * @param c Client.
1045  */
1046 static void
1047 tunnel_delete_active_client (struct MeshTunnel *t, const struct MeshClient *c);
1048
1049 /**
1050  * Notify a tunnel that a connection has broken that affects at least
1051  * some of its peers.
1052  *
1053  * @param t Tunnel affected.
1054  * @param p1 Peer that got disconnected from p2.
1055  * @param p2 Peer that got disconnected from p1.
1056  *
1057  * @return Short ID of the peer disconnected (either p1 or p2).
1058  *         0 if the tunnel remained unaffected.
1059  */
1060 static GNUNET_PEER_Id
1061 tunnel_notify_connection_broken (struct MeshTunnel *t, GNUNET_PEER_Id p1,
1062                                  GNUNET_PEER_Id p2);
1063
1064
1065 /**
1066  * Get the current ack value for a tunnel, for data going from root to leaves,
1067  * taking in account the tunnel mode and the status of all children and clients.
1068  *
1069  * @param t Tunnel.
1070  *
1071  * @return Maximum PID allowed.
1072  */
1073 static uint32_t
1074 tunnel_get_fwd_ack (struct MeshTunnel *t);
1075
1076 /**
1077  * Get the current ack value for a tunnel, for data going from leaves to root,
1078  * taking in account the tunnel mode and the status of all children and clients.
1079  *
1080  * @param t Tunnel.
1081  *
1082  * @return Maximum PID allowed.
1083  */
1084 static uint32_t
1085 tunnel_get_bck_ack (struct MeshTunnel *t);
1086
1087 /**
1088  * Add a client to a tunnel, initializing all needed data structures.
1089  * 
1090  * @param t Tunnel to which add the client.
1091  * @param c Client which to add to the tunnel.
1092  */
1093 static void
1094 tunnel_add_client (struct MeshTunnel *t, struct MeshClient *c);
1095
1096
1097 /**
1098  * Iterator over edges in a regex block retrieved from the DHT.
1099  *
1100  * @param cls Closure.
1101  * @param token Token that follows to next state.
1102  * @param len Lenght of token.
1103  * @param key Hash of next state.
1104  *
1105  * @return GNUNET_YES if should keep iterating, GNUNET_NO otherwise.
1106  */
1107 static int
1108 regex_edge_iterator (void *cls,
1109                      const char *token,
1110                      size_t len,
1111                      const struct GNUNET_HashCode *key);
1112
1113
1114 /**
1115  * Find a path to a peer that offers a regex servcie compatible
1116  * with a given string.
1117  * 
1118  * @param key The key of the accepting state.
1119  * @param ctx Context containing info about the string, tunnel, etc.
1120  */
1121 static void
1122 regex_find_path (const struct GNUNET_HashCode *key,
1123                  struct MeshRegexSearchContext *ctx);
1124
1125
1126 /**
1127  * Queue and pass message to core when possible.
1128  *
1129  * @param cls Closure (type dependant).
1130  * @param type Type of the message, 0 for a raw message.
1131  * @param size Size of the message.
1132  * @param dst Neighbor to send message to.
1133  * @param t Tunnel this message belongs to.
1134  */
1135 static void
1136 queue_add (void *cls, uint16_t type, size_t size,
1137            struct MeshPeerInfo *dst, struct MeshTunnel *t);
1138
1139 /**
1140  * Free a transmission that was already queued with all resources
1141  * associated to the request.
1142  *
1143  * @param queue Queue handler to cancel.
1144  * @param clear_cls Is it necessary to free associated cls?
1145  */
1146 static void
1147 queue_destroy (struct MeshPeerQueue *queue, int clear_cls);
1148
1149 /******************************************************************************/
1150 /************************         ITERATORS        ****************************/
1151 /******************************************************************************/
1152
1153 /**
1154  * Iterator over found existing mesh regex blocks that match an ongoing search.
1155  *
1156  * @param cls closure
1157  * @param key current key code
1158  * @param value value in the hash map
1159  * @return GNUNET_YES if we should continue to iterate,
1160  *         GNUNET_NO if not.
1161  */
1162 static int
1163 regex_result_iterator (void *cls,
1164                        const struct GNUNET_HashCode * key,
1165                        void *value)
1166 {
1167   struct MeshRegexBlock *block = value;
1168   struct MeshRegexSearchContext *ctx = cls;
1169
1170   if (GNUNET_YES == ntohl(block->accepting) &&
1171       ctx->position == strlen (ctx->info->description))
1172   {
1173     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* Found accepting known block\n");
1174     regex_find_path (key, ctx);
1175     return GNUNET_YES; // We found an accept state!
1176   }
1177   else
1178   {
1179     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* %u, %u, [%u]\n",
1180                 ctx->position, strlen(ctx->info->description),
1181                 ntohl(block->accepting));
1182
1183   }
1184   (void) GNUNET_MESH_regex_block_iterate (block, SIZE_MAX,
1185                                           &regex_edge_iterator, ctx);
1186
1187   return GNUNET_YES;
1188 }
1189
1190
1191 /**
1192  * Iterator over edges in a regex block retrieved from the DHT.
1193  *
1194  * @param cls Closure (context of the search).
1195  * @param token Token that follows to next state.
1196  * @param len Lenght of token.
1197  * @param key Hash of next state.
1198  *
1199  * @return GNUNET_YES if should keep iterating, GNUNET_NO otherwise.
1200  */
1201 static int
1202 regex_edge_iterator (void *cls,
1203                      const char *token,
1204                      size_t len,
1205                      const struct GNUNET_HashCode *key)
1206 {
1207   struct MeshRegexSearchContext *ctx = cls;
1208   struct MeshRegexSearchContext *new_ctx;
1209   struct MeshRegexSearchInfo *info = ctx->info;
1210   struct GNUNET_DHT_GetHandle *get_h;
1211   char *current;
1212   size_t current_len;
1213
1214   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*    Start of regex edge iterator\n");
1215   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*     descr : %s\n", info->description);
1216   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*     posit : %u\n", ctx->position);
1217   current = &info->description[ctx->position];
1218   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*     currt : %s\n", current);
1219   current_len = strlen (info->description) - ctx->position;
1220   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*     ctlen : %u\n", current_len);
1221   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*     tklen : %u\n", len);
1222   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*     tk[0] : %c\n", token[0]);
1223   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*     nextk : %s\n", GNUNET_h2s(key));
1224   if (len > current_len)
1225   {
1226     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*     Token too long, END\n");
1227     return GNUNET_YES; // Token too long, wont match
1228   }
1229   if (0 != strncmp (current, token, len))
1230   {
1231     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*     Token doesn't match, END\n");
1232     return GNUNET_YES; // Token doesn't match
1233   }
1234   new_ctx = GNUNET_malloc (sizeof (struct MeshRegexSearchContext));
1235   new_ctx->info = info;
1236   new_ctx->position = ctx->position + len;
1237   GNUNET_array_append (info->contexts, info->n_contexts, new_ctx);
1238   if (GNUNET_YES ==
1239       GNUNET_CONTAINER_multihashmap_contains(info->dht_get_handles, key))
1240   {
1241     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*     GET running, END\n");
1242     GNUNET_CONTAINER_multihashmap_get_multiple (info->dht_get_results, key,
1243                                                 &regex_result_iterator,
1244                                                 new_ctx);
1245     return GNUNET_YES; // We are already looking for it
1246   }
1247   /* Start search in DHT */
1248   get_h = 
1249       GNUNET_DHT_get_start (dht_handle,    /* handle */
1250                             GNUNET_BLOCK_TYPE_MESH_REGEX, /* type */
1251                             key,     /* key to search */
1252                             dht_replication_level, /* replication level */
1253                             GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
1254                             NULL,       /* xquery */ // FIXME BLOOMFILTER
1255                             0,     /* xquery bits */ // FIXME BLOOMFILTER SIZE
1256                             &dht_get_string_handler, new_ctx);
1257   if (GNUNET_OK !=
1258       GNUNET_CONTAINER_multihashmap_put(info->dht_get_handles, key, get_h,
1259                                         GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
1260   {
1261     GNUNET_break (0);
1262     return GNUNET_YES;
1263   }
1264   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*    End of regex edge iterator\n");
1265   return GNUNET_YES;
1266 }
1267
1268 /**
1269  * Iterator over hash map entries to cancel DHT GET requests after a
1270  * successful connect_by_string.
1271  *
1272  * @param cls Closure (unused).
1273  * @param key Current key code (unused).
1274  * @param value Value in the hash map (get handle).
1275  * @return GNUNET_YES if we should continue to iterate,
1276  *         GNUNET_NO if not.
1277  */
1278 static int
1279 regex_cancel_dht_get (void *cls,
1280                       const struct GNUNET_HashCode * key,
1281                       void *value)
1282 {
1283   struct GNUNET_DHT_GetHandle *h = value;
1284
1285   GNUNET_DHT_get_stop (h);
1286   return GNUNET_YES;
1287 }
1288
1289
1290 /**
1291  * Iterator over hash map entries to free MeshRegexBlocks stored during the
1292  * search for connect_by_string.
1293  *
1294  * @param cls Closure (unused).
1295  * @param key Current key code (unused).
1296  * @param value MeshRegexBlock in the hash map.
1297  * @return GNUNET_YES if we should continue to iterate,
1298  *         GNUNET_NO if not.
1299  */
1300 static int
1301 regex_free_result (void *cls,
1302                    const struct GNUNET_HashCode * key,
1303                    void *value)
1304 {
1305
1306   GNUNET_free (value);
1307   return GNUNET_YES;
1308 }
1309
1310
1311 /**
1312  * Regex callback iterator to store own service description in the DHT.
1313  *
1314  * @param cls closure.
1315  * @param key hash for current state.
1316  * @param proof proof for current state.
1317  * @param accepting GNUNET_YES if this is an accepting state, GNUNET_NO if not.
1318  * @param num_edges number of edges leaving current state.
1319  * @param edges edges leaving current state.
1320  */
1321 void
1322 regex_iterator (void *cls, const struct GNUNET_HashCode *key, const char *proof,
1323                 int accepting, unsigned int num_edges,
1324                 const struct GNUNET_REGEX_Edge *edges)
1325 {
1326     struct MeshRegexBlock *block;
1327     struct MeshRegexEdge *block_edge;
1328     enum GNUNET_DHT_RouteOption opt;
1329     size_t size;
1330     size_t len;
1331     unsigned int i;
1332     unsigned int offset;
1333     char *aux;
1334
1335     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1336                 "  regex dht put for state %s\n",
1337                 GNUNET_h2s(key));
1338     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1339                 "   proof: %s\n",
1340                 proof);
1341     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1342                 "   num edges: %u\n",
1343                 num_edges);
1344
1345     opt = GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE;
1346     if (GNUNET_YES == accepting)
1347     {
1348         struct MeshRegexAccept block;
1349
1350         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1351                     "   state %s is accepting, putting own id\n",
1352                     GNUNET_h2s(key));
1353         size = sizeof (block);
1354         block.key = *key;
1355         block.id = my_full_id;
1356         (void)
1357         GNUNET_DHT_put(dht_handle, key,
1358                        dht_replication_level,
1359                        opt | GNUNET_DHT_RO_RECORD_ROUTE,
1360                        GNUNET_BLOCK_TYPE_MESH_REGEX_ACCEPT,
1361                        size,
1362                        (char *) &block,
1363                        GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get (),
1364                                                  app_announce_time),
1365                        app_announce_time,
1366                        NULL, NULL);
1367     }
1368     len = strlen(proof);
1369     size = sizeof (struct MeshRegexBlock) + len;
1370     block = GNUNET_malloc (size);
1371
1372     block->key = *key;
1373     block->n_proof = htonl (len);
1374     block->n_edges = htonl (num_edges);
1375     block->accepting = htonl (accepting);
1376
1377     /* Store the proof at the end of the block. */
1378     aux = (char *) &block[1];
1379     memcpy (aux, proof, len);
1380     aux = &aux[len];
1381
1382     /* Store each edge in a variable length MeshEdge struct at the
1383      * very end of the MeshRegexBlock structure.
1384      */
1385     for (i = 0; i < num_edges; i++)
1386     {
1387         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1388                     "    edge %s towards %s\n",
1389                     edges[i].label,
1390                     GNUNET_h2s(&edges[i].destination));
1391
1392         /* aux points at the end of the last block */
1393         len = strlen (edges[i].label);
1394         size += sizeof (struct MeshRegexEdge) + len;
1395         // Calculate offset FIXME is this ok? use size instead?
1396         offset = aux - (char *) block;
1397         block = GNUNET_realloc (block, size);
1398         aux = &((char *) block)[offset];
1399         block_edge = (struct MeshRegexEdge *) aux;
1400         block_edge->key = edges[i].destination;
1401         block_edge->n_token = htonl (len);
1402         aux = (char *) &block_edge[1];
1403         memcpy (aux, edges[i].label, len);
1404         aux = &aux[len];
1405     }
1406     (void)
1407     GNUNET_DHT_put(dht_handle, key,
1408                    dht_replication_level,
1409                    opt,
1410                    GNUNET_BLOCK_TYPE_MESH_REGEX, size,
1411                    (char *) block,
1412                    GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get (),
1413                                             app_announce_time),
1414                    app_announce_time,
1415                    NULL, NULL);
1416     GNUNET_free (block);
1417 }
1418
1419
1420 /**
1421  * Store the regular expression describing a local service into the DHT.
1422  *
1423  * @param regex The regular expresion.
1424  */
1425 static void
1426 regex_put (const char *regex)
1427 {
1428   struct GNUNET_REGEX_Automaton *dfa;
1429
1430   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "regex_put (%s) start\n", regex);
1431   dfa = GNUNET_REGEX_construct_dfa (regex, strlen(regex));
1432   GNUNET_REGEX_iterate_all_edges (dfa, &regex_iterator, NULL);
1433   GNUNET_REGEX_automaton_destroy (dfa);
1434   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "regex_put (%s) end\n", regex);
1435
1436 }
1437
1438 /**
1439  * Find a path to a peer that offers a regex servcie compatible
1440  * with a given string.
1441  * 
1442  * @param key The key of the accepting state.
1443  * @param ctx Context containing info about the string, tunnel, etc.
1444  */
1445 static void
1446 regex_find_path (const struct GNUNET_HashCode *key,
1447                  struct MeshRegexSearchContext *ctx)
1448 {
1449   struct GNUNET_DHT_GetHandle *get_h;
1450
1451   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Found peer by service\n");
1452   get_h = GNUNET_DHT_get_start (dht_handle,    /* handle */
1453                                 GNUNET_BLOCK_TYPE_MESH_REGEX_ACCEPT, /* type */
1454                                 key,     /* key to search */
1455                                 dht_replication_level, /* replication level */
1456                                 GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE |
1457                                 GNUNET_DHT_RO_RECORD_ROUTE,
1458                                 NULL,       /* xquery */ // FIXME BLOOMFILTER
1459                                 0,     /* xquery bits */ // FIXME BLOOMFILTER SIZE
1460                                 &dht_get_string_accept_handler, ctx);
1461   GNUNET_break (GNUNET_OK ==
1462                 GNUNET_CONTAINER_multihashmap_put(ctx->info->dht_get_handles,
1463                                                   key,
1464                                                   get_h,
1465                                                   GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
1466 }
1467
1468
1469 /**
1470  * Function called if the connect attempt to a peer found via
1471  * connect_by_string times out. Try to connect to another peer, if any.
1472  * Otherwise try to reconnect to the same peer.
1473  *
1474  * @param cls Closure (info about regex search).
1475  * @param tc TaskContext.
1476  */
1477 static void
1478 regex_connect_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1479 {
1480   struct MeshRegexSearchInfo *info = cls;
1481   struct MeshPeerInfo *peer_info;
1482   GNUNET_PEER_Id id;
1483   GNUNET_PEER_Id old;
1484
1485   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Regex connect timeout\n");
1486   info->timeout = GNUNET_SCHEDULER_NO_TASK;
1487   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1488   {
1489     return;
1490   }
1491
1492   old = info->peer;
1493   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  timed out: %u\n", old);
1494
1495   if (0 < info->n_peers)
1496   {
1497     // Select next peer, put current in that spot.
1498     id = info->peers[info->i_peer];
1499     info->peers[info->i_peer] = info->peer;
1500     info->i_peer = (info->i_peer + 1) % info->n_peers;
1501   }
1502   else
1503   {
1504     // Try to connect to same peer again.
1505     id = info->peer;
1506   }
1507   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  trying: %u\n", id);
1508
1509   peer_info = peer_info_get_short(id);
1510   tunnel_add_peer (info->t, peer_info);
1511   if (old != id)
1512     tunnel_delete_peer (info->t, old);
1513   peer_info_connect (peer_info, info->t);
1514   info->timeout = GNUNET_SCHEDULER_add_delayed (connect_timeout,
1515                                                 &regex_connect_timeout,
1516                                                 info);
1517   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Regex connect timeout END\n");
1518 }
1519
1520
1521 /**
1522  * Cancel an ongoing regex search in the DHT and free all resources.
1523  *
1524  * @param ctx The search context.
1525  */
1526 static void
1527 regex_cancel_search(struct MeshRegexSearchContext *ctx)
1528 {
1529   struct MeshRegexSearchInfo *info = ctx->info;
1530   int i;
1531
1532   GNUNET_free (info->description);
1533   GNUNET_CONTAINER_multihashmap_iterate (info->dht_get_handles,
1534                                              &regex_cancel_dht_get, NULL);
1535   GNUNET_CONTAINER_multihashmap_iterate (info->dht_get_results,
1536                                          &regex_free_result, NULL);
1537   GNUNET_CONTAINER_multihashmap_destroy (info->dht_get_results);
1538   GNUNET_CONTAINER_multihashmap_destroy (info->dht_get_handles);
1539   info->t->regex_ctx = NULL;
1540   for (i = 0; i < info->n_contexts; i++)
1541   {
1542     GNUNET_free (info->contexts[i]);
1543   }
1544   if (0 < info->n_contexts)
1545     GNUNET_free (info->contexts);
1546   if (0 < info->n_peers)
1547     GNUNET_free (info->peers);
1548   if (GNUNET_SCHEDULER_NO_TASK != info->timeout)
1549   {
1550     GNUNET_SCHEDULER_cancel(info->timeout);
1551   }
1552   GNUNET_free (info);
1553 }
1554
1555
1556 /******************************************************************************/
1557 /************************    PERIODIC FUNCTIONS    ****************************/
1558 /******************************************************************************/
1559
1560 /**
1561  * Announce iterator over for each application provided by the peer
1562  *
1563  * @param cls closure
1564  * @param key current key code
1565  * @param value value in the hash map
1566  * @return GNUNET_YES if we should continue to
1567  *         iterate,
1568  *         GNUNET_NO if not.
1569  */
1570 static int
1571 announce_application (void *cls, const struct GNUNET_HashCode * key, void *value)
1572 {
1573   struct PBlock block;
1574   struct MeshClient *c;
1575
1576   block.id = my_full_id;
1577   c =  GNUNET_CONTAINER_multihashmap_get (applications, key);
1578   block.type = (long) GNUNET_CONTAINER_multihashmap_get (c->apps, key);
1579   if (0 == block.type)
1580   {
1581     GNUNET_break(0);
1582     return GNUNET_YES;
1583   }
1584   block.type = htonl (block.type);
1585
1586   GNUNET_break (NULL != 
1587                 GNUNET_DHT_put (dht_handle, key,
1588                   dht_replication_level,
1589                   GNUNET_DHT_RO_RECORD_ROUTE |
1590                   GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
1591                   GNUNET_BLOCK_TYPE_MESH_PEER_BY_TYPE,
1592                   sizeof (block),
1593                   (const char *) &block,
1594                   GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get (),
1595                                             app_announce_time),
1596                   app_announce_time, NULL, NULL));
1597   return GNUNET_OK;
1598 }
1599
1600
1601 /**
1602  * Periodically announce what applications are provided by local clients
1603  * (by regex)
1604  *
1605  * @param cls closure
1606  * @param tc task context
1607  */
1608 static void
1609 announce_regex (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1610 {
1611   struct MeshClient *c = cls;
1612   unsigned int i;
1613
1614   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1615   {
1616     c->regex_announce_task = GNUNET_SCHEDULER_NO_TASK;
1617     return;
1618   }
1619
1620   DEBUG_DHT ("Starting PUT for regex\n");
1621
1622   for (i = 0; i < c->n_regex; i++)
1623   {
1624     regex_put (c->regexes[i]);
1625   }
1626   c->regex_announce_task =
1627       GNUNET_SCHEDULER_add_delayed (app_announce_time, &announce_regex, cls);
1628   DEBUG_DHT ("Finished PUT for regex\n");
1629
1630   return;
1631 }
1632
1633
1634 /**
1635  * Periodically announce what applications are provided by local clients
1636  * (by type)
1637  *
1638  * @param cls closure
1639  * @param tc task context
1640  */
1641 static void
1642 announce_applications (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1643 {
1644   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1645   {
1646     announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
1647     return;
1648   }
1649  
1650   DEBUG_DHT ("Starting PUT for apps\n");
1651
1652   GNUNET_CONTAINER_multihashmap_iterate (applications, &announce_application,
1653                                          NULL);
1654   announce_applications_task =
1655       GNUNET_SCHEDULER_add_delayed (app_announce_time, &announce_applications,
1656                                     cls);
1657   DEBUG_DHT ("Finished PUT for apps\n");
1658
1659   return;
1660 }
1661
1662
1663 /**
1664  * Periodically announce self id in the DHT
1665  *
1666  * @param cls closure
1667  * @param tc task context
1668  */
1669 static void
1670 announce_id (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1671 {
1672   struct PBlock block;
1673
1674   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1675   {
1676     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
1677     return;
1678   }
1679   /* TODO
1680    * - Set data expiration in function of X
1681    * - Adapt X to churn
1682    */
1683   DEBUG_DHT ("DHT_put for ID %s started.\n", GNUNET_i2s (&my_full_id));
1684
1685   block.id = my_full_id;
1686   block.type = htonl (0);
1687   GNUNET_DHT_put (dht_handle,   /* DHT handle */
1688                   &my_full_id.hashPubKey,       /* Key to use */
1689                   dht_replication_level,     /* Replication level */
1690                   GNUNET_DHT_RO_RECORD_ROUTE | GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,    /* DHT options */
1691                   GNUNET_BLOCK_TYPE_MESH_PEER,       /* Block type */
1692                   sizeof (block),  /* Size of the data */
1693                   (const char *) &block, /* Data itself */
1694                   GNUNET_TIME_UNIT_FOREVER_ABS,  /* Data expiration */
1695                   GNUNET_TIME_UNIT_FOREVER_REL, /* Retry time */
1696                   NULL,         /* Continuation */
1697                   NULL);        /* Continuation closure */
1698   announce_id_task =
1699       GNUNET_SCHEDULER_add_delayed (id_announce_time, &announce_id, cls);
1700 }
1701
1702
1703 /******************************************************************************/
1704 /******************      GENERAL HELPER FUNCTIONS      ************************/
1705 /******************************************************************************/
1706
1707 /**
1708  * Decrements the reference counter and frees all resources if needed
1709  *
1710  * @param mesh_data Data Descriptor used in a multicast message.
1711  *                  Freed no longer needed (last message).
1712  */
1713 static void
1714 data_descriptor_decrement_rc (struct MeshData *mesh_data)
1715 {
1716   /* Make sure it's a multicast packet */
1717   GNUNET_assert (NULL != mesh_data->reference_counter);
1718
1719   if (0 == --(*(mesh_data->reference_counter)))
1720   {
1721     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Last copy!\n");
1722     if (NULL != mesh_data->task)
1723     {
1724       if (GNUNET_SCHEDULER_NO_TASK != *(mesh_data->task))
1725       {
1726         GNUNET_SCHEDULER_cancel (*(mesh_data->task));
1727         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " notifying client...\n");
1728         GNUNET_SERVER_receive_done (mesh_data->t->owner->handle, GNUNET_OK);
1729       }
1730       GNUNET_free (mesh_data->task);
1731     }
1732     GNUNET_free (mesh_data->reference_counter);
1733     GNUNET_free (mesh_data->data);
1734     GNUNET_free (mesh_data);
1735   }
1736 }
1737
1738
1739 /**
1740  * Check if client has registered with the service and has not disconnected
1741  *
1742  * @param client the client to check
1743  *
1744  * @return non-NULL if client exists in the global DLL
1745  */
1746 static struct MeshClient *
1747 client_get (struct GNUNET_SERVER_Client *client)
1748 {
1749   struct MeshClient *c;
1750
1751   c = clients;
1752   while (NULL != c)
1753   {
1754     if (c->handle == client)
1755       return c;
1756     c = c->next;
1757   }
1758   return NULL;
1759 }
1760
1761
1762 /**
1763  * Checks if a given client has subscribed to certain message type
1764  *
1765  * @param message_type Type of message to check
1766  * @param c Client to check
1767  *
1768  * @return GNUNET_YES or GNUNET_NO, depending on subscription status
1769  */
1770 static int
1771 client_is_subscribed (uint16_t message_type, struct MeshClient *c)
1772 {
1773   struct GNUNET_HashCode hc;
1774
1775   if (NULL == c->types)
1776     return GNUNET_NO;
1777   GNUNET_CRYPTO_hash (&message_type, sizeof (uint16_t), &hc);
1778   return GNUNET_CONTAINER_multihashmap_contains (c->types, &hc);
1779 }
1780
1781
1782 /**
1783  * Allow a client to send more data after transmitting a multicast message
1784  * which some neighbor has not yet accepted altough a reasonable time has
1785  * passed.
1786  *
1787  * @param cls Closure (DataDescriptor containing the task identifier)
1788  * @param tc Task Context
1789  * 
1790  * FIXME reference counter cshould be just int
1791  */
1792 static void
1793 client_allow_send (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1794 {
1795   struct MeshData *mdata = cls;
1796
1797   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1798     return;
1799   GNUNET_assert (NULL != mdata->reference_counter);
1800   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1801               "CLIENT ALLOW SEND DESPITE %u COPIES PENDING\n",
1802               *(mdata->reference_counter));
1803   *(mdata->task) = GNUNET_SCHEDULER_NO_TASK;
1804   GNUNET_SERVER_receive_done (mdata->t->owner->handle, GNUNET_OK);
1805 }
1806
1807
1808 /**
1809  * Check whether client wants traffic from a tunnel.
1810  *
1811  * @param c Client to check.
1812  * @param t Tunnel to be found.
1813  *
1814  * @return GNUNET_YES if client knows tunnel.
1815  * 
1816  * TODO look in client hashmap
1817  */
1818 static int
1819 client_wants_tunnel (struct MeshClient *c, struct MeshTunnel *t)
1820 {
1821   unsigned int i;
1822
1823   for (i = 0; i < t->nclients; i++)
1824     if (t->clients[i] == c)
1825       return GNUNET_YES;
1826   return GNUNET_NO;
1827 }
1828
1829
1830 /**
1831  * Check whether client has been informed about a tunnel.
1832  *
1833  * @param c Client to check.
1834  * @param t Tunnel to be found.
1835  *
1836  * @return GNUNET_YES if client knows tunnel.
1837  * 
1838  * TODO look in client hashmap
1839  */
1840 static int
1841 client_knows_tunnel (struct MeshClient *c, struct MeshTunnel *t)
1842 {
1843   unsigned int i;
1844
1845   for (i = 0; i < t->nignore; i++)
1846     if (t->ignore[i] == c)
1847       return GNUNET_YES;
1848   return client_wants_tunnel(c, t);
1849 }
1850
1851
1852 /**
1853  * Marks a client as uninterested in traffic from the tunnel, updating both
1854  * client and tunnel to reflect this.
1855  *
1856  * @param c Client that doesn't want traffic anymore.
1857  * @param t Tunnel which should be ignored.
1858  *
1859  * FIXME when to delete an incoming tunnel?
1860  */
1861 static void
1862 client_ignore_tunnel (struct MeshClient *c, struct MeshTunnel *t)
1863 {
1864   struct GNUNET_HashCode hash;
1865
1866   GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
1867   GNUNET_break (GNUNET_YES ==
1868                 GNUNET_CONTAINER_multihashmap_remove (c->incoming_tunnels,
1869                                                       &hash, t));
1870   GNUNET_break (GNUNET_YES ==
1871                 GNUNET_CONTAINER_multihashmap_put (c->ignore_tunnels, &hash, t,
1872                                                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
1873   tunnel_delete_active_client (t, c);
1874   GNUNET_array_append (t->ignore, t->nignore, c);
1875 }
1876
1877
1878 /**
1879  * Deletes a tunnel from a client (either owner or destination). To be used on
1880  * tunnel destroy, otherwise, use client_ignore_tunnel.
1881  *
1882  * @param c Client whose tunnel to delete.
1883  * @param t Tunnel which should be deleted.
1884  */
1885 static void
1886 client_delete_tunnel (struct MeshClient *c, struct MeshTunnel *t)
1887 {
1888   struct GNUNET_HashCode hash;
1889
1890   if (c == t->owner)
1891   {
1892     GNUNET_CRYPTO_hash(&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
1893     GNUNET_assert (GNUNET_YES ==
1894                    GNUNET_CONTAINER_multihashmap_remove (c->own_tunnels,
1895                                                          &hash,
1896                                                          t));
1897   }
1898   else
1899   {
1900     GNUNET_CRYPTO_hash(&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
1901     // FIXME XOR?
1902     GNUNET_assert (GNUNET_YES ==
1903                    GNUNET_CONTAINER_multihashmap_remove (c->incoming_tunnels,
1904                                                          &hash,
1905                                                          t) ||
1906                    GNUNET_YES ==
1907                    GNUNET_CONTAINER_multihashmap_remove (c->ignore_tunnels,
1908                                                          &hash,
1909                                                          t));
1910   }
1911 }
1912
1913
1914 /**
1915  * Send the message to all clients that have subscribed to its type
1916  *
1917  * @param msg Pointer to the message itself
1918  * @param payload Pointer to the payload of the message.
1919  * @return number of clients this message was sent to
1920  */
1921 static unsigned int
1922 send_subscribed_clients (const struct GNUNET_MessageHeader *msg,
1923                          const struct GNUNET_MessageHeader *payload)
1924 {
1925   struct GNUNET_PeerIdentity *oid;
1926   struct MeshClient *c;
1927   struct MeshTunnel *t;
1928   MESH_TunnelNumber *tid;
1929   unsigned int count;
1930   uint16_t type;
1931   char cbuf[htons (msg->size)];
1932
1933   type = ntohs (payload->type);
1934   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending to clients...\n");
1935   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "message of type %s\n",
1936               GNUNET_MESH_DEBUG_M2S (type));
1937
1938   memcpy (cbuf, msg, sizeof (cbuf));
1939   switch (htons (msg->type))
1940   {
1941     struct GNUNET_MESH_Unicast *uc;
1942     struct GNUNET_MESH_Multicast *mc;
1943     struct GNUNET_MESH_ToOrigin *to;
1944
1945   case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
1946     uc = (struct GNUNET_MESH_Unicast *) cbuf;
1947     tid = &uc->tid;
1948     oid = &uc->oid;
1949     break;
1950   case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
1951     mc = (struct GNUNET_MESH_Multicast *) cbuf;
1952     tid = &mc->tid;
1953     oid = &mc->oid;
1954     break;
1955   case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
1956     to = (struct GNUNET_MESH_ToOrigin *) cbuf;
1957     tid = &to->tid;
1958     oid = &to->oid;
1959     break;
1960   default:
1961     GNUNET_break (0);
1962     return 0;
1963   }
1964   t = tunnel_get (oid, ntohl (*tid));
1965   if (NULL == t)
1966   {
1967     GNUNET_break (0);
1968     return 0;
1969   }
1970
1971   for (count = 0, c = clients; c != NULL; c = c->next)
1972   {
1973     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   client %u\n", c->id);
1974     if (client_is_subscribed (type, c))
1975     {
1976       if (htons (msg->type) == GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN)
1977       {
1978         if (c != t->owner)
1979           continue;
1980         *tid = htonl (t->local_tid);
1981       }
1982       else
1983       {
1984         if (GNUNET_NO == client_knows_tunnel (c, t))
1985         {
1986           /* This client doesn't know the tunnel */
1987           struct GNUNET_MESH_TunnelNotification tmsg;
1988           struct GNUNET_HashCode hash;
1989
1990           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "     sending tunnel create\n");
1991           tmsg.header.size = htons (sizeof (tmsg));
1992           tmsg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
1993           GNUNET_PEER_resolve (t->id.oid, &tmsg.peer);
1994           tmsg.tunnel_id = htonl (t->local_tid_dest);
1995           GNUNET_SERVER_notification_context_unicast (nc, c->handle,
1996                                                       &tmsg.header, GNUNET_NO);
1997           tunnel_add_client (t, c);
1998           GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber),
1999                               &hash);
2000           GNUNET_break (GNUNET_OK == GNUNET_CONTAINER_multihashmap_put (
2001                                        c->incoming_tunnels, &hash, t,
2002                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
2003         }
2004         *tid = htonl (t->local_tid_dest);
2005       }
2006
2007       /* Check if the client wants to get traffic from the tunnel */
2008       if (GNUNET_NO == client_wants_tunnel(c, t))
2009         continue;
2010       count++;
2011       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "     sending\n");
2012       GNUNET_SERVER_notification_context_unicast (nc, c->handle,
2013                                                   (struct GNUNET_MessageHeader
2014                                                    *) cbuf, GNUNET_NO);
2015     }
2016   }
2017   return count;
2018 }
2019
2020
2021 /**
2022  * Notify the client that owns the tunnel that a peer has connected to it
2023  * (the requested path to it has been confirmed).
2024  *
2025  * @param t Tunnel whose owner to notify
2026  * @param id Short id of the peer that has connected
2027  */
2028 static void
2029 send_client_peer_connected (const struct MeshTunnel *t, const GNUNET_PEER_Id id)
2030 {
2031   struct GNUNET_MESH_PeerControl pc;
2032
2033   pc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD);
2034   pc.header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
2035   pc.tunnel_id = htonl (t->local_tid);
2036   GNUNET_PEER_resolve (id, &pc.peer);
2037   GNUNET_SERVER_notification_context_unicast (nc, t->owner->handle, &pc.header,
2038                                               GNUNET_NO);
2039 }
2040
2041
2042 /**
2043  * Notify a client of a tunnel about how many more
2044  * payload packages will we accept on a given tunnel,
2045  * distinguishing between root and leaf clients.
2046  *
2047  * @param c Client whom to send the ACK.
2048  * @param t Tunnel on which to send the ACK.
2049  */
2050 static void
2051 send_client_tunnel_ack (struct MeshClient *c, struct MeshTunnel *t)
2052 {
2053   struct GNUNET_MESH_LocalAck msg;
2054   MESH_TunnelNumber tid;
2055   uint32_t ack;
2056
2057   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2058               "Sending client ACK on tunnel %X\n",
2059               t->local_tid);
2060   if (NULL == c)
2061     return;
2062
2063   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " to client %u\n", c->id);
2064
2065   if (c == t->owner)
2066   {
2067     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  (owner, FWD ACK)\n");
2068     ack = tunnel_get_fwd_ack (t);
2069     tid = t->local_tid;
2070   }
2071   else
2072   {
2073     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  (leaf, BCK ACK)\n");
2074     ack = tunnel_get_bck_ack (t);
2075     tid = t->local_tid_dest;
2076   }
2077
2078   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ack %u\n", ack);
2079   if (t->last_fwd_ack == ack)
2080     return;
2081
2082   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " sending!\n");
2083   t->last_fwd_ack = ack;
2084   msg.header.size = htons (sizeof (msg));
2085   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
2086   msg.tunnel_id = htonl (tid);
2087   msg.max_pid = htonl (ack);
2088
2089   GNUNET_SERVER_notification_context_unicast (nc, c->handle,
2090                                               &msg.header, GNUNET_NO);
2091 }
2092
2093
2094 /**
2095  * Notify all clients (not depending on registration status) that the incoming
2096  * tunnel is no longer valid.
2097  *
2098  * @param t Tunnel that was destroyed.
2099  */
2100 static void
2101 send_clients_tunnel_destroy (struct MeshTunnel *t)
2102 {
2103   struct GNUNET_MESH_TunnelMessage msg;
2104
2105   msg.header.size = htons (sizeof (msg));
2106   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
2107   msg.tunnel_id = htonl (t->local_tid_dest);
2108   GNUNET_SERVER_notification_context_broadcast (nc, &msg.header, GNUNET_NO);
2109 }
2110
2111
2112 /**
2113  * Notify clients of tunnel disconnections, if needed.
2114  * In case the origin disconnects, the destination clients get a tunnel destroy
2115  * notification. If the last destination disconnects (only one remaining client
2116  * in tunnel), the origin gets a (local ID) peer disconnected.
2117  * Note that the function must be called BEFORE removing the client from
2118  * the tunnel.
2119  *
2120  * @param t Tunnel that was destroyed.
2121  * @param c Client that disconnected.
2122  */
2123 static void
2124 send_client_tunnel_disconnect (struct MeshTunnel *t, struct MeshClient *c)
2125 {
2126   unsigned int i;
2127
2128   if (c == t->owner)
2129   {
2130     struct GNUNET_MESH_TunnelMessage msg;
2131
2132     msg.header.size = htons (sizeof (msg));
2133     msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
2134     msg.tunnel_id = htonl (t->local_tid_dest);
2135     for (i = 0; i < t->nclients; i++)
2136       GNUNET_SERVER_notification_context_unicast (nc, t->clients[i]->handle,
2137                                                   &msg.header, GNUNET_NO);
2138   }
2139   // FIXME when to disconnect an incoming tunnel?
2140   else if (1 == t->nclients && NULL != t->owner)
2141   {
2142     struct GNUNET_MESH_PeerControl msg;
2143
2144     msg.header.size = htons (sizeof (msg));
2145     msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL);
2146     msg.tunnel_id = htonl (t->local_tid);
2147     msg.peer = my_full_id;
2148     GNUNET_SERVER_notification_context_unicast (nc, t->owner->handle,
2149                                                 &msg.header, GNUNET_NO);
2150   }
2151 }
2152
2153
2154 /**
2155  * Retrieve the MeshPeerInfo stucture associated with the peer, create one
2156  * and insert it in the appropiate structures if the peer is not known yet.
2157  *
2158  * @param peer Full identity of the peer.
2159  *
2160  * @return Existing or newly created peer info.
2161  */
2162 static struct MeshPeerInfo *
2163 peer_info_get (const struct GNUNET_PeerIdentity *peer)
2164 {
2165   struct MeshPeerInfo *peer_info;
2166
2167   peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
2168   if (NULL == peer_info)
2169   {
2170     peer_info =
2171         (struct MeshPeerInfo *) GNUNET_malloc (sizeof (struct MeshPeerInfo));
2172     GNUNET_CONTAINER_multihashmap_put (peers, &peer->hashPubKey, peer_info,
2173                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2174     peer_info->id = GNUNET_PEER_intern (peer);
2175   }
2176
2177   return peer_info;
2178 }
2179
2180
2181 /**
2182  * Retrieve the MeshPeerInfo stucture associated with the peer, create one
2183  * and insert it in the appropiate structures if the peer is not known yet.
2184  *
2185  * @param peer Short identity of the peer.
2186  *
2187  * @return Existing or newly created peer info.
2188  */
2189 static struct MeshPeerInfo *
2190 peer_info_get_short (const GNUNET_PEER_Id peer)
2191 {
2192   struct GNUNET_PeerIdentity id;
2193
2194   GNUNET_PEER_resolve (peer, &id);
2195   return peer_info_get (&id);
2196 }
2197
2198
2199 /**
2200  * Iterator to remove the tunnel from the list of tunnels a peer participates
2201  * in.
2202  *
2203  * @param cls Closure (tunnel info)
2204  * @param key GNUNET_PeerIdentity of the peer (unused)
2205  * @param value PeerInfo of the peer
2206  *
2207  * @return always GNUNET_YES, to keep iterating
2208  */
2209 static int
2210 peer_info_delete_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
2211 {
2212   struct MeshTunnel *t = cls;
2213   struct MeshPeerInfo *peer = value;
2214   unsigned int i;
2215
2216   for (i = 0; i < peer->ntunnels; i++)
2217   {
2218     if (0 ==
2219         memcmp (&peer->tunnels[i]->id, &t->id, sizeof (struct MESH_TunnelID)))
2220     {
2221       peer->ntunnels--;
2222       peer->tunnels[i] = peer->tunnels[peer->ntunnels];
2223       peer->tunnels = GNUNET_realloc (peer->tunnels, peer->ntunnels);
2224       return GNUNET_YES;
2225     }
2226   }
2227   return GNUNET_YES;
2228 }
2229
2230
2231 /**
2232   * Core callback to write a pre-constructed data packet to core buffer
2233   *
2234   * @param cls Closure (MeshTransmissionDescriptor with data in "data" member).
2235   * @param size Number of bytes available in buf.
2236   * @param buf Where the to write the message.
2237   *
2238   * @return number of bytes written to buf
2239   */
2240 static size_t
2241 send_core_data_raw (void *cls, size_t size, void *buf)
2242 {
2243   struct MeshTransmissionDescriptor *info = cls;
2244   struct GNUNET_MessageHeader *msg;
2245   size_t total_size;
2246
2247   GNUNET_assert (NULL != info);
2248   GNUNET_assert (NULL != info->mesh_data);
2249   msg = (struct GNUNET_MessageHeader *) info->mesh_data->data;
2250   total_size = ntohs (msg->size);
2251
2252   if (total_size > size)
2253   {
2254     GNUNET_break (0);
2255     return 0;
2256   }
2257   memcpy (buf, msg, total_size);
2258   data_descriptor_decrement_rc (info->mesh_data);
2259   GNUNET_free (info);
2260   return total_size;
2261 }
2262
2263
2264 /**
2265  * Sends an already built non-multicast message to a peer,
2266  * properly registrating all used resources.
2267  *
2268  * @param message Message to send. Function makes a copy of it.
2269  * @param peer Short ID of the neighbor whom to send the message.
2270  * @param t Tunnel on which this message is transmitted.
2271  */
2272 static void
2273 send_message (const struct GNUNET_MessageHeader *message,
2274               const struct GNUNET_PeerIdentity *peer,
2275               struct MeshTunnel *t)
2276 {
2277   struct MeshTransmissionDescriptor *info;
2278   struct MeshPeerInfo *neighbor;
2279   struct MeshPeerPath *p;
2280   size_t size;
2281   uint16_t type;
2282
2283 //   GNUNET_TRANSPORT_try_connect(); FIXME use?
2284
2285   size = ntohs (message->size);
2286   info = GNUNET_malloc (sizeof (struct MeshTransmissionDescriptor));
2287   info->mesh_data = GNUNET_malloc (sizeof (struct MeshData));
2288   info->mesh_data->data = GNUNET_malloc (size);
2289   memcpy (info->mesh_data->data, message, size);
2290   type = ntohs(message->type);
2291   if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == type)
2292   {
2293     struct GNUNET_MESH_Unicast *m;
2294
2295     m = (struct GNUNET_MESH_Unicast *) info->mesh_data->data;
2296     m->ttl = htonl (ntohl (m->ttl) - 1);
2297   }
2298   info->mesh_data->data_len = size;
2299   info->mesh_data->reference_counter = GNUNET_malloc (sizeof (unsigned int));
2300   *info->mesh_data->reference_counter = 1;
2301   neighbor = peer_info_get (peer);
2302   for (p = neighbor->path_head; NULL != p; p = p->next)
2303   {
2304     if (2 >= p->length)
2305     {
2306       break;
2307     }
2308   }
2309   if (NULL == p)
2310   {
2311 #if MESH_DEBUG
2312     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2313                 "  %s IS NOT DIRECTLY CONNECTED\n",
2314                 GNUNET_i2s(peer));
2315     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2316                 "  PATHS TO %s:\n",
2317                 GNUNET_i2s(peer));
2318     for (p = neighbor->path_head; NULL != p; p = p->next)
2319     {
2320       struct GNUNET_PeerIdentity debug_id;
2321       unsigned int i;
2322
2323       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2324                   "    path with %u hops through:\n",
2325                   p->length);
2326       for (i = 0; i < p->length; i++)
2327       {
2328         GNUNET_PEER_resolve(p->peers[i], &debug_id);
2329         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2330                     "      hop %u: %s\n",
2331                     i, GNUNET_i2s(&debug_id));
2332       }
2333     }
2334 #endif
2335     GNUNET_break (0); // FIXME sometimes fails (testing disconnect?)
2336     GNUNET_free (info->mesh_data->data);
2337     GNUNET_free (info->mesh_data);
2338     GNUNET_free (info);
2339     return;
2340   }
2341   info->peer = neighbor;
2342   if (GNUNET_MESSAGE_TYPE_MESH_PATH_ACK == type)
2343   {
2344     /*
2345      * TODO: in this case we only need the service to retransmit
2346      * the message down the path. If we pass the real type to queue_add,
2347      * queue_send will try to build the message from scratch. This can
2348      * probably be done by some other way instead of deleteing the type
2349      * info.
2350      */
2351     type = 0;
2352   }
2353   queue_add (info,
2354              type,
2355              size,
2356              neighbor,
2357              t);
2358 }
2359
2360
2361 /**
2362  * Sends a CREATE PATH message for a path to a peer, properly registrating
2363  * all used resources.
2364  *
2365  * @param peer PeerInfo of the final peer for whom this path is being created.
2366  * @param p Path itself.
2367  * @param t Tunnel for which the path is created.
2368  */
2369 static void
2370 send_create_path (struct MeshPeerInfo *peer, struct MeshPeerPath *p,
2371                   struct MeshTunnel *t)
2372 {
2373   struct GNUNET_PeerIdentity id;
2374   struct MeshPathInfo *path_info;
2375   struct MeshPeerInfo *neighbor;
2376
2377   unsigned int i;
2378
2379   if (NULL == p)
2380   {
2381     p = tree_get_path_to_peer (t->tree, peer->id);
2382     if (NULL == p)
2383     {
2384       GNUNET_break (0);
2385       return;
2386     }
2387   }
2388   for (i = 0; i < p->length; i++)
2389   {
2390     if (p->peers[i] == myid)
2391       break;
2392   }
2393   if (i >= p->length - 1)
2394   {
2395     path_destroy (p);
2396     GNUNET_break (0);
2397     return;
2398   }
2399   GNUNET_PEER_resolve (p->peers[i + 1], &id);
2400
2401   path_info = GNUNET_malloc (sizeof (struct MeshPathInfo));
2402   path_info->path = p;
2403   path_info->t = t;
2404   neighbor = peer_info_get (&id);
2405   path_info->peer = neighbor;
2406   queue_add (path_info,
2407              GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE,
2408              sizeof (struct GNUNET_MESH_ManipulatePath) +
2409                 (p->length * sizeof (struct GNUNET_PeerIdentity)),
2410              neighbor,
2411              t);
2412 }
2413
2414
2415 /**
2416  * Sends a DESTROY PATH message to free resources for a path in a tunnel
2417  *
2418  * @param t Tunnel whose path to destroy.
2419  * @param destination Short ID of the peer to whom the path to destroy.
2420  */
2421 static void
2422 send_destroy_path (struct MeshTunnel *t, GNUNET_PEER_Id destination)
2423 {
2424   struct MeshPeerPath *p;
2425   size_t size;
2426
2427   p = tree_get_path_to_peer (t->tree, destination);
2428   if (NULL == p)
2429   {
2430     GNUNET_break (0);
2431     return;
2432   }
2433   size = sizeof (struct GNUNET_MESH_ManipulatePath);
2434   size += p->length * sizeof (struct GNUNET_PeerIdentity);
2435   {
2436     struct GNUNET_MESH_ManipulatePath *msg;
2437     struct GNUNET_PeerIdentity *pi;
2438     char cbuf[size];
2439     unsigned int i;
2440
2441     msg = (struct GNUNET_MESH_ManipulatePath *) cbuf;
2442     msg->header.size = htons (size);
2443     msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY);
2444     msg->tid = htonl (t->id.tid);
2445     pi = (struct GNUNET_PeerIdentity *) &msg[1];
2446     for (i = 0; i < p->length; i++)
2447     {
2448       GNUNET_PEER_resolve (p->peers[i], &pi[i]);
2449     }
2450     send_message (&msg->header, tree_get_first_hop (t->tree, destination), t);
2451   }
2452   path_destroy (p);
2453 }
2454
2455
2456 /**
2457  * Try to establish a new connection to this peer.
2458  * Use the best path for the given tunnel.
2459  * If the peer doesn't have any path to it yet, try to get one.
2460  * If the peer already has some path, send a CREATE PATH towards it.
2461  *
2462  * @param peer PeerInfo of the peer.
2463  * @param t Tunnel for which to create the path, if possible.
2464  */
2465 static void
2466 peer_info_connect (struct MeshPeerInfo *peer, struct MeshTunnel *t)
2467 {
2468   struct MeshPeerPath *p;
2469   struct MeshPathInfo *path_info;
2470
2471   if (NULL != peer->path_head)
2472   {
2473     p = tree_get_path_to_peer (t->tree, peer->id);
2474     if (NULL == p)
2475     {
2476       GNUNET_break (0);
2477       return;
2478     }
2479
2480     // FIXME always send create path to self
2481     if (p->length > 1)
2482     {
2483       send_create_path (peer, p, t);
2484     }
2485     else
2486     {
2487       struct GNUNET_HashCode hash;
2488
2489       path_destroy (p);
2490       send_client_peer_connected (t, myid);
2491       t->local_tid_dest = next_local_tid++;
2492       GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber),
2493                           &hash);
2494       if (GNUNET_OK !=
2495           GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
2496                                              GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2497       {
2498         GNUNET_break (0);
2499         return;
2500       }
2501     }
2502   }
2503   else if (NULL == peer->dhtget)
2504   {
2505     struct GNUNET_PeerIdentity id;
2506
2507     GNUNET_PEER_resolve (peer->id, &id);
2508     path_info = GNUNET_malloc (sizeof (struct MeshPathInfo));
2509     path_info->peer = peer;
2510     path_info->t = t;
2511     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2512                 "  Starting DHT GET for peer %s\n", GNUNET_i2s (&id));
2513     peer->dhtgetcls = path_info;
2514     peer->dhtget = GNUNET_DHT_get_start (dht_handle,    /* handle */
2515                                          GNUNET_BLOCK_TYPE_MESH_PEER, /* type */
2516                                          &id.hashPubKey,     /* key to search */
2517                                          dht_replication_level, /* replication level */
2518                                          GNUNET_DHT_RO_RECORD_ROUTE |
2519                                          GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
2520                                          NULL,       /* xquery */ // FIXME BLOOMFILTER
2521                                          0,     /* xquery bits */ // FIXME BLOOMFILTER SIZE
2522                                          &dht_get_id_handler, path_info);
2523   }
2524   /* Otherwise, there is no path but the DHT get is already started. */
2525 }
2526
2527
2528 /**
2529  * Task to delay the connection of a peer
2530  *
2531  * @param cls Closure (path info with tunnel and peer to connect).
2532  *            Will be free'd on exection.
2533  * @param tc TaskContext
2534  */
2535 static void
2536 peer_info_connect_task (void *cls,
2537                         const struct GNUNET_SCHEDULER_TaskContext *tc)
2538 {
2539   struct MeshPathInfo *path_info = cls;
2540
2541   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2542   {
2543     GNUNET_free (cls);
2544     return;
2545   }
2546   peer_info_connect (path_info->peer, path_info->t);
2547   GNUNET_free (cls);
2548 }
2549
2550
2551 /**
2552  * Destroy the peer_info and free any allocated resources linked to it
2553  *
2554  * @param pi The peer_info to destroy.
2555  *
2556  * @return GNUNET_OK on success
2557  */
2558 static int
2559 peer_info_destroy (struct MeshPeerInfo *pi)
2560 {
2561   struct GNUNET_PeerIdentity id;
2562   struct MeshPeerPath *p;
2563   struct MeshPeerPath *nextp;
2564
2565   GNUNET_PEER_resolve (pi->id, &id);
2566   GNUNET_PEER_change_rc (pi->id, -1);
2567
2568   if (GNUNET_YES !=
2569       GNUNET_CONTAINER_multihashmap_remove (peers, &id.hashPubKey, pi))
2570   {
2571     GNUNET_break (0);
2572     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2573                 "removing peer %s, not in hashmap\n", GNUNET_i2s (&id));
2574   }
2575   if (NULL != pi->dhtget)
2576   {
2577     GNUNET_DHT_get_stop (pi->dhtget);
2578     GNUNET_free (pi->dhtgetcls);
2579   }
2580   p = pi->path_head;
2581   while (NULL != p)
2582   {
2583     nextp = p->next;
2584     GNUNET_CONTAINER_DLL_remove (pi->path_head, pi->path_tail, p);
2585     path_destroy (p);
2586     p = nextp;
2587   }
2588   GNUNET_free (pi);
2589   return GNUNET_OK;
2590 }
2591
2592
2593 /**
2594  * Remove all paths that rely on a direct connection between p1 and p2
2595  * from the peer itself and notify all tunnels about it.
2596  *
2597  * @param peer PeerInfo of affected peer.
2598  * @param p1 GNUNET_PEER_Id of one peer.
2599  * @param p2 GNUNET_PEER_Id of another peer that was connected to the first and
2600  *           no longer is.
2601  *
2602  * TODO: optimize (see below)
2603  */
2604 static void
2605 peer_info_remove_path (struct MeshPeerInfo *peer, GNUNET_PEER_Id p1,
2606                        GNUNET_PEER_Id p2)
2607 {
2608   struct MeshPeerPath *p;
2609   struct MeshPeerPath *aux;
2610   struct MeshPeerInfo *peer_d;
2611   GNUNET_PEER_Id d;
2612   unsigned int destroyed;
2613   unsigned int best;
2614   unsigned int cost;
2615   unsigned int i;
2616
2617   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "peer_info_remove_path\n");
2618   destroyed = 0;
2619   p = peer->path_head;
2620   while (NULL != p)
2621   {
2622     aux = p->next;
2623     for (i = 0; i < (p->length - 1); i++)
2624     {
2625       if ((p->peers[i] == p1 && p->peers[i + 1] == p2) ||
2626           (p->peers[i] == p2 && p->peers[i + 1] == p1))
2627       {
2628         GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, p);
2629         path_destroy (p);
2630         destroyed++;
2631         break;
2632       }
2633     }
2634     p = aux;
2635   }
2636   if (0 == destroyed)
2637     return;
2638
2639   for (i = 0; i < peer->ntunnels; i++)
2640   {
2641     d = tunnel_notify_connection_broken (peer->tunnels[i], p1, p2);
2642     if (0 == d)
2643       continue;
2644     /* TODO
2645      * Problem: one or more peers have been deleted from the tunnel tree.
2646      * We don't know who they are to try to add them again.
2647      * We need to try to find a new path for each of the disconnected peers.
2648      * Some of them might already have a path to reach them that does not
2649      * involve p1 and p2. Adding all anew might render in a better tree than
2650      * the trivial immediate fix.
2651      *
2652      * Trivial immiediate fix: try to reconnect to the disconnected node. All
2653      * its children will be reachable trough him.
2654      */
2655     peer_d = peer_info_get_short (d);
2656     best = UINT_MAX;
2657     aux = NULL;
2658     for (p = peer_d->path_head; NULL != p; p = p->next)
2659     {
2660       if ((cost = tree_get_path_cost (peer->tunnels[i]->tree, p)) < best)
2661       {
2662         best = cost;
2663         aux = p;
2664       }
2665     }
2666     if (NULL != aux)
2667     {
2668       /* No callback, as peer will be already disconnected and a connection
2669        * scheduled by tunnel_notify_connection_broken.
2670        */
2671       tree_add_path (peer->tunnels[i]->tree, aux, NULL, NULL);
2672     }
2673     else
2674     {
2675       peer_info_connect (peer_d, peer->tunnels[i]);
2676     }
2677   }
2678   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "peer_info_remove_path END\n");
2679 }
2680
2681
2682 /**
2683  * Add the path to the peer and update the path used to reach it in case this
2684  * is the shortest.
2685  *
2686  * @param peer_info Destination peer to add the path to.
2687  * @param path New path to add. Last peer must be the peer in arg 1.
2688  *             Path will be either used of freed if already known.
2689  * @param trusted Do we trust that this path is real?
2690  */
2691 void
2692 peer_info_add_path (struct MeshPeerInfo *peer_info, struct MeshPeerPath *path,
2693                     int trusted)
2694 {
2695   struct MeshPeerPath *aux;
2696   unsigned int l;
2697   unsigned int l2;
2698
2699   if ((NULL == peer_info) || (NULL == path))
2700   {
2701     GNUNET_break (0);
2702     path_destroy (path);
2703     return;
2704   }
2705   if (path->peers[path->length - 1] != peer_info->id)
2706   {
2707     GNUNET_break (0);
2708     path_destroy (path);
2709     return;
2710   }
2711   if (path->length <= 2 && GNUNET_NO == trusted)
2712   {
2713     /* Only allow CORE to tell us about direct paths */
2714     path_destroy (path);
2715     return;
2716   }
2717   GNUNET_assert (peer_info->id == path->peers[path->length - 1]);
2718   for (l = 1; l < path->length; l++)
2719   {
2720     if (path->peers[l] == myid)
2721     {
2722       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shortening path by %u\n", l);
2723       for (l2 = 0; l2 < path->length - l; l2++)
2724       {
2725         path->peers[l2] = path->peers[l + l2];
2726       }
2727       path->length -= l;
2728       l = 1;
2729       path->peers =
2730           GNUNET_realloc (path->peers, path->length * sizeof (GNUNET_PEER_Id));
2731     }
2732   }
2733 #if MESH_DEBUG
2734   {
2735     struct GNUNET_PeerIdentity id;
2736
2737     GNUNET_PEER_resolve (peer_info->id, &id);
2738     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "adding path [%u] to peer %s\n",
2739                 path->length, GNUNET_i2s (&id));
2740   }
2741 #endif
2742   l = path_get_length (path);
2743   if (0 == l)
2744   {
2745     GNUNET_free (path);
2746     return;
2747   }
2748
2749   GNUNET_assert (peer_info->id == path->peers[path->length - 1]);
2750   for (aux = peer_info->path_head; aux != NULL; aux = aux->next)
2751   {
2752     l2 = path_get_length (aux);
2753     if (l2 > l)
2754     {
2755       GNUNET_CONTAINER_DLL_insert_before (peer_info->path_head,
2756                                           peer_info->path_tail, aux, path);
2757       return;
2758     }
2759     else
2760     {
2761       if (l2 == l && memcmp (path->peers, aux->peers, l) == 0)
2762       {
2763         path_destroy (path);
2764         return;
2765       }
2766     }
2767   }
2768   GNUNET_CONTAINER_DLL_insert_tail (peer_info->path_head, peer_info->path_tail,
2769                                     path);
2770   return;
2771 }
2772
2773
2774 /**
2775  * Add the path to the origin peer and update the path used to reach it in case
2776  * this is the shortest.
2777  * The path is given in peer_info -> destination, therefore we turn the path
2778  * upside down first.
2779  *
2780  * @param peer_info Peer to add the path to, being the origin of the path.
2781  * @param path New path to add after being inversed.
2782  * @param trusted Do we trust that this path is real?
2783  */
2784 static void
2785 peer_info_add_path_to_origin (struct MeshPeerInfo *peer_info,
2786                               struct MeshPeerPath *path, int trusted)
2787 {
2788   path_invert (path);
2789   peer_info_add_path (peer_info, path, trusted);
2790 }
2791
2792
2793 /**
2794  * Build a PeerPath from the paths returned from the DHT, reversing the paths
2795  * to obtain a local peer -> destination path and interning the peer ids.
2796  *
2797  * @return Newly allocated and created path
2798  */
2799 static struct MeshPeerPath *
2800 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
2801                      unsigned int get_path_length,
2802                      const struct GNUNET_PeerIdentity *put_path,
2803                      unsigned int put_path_length)
2804 {
2805   struct MeshPeerPath *p;
2806   GNUNET_PEER_Id id;
2807   int i;
2808
2809   p = path_new (1);
2810   p->peers[0] = myid;
2811   GNUNET_PEER_change_rc (myid, 1);
2812   i = get_path_length;
2813   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   GET has %d hops.\n", i);
2814   for (i--; i >= 0; i--)
2815   {
2816     id = GNUNET_PEER_intern (&get_path[i]);
2817     if (p->length > 0 && id == p->peers[p->length - 1])
2818     {
2819       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Optimizing 1 hop out.\n");
2820       GNUNET_PEER_change_rc (id, -1);
2821     }
2822     else
2823     {
2824       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Adding from GET: %s.\n",
2825                   GNUNET_i2s (&get_path[i]));
2826       p->length++;
2827       p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
2828       p->peers[p->length - 1] = id;
2829     }
2830   }
2831   i = put_path_length;
2832   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   PUT has %d hops.\n", i);
2833   for (i--; i >= 0; i--)
2834   {
2835     id = GNUNET_PEER_intern (&put_path[i]);
2836     if (id == myid)
2837     {
2838       /* PUT path went through us, so discard the path up until now and start
2839        * from here to get a much shorter (and loop-free) path.
2840        */
2841       path_destroy (p);
2842       p = path_new (0);
2843     }
2844     if (p->length > 0 && id == p->peers[p->length - 1])
2845     {
2846       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Optimizing 1 hop out.\n");
2847       GNUNET_PEER_change_rc (id, -1);
2848     }
2849     else
2850     {
2851       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Adding from PUT: %s.\n",
2852                   GNUNET_i2s (&put_path[i]));
2853       p->length++;
2854       p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
2855       p->peers[p->length - 1] = id;
2856     }
2857   }
2858 #if MESH_DEBUG
2859   if (get_path_length > 0)
2860     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (first of GET: %s)\n",
2861                 GNUNET_i2s (&get_path[0]));
2862   if (put_path_length > 0)
2863     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (first of PUT: %s)\n",
2864                 GNUNET_i2s (&put_path[0]));
2865   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   In total: %d hops\n",
2866               p->length);
2867   for (i = 0; i < p->length; i++)
2868   {
2869     struct GNUNET_PeerIdentity peer_id;
2870
2871     GNUNET_PEER_resolve (p->peers[i], &peer_id);
2872     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "       %u: %s\n", p->peers[i],
2873                 GNUNET_i2s (&peer_id));
2874   }
2875 #endif
2876   return p;
2877 }
2878
2879
2880 /**
2881  * Adds a path to the peer_infos of all the peers in the path
2882  *
2883  * @param p Path to process.
2884  * @param confirmed Whether we know if the path works or not.
2885  */
2886 static void
2887 path_add_to_peers (struct MeshPeerPath *p, int confirmed)
2888 {
2889   unsigned int i;
2890
2891   /* TODO: invert and add */
2892   for (i = 0; i < p->length && p->peers[i] != myid; i++) /* skip'em */ ;
2893   for (i++; i < p->length; i++)
2894   {
2895     struct MeshPeerInfo *aux;
2896     struct MeshPeerPath *copy;
2897
2898     aux = peer_info_get_short (p->peers[i]);
2899     copy = path_duplicate (p);
2900     copy->length = i + 1;
2901     peer_info_add_path (aux, copy, GNUNET_NO);
2902   }
2903 }
2904
2905
2906 /**
2907  * Send keepalive packets for a peer
2908  *
2909  * @param cls Closure (tunnel for which to send the keepalive).
2910  * @param tc Notification context.
2911  *
2912  * TODO: implement explicit multicast keepalive?
2913  */
2914 static void
2915 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
2916
2917
2918 /**
2919  * Search for a tunnel among the incoming tunnels
2920  *
2921  * @param tid the local id of the tunnel
2922  *
2923  * @return tunnel handler, NULL if doesn't exist
2924  */
2925 static struct MeshTunnel *
2926 tunnel_get_incoming (MESH_TunnelNumber tid)
2927 {
2928   struct GNUNET_HashCode hash;
2929
2930   GNUNET_assert (tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV);
2931   GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
2932   return GNUNET_CONTAINER_multihashmap_get (incoming_tunnels, &hash);
2933 }
2934
2935
2936 /**
2937  * Search for a tunnel among the tunnels for a client
2938  *
2939  * @param c the client whose tunnels to search in
2940  * @param tid the local id of the tunnel
2941  *
2942  * @return tunnel handler, NULL if doesn't exist
2943  */
2944 static struct MeshTunnel *
2945 tunnel_get_by_local_id (struct MeshClient *c, MESH_TunnelNumber tid)
2946 {
2947   if (tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
2948   {
2949     return tunnel_get_incoming (tid);
2950   }
2951   else
2952   {
2953     struct GNUNET_HashCode hash;
2954
2955     GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
2956     return GNUNET_CONTAINER_multihashmap_get (c->own_tunnels, &hash);
2957   }
2958 }
2959
2960
2961 /**
2962  * Search for a tunnel by global ID using PEER_ID
2963  *
2964  * @param pi owner of the tunnel
2965  * @param tid global tunnel number
2966  *
2967  * @return tunnel handler, NULL if doesn't exist
2968  */
2969 static struct MeshTunnel *
2970 tunnel_get_by_pi (GNUNET_PEER_Id pi, MESH_TunnelNumber tid)
2971 {
2972   struct MESH_TunnelID id;
2973   struct GNUNET_HashCode hash;
2974
2975   id.oid = pi;
2976   id.tid = tid;
2977
2978   GNUNET_CRYPTO_hash (&id, sizeof (struct MESH_TunnelID), &hash);
2979   return GNUNET_CONTAINER_multihashmap_get (tunnels, &hash);
2980 }
2981
2982
2983 /**
2984  * Search for a tunnel by global ID using full PeerIdentities
2985  *
2986  * @param oid owner of the tunnel
2987  * @param tid global tunnel number
2988  *
2989  * @return tunnel handler, NULL if doesn't exist
2990  */
2991 static struct MeshTunnel *
2992 tunnel_get (struct GNUNET_PeerIdentity *oid, MESH_TunnelNumber tid)
2993 {
2994   return tunnel_get_by_pi (GNUNET_PEER_search (oid), tid);
2995 }
2996
2997
2998 /**
2999  * Delete an active client from the tunnel.
3000  * 
3001  * @param t Tunnel.
3002  * @param c Client.
3003  */
3004 static void
3005 tunnel_delete_active_client (struct MeshTunnel *t, const struct MeshClient *c)
3006 {
3007   unsigned int i;
3008
3009   for (i = 0; i < t->nclients; i++)
3010   {
3011     if (t->clients[i] == c)
3012     {
3013       t->clients[i] = t->clients[t->nclients - 1];
3014       t->clients_fc[i] = t->clients_fc[t->nclients - 1];
3015       GNUNET_array_grow (t->clients, t->nclients, t->nclients - 1);
3016       t->nclients++;
3017       GNUNET_array_grow (t->clients_fc, t->nclients, t->nclients - 1);
3018       break;
3019     }
3020   }
3021 }
3022
3023
3024 /**
3025  * Delete an ignored client from the tunnel.
3026  * 
3027  * @param t Tunnel.
3028  * @param c Client.
3029  */
3030 static void
3031 tunnel_delete_ignored_client (struct MeshTunnel *t, const struct MeshClient *c)
3032 {
3033   unsigned int i;
3034
3035   for (i = 0; i < t->nignore; i++)
3036   {
3037     if (t->ignore[i] == c)
3038     {
3039       t->ignore[i] = t->ignore[t->nignore - 1];
3040       GNUNET_array_grow (t->ignore, t->nignore, t->nignore - 1);
3041       break;
3042     }
3043   }
3044 }
3045
3046
3047 /**
3048  * Delete a client from the tunnel. It should be only done on
3049  * client disconnection, otherwise use client_ignore_tunnel.
3050  * 
3051  * @param t Tunnel.
3052  * @param c Client.
3053  */
3054 static void
3055 tunnel_delete_client (struct MeshTunnel *t, const struct MeshClient *c)
3056 {
3057   tunnel_delete_ignored_client (t, c);
3058   tunnel_delete_active_client (t, c);
3059 }
3060
3061
3062 /**
3063  * Iterator to free MeshTunnelChildInfo of tunnel children.
3064  *
3065  * @param cls Closure (tunnel info).
3066  * @param key Hash of GNUNET_PEER_Id (unused).
3067  * @param value MeshTunnelChildInfo of the child.
3068  *
3069  * @return always GNUNET_YES, to keep iterating
3070  */
3071 static int
3072 tunnel_destroy_child (void *cls,
3073                       const struct GNUNET_HashCode * key,
3074                       void *value)
3075 {
3076   GNUNET_free (value);
3077   return GNUNET_YES;
3078 }
3079
3080
3081 /**
3082  * Callback used to notify a client owner of a tunnel that a peer has
3083  * disconnected, most likely because of a path change.
3084  *
3085  * @param cls Closure (tunnel this notification is about).
3086  * @param peer_id Short ID of disconnected peer.
3087  */
3088 void
3089 tunnel_notify_client_peer_disconnected (void *cls, GNUNET_PEER_Id peer_id)
3090 {
3091   struct MeshTunnel *t = cls;
3092   struct MeshPeerInfo *peer;
3093   struct MeshPathInfo *path_info;
3094
3095   if (NULL != t->owner && NULL != nc)
3096   {
3097     struct GNUNET_MESH_PeerControl msg;
3098
3099     msg.header.size = htons (sizeof (msg));
3100     msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL);
3101     msg.tunnel_id = htonl (t->local_tid);
3102     GNUNET_PEER_resolve (peer_id, &msg.peer);
3103     GNUNET_SERVER_notification_context_unicast (nc, t->owner->handle,
3104                                                 &msg.header, GNUNET_NO);
3105   }
3106   peer = peer_info_get_short (peer_id);
3107   path_info = GNUNET_malloc (sizeof (struct MeshPathInfo));
3108   path_info->peer = peer;
3109   path_info->t = t;
3110   GNUNET_SCHEDULER_add_now (&peer_info_connect_task, path_info);
3111 }
3112
3113
3114 /**
3115  * Add a peer to a tunnel, accomodating paths accordingly and initializing all
3116  * needed rescources.
3117  * If peer already exists, reevaluate shortest path and change if different.
3118  *
3119  * @param t Tunnel we want to add a new peer to
3120  * @param peer PeerInfo of the peer being added
3121  *
3122  */
3123 static void
3124 tunnel_add_peer (struct MeshTunnel *t, struct MeshPeerInfo *peer)
3125 {
3126   struct GNUNET_PeerIdentity id;
3127   struct MeshPeerPath *best_p;
3128   struct MeshPeerPath *p;
3129   unsigned int best_cost;
3130   unsigned int cost;
3131
3132   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "tunnel_add_peer\n");
3133   GNUNET_PEER_resolve (peer->id, &id);
3134   if (GNUNET_NO ==
3135       GNUNET_CONTAINER_multihashmap_contains (t->peers, &id.hashPubKey))
3136   {
3137     t->peers_total++;
3138     GNUNET_array_append (peer->tunnels, peer->ntunnels, t);
3139     GNUNET_assert (GNUNET_OK ==
3140                    GNUNET_CONTAINER_multihashmap_put (t->peers, &id.hashPubKey,
3141                                                       peer,
3142                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
3143   }
3144
3145   if (NULL != (p = peer->path_head))
3146   {
3147     best_p = p;
3148     best_cost = tree_get_path_cost (t->tree, p);
3149     while (NULL != p)
3150     {
3151       if ((cost = tree_get_path_cost (t->tree, p)) < best_cost)
3152       {
3153         best_cost = cost;
3154         best_p = p;
3155       }
3156       p = p->next;
3157     }
3158     tree_add_path (t->tree, best_p, &tunnel_notify_client_peer_disconnected, t);
3159     if (GNUNET_SCHEDULER_NO_TASK == t->path_refresh_task)
3160       t->path_refresh_task =
3161           GNUNET_SCHEDULER_add_delayed (refresh_path_time, &path_refresh, t);
3162   }
3163   else
3164   {
3165     /* Start a DHT get */
3166     peer_info_connect (peer, t);
3167   }
3168   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "tunnel_add_peer END\n");
3169 }
3170
3171 /**
3172  * Add a path to a tunnel which we don't own, just to remember the next hop.
3173  * If destination node was already in the tunnel, the first hop information
3174  * will be replaced with the new path.
3175  *
3176  * @param t Tunnel we want to add a new peer to
3177  * @param p Path to add
3178  * @param own_pos Position of local node in path.
3179  *
3180  */
3181 static void
3182 tunnel_add_path (struct MeshTunnel *t, struct MeshPeerPath *p,
3183                  unsigned int own_pos)
3184 {
3185   struct GNUNET_PeerIdentity id;
3186
3187   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "tunnel_add_path\n");
3188   GNUNET_assert (0 != own_pos);
3189   tree_add_path (t->tree, p, NULL, NULL);
3190   if (own_pos < p->length - 1)
3191   {
3192     GNUNET_PEER_resolve (p->peers[own_pos + 1], &id);
3193     tree_update_first_hops (t->tree, myid, &id);
3194   }
3195   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "tunnel_add_path END\n");
3196 }
3197
3198 /**
3199  * Add a client to a tunnel, initializing all needed data structures.
3200  * 
3201  * @param t Tunnel to which add the client.
3202  * @param c Client which to add to the tunnel.
3203  */
3204 static void
3205 tunnel_add_client (struct MeshTunnel *t, struct MeshClient *c)
3206 {
3207   struct MeshTunnelClientInfo clinfo;
3208
3209   GNUNET_array_append (t->clients, t->nclients, c);
3210   clinfo.fwd_ack = t->fwd_pid + 1;
3211   clinfo.bck_ack = t->nobuffer ? 1 : INITIAL_WINDOW_SIZE;
3212   clinfo.fwd_pid = t->fwd_pid;
3213   clinfo.bck_pid = (uint32_t) -1; // Expected next: 0
3214   t->nclients--;
3215   GNUNET_array_append (t->clients_fc, t->nclients, clinfo);
3216 }
3217
3218
3219 /**
3220  * Notifies a tunnel that a connection has broken that affects at least
3221  * some of its peers. Sends a notification towards the root of the tree.
3222  * In case the peer is the owner of the tree, notifies the client that owns
3223  * the tunnel and tries to reconnect.
3224  *
3225  * @param t Tunnel affected.
3226  * @param p1 Peer that got disconnected from p2.
3227  * @param p2 Peer that got disconnected from p1.
3228  *
3229  * @return Short ID of the peer disconnected (either p1 or p2).
3230  *         0 if the tunnel remained unaffected.
3231  */
3232 static GNUNET_PEER_Id
3233 tunnel_notify_connection_broken (struct MeshTunnel *t, GNUNET_PEER_Id p1,
3234                                  GNUNET_PEER_Id p2)
3235 {
3236   GNUNET_PEER_Id pid;
3237
3238   pid =
3239       tree_notify_connection_broken (t->tree, p1, p2,
3240                                      &tunnel_notify_client_peer_disconnected,
3241                                      t);
3242   if (myid != p1 && myid != p2)
3243   {
3244     return pid;
3245   }
3246   if (pid != myid)
3247   {
3248     if (tree_get_predecessor (t->tree) != 0)
3249     {
3250       /* We are the peer still connected, notify owner of the disconnection. */
3251       struct GNUNET_MESH_PathBroken msg;
3252       struct GNUNET_PeerIdentity neighbor;
3253
3254       msg.header.size = htons (sizeof (msg));
3255       msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN);
3256       GNUNET_PEER_resolve (t->id.oid, &msg.oid);
3257       msg.tid = htonl (t->id.tid);
3258       msg.peer1 = my_full_id;
3259       GNUNET_PEER_resolve (pid, &msg.peer2);
3260       GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &neighbor);
3261       send_message (&msg.header, &neighbor, t);
3262     }
3263   }
3264   return pid;
3265 }
3266
3267
3268 /**
3269  * Send a multicast packet to a neighbor.
3270  *
3271  * @param cls Closure (Info about the multicast packet)
3272  * @param neighbor_id Short ID of the neighbor to send the packet to.
3273  */
3274 static void
3275 tunnel_send_multicast_iterator (void *cls, GNUNET_PEER_Id neighbor_id)
3276 {
3277   struct MeshData *mdata = cls;
3278   struct MeshTransmissionDescriptor *info;
3279   struct GNUNET_PeerIdentity neighbor;
3280
3281   info = GNUNET_malloc (sizeof (struct MeshTransmissionDescriptor));
3282
3283   info->mesh_data = mdata;
3284   (*(mdata->reference_counter)) ++;
3285   info->destination = neighbor_id;
3286   GNUNET_PEER_resolve (neighbor_id, &neighbor);
3287   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   sending to %s...\n",
3288               GNUNET_i2s (&neighbor));
3289   info->peer = peer_info_get (&neighbor);
3290   GNUNET_assert (NULL != info->peer);
3291   queue_add(info,
3292             GNUNET_MESSAGE_TYPE_MESH_MULTICAST,
3293             info->mesh_data->data_len,
3294             info->peer,
3295             mdata->t);
3296 }
3297
3298
3299 /**
3300  * Send a message in a tunnel in multicast, sending a copy to each child node
3301  * down the local one in the tunnel tree.
3302  *
3303  * @param t Tunnel in which to send the data.
3304  * @param msg Message to be sent.
3305  * @param internal Has the service generated this message?
3306  */
3307 static void
3308 tunnel_send_multicast (struct MeshTunnel *t,
3309                        const struct GNUNET_MessageHeader *msg,
3310                        int internal)
3311 {
3312   struct MeshData *mdata;
3313
3314   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3315               " sending a multicast packet...\n");
3316   mdata = GNUNET_malloc (sizeof (struct MeshData));
3317   mdata->data_len = ntohs (msg->size);
3318   mdata->reference_counter = GNUNET_malloc (sizeof (unsigned int));
3319   mdata->t = t;
3320   mdata->data = GNUNET_malloc (mdata->data_len);
3321   memcpy (mdata->data, msg, mdata->data_len);
3322   if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_MESH_MULTICAST)
3323   {
3324     struct GNUNET_MESH_Multicast *mcast;
3325
3326     mcast = (struct GNUNET_MESH_Multicast *) mdata->data;
3327     mcast->ttl = htonl (ntohl (mcast->ttl) - 1);
3328     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  data packet, ttl: %u\n",
3329                 ntohl (mcast->ttl));
3330   }
3331   else
3332   {
3333     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  not a data packet, no ttl\n");
3334   }
3335   if (NULL != t->owner && GNUNET_YES != t->owner->shutting_down
3336       && GNUNET_NO == internal)
3337   {
3338     mdata->task = GNUNET_malloc (sizeof (GNUNET_SCHEDULER_TaskIdentifier));
3339     (*(mdata->task)) =
3340         GNUNET_SCHEDULER_add_delayed (unacknowledged_wait_time, &client_allow_send,
3341                                       mdata);
3342     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "timeout task %u\n",
3343                 *(mdata->task));
3344   }
3345
3346   tree_iterate_children (t->tree, &tunnel_send_multicast_iterator, mdata);
3347   if (*(mdata->reference_counter) == 0)
3348   {
3349     GNUNET_free (mdata->data);
3350     GNUNET_free (mdata->reference_counter);
3351     if (NULL != mdata->task)
3352     {
3353       GNUNET_SCHEDULER_cancel(*(mdata->task));
3354       GNUNET_free (mdata->task);
3355       GNUNET_SERVER_receive_done (t->owner->handle, GNUNET_OK);
3356     }
3357     // FIXME change order?
3358     GNUNET_free (mdata);
3359   }
3360   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3361               " sending a multicast packet done\n");
3362   return;
3363 }
3364
3365
3366 /**
3367  * Increase the SKIP value of all peers that
3368  * have not received a unicast message.
3369  *
3370  * @param cls Closure (ID of the peer that HAS received the message).
3371  * @param key ID of the neighbor.
3372  * @param value Information about the neighbor.
3373  *
3374  * @return GNUNET_YES to keep iterating.
3375  */
3376 static int
3377 tunnel_add_skip (void *cls,
3378                  const struct GNUNET_HashCode * key,
3379                  void *value)
3380 {
3381   struct GNUNET_PeerIdentity *neighbor = cls;
3382   struct MeshTunnelChildInfo *cinfo = value;
3383
3384   /* TODO compare only pointers? key == neighbor? */
3385   if (0 == memcmp (&neighbor->hashPubKey, key, sizeof (struct GNUNET_HashCode)))
3386   {
3387     return GNUNET_YES;
3388   }
3389   cinfo->skip++;
3390   return GNUNET_YES;
3391 }
3392
3393
3394 /**
3395  * @brief Get neighbor's Flow Control information.
3396  *
3397  * Retrieves the MeshTunnelChildInfo containing Flow Control data about a direct
3398  * descendant of the local node in a certain tunnel.
3399  * If the info is not yet there (recently created path), creates the data struct
3400  * and inserts it into the tunnel info, initialized to the current tunnel ACK
3401  * values.
3402  *
3403  * @param t Tunnel related.
3404  * @param peer Neighbor whose Flow Control info is needed.
3405  *
3406  * @return Neighbor's Flow Control info.
3407  */
3408 static struct MeshTunnelChildInfo *
3409 tunnel_get_neighbor_fc (const struct MeshTunnel *t,
3410                         const struct GNUNET_PeerIdentity *peer)
3411 {
3412   struct MeshTunnelChildInfo *cinfo;
3413   cinfo = GNUNET_CONTAINER_multihashmap_get (t->children_fc,
3414                                              &peer->hashPubKey);
3415   if (NULL == cinfo)
3416   {
3417     uint32_t delta;
3418
3419     cinfo = GNUNET_malloc (sizeof (struct MeshTunnelChildInfo));
3420     cinfo->id = GNUNET_PEER_intern (peer);
3421     cinfo->skip = t->fwd_pid;
3422
3423     delta = t->nobuffer ? 1 : INITIAL_WINDOW_SIZE;
3424     cinfo->fwd_ack = t->fwd_pid + delta;
3425     cinfo->bck_ack = delta;
3426
3427     GNUNET_assert (GNUNET_OK ==
3428       GNUNET_CONTAINER_multihashmap_put (t->children_fc,
3429                                          &peer->hashPubKey,
3430                                          cinfo,
3431                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
3432   }
3433   return cinfo;
3434 }
3435
3436
3437 /**
3438  * Get the Flow Control info of a client.
3439  * 
3440  * @param t Tunnel on which to look.
3441  * @param c Client whose ACK to get.
3442  * 
3443  * @return ACK value.
3444  */
3445 static struct MeshTunnelClientInfo *
3446 tunnel_get_client_fc (struct MeshTunnel *t,
3447                       struct MeshClient *c)
3448 {
3449   unsigned int i;
3450
3451   for (i = 0; i < t->nclients; i++)
3452   {
3453     if (t->clients[i] != c)
3454       continue;
3455     return &t->clients_fc[i];
3456   }
3457   GNUNET_assert (0);
3458   return NULL; // avoid compiler / coverity complaints
3459 }
3460
3461
3462 /**
3463  * Iterator to get the appropiate ACK value from all children nodes.
3464  *
3465  * @param cls Closue (tunnel).
3466  * @param id Id of the child node.
3467  */
3468 static void
3469 tunnel_get_child_fwd_ack (void *cls,
3470                           GNUNET_PEER_Id id)
3471 {
3472   struct GNUNET_PeerIdentity peer_id;
3473   struct MeshTunnelChildInfo *cinfo;
3474   struct MeshTunnelChildIteratorContext *ctx = cls;
3475   struct MeshTunnel *t = ctx->t;
3476   uint32_t ack;
3477
3478   GNUNET_PEER_resolve (id, &peer_id);
3479   cinfo = tunnel_get_neighbor_fc (t, &peer_id);
3480   ack = cinfo->fwd_ack;
3481
3482   if (GNUNET_NO == ctx->init)
3483   {
3484     ctx->max_child_ack = ack;
3485     ctx->init = GNUNET_YES;
3486   }
3487
3488   if (GNUNET_YES == t->speed_min)
3489   {
3490     ctx->max_child_ack = ctx->max_child_ack > ack ? ack : ctx->max_child_ack;
3491   }
3492   else
3493   {
3494     ctx->max_child_ack = ctx->max_child_ack > ack ? ctx->max_child_ack : ack;
3495   }
3496
3497 }
3498
3499
3500 /**
3501  * Get the maximum PID allowed to transmit to any
3502  * tunnel child of the local peer, depending on the tunnel
3503  * buffering/speed settings.
3504  *
3505  * @param t Tunnel.
3506  *
3507  * @return Maximum PID allowed (uint32 MAX), -1 if node has no children.
3508  */
3509 static int64_t
3510 tunnel_get_children_fwd_ack (struct MeshTunnel *t)
3511 {
3512   struct MeshTunnelChildIteratorContext ctx;
3513   ctx.t = t;
3514   ctx.max_child_ack = 0;
3515   ctx.nchildren = 0;
3516   tree_iterate_children (t->tree, tunnel_get_child_fwd_ack, &ctx);
3517
3518   if (0 == ctx.nchildren)
3519     return -1LL;
3520
3521   if (GNUNET_YES == t->nobuffer && GMC_is_pid_bigger(ctx.max_child_ack, t->fwd_pid))
3522     ctx.max_child_ack = t->fwd_pid + 1; // Might overflow, it's ok.
3523
3524   return (int64_t) ctx.max_child_ack;
3525 }
3526
3527
3528 /**
3529  * Set the FWD ACK value of a client in a particular tunnel.
3530  * 
3531  * @param t Tunnel affected.
3532  * @param c Client whose ACK to set.
3533  * @param ack ACK value.
3534  */
3535 static void
3536 tunnel_set_client_fwd_ack (struct MeshTunnel *t,
3537                            struct MeshClient *c, 
3538                            uint32_t ack)
3539 {
3540   unsigned int i;
3541
3542   for (i = 0; i < t->nclients; i++)
3543   {
3544     if (t->clients[i] != c)
3545       continue;
3546     t->clients_fc[i].fwd_ack = ack;
3547     return;
3548   }
3549   GNUNET_break (0);
3550 }
3551
3552
3553 /**
3554  * Get the highest ACK value of all clients in a particular tunnel,
3555  * according to the buffering/speed settings.
3556  * 
3557  * @param t Tunnel on which to look.
3558  * 
3559  * @return Corresponding ACK value (max uint32_t).
3560  *         If no clients are suscribed, -1.
3561  */
3562 static int64_t
3563 tunnel_get_clients_fwd_ack (struct MeshTunnel *t)
3564 {
3565   unsigned int i;
3566   int64_t ack;
3567
3568   if (0 == t->nclients)
3569     return -1;
3570
3571   for (ack = -1, i = 0; i < t->nclients; i++)
3572   {
3573     if (-1 == ack ||
3574         (GNUNET_YES == t->speed_min &&
3575          GNUNET_YES == GMC_is_pid_bigger (ack, t->clients_fc[i].fwd_ack)) ||
3576         (GNUNET_NO == t->speed_min &&
3577          GNUNET_YES == GMC_is_pid_bigger (t->clients_fc[i].fwd_ack, ack)))
3578     {
3579       ack = t->clients_fc[i].fwd_ack;
3580     }
3581   }
3582
3583   if (GNUNET_YES == t->nobuffer && GMC_is_pid_bigger(ack, t->fwd_pid))
3584     ack = (uint32_t) t->fwd_pid + 1; // Might overflow, it's ok.
3585
3586   return (uint32_t) ack;
3587 }
3588
3589
3590 /**
3591  * Get the current fwd ack value for a tunnel, taking in account the tunnel
3592  * mode and the status of all children nodes.
3593  *
3594  * @param t Tunnel.
3595  *
3596  * @return Maximum PID allowed.
3597  */
3598 static uint32_t
3599 tunnel_get_fwd_ack (struct MeshTunnel *t)
3600 {
3601   uint32_t count;
3602   uint32_t buffer_free;
3603   int64_t child_ack;
3604   int64_t client_ack;
3605   uint32_t ack;
3606
3607   count = t->fwd_pid - t->skip;
3608   buffer_free = t->fwd_queue_max - t->fwd_queue_n;
3609   ack = count + buffer_free; // Might overflow 32 bits, it's ok!
3610   child_ack = tunnel_get_children_fwd_ack (t);
3611   client_ack = tunnel_get_clients_fwd_ack (t);
3612   if (-1 == child_ack)
3613   {
3614     // Node has no children, child_ack AND core buffer are irrelevant.
3615     GNUNET_break (-1 != client_ack); // No children AND no clients? Not good! // FIXME fc
3616     return (uint32_t) client_ack;
3617   }
3618
3619   if (GNUNET_YES == t->speed_min)
3620   {
3621     ack = GMC_min_pid ((uint32_t) child_ack, ack);
3622     ack = GMC_min_pid ((uint32_t) client_ack, ack);
3623   }
3624   else
3625   {
3626     ack = GMC_max_pid ((uint32_t) child_ack, ack);
3627     ack = GMC_max_pid ((uint32_t) client_ack, ack);
3628   }
3629   if (GNUNET_YES == t->nobuffer && GMC_is_pid_bigger(ack, t->fwd_pid))
3630     ack = t->fwd_pid + 1; // Might overflow 32 bits, it's ok!
3631   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "c %u, bf %u, ch %u, cl %u, ACK: %u\n",
3632               count, buffer_free, child_ack, client_ack, ack);
3633   return ack;
3634 }
3635
3636 /**
3637  * Get the current bck ack value for a tunnel, taking in account the tunnel
3638  * mode and the status of all children nodes.
3639  *
3640  * @param t Tunnel.
3641  *
3642  * @return Maximum PID allowed.
3643  */
3644 static uint32_t
3645 tunnel_get_bck_ack (struct MeshTunnel *t)
3646 {
3647   uint32_t ack;
3648
3649   if (GNUNET_YES == t->nobuffer)
3650   {
3651     if (t->bck_ack > t->bck_pid)
3652     {
3653       return t->bck_pid + 1;
3654     }
3655     else
3656     {
3657       return t->bck_pid;
3658     }
3659   }
3660   ack = t->bck_pid + t->bck_queue_max - t->bck_queue_n;
3661
3662   // FIXME fc
3663   return ack;
3664 }
3665
3666
3667 /**
3668  * Build a local ACK message and send it to a local client.
3669  * 
3670  * @param t Tunnel on which to send the ACK.
3671  * @param c Client to whom send the ACK.
3672  * @param ack Value of the ACK.
3673  */
3674 static void
3675 send_local_ack (struct MeshTunnel *t, struct MeshClient *c, uint32_t ack)
3676 {
3677   struct GNUNET_MESH_LocalAck msg;
3678
3679   msg.header.size = htons (sizeof (msg));
3680   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
3681   msg.tunnel_id = htonl (t->local_tid_dest);
3682   msg.max_pid = htonl (ack); 
3683   GNUNET_SERVER_notification_context_unicast(nc,
3684                                               c->handle,
3685                                               &msg.header,
3686                                               GNUNET_NO);
3687 }
3688
3689 /**
3690  * Build an ACK message and queue it to send to the given peer.
3691  * 
3692  * @param t Tunnel on which to send the ACK.
3693  * @param peer Peer to whom send the ACK.
3694  * @param ack Value of the ACK.
3695  */
3696 static void
3697 send_ack (struct MeshTunnel *t, struct GNUNET_PeerIdentity *peer,  uint32_t ack)
3698 {
3699   struct GNUNET_MESH_ACK msg;
3700
3701   GNUNET_PEER_resolve (t->id.oid, &msg.oid);
3702   msg.header.size = htons (sizeof (msg));
3703   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_ACK);
3704   msg.pid = htonl (ack);
3705   msg.tid = htonl (t->id.tid);
3706
3707   send_message (&msg.header, peer, t);
3708 }
3709
3710
3711 /**
3712  * Send an ACK informing the predecessor about the available buffer space.
3713  * In case there is no predecessor, inform the owning client.
3714  * If buffering is off, send only on behalf of children or self if endpoint.
3715  * If buffering is on, send when sent to children and buffer space is free.
3716  * Note that although the name is fwd_ack, the FWD mean forward *traffic*,
3717  * the ACK itself goes "back" (towards root).
3718  * 
3719  * @param t Tunnel on which to send the ACK.
3720  * @param type Type of message that triggered the ACK transmission.
3721  */
3722 static void
3723 tunnel_send_fwd_ack (struct MeshTunnel *t, uint16_t type)
3724 {
3725   struct GNUNET_PeerIdentity id;
3726   uint32_t ack;
3727
3728   if (NULL != t->owner)
3729   {
3730     send_client_tunnel_ack (t->owner, t);
3731     return;
3732   }
3733   /* Is it after unicast / multicast retransmission? */
3734   switch (type)
3735   {
3736     case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
3737     case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
3738       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3739                   "ACK due to FWD DATA retransmission\n");
3740       if (GNUNET_YES == t->nobuffer)
3741       {
3742         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, nobuffer\n");
3743         return;
3744       }
3745       if (t->fwd_queue_max > t->fwd_queue_n * 2)
3746       {
3747         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, buffer free\n");
3748         return;
3749       }
3750       break;
3751     case GNUNET_MESSAGE_TYPE_MESH_ACK:
3752     case GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK:
3753       break;
3754     default:
3755       GNUNET_break (0);
3756   }
3757
3758   /* Ok, ACK might be necessary, what PID to ACK? */
3759   ack = tunnel_get_fwd_ack (t);
3760
3761   /* If speed_min and not all children have ack'd, dont send yet */
3762   if (ack == t->last_fwd_ack)
3763   {
3764     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending FWD ACK, not ready\n");
3765     return;
3766   }
3767
3768   t->last_fwd_ack = ack;
3769   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
3770   send_ack (t, &id, ack);
3771 }
3772
3773
3774 /**
3775  * Iterator to send a child node a BCK ACK to allow him to send more
3776  * to_origin data.
3777  *
3778  * @param cls Closure (tunnel).
3779  * @param id Id of the child node.
3780  */
3781 static void
3782 tunnel_send_child_bck_ack (void *cls,
3783                            GNUNET_PEER_Id id)
3784 {
3785   struct MeshTunnel *t = cls;
3786   struct MeshTunnelChildInfo *cinfo;
3787   struct GNUNET_PeerIdentity peer;
3788
3789   GNUNET_PEER_resolve (id, &peer);
3790   cinfo = tunnel_get_neighbor_fc (t, &peer);
3791
3792   if (cinfo->bck_ack != cinfo->pid &&
3793       GNUNET_NO == GMC_is_pid_bigger (cinfo->bck_ack, cinfo->pid))
3794     return;
3795
3796   cinfo->bck_ack++;
3797   send_ack (t, &peer, cinfo->bck_ack);
3798 }
3799
3800
3801 /**
3802  * @brief Send BCK ACKs to clients to allow them more to_origin traffic
3803  * 
3804  * Iterates over all clients and sends BCK ACKs to the ones that need it.
3805  * 
3806  * @param t Tunnel on which to send the BCK ACKs.
3807  */
3808 static void
3809 tunnel_send_clients_bck_ack (struct MeshTunnel *t)
3810 {
3811   unsigned int i;
3812
3813   /* Find client whom to allow to send to origin (with lowest buffer space) */
3814   for (i = 0; i < t->nclients; i++)
3815   {
3816     struct MeshTunnelClientInfo *clinfo;
3817     unsigned int delta;
3818
3819     clinfo = &t->clients_fc[i];
3820     delta = clinfo->bck_ack - clinfo->bck_pid;
3821
3822     if ((GNUNET_NO == t->nobuffer && ACK_THRESHOLD > delta) ||
3823         (GNUNET_YES == t->nobuffer && 0 == delta))
3824     {
3825       uint32_t ack;
3826
3827       ack = clinfo->bck_pid;
3828       ack += t->nobuffer ? 1 : INITIAL_WINDOW_SIZE;
3829       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3830                   "  sending ack to client %u: %u\n",
3831                   t->clients[i]->id, ack);
3832       send_local_ack (t, t->clients[i], ack);
3833       clinfo->bck_ack = ack;
3834     }
3835   }
3836 }
3837
3838
3839 /**
3840  * Send an ACK informing the children nodes and destination clients about
3841  * the available buffer space.
3842  * If buffering is off, send only on behalf of root (can be self).
3843  * If buffering is on, send when sent to predecessor and buffer space is free.
3844  * Note that although the name is bck_ack, the BCK mean backwards *traffic*,
3845  * the ACK itself goes "forward" (towards children/clients).
3846  * 
3847  * @param t Tunnel on which to send the ACK.
3848  * @param type Type of message that triggered the ACK transmission.
3849  */
3850 static void
3851 tunnel_send_bck_ack (struct MeshTunnel *t, uint16_t type)
3852 {
3853   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3854               "Sending BCK ACK on tunnel %u [%u]\n",
3855               t->id.oid, t->id.tid);
3856   /* Is it after data to_origin retransmission? */
3857   switch (type)
3858   {
3859     case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
3860       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3861                   "ACK due to BCK DATA retransmission\n");
3862       if (GNUNET_YES == t->nobuffer)
3863       {
3864         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, nobuffer\n");
3865         return;
3866       }
3867       if (t->bck_queue_max > t->bck_queue_n * 2)
3868       {
3869 //         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, buffer free\n");
3870 //         return;
3871       }
3872       break;
3873     case GNUNET_MESSAGE_TYPE_MESH_ACK:
3874     case GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK:
3875       // FIXME fc
3876       break;
3877     default:
3878       GNUNET_break (0);
3879   }
3880
3881   tunnel_send_clients_bck_ack (t);
3882   tree_iterate_children (t->tree, &tunnel_send_child_bck_ack, NULL);
3883 }
3884
3885
3886 /**
3887  * Send a message to all peers in this tunnel that the tunnel is no longer
3888  * valid.
3889  *
3890  * @param t The tunnel whose peers to notify.
3891  */
3892 static void
3893 tunnel_send_destroy (struct MeshTunnel *t)
3894 {
3895   struct GNUNET_MESH_TunnelDestroy msg;
3896
3897   msg.header.size = htons (sizeof (msg));
3898   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY);
3899   GNUNET_PEER_resolve (t->id.oid, &msg.oid);
3900   msg.tid = htonl (t->id.tid);
3901   tunnel_send_multicast (t, &msg.header, GNUNET_NO);
3902 }
3903
3904
3905 /**
3906  * Cancel all transmissions towards a neighbor that belong to a certain tunnel.
3907  *
3908  * @param cls Closure (Tunnel which to cancel).
3909  * @param neighbor_id Short ID of the neighbor to whom cancel the transmissions.
3910  */
3911 static void
3912 tunnel_cancel_queues (void *cls, GNUNET_PEER_Id neighbor_id)
3913 {
3914   struct MeshTunnel *t = cls;
3915   struct MeshPeerInfo *peer_info;
3916   struct MeshPeerQueue *pq;
3917   struct MeshPeerQueue *next;
3918
3919   peer_info = peer_info_get_short (neighbor_id);
3920   for (pq = peer_info->queue_head; NULL != pq; pq = next)
3921   {
3922     next = pq->next;
3923     if (pq->tunnel == t)
3924     {
3925       queue_destroy (pq, GNUNET_YES);
3926     }
3927   }
3928   if (NULL == peer_info->queue_head && NULL != peer_info->core_transmit)
3929   {
3930     GNUNET_CORE_notify_transmit_ready_cancel(peer_info->core_transmit);
3931     peer_info->core_transmit = NULL;
3932   }
3933 }
3934
3935 /**
3936  * Destroy the tunnel and free any allocated resources linked to it.
3937  *
3938  * @param t the tunnel to destroy
3939  *
3940  * @return GNUNET_OK on success
3941  */
3942 static int
3943 tunnel_destroy (struct MeshTunnel *t)
3944 {
3945   struct MeshClient *c;
3946   struct GNUNET_HashCode hash;
3947   unsigned int i;
3948   int r;
3949
3950   if (NULL == t)
3951     return GNUNET_OK;
3952
3953   tree_iterate_children (t->tree, &tunnel_cancel_queues, t);
3954
3955   r = GNUNET_OK;
3956   c = t->owner;
3957 #if MESH_DEBUG
3958   {
3959     struct GNUNET_PeerIdentity id;
3960
3961     GNUNET_PEER_resolve (t->id.oid, &id);
3962     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s [%x]\n",
3963                 GNUNET_i2s (&id), t->id.tid);
3964     if (NULL != c)
3965       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
3966   }
3967 #endif
3968
3969   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
3970   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &hash, t))
3971   {
3972     r = GNUNET_SYSERR;
3973   }
3974
3975   GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
3976   if (NULL != c &&
3977       GNUNET_YES !=
3978       GNUNET_CONTAINER_multihashmap_remove (c->own_tunnels, &hash, t))
3979   {
3980     r = GNUNET_SYSERR;
3981   }
3982   GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
3983   for (i = 0; i < t->nclients; i++)
3984   {
3985     c = t->clients[i];
3986     if (GNUNET_YES !=
3987           GNUNET_CONTAINER_multihashmap_remove (c->incoming_tunnels, &hash, t))
3988     {
3989       r = GNUNET_SYSERR;
3990     }
3991   }
3992   for (i = 0; i < t->nignore; i++)
3993   {
3994     c = t->ignore[i];
3995     if (GNUNET_YES !=
3996           GNUNET_CONTAINER_multihashmap_remove (c->ignore_tunnels, &hash, t))
3997     {
3998       r = GNUNET_SYSERR;
3999     }
4000   }
4001   if (t->nclients > 0)
4002   {
4003     if (GNUNET_YES !=
4004         GNUNET_CONTAINER_multihashmap_remove (incoming_tunnels, &hash, t))
4005     {
4006       r = GNUNET_SYSERR;
4007     }
4008     GNUNET_free (t->clients);
4009   }
4010   if (NULL != t->peers)
4011   {
4012     GNUNET_CONTAINER_multihashmap_iterate (t->peers, &peer_info_delete_tunnel,
4013                                            t);
4014     GNUNET_CONTAINER_multihashmap_destroy (t->peers);
4015   }
4016
4017   GNUNET_CONTAINER_multihashmap_iterate (t->children_fc,
4018                                          &tunnel_destroy_child,
4019                                          t);
4020   GNUNET_CONTAINER_multihashmap_destroy (t->children_fc);
4021
4022   tree_destroy (t->tree);
4023
4024   if (NULL != t->regex_ctx)
4025     regex_cancel_search (t->regex_ctx);
4026   if (NULL != t->dht_get_type)
4027     GNUNET_DHT_get_stop (t->dht_get_type);
4028   if (GNUNET_SCHEDULER_NO_TASK != t->timeout_task)
4029     GNUNET_SCHEDULER_cancel (t->timeout_task);
4030   if (GNUNET_SCHEDULER_NO_TASK != t->path_refresh_task)
4031     GNUNET_SCHEDULER_cancel (t->path_refresh_task);
4032
4033   n_tunnels--;
4034   GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
4035   GNUNET_assert (0 <= n_tunnels);
4036   GNUNET_free (t);
4037   return r;
4038 }
4039
4040
4041 /**
4042  * Create a new tunnel
4043  * 
4044  * @param owner Who is the owner of the tunnel (short ID).
4045  * @param tid Tunnel Number of the tunnel.
4046  * @param client Clients that owns the tunnel, NULL for foreign tunnels.
4047  * @param local Tunnel Number for the tunnel, for the client point of view.
4048  * 
4049  * @return A new initialized tunnel. NULL on error.
4050  */
4051 static struct MeshTunnel *
4052 tunnel_new (GNUNET_PEER_Id owner,
4053             MESH_TunnelNumber tid,
4054             struct MeshClient *client,
4055             MESH_TunnelNumber local)
4056 {
4057   struct MeshTunnel *t;
4058   struct GNUNET_HashCode hash;
4059
4060   if (n_tunnels >= max_tunnels && NULL == client)
4061     return NULL;
4062
4063   t = GNUNET_malloc (sizeof (struct MeshTunnel));
4064   t->id.oid = owner;
4065   t->id.tid = tid;
4066   t->fwd_queue_max = (max_msgs_queue / max_tunnels) + 1;
4067   t->bck_queue_max = t->fwd_queue_max;
4068   t->tree = tree_new (owner);
4069   t->owner = client;
4070   t->fwd_pid = (uint32_t) -1; // Next (expected) = 0
4071   t->bck_pid = (uint32_t) -1; // Next (expected) = 0
4072   t->bck_ack = INITIAL_WINDOW_SIZE - 1;
4073   t->last_fwd_ack = INITIAL_WINDOW_SIZE - 1;
4074   t->local_tid = local;
4075   t->children_fc = GNUNET_CONTAINER_multihashmap_create (8);
4076   n_tunnels++;
4077   GNUNET_STATISTICS_update (stats, "# tunnels", 1, GNUNET_NO);
4078
4079   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
4080   if (GNUNET_OK !=
4081       GNUNET_CONTAINER_multihashmap_put (tunnels, &hash, t,
4082                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
4083   {
4084     GNUNET_break (0);
4085     tunnel_destroy (t);
4086     if (NULL != client)
4087     {
4088       GNUNET_break (0);
4089       GNUNET_SERVER_receive_done (client->handle, GNUNET_SYSERR);
4090     }
4091     return NULL;
4092   }
4093
4094   if (NULL != client)
4095   {
4096     GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
4097     if (GNUNET_OK !=
4098         GNUNET_CONTAINER_multihashmap_put (client->own_tunnels, &hash, t,
4099                                           GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
4100     {
4101       tunnel_destroy (t);
4102       GNUNET_break (0);
4103       GNUNET_SERVER_receive_done (client->handle, GNUNET_SYSERR);
4104       return NULL;
4105     }
4106   }
4107
4108   return t;
4109 }
4110
4111
4112 /**
4113  * Removes an explicit path from a tunnel, freeing all intermediate nodes
4114  * that are no longer needed, as well as nodes of no longer reachable peers.
4115  * The tunnel itself is also destoyed if results in a remote empty tunnel.
4116  *
4117  * @param t Tunnel from which to remove the path.
4118  * @param peer Short id of the peer which should be removed.
4119  */
4120 static void
4121 tunnel_delete_peer (struct MeshTunnel *t, GNUNET_PEER_Id peer)
4122 {
4123   if (GNUNET_NO == tree_del_peer (t->tree, peer, NULL, NULL))
4124     tunnel_destroy (t);
4125 }
4126
4127
4128 /**
4129  * tunnel_destroy_iterator: iterator for deleting each tunnel that belongs to a
4130  * client when the client disconnects. If the client is not the owner, the
4131  * owner will get notified if no more clients are in the tunnel and the client
4132  * get removed from the tunnel's list.
4133  *
4134  * @param cls closure (client that is disconnecting)
4135  * @param key the hash of the local tunnel id (used to access the hashmap)
4136  * @param value the value stored at the key (tunnel to destroy)
4137  *
4138  * @return GNUNET_OK on success
4139  */
4140 static int
4141 tunnel_destroy_iterator (void *cls, const struct GNUNET_HashCode * key, void *value)
4142 {
4143   struct MeshTunnel *t = value;
4144   struct MeshClient *c = cls;
4145   int r;
4146
4147   send_client_tunnel_disconnect(t, c);
4148   if (c != t->owner)
4149   {
4150     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4151                 "Client %u is destination, keeping the tunnel alive.\n", c->id);
4152     tunnel_delete_client(t, c);
4153     client_delete_tunnel(c, t);
4154     return GNUNET_OK;
4155   }
4156   tunnel_send_destroy(t);
4157   r = tunnel_destroy (t);
4158   return r;
4159 }
4160
4161
4162 /**
4163  * Timeout function, destroys tunnel if called
4164  *
4165  * @param cls Closure (tunnel to destroy).
4166  * @param tc TaskContext
4167  */
4168 static void
4169 tunnel_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4170 {
4171   struct MeshTunnel *t = cls;
4172
4173   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4174     return;
4175   t->timeout_task = GNUNET_SCHEDULER_NO_TASK;
4176   tunnel_destroy (t);
4177 }
4178
4179 /**
4180  * Resets the tunnel timeout. Starts it if no timeout was running.
4181  *
4182  * @param t Tunnel whose timeout to reset.
4183  *
4184  * TODO use heap to improve efficiency of scheduler.
4185  */
4186 static void
4187 tunnel_reset_timeout (struct MeshTunnel *t)
4188 {
4189   if (GNUNET_SCHEDULER_NO_TASK != t->timeout_task)
4190     GNUNET_SCHEDULER_cancel (t->timeout_task);
4191   t->timeout_task =
4192       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
4193                                     (refresh_path_time, 4), &tunnel_timeout, t);
4194 }
4195
4196
4197 /******************************************************************************/
4198 /****************      MESH NETWORK HANDLER HELPERS     ***********************/
4199 /******************************************************************************/
4200
4201 /**
4202  * Function to send a create path packet to a peer.
4203  *
4204  * @param cls closure
4205  * @param size number of bytes available in buf
4206  * @param buf where the callee should write the message
4207  * @return number of bytes written to buf
4208  */
4209 static size_t
4210 send_core_path_create (void *cls, size_t size, void *buf)
4211 {
4212   struct MeshPathInfo *info = cls;
4213   struct GNUNET_MESH_ManipulatePath *msg;
4214   struct GNUNET_PeerIdentity *peer_ptr;
4215   struct MeshTunnel *t = info->t;
4216   struct MeshPeerPath *p = info->path;
4217   size_t size_needed;
4218   uint32_t opt;
4219   int i;
4220
4221   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATE PATH sending...\n");
4222   size_needed =
4223       sizeof (struct GNUNET_MESH_ManipulatePath) +
4224       p->length * sizeof (struct GNUNET_PeerIdentity);
4225
4226   if (size < size_needed || NULL == buf)
4227   {
4228     GNUNET_break (0);
4229     return 0;
4230   }
4231   msg = (struct GNUNET_MESH_ManipulatePath *) buf;
4232   msg->header.size = htons (size_needed);
4233   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE);
4234   msg->tid = ntohl (t->id.tid);
4235
4236   if (GNUNET_YES == t->speed_min)
4237     opt = MESH_TUNNEL_OPT_SPEED_MIN;
4238   if (GNUNET_YES == t->nobuffer)
4239     opt |= MESH_TUNNEL_OPT_NOBUFFER;
4240   msg->opt = htonl(opt);
4241
4242   peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
4243   for (i = 0; i < p->length; i++)
4244   {
4245     GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
4246   }
4247
4248   path_destroy (p);
4249   GNUNET_free (info);
4250
4251   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4252               "CREATE PATH (%u bytes long) sent!\n", size_needed);
4253   return size_needed;
4254 }
4255
4256
4257 /**
4258  * Fill the core buffer 
4259  *
4260  * @param cls closure (data itself)
4261  * @param size number of bytes available in buf
4262  * @param buf where the callee should write the message
4263  *
4264  * @return number of bytes written to buf
4265  */
4266 static size_t
4267 send_core_data_multicast (void *cls, size_t size, void *buf)
4268 {
4269   struct MeshTransmissionDescriptor *info = cls;
4270   size_t total_size;
4271
4272   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Multicast callback.\n");
4273   GNUNET_assert (NULL != info);
4274   GNUNET_assert (NULL != info->peer);
4275   total_size = info->mesh_data->data_len;
4276   GNUNET_assert (total_size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
4277
4278   if (total_size > size)
4279   {
4280     GNUNET_break (0);
4281     return 0;
4282   }
4283   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " copying data...\n");
4284   memcpy (buf, info->mesh_data->data, total_size);
4285 #if MESH_DEBUG
4286   {
4287     struct GNUNET_MESH_Multicast *mc;
4288     struct GNUNET_MessageHeader *mh;
4289
4290     mh = buf;
4291     if (ntohs (mh->type) == GNUNET_MESSAGE_TYPE_MESH_MULTICAST)
4292     {
4293       mc = (struct GNUNET_MESH_Multicast *) mh;
4294       mh = (struct GNUNET_MessageHeader *) &mc[1];
4295       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4296                   " multicast, payload type %s\n",
4297                   GNUNET_MESH_DEBUG_M2S (ntohs (mh->type)));
4298       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4299                   " multicast, payload size %u\n", ntohs (mh->size));
4300     }
4301     else
4302     {
4303       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " type %s\n",
4304                   GNUNET_MESH_DEBUG_M2S (ntohs (mh->type)));
4305     }
4306   }
4307 #endif
4308   data_descriptor_decrement_rc (info->mesh_data);
4309   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "freeing info...\n");
4310   GNUNET_free (info);
4311   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "return %u\n", total_size);
4312   return total_size;
4313 }
4314
4315
4316 /**
4317  * Creates a path ack message in buf and frees all unused resources.
4318  *
4319  * @param cls closure (MeshTransmissionDescriptor)
4320  * @param size number of bytes available in buf
4321  * @param buf where the callee should write the message
4322  * @return number of bytes written to buf
4323  */
4324 static size_t
4325 send_core_path_ack (void *cls, size_t size, void *buf)
4326 {
4327   struct MeshTransmissionDescriptor *info = cls;
4328   struct GNUNET_MESH_PathACK *msg = buf;
4329
4330   GNUNET_assert (NULL != info);
4331   if (sizeof (struct GNUNET_MESH_PathACK) > size)
4332   {
4333     GNUNET_break (0);
4334     return 0;
4335   }
4336   msg->header.size = htons (sizeof (struct GNUNET_MESH_PathACK));
4337   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_ACK);
4338   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
4339   msg->tid = htonl (info->origin->tid);
4340   msg->peer_id = my_full_id;
4341
4342   GNUNET_free (info);
4343   /* TODO add signature */
4344
4345   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "PATH ACK sent!\n");
4346   return sizeof (struct GNUNET_MESH_PathACK);
4347 }
4348
4349
4350 /**
4351  * Free a transmission that was already queued with all resources
4352  * associated to the request.
4353  *
4354  * @param queue Queue handler to cancel.
4355  * @param clear_cls Is it necessary to free associated cls?
4356  */
4357 static void
4358 queue_destroy (struct MeshPeerQueue *queue, int clear_cls)
4359 {
4360   struct MeshTransmissionDescriptor *dd;
4361   struct MeshPathInfo *path_info;
4362
4363   if (GNUNET_YES == clear_cls)
4364   {
4365     switch (queue->type)
4366     {
4367     case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4368     case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
4369     case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4370         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   type payload\n");
4371         dd = queue->cls;
4372         data_descriptor_decrement_rc (dd->mesh_data);
4373         break;
4374     case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
4375         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   type create path\n");
4376         path_info = queue->cls;
4377         path_destroy (path_info->path);
4378         break;
4379     default:
4380         GNUNET_break (0);
4381         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   type unknown!\n");
4382     }
4383     GNUNET_free_non_null (queue->cls);
4384   }
4385   GNUNET_CONTAINER_DLL_remove (queue->peer->queue_head,
4386                                queue->peer->queue_tail,
4387                                queue);
4388   GNUNET_free (queue);
4389 }
4390
4391
4392 /**
4393   * Core callback to write a queued packet to core buffer
4394   *
4395   * @param cls Closure (peer info).
4396   * @param size Number of bytes available in buf.
4397   * @param buf Where the to write the message.
4398   *
4399   * @return number of bytes written to buf
4400   */
4401 static size_t
4402 queue_send (void *cls, size_t size, void *buf)
4403 {
4404     struct MeshPeerInfo *peer = cls;
4405     struct GNUNET_MessageHeader *msg;
4406     struct MeshPeerQueue *queue;
4407     struct MeshTunnel *t;
4408     size_t data_size;
4409
4410     peer->core_transmit = NULL;
4411     queue = peer->queue_head;
4412
4413     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "********* Queue send\n");
4414
4415     /* If queue is empty, send should have been cancelled */
4416     if (NULL == queue)
4417     {
4418         GNUNET_break(0);
4419         return 0;
4420     }
4421     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   not empty\n");
4422
4423     /* Check if buffer size is enough for the message */
4424     if (queue->size > size)
4425     {
4426         struct GNUNET_PeerIdentity id;
4427
4428         GNUNET_PEER_resolve (peer->id, &id);
4429         peer->core_transmit =
4430             GNUNET_CORE_notify_transmit_ready(core_handle,
4431                                               0,
4432                                               0,
4433                                               GNUNET_TIME_UNIT_FOREVER_REL,
4434                                               &id,
4435                                               queue->size,
4436                                               &queue_send,
4437                                               peer);
4438         return 0;
4439     }
4440     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   size ok\n");
4441
4442     t = queue->tunnel;
4443     if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == queue->type)
4444     {
4445       t->fwd_queue_n--;
4446       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   unicast: %u\n");
4447     }
4448     else if (GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == queue->type)
4449     {
4450       t->bck_queue_n--;
4451       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   to origin\n");
4452     }
4453
4454     /* Fill buf */
4455     switch (queue->type)
4456     {
4457       case 0:
4458       case GNUNET_MESSAGE_TYPE_MESH_ACK:
4459       case GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN:
4460       case GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY:
4461         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4462                     "*********   raw: %u\n",
4463                     queue->type);
4464         /* Fall through */
4465       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4466       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4467         data_size = send_core_data_raw (queue->cls, size, buf);
4468         msg = (struct GNUNET_MessageHeader *) buf;
4469         switch (ntohs (msg->type)) // Type of preconstructed message
4470         {
4471           case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4472             tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_UNICAST);
4473             break;
4474           case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4475             tunnel_send_bck_ack(t, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
4476             break;
4477           default:
4478               break;
4479         }
4480         break;
4481       case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
4482         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   multicast\n");
4483         data_size = send_core_data_multicast(queue->cls, size, buf);
4484         tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
4485         break;
4486       case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
4487         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path create\n");
4488         data_size = send_core_path_create(queue->cls, size, buf);
4489         break;
4490       case GNUNET_MESSAGE_TYPE_MESH_PATH_ACK:
4491         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path ack\n");
4492         data_size = send_core_path_ack(queue->cls, size, buf);
4493         break;
4494       default:
4495         GNUNET_break (0);
4496         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4497                     "*********   type unknown: %u\n",
4498                     queue->type);
4499         data_size = 0;
4500     }
4501
4502     /* Free queue, but cls was freed by send_core_* */
4503     queue_destroy (queue, GNUNET_NO);
4504
4505     if (GNUNET_YES == t->destroy && 0 == t->fwd_queue_n)
4506     {
4507       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********  destroying tunnel!\n");
4508       tunnel_destroy (t);
4509     }
4510
4511     /* If more data in queue, send next */
4512     if (NULL != peer->queue_head)
4513     {
4514         struct GNUNET_PeerIdentity id;
4515
4516         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   more data!\n");
4517         GNUNET_PEER_resolve (peer->id, &id);
4518         peer->core_transmit =
4519             GNUNET_CORE_notify_transmit_ready(core_handle,
4520                                               0,
4521                                               0,
4522                                               GNUNET_TIME_UNIT_FOREVER_REL,
4523                                               &id,
4524                                               peer->queue_head->size,
4525                                               &queue_send,
4526                                               peer);
4527     }
4528     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   return %d\n", data_size);
4529     return data_size;
4530 }
4531
4532
4533 /**
4534  * Queue and pass message to core when possible.
4535  *
4536  * @param cls Closure (type dependant).
4537  * @param type Type of the message, 0 for a raw message.
4538  * @param size Size of the message.
4539  * @param dst Neighbor to send message to.
4540  * @param t Tunnel this message belongs to.
4541  */
4542 static void
4543 queue_add (void *cls, uint16_t type, size_t size,
4544            struct MeshPeerInfo *dst, struct MeshTunnel *t)
4545 {
4546   struct MeshPeerQueue *queue;
4547   unsigned int *max;
4548   unsigned int *n;
4549
4550   n = NULL;
4551   if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == type ||
4552       GNUNET_MESSAGE_TYPE_MESH_MULTICAST == type)
4553   {
4554     n = &t->fwd_queue_n;
4555     max = &t->fwd_queue_max;
4556   }
4557   else if (GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == type)
4558   {
4559     n = &t->bck_queue_n;
4560     max = &t->bck_queue_max;
4561   }
4562   if (NULL != n) {
4563     if (*n >= *max)
4564     {
4565       if (NULL == t->owner)
4566         GNUNET_break_op(0);       // TODO: kill connection?
4567       else
4568         GNUNET_break(0);
4569       return;                       // Drop message
4570     }
4571     (*n)++;
4572   }
4573   queue = GNUNET_malloc (sizeof (struct MeshPeerQueue));
4574   queue->cls = cls;
4575   queue->type = type;
4576   queue->size = size;
4577   queue->peer = dst;
4578   queue->tunnel = t;
4579   GNUNET_CONTAINER_DLL_insert_tail (dst->queue_head, dst->queue_tail, queue);
4580   if (NULL == dst->core_transmit)
4581   {
4582       struct GNUNET_PeerIdentity id;
4583
4584       GNUNET_PEER_resolve (dst->id, &id);
4585       dst->core_transmit =
4586           GNUNET_CORE_notify_transmit_ready(core_handle,
4587                                             0,
4588                                             0,
4589                                             GNUNET_TIME_UNIT_FOREVER_REL,
4590                                             &id,
4591                                             size,
4592                                             &queue_send,
4593                                             dst);
4594   }
4595 }
4596
4597
4598 /******************************************************************************/
4599 /********************      MESH NETWORK HANDLERS     **************************/
4600 /******************************************************************************/
4601
4602
4603 /**
4604  * Core handler for path creation
4605  *
4606  * @param cls closure
4607  * @param message message
4608  * @param peer peer identity this notification is about
4609  * @param atsi performance data
4610  * @param atsi_count number of records in 'atsi'
4611  *
4612  * @return GNUNET_OK to keep the connection open,
4613  *         GNUNET_SYSERR to close it (signal serious error)
4614  */
4615 static int
4616 handle_mesh_path_create (void *cls, const struct GNUNET_PeerIdentity *peer,
4617                          const struct GNUNET_MessageHeader *message,
4618                          const struct GNUNET_ATS_Information *atsi,
4619                          unsigned int atsi_count)
4620 {
4621   unsigned int own_pos;
4622   uint16_t size;
4623   uint16_t i;
4624   MESH_TunnelNumber tid;
4625   struct GNUNET_MESH_ManipulatePath *msg;
4626   struct GNUNET_PeerIdentity *pi;
4627   struct GNUNET_HashCode hash;
4628   struct MeshPeerPath *path;
4629   struct MeshPeerInfo *dest_peer_info;
4630   struct MeshPeerInfo *orig_peer_info;
4631   struct MeshTunnel *t;
4632
4633   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4634               "Received a path create msg [%s]\n",
4635               GNUNET_i2s (&my_full_id));
4636   size = ntohs (message->size);
4637   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
4638   {
4639     GNUNET_break_op (0);
4640     return GNUNET_OK;
4641   }
4642
4643   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
4644   if (size % sizeof (struct GNUNET_PeerIdentity))
4645   {
4646     GNUNET_break_op (0);
4647     return GNUNET_OK;
4648   }
4649   size /= sizeof (struct GNUNET_PeerIdentity);
4650   if (size < 2)
4651   {
4652     GNUNET_break_op (0);
4653     return GNUNET_OK;
4654   }
4655   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
4656   msg = (struct GNUNET_MESH_ManipulatePath *) message;
4657
4658   tid = ntohl (msg->tid);
4659   pi = (struct GNUNET_PeerIdentity *) &msg[1];
4660   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4661               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi), tid);
4662   t = tunnel_get (pi, tid);
4663   if (NULL == t) // FIXME only for INCOMING tunnels?
4664   {
4665     uint32_t opt;
4666
4667     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating tunnel\n");
4668     t = tunnel_new (GNUNET_PEER_intern (pi), tid, NULL, 0);
4669     if (NULL == t)
4670     {
4671       // FIXME notify failure
4672       return GNUNET_OK;
4673     }
4674     opt = ntohl (msg->opt);
4675     t->speed_min = (0 != (opt & MESH_TUNNEL_OPT_SPEED_MIN)) ?
4676                    GNUNET_YES : GNUNET_NO;
4677     t->nobuffer = (0 != (opt & MESH_TUNNEL_OPT_NOBUFFER)) ?
4678                   GNUNET_YES : GNUNET_NO;
4679
4680     if (GNUNET_YES == t->nobuffer)
4681     {
4682       t->bck_queue_max = 1;
4683       t->fwd_queue_max = 1;
4684     }
4685
4686     // FIXME only assign a local tid if a local client is interested (on demand)
4687     while (NULL != tunnel_get_incoming (next_local_tid))
4688       next_local_tid = (next_local_tid + 1) | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
4689     t->local_tid_dest = next_local_tid++;
4690     next_local_tid = next_local_tid | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
4691     // FIXME end
4692
4693     tunnel_reset_timeout (t);
4694     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
4695     if (GNUNET_OK !=
4696         GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
4697                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
4698     {
4699       tunnel_destroy (t);
4700       GNUNET_break (0);
4701       return GNUNET_OK;
4702     }
4703   }
4704   dest_peer_info =
4705       GNUNET_CONTAINER_multihashmap_get (peers, &pi[size - 1].hashPubKey);
4706   if (NULL == dest_peer_info)
4707   {
4708     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4709                 "  Creating PeerInfo for destination.\n");
4710     dest_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
4711     dest_peer_info->id = GNUNET_PEER_intern (&pi[size - 1]);
4712     GNUNET_CONTAINER_multihashmap_put (peers, &pi[size - 1].hashPubKey,
4713                                        dest_peer_info,
4714                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
4715   }
4716   orig_peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &pi->hashPubKey);
4717   if (NULL == orig_peer_info)
4718   {
4719     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4720                 "  Creating PeerInfo for origin.\n");
4721     orig_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
4722     orig_peer_info->id = GNUNET_PEER_intern (pi);
4723     GNUNET_CONTAINER_multihashmap_put (peers, &pi->hashPubKey, orig_peer_info,
4724                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
4725   }
4726   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
4727   path = path_new (size);
4728   own_pos = 0;
4729   for (i = 0; i < size; i++)
4730   {
4731     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
4732                 GNUNET_i2s (&pi[i]));
4733     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
4734     if (path->peers[i] == myid)
4735       own_pos = i;
4736   }
4737   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
4738   if (own_pos == 0)
4739   {
4740     /* cannot be self, must be 'not found' */
4741     /* create path: self not found in path through self */
4742     GNUNET_break_op (0);
4743     path_destroy (path);
4744     tunnel_destroy (t);
4745     return GNUNET_OK;
4746   }
4747   path_add_to_peers (path, GNUNET_NO);
4748   tunnel_add_path (t, path, own_pos);
4749   if (own_pos == size - 1)
4750   {
4751     /* It is for us! Send ack. */
4752     struct MeshTransmissionDescriptor *info;
4753
4754     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
4755     peer_info_add_path_to_origin (orig_peer_info, path, GNUNET_NO);
4756     if (NULL == t->peers)
4757     {
4758       /* New tunnel! Notify clients on data. */
4759       t->peers = GNUNET_CONTAINER_multihashmap_create (4);
4760     }
4761     GNUNET_break (GNUNET_SYSERR !=
4762                   GNUNET_CONTAINER_multihashmap_put (t->peers,
4763                                                      &my_full_id.hashPubKey,
4764                                                      peer_info_get
4765                                                      (&my_full_id),
4766                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE));
4767     info = GNUNET_malloc (sizeof (struct MeshTransmissionDescriptor));
4768     info->origin = &t->id;
4769     info->peer = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
4770     GNUNET_assert (NULL != info->peer);
4771     queue_add(info,
4772               GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
4773               sizeof (struct GNUNET_MESH_PathACK),
4774               info->peer,
4775               t);
4776   }
4777   else
4778   {
4779     struct MeshPeerPath *path2;
4780
4781     /* It's for somebody else! Retransmit. */
4782     path2 = path_duplicate (path);
4783     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Retransmitting.\n");
4784     peer_info_add_path (dest_peer_info, path2, GNUNET_NO);
4785     path2 = path_duplicate (path);
4786     peer_info_add_path_to_origin (orig_peer_info, path2, GNUNET_NO);
4787     send_create_path (dest_peer_info, path, t);
4788   }
4789   return GNUNET_OK;
4790 }
4791
4792
4793 /**
4794  * Core handler for path destruction
4795  *
4796  * @param cls closure
4797  * @param message message
4798  * @param peer peer identity this notification is about
4799  * @param atsi performance data
4800  * @param atsi_count number of records in 'atsi'
4801  *
4802  * @return GNUNET_OK to keep the connection open,
4803  *         GNUNET_SYSERR to close it (signal serious error)
4804  */
4805 static int
4806 handle_mesh_path_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
4807                           const struct GNUNET_MessageHeader *message,
4808                           const struct GNUNET_ATS_Information *atsi,
4809                           unsigned int atsi_count)
4810 {
4811   struct GNUNET_MESH_ManipulatePath *msg;
4812   struct GNUNET_PeerIdentity *pi;
4813   struct MeshPeerPath *path;
4814   struct MeshTunnel *t;
4815   unsigned int own_pos;
4816   unsigned int i;
4817   size_t size;
4818
4819   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4820               "Received a PATH DESTROY msg from %s\n", GNUNET_i2s (peer));
4821   size = ntohs (message->size);
4822   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
4823   {
4824     GNUNET_break_op (0);
4825     return GNUNET_OK;
4826   }
4827
4828   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
4829   if (size % sizeof (struct GNUNET_PeerIdentity))
4830   {
4831     GNUNET_break_op (0);
4832     return GNUNET_OK;
4833   }
4834   size /= sizeof (struct GNUNET_PeerIdentity);
4835   if (size < 2)
4836   {
4837     GNUNET_break_op (0);
4838     return GNUNET_OK;
4839   }
4840   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
4841
4842   msg = (struct GNUNET_MESH_ManipulatePath *) message;
4843   pi = (struct GNUNET_PeerIdentity *) &msg[1];
4844   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4845               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi),
4846               msg->tid);
4847   t = tunnel_get (pi, ntohl (msg->tid));
4848   if (NULL == t)
4849   {
4850     /* TODO notify back: we don't know this tunnel */
4851     GNUNET_break_op (0);
4852     return GNUNET_OK;
4853   }
4854   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
4855   path = path_new (size);
4856   own_pos = 0;
4857   for (i = 0; i < size; i++)
4858   {
4859     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
4860                 GNUNET_i2s (&pi[i]));
4861     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
4862     if (path->peers[i] == myid)
4863       own_pos = i;
4864   }
4865   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
4866   if (own_pos < path->length - 1)
4867     send_message (message, &pi[own_pos + 1], t);
4868   else
4869     send_client_tunnel_disconnect(t, NULL);
4870
4871   tunnel_delete_peer (t, path->peers[path->length - 1]);
4872   path_destroy (path);
4873   return GNUNET_OK;
4874 }
4875
4876
4877 /**
4878  * Core handler for notifications of broken paths
4879  *
4880  * @param cls closure
4881  * @param message message
4882  * @param peer peer identity this notification is about
4883  * @param atsi performance data
4884  * @param atsi_count number of records in 'atsi'
4885  *
4886  * @return GNUNET_OK to keep the connection open,
4887  *         GNUNET_SYSERR to close it (signal serious error)
4888  */
4889 static int
4890 handle_mesh_path_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
4891                          const struct GNUNET_MessageHeader *message,
4892                          const struct GNUNET_ATS_Information *atsi,
4893                          unsigned int atsi_count)
4894 {
4895   struct GNUNET_MESH_PathBroken *msg;
4896   struct MeshTunnel *t;
4897
4898   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4899               "Received a PATH BROKEN msg from %s\n", GNUNET_i2s (peer));
4900   msg = (struct GNUNET_MESH_PathBroken *) message;
4901   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
4902               GNUNET_i2s (&msg->peer1));
4903   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
4904               GNUNET_i2s (&msg->peer2));
4905   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4906   if (NULL == t)
4907   {
4908     GNUNET_break_op (0);
4909     return GNUNET_OK;
4910   }
4911   tunnel_notify_connection_broken (t, GNUNET_PEER_search (&msg->peer1),
4912                                    GNUNET_PEER_search (&msg->peer2));
4913   return GNUNET_OK;
4914
4915 }
4916
4917
4918 /**
4919  * Core handler for tunnel destruction
4920  *
4921  * @param cls closure
4922  * @param message message
4923  * @param peer peer identity this notification is about
4924  * @param atsi performance data
4925  * @param atsi_count number of records in 'atsi'
4926  *
4927  * @return GNUNET_OK to keep the connection open,
4928  *         GNUNET_SYSERR to close it (signal serious error)
4929  */
4930 static int
4931 handle_mesh_tunnel_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
4932                             const struct GNUNET_MessageHeader *message,
4933                             const struct GNUNET_ATS_Information *atsi,
4934                             unsigned int atsi_count)
4935 {
4936   struct GNUNET_MESH_TunnelDestroy *msg;
4937   struct MeshTunnel *t;
4938
4939   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4940               "Got a TUNNEL DESTROY packet from %s\n", GNUNET_i2s (peer));
4941   msg = (struct GNUNET_MESH_TunnelDestroy *) message;
4942   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for tunnel %s [%u]\n",
4943               GNUNET_i2s (&msg->oid), ntohl (msg->tid));
4944   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4945   if (NULL == t)
4946   {
4947     /* Probably already got the message from another path,
4948      * destroyed the tunnel and retransmitted to children.
4949      * Safe to ignore.
4950      */
4951     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel", 1, GNUNET_NO);
4952     return GNUNET_OK;
4953   }
4954   if (t->id.oid == myid)
4955   {
4956     GNUNET_break_op (0);
4957     return GNUNET_OK;
4958   }
4959   if (t->local_tid_dest >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
4960   {
4961     /* Tunnel was incoming, notify clients */
4962     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "INCOMING TUNNEL %X %X\n",
4963                 t->local_tid, t->local_tid_dest);
4964     send_clients_tunnel_destroy (t);
4965   }
4966   tunnel_send_destroy (t);
4967   t->destroy = GNUNET_YES;
4968   // TODO: add timeout to destroy the tunnel anyway
4969   return GNUNET_OK;
4970 }
4971
4972
4973 /**
4974  * Core handler for mesh network traffic going from the origin to a peer
4975  *
4976  * @param cls closure
4977  * @param peer peer identity this notification is about
4978  * @param message message
4979  * @param atsi performance data
4980  * @param atsi_count number of records in 'atsi'
4981  * @return GNUNET_OK to keep the connection open,
4982  *         GNUNET_SYSERR to close it (signal serious error)
4983  */
4984 static int
4985 handle_mesh_data_unicast (void *cls, const struct GNUNET_PeerIdentity *peer,
4986                           const struct GNUNET_MessageHeader *message,
4987                           const struct GNUNET_ATS_Information *atsi,
4988                           unsigned int atsi_count)
4989 {
4990   struct GNUNET_MESH_Unicast *msg;
4991   struct GNUNET_PeerIdentity *neighbor;
4992   struct MeshTunnelChildInfo *cinfo;
4993   struct MeshTunnel *t;
4994   GNUNET_PEER_Id dest_id;
4995   uint32_t pid;
4996   uint32_t ttl;
4997   size_t size;
4998
4999   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a unicast packet from %s\n",
5000               GNUNET_i2s (peer));
5001   /* Check size */
5002   size = ntohs (message->size);
5003   if (size <
5004       sizeof (struct GNUNET_MESH_Unicast) +
5005       sizeof (struct GNUNET_MessageHeader))
5006   {
5007     GNUNET_break (0);
5008     return GNUNET_OK;
5009   }
5010   msg = (struct GNUNET_MESH_Unicast *) message;
5011   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %s\n",
5012               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
5013   /* Check tunnel */
5014   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5015   if (NULL == t)
5016   {
5017     /* TODO notify back: we don't know this tunnel */
5018     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
5019     GNUNET_break_op (0);
5020     return GNUNET_OK;
5021   }
5022   pid = ntohl (msg->pid);
5023   if (t->fwd_pid == pid)
5024   {
5025     GNUNET_STATISTICS_update (stats, "# duplicate PID drops", 1, GNUNET_NO);
5026     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5027                 " Already seen pid %u, DROPPING!\n", pid);
5028     return GNUNET_OK;
5029   }
5030   else
5031   {
5032     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5033                 " pid %u not seen yet, forwarding\n", pid);
5034   }
5035   t->skip += (pid - t->fwd_pid) - 1;
5036   t->fwd_pid = pid;
5037   if (GMC_is_pid_bigger (pid, t->last_fwd_ack))
5038   {
5039     GNUNET_STATISTICS_update (stats, "# unsolicited unicast", 1, GNUNET_NO);
5040     GNUNET_break_op (0);
5041     return GNUNET_OK;
5042   }
5043   tunnel_reset_timeout (t);
5044   dest_id = GNUNET_PEER_search (&msg->destination);
5045   if (dest_id == myid)
5046   {
5047     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5048                 "  it's for us! sending to clients...\n");
5049     GNUNET_STATISTICS_update (stats, "# unicast received", 1, GNUNET_NO);
5050     send_subscribed_clients (message, (struct GNUNET_MessageHeader *) &msg[1]);
5051     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_UNICAST);
5052     return GNUNET_OK;
5053   }
5054   ttl = ntohl (msg->ttl);
5055   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ttl);
5056   if (ttl == 0)
5057   {
5058     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
5059     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
5060     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5061     return GNUNET_OK;
5062   }
5063   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5064               "  not for us, retransmitting...\n");
5065
5066   neighbor = tree_get_first_hop (t->tree, dest_id);
5067   cinfo = tunnel_get_neighbor_fc (t, neighbor);
5068   cinfo->pid = pid;
5069   GNUNET_CONTAINER_multihashmap_iterate (t->children_fc,
5070                                          &tunnel_add_skip,
5071                                          &neighbor);
5072   if (GMC_is_pid_bigger (pid, cinfo->fwd_ack))
5073   {
5074     GNUNET_STATISTICS_update (stats, "# unsolicited unicast", 1, GNUNET_NO);
5075     GNUNET_break_op (0);
5076     return GNUNET_OK;
5077   }
5078   send_message (message, neighbor, t);
5079   GNUNET_STATISTICS_update (stats, "# unicast forwarded", 1, GNUNET_NO);
5080
5081   return GNUNET_OK;
5082 }
5083
5084
5085 /**
5086  * Core handler for mesh network traffic going from the origin to all peers
5087  *
5088  * @param cls closure
5089  * @param message message
5090  * @param peer peer identity this notification is about
5091  * @param atsi performance data
5092  * @param atsi_count number of records in 'atsi'
5093  * @return GNUNET_OK to keep the connection open,
5094  *         GNUNET_SYSERR to close it (signal serious error)
5095  *
5096  * TODO: Check who we got this from, to validate route.
5097  */
5098 static int
5099 handle_mesh_data_multicast (void *cls, const struct GNUNET_PeerIdentity *peer,
5100                             const struct GNUNET_MessageHeader *message,
5101                             const struct GNUNET_ATS_Information *atsi,
5102                             unsigned int atsi_count)
5103 {
5104   struct GNUNET_MESH_Multicast *msg;
5105   struct MeshTunnel *t;
5106   size_t size;
5107   uint32_t pid;
5108
5109   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a multicast packet from %s\n",
5110               GNUNET_i2s (peer));
5111   size = ntohs (message->size);
5112   if (sizeof (struct GNUNET_MESH_Multicast) +
5113       sizeof (struct GNUNET_MessageHeader) > size)
5114   {
5115     GNUNET_break_op (0);
5116     return GNUNET_OK;
5117   }
5118   msg = (struct GNUNET_MESH_Multicast *) message;
5119   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5120
5121   if (NULL == t)
5122   {
5123     /* TODO notify that we dont know that tunnel */
5124     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
5125     GNUNET_break_op (0);
5126     return GNUNET_OK;
5127   }
5128   pid = ntohl (msg->pid);
5129   if (t->fwd_pid == pid)
5130   {
5131     /* already seen this packet, drop */
5132     GNUNET_STATISTICS_update (stats, "# duplicate PID drops", 1, GNUNET_NO);
5133     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5134                 " Already seen pid %u, DROPPING!\n", pid);
5135     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5136     return GNUNET_OK;
5137   }
5138   else
5139   {
5140     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5141                 " pid %u not seen yet, forwarding\n", pid);
5142   }
5143   t->skip += (pid - t->fwd_pid) - 1;
5144   t->fwd_pid = pid;
5145   tunnel_reset_timeout (t);
5146
5147   /* Transmit to locally interested clients */
5148   if (NULL != t->peers &&
5149       GNUNET_CONTAINER_multihashmap_contains (t->peers, &my_full_id.hashPubKey))
5150   {
5151     GNUNET_STATISTICS_update (stats, "# multicast received", 1, GNUNET_NO);
5152     send_subscribed_clients (message, &msg[1].header);
5153     tunnel_send_fwd_ack(t, GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
5154   }
5155   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ntohl (msg->ttl));
5156   if (ntohl (msg->ttl) == 0)
5157   {
5158     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
5159     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
5160     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5161     return GNUNET_OK;
5162   }
5163   GNUNET_STATISTICS_update (stats, "# multicast forwarded", 1, GNUNET_NO);
5164   tunnel_send_multicast (t, message, GNUNET_NO);
5165   return GNUNET_OK;
5166 }
5167
5168
5169 /**
5170  * Core handler for mesh network traffic toward the owner of a tunnel
5171  *
5172  * @param cls closure
5173  * @param message message
5174  * @param peer peer identity this notification is about
5175  * @param atsi performance data
5176  * @param atsi_count number of records in 'atsi'
5177  *
5178  * @return GNUNET_OK to keep the connection open,
5179  *         GNUNET_SYSERR to close it (signal serious error)
5180  */
5181 static int
5182 handle_mesh_data_to_orig (void *cls, const struct GNUNET_PeerIdentity *peer,
5183                           const struct GNUNET_MessageHeader *message,
5184                           const struct GNUNET_ATS_Information *atsi,
5185                           unsigned int atsi_count)
5186 {
5187   struct GNUNET_MESH_ToOrigin *msg;
5188   struct GNUNET_PeerIdentity id;
5189   struct MeshPeerInfo *peer_info;
5190   struct MeshTunnel *t;
5191   size_t size;
5192
5193   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a ToOrigin packet from %s\n",
5194               GNUNET_i2s (peer));
5195   size = ntohs (message->size);
5196   if (size < sizeof (struct GNUNET_MESH_ToOrigin) +     /* Payload must be */
5197       sizeof (struct GNUNET_MessageHeader))     /* at least a header */
5198   {
5199     GNUNET_break_op (0);
5200     return GNUNET_OK;
5201   }
5202   msg = (struct GNUNET_MESH_ToOrigin *) message;
5203   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %s\n",
5204               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
5205   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5206
5207   if (NULL == t)
5208   {
5209     /* TODO notify that we dont know this tunnel (whom)? */
5210     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
5211     GNUNET_break_op (0);
5212     return GNUNET_OK;
5213   }
5214
5215   if (NULL != t->owner)
5216   {
5217     char cbuf[size];
5218     struct GNUNET_MESH_ToOrigin *copy;
5219
5220     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5221                 "  it's for us! sending to clients...\n");
5222     /* TODO signature verification */
5223     memcpy (cbuf, message, size);
5224     copy = (struct GNUNET_MESH_ToOrigin *) cbuf;
5225     copy->tid = htonl (t->local_tid);
5226     GNUNET_STATISTICS_update (stats, "# to origin received", 1, GNUNET_NO);
5227     GNUNET_SERVER_notification_context_unicast (nc, t->owner->handle,
5228                                                 &copy->header, GNUNET_NO);
5229     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
5230     return GNUNET_OK;
5231   }
5232   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5233               "  not for us, retransmitting...\n");
5234
5235   peer_info = peer_info_get (&msg->oid);
5236   if (NULL == peer_info)
5237   {
5238     /* unknown origin of tunnel */
5239     GNUNET_break (0);
5240     return GNUNET_OK;
5241   }
5242   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
5243   send_message (message, &id, t);
5244   GNUNET_STATISTICS_update (stats, "# to origin forwarded", 1, GNUNET_NO);
5245
5246   return GNUNET_OK;
5247 }
5248
5249
5250 /**
5251  * Core handler for mesh network traffic point-to-point acks.
5252  *
5253  * @param cls closure
5254  * @param message message
5255  * @param peer peer identity this notification is about
5256  * @param atsi performance data
5257  * @param atsi_count number of records in 'atsi'
5258  *
5259  * @return GNUNET_OK to keep the connection open,
5260  *         GNUNET_SYSERR to close it (signal serious error)
5261  */
5262 static int
5263 handle_mesh_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5264                  const struct GNUNET_MessageHeader *message,
5265                  const struct GNUNET_ATS_Information *atsi,
5266                  unsigned int atsi_count)
5267 {
5268   struct GNUNET_MESH_ACK *msg;
5269   struct MeshTunnel *t;
5270   uint32_t ack;
5271
5272   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK packet from %s!\n",
5273               GNUNET_i2s (peer));
5274   msg = (struct GNUNET_MESH_ACK *) message;
5275   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %s\n",
5276               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
5277   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5278
5279   if (NULL == t)
5280   {
5281     /* TODO notify that we dont know this tunnel (whom)? */
5282     GNUNET_STATISTICS_update (stats, "# ack on unknown tunnel", 1, GNUNET_NO);
5283     GNUNET_break_op (0);
5284     return GNUNET_OK;
5285   }
5286   ack = ntohl (msg->pid);
5287
5288   /* Is this a forward or backward ACK? */
5289   if (tree_get_predecessor(t->tree) == GNUNET_PEER_search(peer))
5290   {
5291     struct MeshTunnelChildInfo *cinfo;
5292
5293     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
5294     cinfo = tunnel_get_neighbor_fc (t, peer);
5295     cinfo->fwd_ack = ack;
5296     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5297   }
5298   else
5299   {
5300     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
5301     t->bck_ack = ack;
5302     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5303   }
5304   // FIXME fc Unlock queues?
5305   return GNUNET_OK;
5306 }
5307
5308
5309 /**
5310  * Core handler for path ACKs
5311  *
5312  * @param cls closure
5313  * @param message message
5314  * @param peer peer identity this notification is about
5315  * @param atsi performance data
5316  * @param atsi_count number of records in 'atsi'
5317  *
5318  * @return GNUNET_OK to keep the connection open,
5319  *         GNUNET_SYSERR to close it (signal serious error)
5320  */
5321 static int
5322 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5323                       const struct GNUNET_MessageHeader *message,
5324                       const struct GNUNET_ATS_Information *atsi,
5325                       unsigned int atsi_count)
5326 {
5327   struct GNUNET_MESH_PathACK *msg;
5328   struct GNUNET_PeerIdentity id;
5329   struct MeshPeerInfo *peer_info;
5330   struct MeshPeerPath *p;
5331   struct MeshTunnel *t;
5332
5333   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a path ACK msg [%s]\n",
5334               GNUNET_i2s (&my_full_id));
5335   msg = (struct GNUNET_MESH_PathACK *) message;
5336   t = tunnel_get (&msg->oid, ntohl(msg->tid));
5337   if (NULL == t)
5338   {
5339     /* TODO notify that we don't know the tunnel */
5340     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel", 1, GNUNET_NO);
5341     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  don't know the tunnel %s [%X]!\n",
5342                 GNUNET_i2s (&msg->oid), ntohl(msg->tid));
5343     return GNUNET_OK;
5344   }
5345   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %s [%X]\n",
5346               GNUNET_i2s (&msg->oid), ntohl(msg->tid));
5347
5348   peer_info = peer_info_get (&msg->peer_id);
5349   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by peer %s\n",
5350               GNUNET_i2s (&msg->peer_id));
5351   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  via peer %s\n",
5352               GNUNET_i2s (peer));
5353
5354   if (NULL != t->regex_ctx && t->regex_ctx->info->peer == peer_info->id)
5355   {
5356     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5357                 "connect_by_string completed, stopping search\n");
5358     regex_cancel_search (t->regex_ctx);
5359     t->regex_ctx = NULL;
5360   }
5361
5362   /* Add paths to peers? */
5363   p = tree_get_path_to_peer (t->tree, peer_info->id);
5364   if (NULL != p)
5365   {
5366     path_add_to_peers (p, GNUNET_YES);
5367     path_destroy (p);
5368   }
5369   else
5370   {
5371     GNUNET_break (0);
5372   }
5373
5374   /* Message for us? */
5375   if (0 == memcmp (&msg->oid, &my_full_id, sizeof (struct GNUNET_PeerIdentity)))
5376   {
5377     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
5378     if (NULL == t->owner)
5379     {
5380       GNUNET_break_op (0);
5381       return GNUNET_OK;
5382     }
5383     if (NULL != t->dht_get_type)
5384     {
5385       GNUNET_DHT_get_stop (t->dht_get_type);
5386       t->dht_get_type = NULL;
5387     }
5388     if (tree_get_status (t->tree, peer_info->id) != MESH_PEER_READY)
5389     {
5390       tree_set_status (t->tree, peer_info->id, MESH_PEER_READY);
5391       send_client_peer_connected (t, peer_info->id);
5392     }
5393     return GNUNET_OK;
5394   }
5395
5396   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5397               "  not for us, retransmitting...\n");
5398   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
5399   peer_info = peer_info_get (&msg->oid);
5400   if (NULL == peer_info)
5401   {
5402     /* If we know the tunnel, we should DEFINITELY know the peer */
5403     GNUNET_break (0);
5404     return GNUNET_OK;
5405   }
5406   send_message (message, &id, t);
5407   return GNUNET_OK;
5408 }
5409
5410
5411 /**
5412  * Functions to handle messages from core
5413  */
5414 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
5415   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
5416   {&handle_mesh_path_destroy, GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY, 0},
5417   {&handle_mesh_path_broken, GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN,
5418    sizeof (struct GNUNET_MESH_PathBroken)},
5419   {&handle_mesh_tunnel_destroy, GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY,
5420    sizeof (struct GNUNET_MESH_TunnelDestroy)},
5421   {&handle_mesh_data_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
5422   {&handle_mesh_data_multicast, GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
5423   {&handle_mesh_data_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
5424   {&handle_mesh_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
5425     sizeof (struct GNUNET_MESH_ACK)},
5426   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
5427    sizeof (struct GNUNET_MESH_PathACK)},
5428   {NULL, 0, 0}
5429 };
5430
5431
5432
5433 /******************************************************************************/
5434 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
5435 /******************************************************************************/
5436
5437 /**
5438  * deregister_app: iterator for removing each application registered by a client
5439  *
5440  * @param cls closure
5441  * @param key the hash of the application id (used to access the hashmap)
5442  * @param value the value stored at the key (client)
5443  *
5444  * @return GNUNET_OK on success
5445  */
5446 static int
5447 deregister_app (void *cls, const struct GNUNET_HashCode * key, void *value)
5448 {
5449   struct GNUNET_CONTAINER_MultiHashMap *h = cls;
5450   GNUNET_break (GNUNET_YES ==
5451                 GNUNET_CONTAINER_multihashmap_remove (h, key, value));
5452   return GNUNET_OK;
5453 }
5454
5455 #if LATER
5456 /**
5457  * notify_client_connection_failure: notify a client that the connection to the
5458  * requested remote peer is not possible (for instance, no route found)
5459  * Function called when the socket is ready to queue more data. "buf" will be
5460  * NULL and "size" zero if the socket was closed for writing in the meantime.
5461  *
5462  * @param cls closure
5463  * @param size number of bytes available in buf
5464  * @param buf where the callee should write the message
5465  * @return number of bytes written to buf
5466  */
5467 static size_t
5468 notify_client_connection_failure (void *cls, size_t size, void *buf)
5469 {
5470   int size_needed;
5471   struct MeshPeerInfo *peer_info;
5472   struct GNUNET_MESH_PeerControl *msg;
5473   struct GNUNET_PeerIdentity id;
5474
5475   if (0 == size && NULL == buf)
5476   {
5477     // TODO retry? cancel?
5478     return 0;
5479   }
5480
5481   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
5482   peer_info = (struct MeshPeerInfo *) cls;
5483   msg = (struct GNUNET_MESH_PeerControl *) buf;
5484   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
5485   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
5486 //     msg->tunnel_id = htonl(peer_info->t->tid);
5487   GNUNET_PEER_resolve (peer_info->id, &id);
5488   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
5489
5490   return size_needed;
5491 }
5492 #endif
5493
5494
5495 /**
5496  * Send keepalive packets for a peer
5497  *
5498  * @param cls Closure (tunnel for which to send the keepalive).
5499  * @param tc Notification context.
5500  *
5501  * TODO: implement explicit multicast keepalive?
5502  */
5503 static void
5504 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
5505 {
5506   struct MeshTunnel *t = cls;
5507   struct GNUNET_MessageHeader *payload;
5508   struct GNUNET_MESH_Multicast *msg;
5509   size_t size =
5510       sizeof (struct GNUNET_MESH_Multicast) +
5511       sizeof (struct GNUNET_MessageHeader);
5512   char cbuf[size];
5513
5514   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
5515   {
5516     return;
5517   }
5518   t->path_refresh_task = GNUNET_SCHEDULER_NO_TASK;
5519
5520   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5521               "sending keepalive for tunnel %d\n", t->id.tid);
5522
5523   msg = (struct GNUNET_MESH_Multicast *) cbuf;
5524   msg->header.size = htons (size);
5525   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
5526   msg->oid = my_full_id;
5527   msg->tid = htonl (t->id.tid);
5528   msg->ttl = htonl (default_ttl);
5529   msg->pid = htonl (t->fwd_pid + 1);
5530   t->fwd_pid++;
5531   payload = (struct GNUNET_MessageHeader *) &msg[1];
5532   payload->size = htons (sizeof (struct GNUNET_MessageHeader));
5533   payload->type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE);
5534   tunnel_send_multicast (t, &msg->header, GNUNET_YES);
5535
5536   t->path_refresh_task =
5537       GNUNET_SCHEDULER_add_delayed (refresh_path_time, &path_refresh, t);
5538   return;
5539 }
5540
5541
5542 /**
5543  * Function to process paths received for a new peer addition. The recorded
5544  * paths form the initial tunnel, which can be optimized later.
5545  * Called on each result obtained for the DHT search.
5546  *
5547  * @param cls closure
5548  * @param exp when will this value expire
5549  * @param key key of the result
5550  * @param get_path path of the get request
5551  * @param get_path_length lenght of get_path
5552  * @param put_path path of the put request
5553  * @param put_path_length length of the put_path
5554  * @param type type of the result
5555  * @param size number of bytes in data
5556  * @param data pointer to the result data
5557  *
5558  * TODO: re-issue the request after certain time? cancel after X results?
5559  */
5560 static void
5561 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
5562                     const struct GNUNET_HashCode * key,
5563                     const struct GNUNET_PeerIdentity *get_path,
5564                     unsigned int get_path_length,
5565                     const struct GNUNET_PeerIdentity *put_path,
5566                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
5567                     size_t size, const void *data)
5568 {
5569   struct MeshPathInfo *path_info = cls;
5570   struct MeshPeerPath *p;
5571   struct GNUNET_PeerIdentity pi;
5572   int i;
5573
5574   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
5575   GNUNET_PEER_resolve (path_info->peer->id, &pi);
5576   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", GNUNET_i2s (&pi));
5577
5578   p = path_build_from_dht (get_path, get_path_length, put_path,
5579                            put_path_length);
5580   path_add_to_peers (p, GNUNET_NO);
5581   path_destroy(p);
5582   for (i = 0; i < path_info->peer->ntunnels; i++)
5583   {
5584     tunnel_add_peer (path_info->peer->tunnels[i], path_info->peer);
5585     peer_info_connect (path_info->peer, path_info->t);
5586   }
5587
5588   return;
5589 }
5590
5591
5592 /**
5593  * Function to process paths received for a new peer addition. The recorded
5594  * paths form the initial tunnel, which can be optimized later.
5595  * Called on each result obtained for the DHT search.
5596  *
5597  * @param cls closure
5598  * @param exp when will this value expire
5599  * @param key key of the result
5600  * @param get_path path of the get request
5601  * @param get_path_length lenght of get_path
5602  * @param put_path path of the put request
5603  * @param put_path_length length of the put_path
5604  * @param type type of the result
5605  * @param size number of bytes in data
5606  * @param data pointer to the result data
5607  */
5608 static void
5609 dht_get_type_handler (void *cls, struct GNUNET_TIME_Absolute exp,
5610                       const struct GNUNET_HashCode * key,
5611                       const struct GNUNET_PeerIdentity *get_path,
5612                       unsigned int get_path_length,
5613                       const struct GNUNET_PeerIdentity *put_path,
5614                       unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
5615                       size_t size, const void *data)
5616 {
5617   const struct PBlock *pb = data;
5618   const struct GNUNET_PeerIdentity *pi = &pb->id;
5619   struct MeshTunnel *t = cls;
5620   struct MeshPeerInfo *peer_info;
5621   struct MeshPeerPath *p;
5622
5623   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got type DHT result!\n");
5624   if (size != sizeof (struct PBlock))
5625   {
5626     GNUNET_break_op (0);
5627     return;
5628   }
5629   if (ntohl(pb->type) != t->type)
5630   {
5631     GNUNET_break_op (0);
5632     return;
5633   }
5634   GNUNET_assert (NULL != t->owner);
5635   peer_info = peer_info_get (pi);
5636   (void) GNUNET_CONTAINER_multihashmap_put (t->peers, &pi->hashPubKey,
5637                                             peer_info,
5638                                             GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
5639
5640   p = path_build_from_dht (get_path, get_path_length, put_path,
5641                            put_path_length);
5642   path_add_to_peers (p, GNUNET_NO);
5643   path_destroy(p);
5644   tunnel_add_peer (t, peer_info);
5645   peer_info_connect (peer_info, t);
5646 }
5647
5648
5649 /**
5650  * Function to process DHT string to regex matching.
5651  * Called on each result obtained for the DHT search.
5652  *
5653  * @param cls closure (search context)
5654  * @param exp when will this value expire
5655  * @param key key of the result
5656  * @param get_path path of the get request (not used)
5657  * @param get_path_length lenght of get_path (not used)
5658  * @param put_path path of the put request (not used)
5659  * @param put_path_length length of the put_path (not used)
5660  * @param type type of the result
5661  * @param size number of bytes in data
5662  * @param data pointer to the result data
5663  */
5664 static void
5665 dht_get_string_accept_handler (void *cls, struct GNUNET_TIME_Absolute exp,
5666                                const struct GNUNET_HashCode * key,
5667                                const struct GNUNET_PeerIdentity *get_path,
5668                                unsigned int get_path_length,
5669                                const struct GNUNET_PeerIdentity *put_path,
5670                                unsigned int put_path_length,
5671                                enum GNUNET_BLOCK_Type type,
5672                                size_t size, const void *data)
5673 {
5674   const struct MeshRegexAccept *block = data;
5675   struct MeshRegexSearchContext *ctx = cls;
5676   struct MeshRegexSearchInfo *info = ctx->info;
5677   struct MeshPeerPath *p;
5678   struct MeshPeerInfo *peer_info;
5679
5680   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got regex results from DHT!\n");
5681   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", info->description);
5682
5683   peer_info = peer_info_get(&block->id);
5684   p = path_build_from_dht (get_path, get_path_length, put_path,
5685                            put_path_length);
5686   path_add_to_peers (p, GNUNET_NO);
5687   path_destroy(p);
5688
5689   tunnel_add_peer (info->t, peer_info);
5690   peer_info_connect (peer_info, info->t);
5691   if (0 == info->peer)
5692   {
5693     info->peer = peer_info->id;
5694   }
5695   else
5696   {
5697     GNUNET_array_append (info->peers, info->n_peers, peer_info->id);
5698   }
5699
5700   info->timeout = GNUNET_SCHEDULER_add_delayed (connect_timeout,
5701                                                 &regex_connect_timeout,
5702                                                 info);
5703
5704   return;
5705 }
5706
5707
5708 /**
5709  * Function to process DHT string to regex matching.
5710  * Called on each result obtained for the DHT search.
5711  *
5712  * @param cls closure (search context)
5713  * @param exp when will this value expire
5714  * @param key key of the result
5715  * @param get_path path of the get request (not used)
5716  * @param get_path_length lenght of get_path (not used)
5717  * @param put_path path of the put request (not used)
5718  * @param put_path_length length of the put_path (not used)
5719  * @param type type of the result
5720  * @param size number of bytes in data
5721  * @param data pointer to the result data
5722  *
5723  * TODO: re-issue the request after certain time? cancel after X results?
5724  */
5725 static void
5726 dht_get_string_handler (void *cls, struct GNUNET_TIME_Absolute exp,
5727                         const struct GNUNET_HashCode * key,
5728                         const struct GNUNET_PeerIdentity *get_path,
5729                         unsigned int get_path_length,
5730                         const struct GNUNET_PeerIdentity *put_path,
5731                         unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
5732                         size_t size, const void *data)
5733 {
5734   const struct MeshRegexBlock *block = data;
5735   struct MeshRegexSearchContext *ctx = cls;
5736   struct MeshRegexSearchInfo *info = ctx->info;
5737   void *copy;
5738   size_t len;
5739
5740   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5741               "DHT GET STRING RETURNED RESULTS\n");
5742   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5743               "  key: %s\n", GNUNET_h2s (key));
5744
5745   copy = GNUNET_malloc (size);
5746   memcpy (copy, data, size);
5747   GNUNET_break (GNUNET_OK ==
5748                 GNUNET_CONTAINER_multihashmap_put(info->dht_get_results, key, copy,
5749                                                   GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
5750   len = ntohl (block->n_proof);
5751   {
5752     char proof[len + 1];
5753
5754     memcpy (proof, &block[1], len);
5755     proof[len] = '\0';
5756     if (GNUNET_OK != GNUNET_REGEX_check_proof (proof, key))
5757     {
5758       GNUNET_break_op (0);
5759       return;
5760     }
5761   }
5762   len = strlen (info->description);
5763   if (len == ctx->position) // String processed
5764   {
5765     if (GNUNET_YES == ntohl (block->accepting))
5766     {
5767       regex_find_path(key, ctx);
5768     }
5769     else
5770     {
5771       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  block not accepting!\n");
5772       // FIXME REGEX this block not successful, wait for more? start timeout?
5773     }
5774     return;
5775   }
5776   GNUNET_break (GNUNET_OK ==
5777                 GNUNET_MESH_regex_block_iterate (block, size,
5778                                                  &regex_edge_iterator, ctx));
5779   return;
5780 }
5781
5782 /******************************************************************************/
5783 /*********************       MESH LOCAL HANDLES      **************************/
5784 /******************************************************************************/
5785
5786
5787 /**
5788  * Handler for client disconnection
5789  *
5790  * @param cls closure
5791  * @param client identification of the client; NULL
5792  *        for the last call when the server is destroyed
5793  */
5794 static void
5795 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
5796 {
5797   struct MeshClient *c;
5798   struct MeshClient *next;
5799   unsigned int i;
5800
5801   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected\n");
5802   if (client == NULL)
5803   {
5804     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (SERVER DOWN)\n");
5805     return;
5806   }
5807   c = clients;
5808   while (NULL != c)
5809   {
5810     if (c->handle != client)
5811     {
5812       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ... searching\n");
5813       c = c->next;
5814       continue;
5815     }
5816     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u)\n",
5817                 c->id);
5818     GNUNET_SERVER_client_drop (c->handle);
5819     c->shutting_down = GNUNET_YES;
5820     GNUNET_assert (NULL != c->own_tunnels);
5821     GNUNET_assert (NULL != c->incoming_tunnels);
5822     GNUNET_CONTAINER_multihashmap_iterate (c->own_tunnels,
5823                                            &tunnel_destroy_iterator, c);
5824     GNUNET_CONTAINER_multihashmap_iterate (c->incoming_tunnels,
5825                                            &tunnel_destroy_iterator, c);
5826     GNUNET_CONTAINER_multihashmap_iterate (c->ignore_tunnels,
5827                                            &tunnel_destroy_iterator, c);
5828     GNUNET_CONTAINER_multihashmap_destroy (c->own_tunnels);
5829     GNUNET_CONTAINER_multihashmap_destroy (c->incoming_tunnels);
5830     GNUNET_CONTAINER_multihashmap_destroy (c->ignore_tunnels);
5831
5832     /* deregister clients applications */
5833     if (NULL != c->apps)
5834     {
5835       GNUNET_CONTAINER_multihashmap_iterate (c->apps, &deregister_app, c->apps);
5836       GNUNET_CONTAINER_multihashmap_destroy (c->apps);
5837     }
5838     if (0 == GNUNET_CONTAINER_multihashmap_size (applications) &&
5839         GNUNET_SCHEDULER_NO_TASK != announce_applications_task)
5840     {
5841       GNUNET_SCHEDULER_cancel (announce_applications_task);
5842       announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
5843     }
5844     if (NULL != c->types)
5845       GNUNET_CONTAINER_multihashmap_destroy (c->types);
5846     for (i = 0; i < c->n_regex; i++)
5847     {
5848       GNUNET_free (c->regexes[i]);
5849     }
5850     GNUNET_free_non_null (c->regexes);
5851     if (GNUNET_SCHEDULER_NO_TASK != c->regex_announce_task)
5852       GNUNET_SCHEDULER_cancel (c->regex_announce_task);
5853     next = c->next;
5854     GNUNET_CONTAINER_DLL_remove (clients, clients_tail, c);
5855     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT FREE at %p\n", c);
5856     GNUNET_free (c);
5857     GNUNET_STATISTICS_update (stats, "# clients", -1, GNUNET_NO);
5858     c = next;
5859   }
5860   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   done!\n");
5861   return;
5862 }
5863
5864
5865 /**
5866  * Handler for new clients
5867  *
5868  * @param cls closure
5869  * @param client identification of the client
5870  * @param message the actual message, which includes messages the client wants
5871  */
5872 static void
5873 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
5874                          const struct GNUNET_MessageHeader *message)
5875 {
5876   struct GNUNET_MESH_ClientConnect *cc_msg;
5877   struct MeshClient *c;
5878   GNUNET_MESH_ApplicationType *a;
5879   unsigned int size;
5880   uint16_t ntypes;
5881   uint16_t *t;
5882   uint16_t napps;
5883   uint16_t i;
5884
5885   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected\n");
5886   /* Check data sanity */
5887   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
5888   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
5889   ntypes = ntohs (cc_msg->types);
5890   napps = ntohs (cc_msg->applications);
5891   if (size !=
5892       ntypes * sizeof (uint16_t) + napps * sizeof (GNUNET_MESH_ApplicationType))
5893   {
5894     GNUNET_break (0);
5895     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5896     return;
5897   }
5898
5899   /* Create new client structure */
5900   c = GNUNET_malloc (sizeof (struct MeshClient));
5901   c->id = next_client_id++;
5902   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT NEW %u\n", c->id);
5903   c->handle = client;
5904   GNUNET_SERVER_client_keep (client);
5905   a = (GNUNET_MESH_ApplicationType *) &cc_msg[1];
5906   if (napps > 0)
5907   {
5908     GNUNET_MESH_ApplicationType at;
5909     struct GNUNET_HashCode hc;
5910
5911     c->apps = GNUNET_CONTAINER_multihashmap_create (napps);
5912     for (i = 0; i < napps; i++)
5913     {
5914       at = ntohl (a[i]);
5915       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  app type: %u\n", at);
5916       GNUNET_CRYPTO_hash (&at, sizeof (at), &hc);
5917       /* store in clients hashmap */
5918       GNUNET_CONTAINER_multihashmap_put (c->apps, &hc, (void *) (long) at,
5919                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
5920       /* store in global hashmap, for announcements */
5921       GNUNET_CONTAINER_multihashmap_put (applications, &hc, c,
5922                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
5923     }
5924     if (GNUNET_SCHEDULER_NO_TASK == announce_applications_task)
5925       announce_applications_task =
5926           GNUNET_SCHEDULER_add_now (&announce_applications, NULL);
5927
5928   }
5929   if (ntypes > 0)
5930   {
5931     uint16_t u16;
5932     struct GNUNET_HashCode hc;
5933
5934     t = (uint16_t *) & a[napps];
5935     c->types = GNUNET_CONTAINER_multihashmap_create (ntypes);
5936     for (i = 0; i < ntypes; i++)
5937     {
5938       u16 = ntohs (t[i]);
5939       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  msg type: %u\n", u16);
5940       GNUNET_CRYPTO_hash (&u16, sizeof (u16), &hc);
5941
5942       /* store in clients hashmap */
5943       GNUNET_CONTAINER_multihashmap_put (c->types, &hc, c,
5944                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
5945       /* store in global hashmap */
5946       GNUNET_CONTAINER_multihashmap_put (types, &hc, c,
5947                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
5948     }
5949   }
5950   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5951               " client has %u+%u subscriptions\n", napps, ntypes);
5952
5953   GNUNET_CONTAINER_DLL_insert (clients, clients_tail, c);
5954   c->own_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
5955   c->incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
5956   c->ignore_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
5957   GNUNET_SERVER_notification_context_add (nc, client);
5958   GNUNET_STATISTICS_update (stats, "# clients", 1, GNUNET_NO);
5959
5960   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5961   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
5962 }
5963
5964
5965 /**
5966  * Handler for clients announcing available services by a regular expression.
5967  *
5968  * @param cls closure
5969  * @param client identification of the client
5970  * @param message the actual message, which includes messages the client wants
5971  */
5972 static void
5973 handle_local_announce_regex (void *cls, struct GNUNET_SERVER_Client *client,
5974                              const struct GNUNET_MessageHeader *message)
5975 {
5976   struct MeshClient *c;
5977   char *regex;
5978   size_t len;
5979
5980   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "announce regex started\n");
5981
5982   /* Sanity check for client registration */
5983   if (NULL == (c = client_get (client)))
5984   {
5985     GNUNET_break (0);
5986     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5987     return;
5988   }
5989   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
5990
5991   len = ntohs (message->size) - sizeof(struct GNUNET_MessageHeader);
5992   regex = GNUNET_malloc (len + 1);
5993   memcpy (regex, &message[1], len);
5994   regex[len] = '\0';
5995   GNUNET_array_append (c->regexes, c->n_regex, regex);
5996   if (GNUNET_SCHEDULER_NO_TASK == c->regex_announce_task)
5997   {
5998     c->regex_announce_task = GNUNET_SCHEDULER_add_now(&announce_regex, c);
5999   }
6000   else
6001   {
6002     regex_put(regex);
6003   }
6004   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6005   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "announce regex processed\n");
6006 }
6007
6008
6009 /**
6010  * Handler for requests of new tunnels
6011  *
6012  * @param cls closure
6013  * @param client identification of the client
6014  * @param message the actual message
6015  */
6016 static void
6017 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
6018                             const struct GNUNET_MessageHeader *message)
6019 {
6020   struct GNUNET_MESH_TunnelMessage *t_msg;
6021   struct MeshTunnel *t;
6022   struct MeshClient *c;
6023   MESH_TunnelNumber tid;
6024
6025   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel requested\n");
6026
6027   /* Sanity check for client registration */
6028   if (NULL == (c = client_get (client)))
6029   {
6030     GNUNET_break (0);
6031     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6032     return;
6033   }
6034   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6035
6036   /* Message sanity check */
6037   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
6038   {
6039     GNUNET_break (0);
6040     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6041     return;
6042   }
6043
6044   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6045   /* Sanity check for tunnel numbering */
6046   tid = ntohl (t_msg->tunnel_id);
6047   if (0 == (tid & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
6048   {
6049     GNUNET_break (0);
6050     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6051     return;
6052   }
6053   /* Sanity check for duplicate tunnel IDs */
6054   if (NULL != tunnel_get_by_local_id (c, tid))
6055   {
6056     GNUNET_break (0);
6057     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6058     return;
6059   }
6060
6061   while (NULL != tunnel_get_by_pi (myid, next_tid))
6062     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
6063   t = tunnel_new (myid, next_tid++, c, tid);
6064   if (NULL == t)
6065   {
6066     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Tunnel creation failed.\n");
6067     GNUNET_break (0);
6068     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6069     return;
6070   }
6071   next_tid = next_tid & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
6072   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED TUNNEL %s [%x] (%x)\n",
6073               GNUNET_i2s (&my_full_id), t->id.tid, t->local_tid);
6074   t->peers = GNUNET_CONTAINER_multihashmap_create (32);
6075
6076   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel created\n");
6077   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6078   return;
6079 }
6080
6081
6082 /**
6083  * Handler for requests of deleting tunnels
6084  *
6085  * @param cls closure
6086  * @param client identification of the client
6087  * @param message the actual message
6088  */
6089 static void
6090 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
6091                              const struct GNUNET_MessageHeader *message)
6092 {
6093   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
6094   struct MeshClient *c;
6095   struct MeshTunnel *t;
6096   MESH_TunnelNumber tid;
6097
6098   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6099               "Got a DESTROY TUNNEL from client!\n");
6100
6101   /* Sanity check for client registration */
6102   if (NULL == (c = client_get (client)))
6103   {
6104     GNUNET_break (0);
6105     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6106     return;
6107   }
6108   /* Message sanity check */
6109   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
6110   {
6111     GNUNET_break (0);
6112     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6113     return;
6114   }
6115   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6116   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6117
6118   /* Retrieve tunnel */
6119   tid = ntohl (tunnel_msg->tunnel_id);
6120   t = tunnel_get_by_local_id(c, tid);
6121   if (NULL == t)
6122   {
6123     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
6124     GNUNET_break (0);
6125     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6126     return;
6127   }
6128   if (c != t->owner || tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
6129   {
6130     client_ignore_tunnel (c, t);
6131 #if 0
6132     // TODO: when to destroy incoming tunnel?
6133     if (t->nclients == 0)
6134     {
6135       GNUNET_assert (GNUNET_YES ==
6136                      GNUNET_CONTAINER_multihashmap_remove (incoming_tunnels,
6137                                                            &hash, t));
6138       GNUNET_assert (GNUNET_YES ==
6139                      GNUNET_CONTAINER_multihashmap_remove (t->peers,
6140                                                            &my_full_id.hashPubKey,
6141                                                            t));
6142     }
6143 #endif
6144     GNUNET_SERVER_receive_done (client, GNUNET_OK);
6145     return;
6146   }
6147   send_client_tunnel_disconnect(t, c);
6148   client_delete_tunnel(c, t);
6149
6150   /* Don't try to ACK the client about the tunnel_destroy multicast packet */
6151   t->owner = NULL;
6152   tunnel_send_destroy (t);
6153   t->destroy = GNUNET_YES;
6154   // The tunnel will be destroyed when the last message is transmitted.
6155   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6156   return;
6157 }
6158
6159
6160 /**
6161  * Handler for requests of seeting tunnel's speed.
6162  *
6163  * @param cls Closure (unused).
6164  * @param client Identification of the client.
6165  * @param message The actual message.
6166  */
6167 static void
6168 handle_local_tunnel_speed (void *cls, struct GNUNET_SERVER_Client *client,
6169                            const struct GNUNET_MessageHeader *message)
6170 {
6171   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
6172   struct MeshClient *c;
6173   struct MeshTunnel *t;
6174   MESH_TunnelNumber tid;
6175
6176   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6177               "Got a SPEED request from client!\n");
6178
6179   /* Sanity check for client registration */
6180   if (NULL == (c = client_get (client)))
6181   {
6182     GNUNET_break (0);
6183     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6184     return;
6185   }
6186
6187   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6188   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6189
6190   /* Retrieve tunnel */
6191   tid = ntohl (tunnel_msg->tunnel_id);
6192   t = tunnel_get_by_local_id(c, tid);
6193   if (NULL == t)
6194   {
6195     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  tunnel %X not found\n", tid);
6196     GNUNET_break (0);
6197     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6198     return;
6199   }
6200
6201   switch (ntohs(message->type))
6202   {
6203       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MIN:
6204           t->speed_min = GNUNET_YES;
6205           break;
6206       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MAX:
6207           t->speed_min = GNUNET_NO;
6208           break;
6209       default:
6210           GNUNET_break (0);
6211   }
6212   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6213 }
6214
6215
6216 /**
6217  * Handler for requests of seeting tunnel's buffering policy.
6218  *
6219  * @param cls Closure (unused).
6220  * @param client Identification of the client.
6221  * @param message The actual message.
6222  */
6223 static void
6224 handle_local_tunnel_buffer (void *cls, struct GNUNET_SERVER_Client *client,
6225                             const struct GNUNET_MessageHeader *message)
6226 {
6227   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
6228   struct MeshClient *c;
6229   struct MeshTunnel *t;
6230   MESH_TunnelNumber tid;
6231
6232   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6233               "Got a BUFFER request from client!\n");
6234
6235   /* Sanity check for client registration */
6236   if (NULL == (c = client_get (client)))
6237   {
6238     GNUNET_break (0);
6239     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6240     return;
6241   }
6242
6243   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6244   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6245
6246   /* Retrieve tunnel */
6247   tid = ntohl (tunnel_msg->tunnel_id);
6248   t = tunnel_get_by_local_id(c, tid);
6249   if (NULL == t)
6250   {
6251     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
6252     GNUNET_break (0);
6253     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6254     return;
6255   }
6256
6257   switch (ntohs(message->type))
6258   {
6259       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER:
6260           t->nobuffer = GNUNET_NO;
6261           break;
6262       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER:
6263           t->nobuffer = GNUNET_YES;
6264           break;
6265       default:
6266           GNUNET_break (0);
6267   }
6268
6269   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6270 }
6271
6272
6273 /**
6274  * Handler for connection requests to new peers
6275  *
6276  * @param cls closure
6277  * @param client identification of the client
6278  * @param message the actual message (PeerControl)
6279  */
6280 static void
6281 handle_local_connect_add (void *cls, struct GNUNET_SERVER_Client *client,
6282                           const struct GNUNET_MessageHeader *message)
6283 {
6284   struct GNUNET_MESH_PeerControl *peer_msg;
6285   struct MeshPeerInfo *peer_info;
6286   struct MeshClient *c;
6287   struct MeshTunnel *t;
6288   MESH_TunnelNumber tid;
6289
6290   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got connection request\n");
6291   /* Sanity check for client registration */
6292   if (NULL == (c = client_get (client)))
6293   {
6294     GNUNET_break (0);
6295     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6296     return;
6297   }
6298
6299   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6300   /* Sanity check for message size */
6301   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6302   {
6303     GNUNET_break (0);
6304     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6305     return;
6306   }
6307
6308   /* Tunnel exists? */
6309   tid = ntohl (peer_msg->tunnel_id);
6310   t = tunnel_get_by_local_id (c, tid);
6311   if (NULL == t)
6312   {
6313     GNUNET_break (0);
6314     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6315     return;
6316   }
6317
6318   /* Does client own tunnel? */
6319   if (t->owner->handle != client)
6320   {
6321     GNUNET_break (0);
6322     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6323     return;
6324   }
6325   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "     for %s\n",
6326               GNUNET_i2s (&peer_msg->peer));
6327   peer_info = peer_info_get (&peer_msg->peer);
6328
6329   tunnel_add_peer (t, peer_info);
6330   peer_info_connect (peer_info, t);
6331
6332   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6333   return;
6334 }
6335
6336
6337 /**
6338  * Handler for disconnection requests of peers in a tunnel
6339  *
6340  * @param cls closure
6341  * @param client identification of the client
6342  * @param message the actual message (PeerControl)
6343  */
6344 static void
6345 handle_local_connect_del (void *cls, struct GNUNET_SERVER_Client *client,
6346                           const struct GNUNET_MessageHeader *message)
6347 {
6348   struct GNUNET_MESH_PeerControl *peer_msg;
6349   struct MeshPeerInfo *peer_info;
6350   struct MeshClient *c;
6351   struct MeshTunnel *t;
6352   MESH_TunnelNumber tid;
6353
6354   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER DEL request\n");
6355   /* Sanity check for client registration */
6356   if (NULL == (c = client_get (client)))
6357   {
6358     GNUNET_break (0);
6359     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6360     return;
6361   }
6362   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6363   /* Sanity check for message size */
6364   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6365   {
6366     GNUNET_break (0);
6367     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6368     return;
6369   }
6370
6371   /* Tunnel exists? */
6372   tid = ntohl (peer_msg->tunnel_id);
6373   t = tunnel_get_by_local_id (c, tid);
6374   if (NULL == t)
6375   {
6376     GNUNET_break (0);
6377     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6378     return;
6379   }
6380   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
6381
6382   /* Does client own tunnel? */
6383   if (t->owner->handle != client)
6384   {
6385     GNUNET_break (0);
6386     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6387     return;
6388   }
6389
6390   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for peer %s\n",
6391               GNUNET_i2s (&peer_msg->peer));
6392   /* Is the peer in the tunnel? */
6393   peer_info =
6394       GNUNET_CONTAINER_multihashmap_get (t->peers, &peer_msg->peer.hashPubKey);
6395   if (NULL == peer_info)
6396   {
6397     GNUNET_break (0);
6398     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6399     return;
6400   }
6401
6402   /* Ok, delete peer from tunnel */
6403   GNUNET_CONTAINER_multihashmap_remove_all (t->peers,
6404                                             &peer_msg->peer.hashPubKey);
6405
6406   send_destroy_path (t, peer_info->id);
6407   tunnel_delete_peer (t, peer_info->id);
6408   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6409   return;
6410 }
6411
6412 /**
6413  * Handler for blacklist requests of peers in a tunnel
6414  *
6415  * @param cls closure
6416  * @param client identification of the client
6417  * @param message the actual message (PeerControl)
6418  */
6419 static void
6420 handle_local_blacklist (void *cls, struct GNUNET_SERVER_Client *client,
6421                           const struct GNUNET_MessageHeader *message)
6422 {
6423   struct GNUNET_MESH_PeerControl *peer_msg;
6424   struct MeshClient *c;
6425   struct MeshTunnel *t;
6426   MESH_TunnelNumber tid;
6427
6428   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER BLACKLIST request\n");
6429   /* Sanity check for client registration */
6430   if (NULL == (c = client_get (client)))
6431   {
6432     GNUNET_break (0);
6433     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6434     return;
6435   }
6436   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6437
6438   /* Sanity check for message size */
6439   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6440   {
6441     GNUNET_break (0);
6442     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6443     return;
6444   }
6445
6446   /* Tunnel exists? */
6447   tid = ntohl (peer_msg->tunnel_id);
6448   t = tunnel_get_by_local_id (c, tid);
6449   if (NULL == t)
6450   {
6451     GNUNET_break (0);
6452     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6453     return;
6454   }
6455   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
6456
6457   GNUNET_array_append(t->blacklisted, t->nblacklisted,
6458                       GNUNET_PEER_intern(&peer_msg->peer));
6459 }
6460
6461
6462 /**
6463  * Handler for unblacklist requests of peers in a tunnel
6464  *
6465  * @param cls closure
6466  * @param client identification of the client
6467  * @param message the actual message (PeerControl)
6468  */
6469 static void
6470 handle_local_unblacklist (void *cls, struct GNUNET_SERVER_Client *client,
6471                           const struct GNUNET_MessageHeader *message)
6472 {
6473   struct GNUNET_MESH_PeerControl *peer_msg;
6474   struct MeshClient *c;
6475   struct MeshTunnel *t;
6476   MESH_TunnelNumber tid;
6477   GNUNET_PEER_Id pid;
6478   unsigned int i;
6479
6480   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER UNBLACKLIST request\n");
6481   /* Sanity check for client registration */
6482   if (NULL == (c = client_get (client)))
6483   {
6484     GNUNET_break (0);
6485     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6486     return;
6487   }
6488   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6489
6490   /* Sanity check for message size */
6491   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6492   {
6493     GNUNET_break (0);
6494     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6495     return;
6496   }
6497
6498   /* Tunnel exists? */
6499   tid = ntohl (peer_msg->tunnel_id);
6500   t = tunnel_get_by_local_id (c, tid);
6501   if (NULL == t)
6502   {
6503     GNUNET_break (0);
6504     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6505     return;
6506   }
6507   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
6508
6509   /* if peer is not known, complain */
6510   pid = GNUNET_PEER_search (&peer_msg->peer);
6511   if (0 == pid)
6512   {
6513     GNUNET_break (0);
6514     return;
6515   }
6516
6517   /* search and remove from list */
6518   for (i = 0; i < t->nblacklisted; i++)
6519   {
6520     if (t->blacklisted[i] == pid)
6521     {
6522       t->blacklisted[i] = t->blacklisted[t->nblacklisted - 1];
6523       GNUNET_array_grow (t->blacklisted, t->nblacklisted, t->nblacklisted - 1);
6524       return;
6525     }
6526   }
6527
6528   /* if peer hasn't been blacklisted, complain */
6529   GNUNET_break (0);
6530 }
6531
6532
6533 /**
6534  * Handler for connection requests to new peers by type
6535  *
6536  * @param cls closure
6537  * @param client identification of the client
6538  * @param message the actual message (ConnectPeerByType)
6539  */
6540 static void
6541 handle_local_connect_by_type (void *cls, struct GNUNET_SERVER_Client *client,
6542                               const struct GNUNET_MessageHeader *message)
6543 {
6544   struct GNUNET_MESH_ConnectPeerByType *connect_msg;
6545   struct MeshClient *c;
6546   struct MeshTunnel *t;
6547   struct GNUNET_HashCode hash;
6548   MESH_TunnelNumber tid;
6549
6550   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got connect by type request\n");
6551   /* Sanity check for client registration */
6552   if (NULL == (c = client_get (client)))
6553   {
6554     GNUNET_break (0);
6555     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6556     return;
6557   }
6558
6559   connect_msg = (struct GNUNET_MESH_ConnectPeerByType *) message;
6560   /* Sanity check for message size */
6561   if (sizeof (struct GNUNET_MESH_ConnectPeerByType) !=
6562       ntohs (connect_msg->header.size))
6563   {
6564     GNUNET_break (0);
6565     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6566     return;
6567   }
6568
6569   /* Tunnel exists? */
6570   tid = ntohl (connect_msg->tunnel_id);
6571   t = tunnel_get_by_local_id (c, tid);
6572   if (NULL == t)
6573   {
6574     GNUNET_break (0);
6575     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6576     return;
6577   }
6578
6579   /* Does client own tunnel? */
6580   if (t->owner->handle != client)
6581   {
6582     GNUNET_break (0);
6583     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6584     return;
6585   }
6586
6587   /* Do WE have the service? */
6588   t->type = ntohl (connect_msg->type);
6589   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " type requested: %u\n", t->type);
6590   GNUNET_CRYPTO_hash (&t->type, sizeof (GNUNET_MESH_ApplicationType), &hash);
6591   if (GNUNET_CONTAINER_multihashmap_contains (applications, &hash) ==
6592       GNUNET_YES)
6593   {
6594     /* Yes! Fast forward, add ourselves to the tunnel and send the
6595      * good news to the client, and alert the destination client of
6596      * an incoming tunnel.
6597      *
6598      * FIXME send a path create to self, avoid code duplication
6599      */
6600     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " available locally\n");
6601     GNUNET_CONTAINER_multihashmap_put (t->peers, &my_full_id.hashPubKey,
6602                                        peer_info_get (&my_full_id),
6603                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
6604
6605     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " notifying client\n");
6606     send_client_peer_connected (t, myid);
6607     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Done\n");
6608     GNUNET_SERVER_receive_done (client, GNUNET_OK);
6609
6610     t->local_tid_dest = next_local_tid++;
6611     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
6612     GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
6613                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
6614
6615     return;
6616   }
6617   /* Ok, lets find a peer offering the service */
6618   if (NULL != t->dht_get_type)
6619   {
6620     GNUNET_DHT_get_stop (t->dht_get_type);
6621   }
6622   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " looking in DHT for %s\n",
6623               GNUNET_h2s (&hash));
6624   t->dht_get_type =
6625       GNUNET_DHT_get_start (dht_handle, 
6626                             GNUNET_BLOCK_TYPE_MESH_PEER_BY_TYPE,
6627                             &hash,
6628                             dht_replication_level,
6629                             GNUNET_DHT_RO_RECORD_ROUTE |
6630                             GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
6631                             NULL, 0,
6632                             &dht_get_type_handler, t);
6633
6634   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6635   return;
6636 }
6637
6638
6639 /**
6640  * Handler for connection requests to new peers by a string service description.
6641  *
6642  * @param cls closure
6643  * @param client identification of the client
6644  * @param message the actual message, which includes messages the client wants
6645  */
6646 static void
6647 handle_local_connect_by_string (void *cls, struct GNUNET_SERVER_Client *client,
6648                                 const struct GNUNET_MessageHeader *message)
6649 {
6650   struct GNUNET_MESH_ConnectPeerByString *msg;
6651   struct MeshRegexSearchContext *ctx;
6652   struct MeshRegexSearchInfo *info;
6653   struct GNUNET_DHT_GetHandle *get_h;
6654   struct GNUNET_HashCode key;
6655   struct MeshTunnel *t;
6656   struct MeshClient *c;
6657   MESH_TunnelNumber tid;
6658   const char *string;
6659   size_t size;
6660   size_t len;
6661   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6662               "Connect by string started\n");
6663   msg = (struct GNUNET_MESH_ConnectPeerByString *) message;
6664   size = htons (message->size);
6665
6666   /* Sanity check for client registration */
6667   if (NULL == (c = client_get (client)))
6668   {
6669     GNUNET_break (0);
6670     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6671     return;
6672   }
6673
6674   /* Message size sanity check */
6675   if (sizeof(struct GNUNET_MESH_ConnectPeerByString) >= size)
6676   {
6677     GNUNET_break (0);
6678     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6679     return;
6680   }
6681
6682   /* Tunnel exists? */
6683   tid = ntohl (msg->tunnel_id);
6684   t = tunnel_get_by_local_id (c, tid);
6685   if (NULL == t)
6686   {
6687     GNUNET_break (0);
6688     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6689     return;
6690   }
6691
6692   /* Does client own tunnel? */
6693   if (t->owner->handle != client)
6694   {
6695     GNUNET_break (0);
6696     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6697     return;
6698   }
6699
6700   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6701               "  on tunnel %s [%u]\n",
6702               GNUNET_i2s(&my_full_id),
6703               t->id.tid);
6704
6705   /* Only one connect_by_string allowed at the same time! */
6706   /* FIXME: allow more, return handle at api level to cancel, document */
6707   if (NULL != t->regex_ctx)
6708   {
6709     GNUNET_break (0);
6710     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6711     return;
6712   }
6713
6714   /* Find string itself */
6715   len = size - sizeof(struct GNUNET_MESH_ConnectPeerByString);
6716   string = (const char *) &msg[1];
6717
6718   /* Initialize context */
6719   size = GNUNET_REGEX_get_first_key(string, len, &key);
6720   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6721               "  consumed %u bits out of %u\n", size, len);
6722   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6723               "  looking for %s\n", GNUNET_h2s (&key));
6724
6725   info = GNUNET_malloc (sizeof (struct MeshRegexSearchInfo));
6726   info->t = t;
6727   info->description = GNUNET_malloc (len + 1);
6728   memcpy (info->description, string, len);
6729   info->description[len] = '\0';
6730   info->dht_get_handles = GNUNET_CONTAINER_multihashmap_create(32);
6731   info->dht_get_results = GNUNET_CONTAINER_multihashmap_create(32);
6732   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   string: %s\n", info->description);
6733
6734   ctx = GNUNET_malloc (sizeof (struct MeshRegexSearchContext));
6735   ctx->position = size;
6736   ctx->info = info;
6737   t->regex_ctx = ctx;
6738
6739   GNUNET_array_append (info->contexts, info->n_contexts, ctx);
6740
6741   /* Start search in DHT */
6742   get_h = GNUNET_DHT_get_start (dht_handle,    /* handle */
6743                                 GNUNET_BLOCK_TYPE_MESH_REGEX, /* type */
6744                                 &key,     /* key to search */
6745                                 dht_replication_level, /* replication level */
6746                                 GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
6747                                 NULL,       /* xquery */ // FIXME BLOOMFILTER
6748                                 0,     /* xquery bits */ // FIXME BLOOMFILTER SIZE
6749                                 &dht_get_string_handler, ctx);
6750
6751   GNUNET_break (GNUNET_OK ==
6752                 GNUNET_CONTAINER_multihashmap_put(info->dht_get_handles,
6753                                                   &key,
6754                                                   get_h,
6755                                                   GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
6756
6757   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6758   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "connect by string processed\n");
6759 }
6760
6761
6762 /**
6763  * Handler for client traffic directed to one peer
6764  *
6765  * @param cls closure
6766  * @param client identification of the client
6767  * @param message the actual message
6768  */
6769 static void
6770 handle_local_unicast (void *cls, struct GNUNET_SERVER_Client *client,
6771                       const struct GNUNET_MessageHeader *message)
6772 {
6773   struct MeshClient *c;
6774   struct MeshTunnel *t;
6775   struct MeshPeerInfo *pi;
6776   struct GNUNET_MESH_Unicast *data_msg;
6777   MESH_TunnelNumber tid;
6778   size_t size;
6779
6780   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6781               "Got a unicast request from a client!\n");
6782
6783   /* Sanity check for client registration */
6784   if (NULL == (c = client_get (client)))
6785   {
6786     GNUNET_break (0);
6787     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6788     return;
6789   }
6790   data_msg = (struct GNUNET_MESH_Unicast *) message;
6791   /* Sanity check for message size */
6792   size = ntohs (message->size);
6793   if (sizeof (struct GNUNET_MESH_Unicast) +
6794       sizeof (struct GNUNET_MessageHeader) > size)
6795   {
6796     GNUNET_break (0);
6797     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6798     return;
6799   }
6800
6801   /* Tunnel exists? */
6802   tid = ntohl (data_msg->tid);
6803   t = tunnel_get_by_local_id (c, tid);
6804   if (NULL == t)
6805   {
6806     GNUNET_break (0);
6807     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6808     return;
6809   }
6810
6811   /*  Is it a local tunnel? Then, does client own the tunnel? */
6812   if (t->owner->handle != client)
6813   {
6814     GNUNET_break (0);
6815     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6816     return;
6817   }
6818
6819   pi = GNUNET_CONTAINER_multihashmap_get (t->peers,
6820                                           &data_msg->destination.hashPubKey);
6821   /* Is the selected peer in the tunnel? */
6822   if (NULL == pi)
6823   {
6824     GNUNET_break (0);
6825     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6826     return;
6827   }
6828
6829   /* PID should be as expected */
6830   if (ntohl (data_msg->pid) != t->fwd_pid + 1)
6831   {
6832     GNUNET_break (0);
6833     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6834               "Unicast PID, expected %u, got %u\n",
6835               t->fwd_pid + 1, ntohl (data_msg->pid));
6836     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6837     return;
6838   }
6839
6840   /* Ok, everything is correct, send the message
6841    * (pretend we got it from a mesh peer)
6842    */
6843   {
6844     /* Work around const limitation */
6845     char buf[ntohs (message->size)] GNUNET_ALIGN;
6846     struct GNUNET_MESH_Unicast *copy;
6847
6848     copy = (struct GNUNET_MESH_Unicast *) buf;
6849     memcpy (buf, data_msg, size);
6850     copy->oid = my_full_id;
6851     copy->tid = htonl (t->id.tid);
6852     copy->ttl = htonl (default_ttl);
6853     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6854                 "  calling generic handler...\n");
6855     handle_mesh_data_unicast (NULL, &my_full_id, &copy->header, NULL, 0);
6856   }
6857   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "receive done OK\n");
6858   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6859   return;
6860 }
6861
6862
6863 /**
6864  * Handler for client traffic directed to the origin
6865  *
6866  * @param cls closure
6867  * @param client identification of the client
6868  * @param message the actual message
6869  */
6870 static void
6871 handle_local_to_origin (void *cls, struct GNUNET_SERVER_Client *client,
6872                         const struct GNUNET_MessageHeader *message)
6873 {
6874   struct GNUNET_MESH_ToOrigin *data_msg;
6875   struct MeshTunnelClientInfo *clinfo;
6876   struct MeshClient *c;
6877   struct MeshTunnel *t;
6878   MESH_TunnelNumber tid;
6879   size_t size;
6880
6881   /* Sanity check for client registration */
6882   if (NULL == (c = client_get (client)))
6883   {
6884     GNUNET_break (0);
6885     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6886     return;
6887   }
6888   data_msg = (struct GNUNET_MESH_ToOrigin *) message;
6889   /* Sanity check for message size */
6890   size = ntohs (message->size);
6891   if (sizeof (struct GNUNET_MESH_ToOrigin) +
6892       sizeof (struct GNUNET_MessageHeader) > size)
6893   {
6894     GNUNET_break (0);
6895     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6896     return;
6897   }
6898
6899   /* Tunnel exists? */
6900   tid = ntohl (data_msg->tid);
6901   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6902               "Got a ToOrigin request from a client! Tunnel %X\n", tid);
6903   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
6904   {
6905     GNUNET_break (0);
6906     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6907     return;
6908   }
6909   t = tunnel_get_by_local_id (c, tid);
6910   if (NULL == t)
6911   {
6912     GNUNET_break (0);
6913     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6914     return;
6915   }
6916
6917   /*  It should be sent by someone who has this as incoming tunnel. */
6918   if (GNUNET_NO == client_knows_tunnel (c, t))
6919   {
6920     GNUNET_break (0);
6921     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6922     return;
6923   }
6924
6925   /* PID should be as expected */
6926   clinfo = tunnel_get_client_fc (t, c);
6927   if (ntohl (data_msg->pid) != clinfo->bck_pid + 1)
6928   {
6929     GNUNET_break (0);
6930     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6931                 "To Origin PID, expected %u, got %u\n",
6932                 clinfo->bck_pid + 1, ntohl (data_msg->pid));
6933     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6934     return;
6935   }
6936
6937   /* Ok, everything is correct, send the message
6938    * (pretend we got it from a mesh peer)
6939    */
6940   {
6941     char buf[ntohs (message->size)] GNUNET_ALIGN;
6942     struct GNUNET_MESH_ToOrigin *copy;
6943
6944     /* Work around const limitation */
6945     copy = (struct GNUNET_MESH_ToOrigin *) buf;
6946     memcpy (buf, data_msg, size);
6947     GNUNET_PEER_resolve (t->id.oid, &copy->oid);
6948     copy->tid = htonl (t->id.tid);
6949     copy->ttl = htonl (default_ttl);
6950     GNUNET_assert (ntohl (copy->pid) == (t->bck_pid + 1));
6951     copy->sender = my_full_id;
6952     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6953                 "  calling generic handler...\n");
6954     handle_mesh_data_to_orig (NULL, &my_full_id, &copy->header, NULL, 0);
6955   }
6956   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6957   return;
6958 }
6959
6960
6961 /**
6962  * Handler for client traffic directed to all peers in a tunnel
6963  *
6964  * @param cls closure
6965  * @param client identification of the client
6966  * @param message the actual message
6967  */
6968 static void
6969 handle_local_multicast (void *cls, struct GNUNET_SERVER_Client *client,
6970                         const struct GNUNET_MessageHeader *message)
6971 {
6972   struct MeshClient *c;
6973   struct MeshTunnel *t;
6974   struct GNUNET_MESH_Multicast *data_msg;
6975   MESH_TunnelNumber tid;
6976
6977   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6978               "Got a multicast request from a client!\n");
6979
6980   /* Sanity check for client registration */
6981   if (NULL == (c = client_get (client)))
6982   {
6983     GNUNET_break (0);
6984     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6985     return;
6986   }
6987   data_msg = (struct GNUNET_MESH_Multicast *) message;
6988   /* Sanity check for message size */
6989   if (sizeof (struct GNUNET_MESH_Multicast) +
6990       sizeof (struct GNUNET_MessageHeader) > ntohs (data_msg->header.size))
6991   {
6992     GNUNET_break (0);
6993     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6994     return;
6995   }
6996
6997   /* Tunnel exists? */
6998   tid = ntohl (data_msg->tid);
6999   t = tunnel_get_by_local_id (c, tid);
7000   if (NULL == t)
7001   {
7002     GNUNET_break (0);
7003     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7004     return;
7005   }
7006
7007   /* Does client own tunnel? */
7008   if (t->owner->handle != client)
7009   {
7010     GNUNET_break (0);
7011     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7012     return;
7013   }
7014
7015   /* PID should be as expected */
7016   if (ntohl (data_msg->pid) != t->fwd_pid + 1)
7017   {
7018     GNUNET_break (0);
7019     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7020               "Multicast PID, expected %u, got %u\n",
7021               t->fwd_pid + 1, ntohl (data_msg->pid));
7022     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7023     return;
7024   }
7025
7026   {
7027     char buf[ntohs (message->size)] GNUNET_ALIGN;
7028     struct GNUNET_MESH_Multicast *copy;
7029
7030     copy = (struct GNUNET_MESH_Multicast *) buf;
7031     memcpy (buf, message, ntohs (message->size));
7032     copy->oid = my_full_id;
7033     copy->tid = htonl (t->id.tid);
7034     copy->ttl = htonl (default_ttl);
7035     GNUNET_assert (ntohl (copy->pid) == (t->fwd_pid + 1));
7036     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7037                 "  calling generic handler...\n");
7038     handle_mesh_data_multicast (client, &my_full_id, &copy->header, NULL, 0);
7039   }
7040
7041   /* receive done gets called when last copy is sent to a neighbor */
7042   return;
7043 }
7044
7045
7046 /**
7047  * Handler for client's ACKs for payload traffic.
7048  *
7049  * @param cls Closure (unused).
7050  * @param client Identification of the client.
7051  * @param message The actual message.
7052  */
7053 static void
7054 handle_local_ack (void *cls, struct GNUNET_SERVER_Client *client,
7055                   const struct GNUNET_MessageHeader *message)
7056 {
7057   struct GNUNET_MESH_LocalAck *msg;
7058   struct MeshTunnel *t;
7059   struct MeshClient *c;
7060   MESH_TunnelNumber tid;
7061
7062   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a local ACK\n");
7063   /* Sanity check for client registration */
7064   if (NULL == (c = client_get (client)))
7065   {
7066     GNUNET_break (0);
7067     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7068     return;
7069   }
7070
7071   msg = (struct GNUNET_MESH_LocalAck *) message;
7072   /* Tunnel exists? */
7073   tid = ntohl (msg->tunnel_id);
7074   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
7075   t = tunnel_get_by_local_id (c, tid);
7076   if (NULL == t)
7077   {
7078     GNUNET_break (0); // FIXME fc
7079     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7080     return;
7081   }
7082
7083   /* Does client own tunnel? I.E: Is this and ACK for BCK traffic? */
7084   if (NULL != t->owner && t->owner->handle == client)
7085   {
7086     /* The client owns the tunnel, ACK is for data to_origin, send BCK ACK. */
7087     t->bck_ack = ntohl(msg->max_pid);
7088     tunnel_send_bck_ack(t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
7089   }
7090   else
7091   {
7092     /* The client doesn't own the tunnel, this ACK is for FWD traffic. */
7093     tunnel_set_client_fwd_ack (t, c, ntohl (msg->max_pid));
7094     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
7095   }
7096
7097   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7098   return;
7099 }
7100
7101
7102 /**
7103  * Functions to handle messages from clients
7104  */
7105 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
7106   {&handle_local_new_client, NULL,
7107    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
7108   {&handle_local_announce_regex, NULL,
7109    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ANNOUNCE_REGEX, 0},
7110   {&handle_local_tunnel_create, NULL,
7111    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
7112    sizeof (struct GNUNET_MESH_TunnelMessage)},
7113   {&handle_local_tunnel_destroy, NULL,
7114    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
7115    sizeof (struct GNUNET_MESH_TunnelMessage)},
7116   {&handle_local_tunnel_speed, NULL,
7117    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MIN,
7118    sizeof (struct GNUNET_MESH_TunnelMessage)},
7119   {&handle_local_tunnel_speed, NULL,
7120    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MAX,
7121    sizeof (struct GNUNET_MESH_TunnelMessage)},
7122   {&handle_local_tunnel_buffer, NULL,
7123    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER,
7124    sizeof (struct GNUNET_MESH_TunnelMessage)},
7125   {&handle_local_tunnel_buffer, NULL,
7126    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER,
7127    sizeof (struct GNUNET_MESH_TunnelMessage)},
7128   {&handle_local_connect_add, NULL,
7129    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD,
7130    sizeof (struct GNUNET_MESH_PeerControl)},
7131   {&handle_local_connect_del, NULL,
7132    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL,
7133    sizeof (struct GNUNET_MESH_PeerControl)},
7134   {&handle_local_blacklist, NULL,
7135    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_BLACKLIST,
7136    sizeof (struct GNUNET_MESH_PeerControl)},
7137   {&handle_local_unblacklist, NULL,
7138    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_UNBLACKLIST,
7139    sizeof (struct GNUNET_MESH_PeerControl)},
7140   {&handle_local_connect_by_type, NULL,
7141    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE,
7142    sizeof (struct GNUNET_MESH_ConnectPeerByType)},
7143   {&handle_local_connect_by_string, NULL,
7144    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_STRING, 0},
7145   {&handle_local_unicast, NULL,
7146    GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
7147   {&handle_local_to_origin, NULL,
7148    GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
7149   {&handle_local_multicast, NULL,
7150    GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
7151   {&handle_local_ack, NULL,
7152    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK,
7153    sizeof (struct GNUNET_MESH_LocalAck)},
7154   {NULL, NULL, 0, 0}
7155 };
7156
7157
7158 /**
7159  * To be called on core init/fail.
7160  *
7161  * @param cls service closure
7162  * @param server handle to the server for this service
7163  * @param identity the public identity of this peer
7164  */
7165 static void
7166 core_init (void *cls, struct GNUNET_CORE_Handle *server,
7167            const struct GNUNET_PeerIdentity *identity)
7168 {
7169   static int i = 0;
7170   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
7171   core_handle = server;
7172   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)) ||
7173       NULL == server)
7174   {
7175     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
7176     GNUNET_SCHEDULER_shutdown (); // Try gracefully
7177     if (10 < i++)
7178       GNUNET_abort(); // Try harder
7179   }
7180   return;
7181 }
7182
7183
7184 /**
7185  * Method called whenever a given peer connects.
7186  *
7187  * @param cls closure
7188  * @param peer peer identity this notification is about
7189  * @param atsi performance data for the connection
7190  * @param atsi_count number of records in 'atsi'
7191  */
7192 static void
7193 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
7194               const struct GNUNET_ATS_Information *atsi,
7195               unsigned int atsi_count)
7196 {
7197   struct MeshPeerInfo *peer_info;
7198   struct MeshPeerPath *path;
7199
7200   DEBUG_CONN ("Peer connected\n");
7201   DEBUG_CONN ("     %s\n", GNUNET_i2s (&my_full_id));
7202   peer_info = peer_info_get (peer);
7203   if (myid == peer_info->id)
7204   {
7205     DEBUG_CONN ("     (self)\n");
7206     return;
7207   }
7208   else
7209   {
7210     DEBUG_CONN ("     %s\n", GNUNET_i2s (peer));
7211   }
7212   path = path_new (2);
7213   path->peers[0] = myid;
7214   path->peers[1] = peer_info->id;
7215   GNUNET_PEER_change_rc (myid, 1);
7216   GNUNET_PEER_change_rc (peer_info->id, 1);
7217   peer_info_add_path (peer_info, path, GNUNET_YES);
7218   GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
7219   return;
7220 }
7221
7222
7223 /**
7224  * Method called whenever a peer disconnects.
7225  *
7226  * @param cls closure
7227  * @param peer peer identity this notification is about
7228  */
7229 static void
7230 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
7231 {
7232   struct MeshPeerInfo *pi;
7233   struct MeshPeerQueue *q;
7234   struct MeshPeerQueue *n;
7235
7236   DEBUG_CONN ("Peer disconnected\n");
7237   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
7238   if (NULL == pi)
7239   {
7240     GNUNET_break (0);
7241     return;
7242   }
7243   q = pi->queue_head;
7244   while (NULL != q)
7245   {
7246       n = q->next;
7247       if (q->peer == pi)
7248       {
7249         /* try to reroute this traffic instead */
7250         queue_destroy(q, GNUNET_YES);
7251       }
7252       q = n;
7253   }
7254   peer_info_remove_path (pi, pi->id, myid);
7255   if (myid == pi->id)
7256   {
7257     DEBUG_CONN ("     (self)\n");
7258   }
7259   GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
7260   return;
7261 }
7262
7263
7264 /******************************************************************************/
7265 /************************      MAIN FUNCTIONS      ****************************/
7266 /******************************************************************************/
7267
7268 /**
7269  * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
7270  *
7271  * @param cls closure
7272  * @param key current key code
7273  * @param value value in the hash map
7274  * @return GNUNET_YES if we should continue to iterate,
7275  *         GNUNET_NO if not.
7276  */
7277 static int
7278 shutdown_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
7279 {
7280   struct MeshTunnel *t = value;
7281
7282   tunnel_destroy (t);
7283   return GNUNET_YES;
7284 }
7285
7286 /**
7287  * Iterator over peer hash map entries to destroy the tunnel during shutdown.
7288  *
7289  * @param cls closure
7290  * @param key current key code
7291  * @param value value in the hash map
7292  * @return GNUNET_YES if we should continue to iterate,
7293  *         GNUNET_NO if not.
7294  */
7295 static int
7296 shutdown_peer (void *cls, const struct GNUNET_HashCode * key, void *value)
7297 {
7298   struct MeshPeerInfo *p = value;
7299   struct MeshPeerQueue *q;
7300   struct MeshPeerQueue *n;
7301
7302   q = p->queue_head;
7303   while (NULL != q)
7304   {
7305       n = q->next;
7306       if (q->peer == p)
7307       {
7308         queue_destroy(q, GNUNET_YES);
7309       }
7310       q = n;
7311   }
7312   peer_info_destroy (p);
7313   return GNUNET_YES;
7314 }
7315
7316 /**
7317  * Task run during shutdown.
7318  *
7319  * @param cls unused
7320  * @param tc unused
7321  */
7322 static void
7323 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
7324 {
7325   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
7326
7327   if (core_handle != NULL)
7328   {
7329     GNUNET_CORE_disconnect (core_handle);
7330     core_handle = NULL;
7331   }
7332   GNUNET_CONTAINER_multihashmap_iterate (tunnels, &shutdown_tunnel, NULL);
7333   GNUNET_CONTAINER_multihashmap_iterate (peers, &shutdown_peer, NULL);
7334   if (dht_handle != NULL)
7335   {
7336     GNUNET_DHT_disconnect (dht_handle);
7337     dht_handle = NULL;
7338   }
7339   if (nc != NULL)
7340   {
7341     GNUNET_SERVER_notification_context_destroy (nc);
7342     nc = NULL;
7343   }
7344   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
7345   {
7346     GNUNET_SCHEDULER_cancel (announce_id_task);
7347     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
7348   }
7349   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
7350 }
7351
7352 /**
7353  * Process mesh requests.
7354  *
7355  * @param cls closure
7356  * @param server the initialized server
7357  * @param c configuration to use
7358  */
7359 static void
7360 run (void *cls, struct GNUNET_SERVER_Handle *server,
7361      const struct GNUNET_CONFIGURATION_Handle *c)
7362 {
7363   struct MeshPeerInfo *peer;
7364   struct MeshPeerPath *p;
7365   char *keyfile;
7366
7367   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
7368   server_handle = server;
7369   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
7370                                      NULL,      /* Closure passed to MESH functions */
7371                                      &core_init,        /* Call core_init once connected */
7372                                      &core_connect,     /* Handle connects */
7373                                      &core_disconnect,  /* remove peers on disconnects */
7374                                      NULL,      /* Don't notify about all incoming messages */
7375                                      GNUNET_NO, /* For header only in notification */
7376                                      NULL,      /* Don't notify about all outbound messages */
7377                                      GNUNET_NO, /* For header-only out notification */
7378                                      core_handlers);    /* Register these handlers */
7379
7380   if (core_handle == NULL)
7381   {
7382     GNUNET_break (0);
7383     GNUNET_SCHEDULER_shutdown ();
7384     return;
7385   }
7386
7387   if (GNUNET_OK !=
7388       GNUNET_CONFIGURATION_get_value_filename (c, "GNUNETD", "HOSTKEY",
7389                                                &keyfile))
7390   {
7391     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7392                 _
7393                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7394                 "hostkey");
7395     GNUNET_SCHEDULER_shutdown ();
7396     return;
7397   }
7398
7399   if (GNUNET_OK !=
7400       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_PATH_TIME",
7401                                            &refresh_path_time))
7402   {
7403     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7404                 _
7405                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7406                 "refresh path time");
7407     GNUNET_SCHEDULER_shutdown ();
7408     return;
7409   }
7410
7411   if (GNUNET_OK !=
7412       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "APP_ANNOUNCE_TIME",
7413                                            &app_announce_time))
7414   {
7415     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7416                 _
7417                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7418                 "app announce time");
7419     GNUNET_SCHEDULER_shutdown ();
7420     return;
7421   }
7422
7423   if (GNUNET_OK !=
7424       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "ID_ANNOUNCE_TIME",
7425                                            &id_announce_time))
7426   {
7427     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7428                 _
7429                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7430                 "id announce time");
7431     GNUNET_SCHEDULER_shutdown ();
7432     return;
7433   }
7434
7435   if (GNUNET_OK !=
7436       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "UNACKNOWLEDGED_WAIT",
7437                                            &unacknowledged_wait_time))
7438   {
7439     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7440                 _
7441                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7442                 "unacknowledged wait time");
7443     GNUNET_SCHEDULER_shutdown ();
7444     return;
7445   }
7446
7447   if (GNUNET_OK !=
7448       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "CONNECT_TIMEOUT",
7449                                            &connect_timeout))
7450   {
7451     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7452                 _
7453                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7454                 "connect timeout");
7455     GNUNET_SCHEDULER_shutdown ();
7456     return;
7457   }
7458
7459   if (GNUNET_OK !=
7460       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
7461                                              &max_msgs_queue))
7462   {
7463     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7464                 _
7465                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7466                 "max msgs queue");
7467     GNUNET_SCHEDULER_shutdown ();
7468     return;
7469   }
7470
7471   if (GNUNET_OK !=
7472       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_TUNNELS",
7473                                              &max_tunnels))
7474   {
7475     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7476                 _
7477                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7478                 "max tunnels");
7479     GNUNET_SCHEDULER_shutdown ();
7480     return;
7481   }
7482
7483   if (GNUNET_OK !=
7484       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
7485                                              &default_ttl))
7486   {
7487     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7488                 _
7489                 ("Mesh service is lacking key configuration settings (%s). Using default (%u).\n"),
7490                 "default ttl", 64);
7491     default_ttl = 64;
7492   }
7493
7494   if (GNUNET_OK !=
7495       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DHT_REPLICATION_LEVEL",
7496                                              &dht_replication_level))
7497   {
7498     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7499                 _
7500                 ("Mesh service is lacking key configuration settings (%s). Using default (%u).\n"),
7501                 "dht replication level", 10);
7502     dht_replication_level = 10;
7503   }
7504
7505   
7506   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
7507   GNUNET_free (keyfile);
7508   if (my_private_key == NULL)
7509   {
7510     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7511                 _("Mesh service could not access hostkey.  Exiting.\n"));
7512     GNUNET_SCHEDULER_shutdown ();
7513     return;
7514   }
7515   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
7516   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
7517                       &my_full_id.hashPubKey);
7518   myid = GNUNET_PEER_intern (&my_full_id);
7519
7520 //   transport_handle = GNUNET_TRANSPORT_connect(c,
7521 //                                               &my_full_id,
7522 //                                               NULL,
7523 //                                               NULL,
7524 //                                               NULL,
7525 //                                               NULL);
7526
7527   dht_handle = GNUNET_DHT_connect (c, 64);
7528   if (dht_handle == NULL)
7529   {
7530     GNUNET_break (0);
7531   }
7532
7533   stats = GNUNET_STATISTICS_create ("mesh", c);
7534
7535
7536   next_tid = 0;
7537   next_local_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
7538
7539   tunnels = GNUNET_CONTAINER_multihashmap_create (32);
7540   incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
7541   peers = GNUNET_CONTAINER_multihashmap_create (32);
7542   applications = GNUNET_CONTAINER_multihashmap_create (32);
7543   types = GNUNET_CONTAINER_multihashmap_create (32);
7544
7545   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
7546   nc = GNUNET_SERVER_notification_context_create (server_handle, 1);
7547   GNUNET_SERVER_disconnect_notify (server_handle,
7548                                    &handle_local_client_disconnect, NULL);
7549
7550
7551   clients = NULL;
7552   clients_tail = NULL;
7553   next_client_id = 0;
7554
7555   announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
7556   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
7557
7558   /* Create a peer_info for the local peer */
7559   peer = peer_info_get (&my_full_id);
7560   p = path_new (1);
7561   p->peers[0] = myid;
7562   GNUNET_PEER_change_rc (myid, 1);
7563   peer_info_add_path (peer, p, GNUNET_YES);
7564
7565   /* Scheduled the task to clean up when shutdown is called */
7566   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
7567                                 NULL);
7568
7569   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "end of run()\n");
7570 }
7571
7572 /**
7573  * The main function for the mesh service.
7574  *
7575  * @param argc number of arguments from the command line
7576  * @param argv command line arguments
7577  * @return 0 ok, 1 on error
7578  */
7579 int
7580 main (int argc, char *const *argv)
7581 {
7582   int ret;
7583
7584   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
7585   ret =
7586       (GNUNET_OK ==
7587        GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
7588                            NULL)) ? 0 : 1;
7589   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");
7590
7591   return ret;
7592 }