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