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