6a2ae46afe7172fbf65d7c7f0b2170b1d0293f47
[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 %s\n",
1985               GNUNET_MESH_DEBUG_M2S (type));
1986
1987   memcpy (cbuf, msg, sizeof (cbuf));
1988   switch (htons (msg->type))
1989   {
1990     struct GNUNET_MESH_Unicast *uc;
1991     struct GNUNET_MESH_Multicast *mc;
1992     struct GNUNET_MESH_ToOrigin *to;
1993
1994   case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
1995     uc = (struct GNUNET_MESH_Unicast *) cbuf;
1996     tid = &uc->tid;
1997     oid = &uc->oid;
1998     break;
1999   case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
2000     mc = (struct GNUNET_MESH_Multicast *) cbuf;
2001     tid = &mc->tid;
2002     oid = &mc->oid;
2003     break;
2004   case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
2005     to = (struct GNUNET_MESH_ToOrigin *) cbuf;
2006     tid = &to->tid;
2007     oid = &to->oid;
2008     break;
2009   default:
2010     GNUNET_break (0);
2011     return 0;
2012   }
2013   t = tunnel_get (oid, ntohl (*tid));
2014   if (NULL == t)
2015   {
2016     GNUNET_break (0);
2017     return 0;
2018   }
2019
2020   for (count = 0, c = clients; c != NULL; c = c->next)
2021   {
2022     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   client %u\n", c->id);
2023     if (client_is_subscribed (type, c))
2024     {
2025       if (htons (msg->type) == GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN)
2026       {
2027         if (c != t->owner)
2028           continue;
2029         *tid = htonl (t->local_tid);
2030       }
2031       else
2032       {
2033         if (GNUNET_NO == client_knows_tunnel (c, t))
2034         {
2035           /* This client doesn't know the tunnel */
2036           struct GNUNET_MESH_TunnelNotification tmsg;
2037           struct GNUNET_HashCode hash;
2038
2039           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "     sending tunnel create\n");
2040           tmsg.header.size = htons (sizeof (tmsg));
2041           tmsg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
2042           GNUNET_PEER_resolve (t->id.oid, &tmsg.peer);
2043           tmsg.tunnel_id = htonl (t->local_tid_dest);
2044           GNUNET_SERVER_notification_context_unicast (nc, c->handle,
2045                                                       &tmsg.header, GNUNET_NO);
2046           tunnel_add_client (t, c);
2047           GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber),
2048                               &hash);
2049           GNUNET_break (GNUNET_OK == GNUNET_CONTAINER_multihashmap_put (
2050                                        c->incoming_tunnels, &hash, t,
2051                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
2052         }
2053         *tid = htonl (t->local_tid_dest);
2054       }
2055
2056       /* Check if the client wants to get traffic from the tunnel */
2057       if (GNUNET_NO == client_wants_tunnel(c, t))
2058         continue;
2059       count++;
2060       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "     sending\n");
2061       GNUNET_SERVER_notification_context_unicast (nc, c->handle,
2062                                                   (struct GNUNET_MessageHeader
2063                                                    *) cbuf, GNUNET_NO);
2064     }
2065   }
2066   return count;
2067 }
2068
2069
2070 /**
2071  * Notify the client that owns the tunnel that a peer has connected to it
2072  * (the requested path to it has been confirmed).
2073  *
2074  * @param t Tunnel whose owner to notify
2075  * @param id Short id of the peer that has connected
2076  */
2077 static void
2078 send_client_peer_connected (const struct MeshTunnel *t, const GNUNET_PEER_Id id)
2079 {
2080   struct GNUNET_MESH_PeerControl pc;
2081
2082   pc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD);
2083   pc.header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
2084   pc.tunnel_id = htonl (t->local_tid);
2085   GNUNET_PEER_resolve (id, &pc.peer);
2086   GNUNET_SERVER_notification_context_unicast (nc, t->owner->handle, &pc.header,
2087                                               GNUNET_NO);
2088 }
2089
2090
2091 /**
2092  * Notify a the client of a tunnel about how many more
2093  * payload packages will we accept on a given tunnel,
2094  * distinguishing between root and leaf clients.
2095  *
2096  * @param c Client whom to send the ACK.
2097  * @param t Tunnel on which to send the ACK.
2098  */
2099 static void
2100 send_client_tunnel_ack (struct MeshClient *c, struct MeshTunnel *t)
2101 {
2102   struct GNUNET_MESH_LocalAck msg;
2103   MESH_TunnelNumber tid;
2104   uint32_t ack;
2105
2106   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2107               "Sending client ACK on tunnel %X\n",
2108               t->local_tid);
2109   if (NULL == c)
2110     return;
2111
2112   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " to client %u\n", c->id);
2113
2114   if (c == t->owner)
2115   {
2116     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  (owner, FWD ACK)\n");
2117     ack = tunnel_get_fwd_ack (t);
2118     tid = t->local_tid;
2119   }
2120   else
2121   {
2122     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  (leaf, BCK ACK)\n");
2123     ack = tunnel_get_bck_ack (t);
2124     tid = t->local_tid_dest;
2125   }
2126
2127   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ack %u\n", ack);
2128   if (t->last_fwd_ack == ack)
2129     return;
2130
2131   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " sending!\n");
2132   t->last_fwd_ack = ack;
2133   msg.header.size = htons (sizeof (msg));
2134   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
2135   msg.tunnel_id = htonl (tid);
2136   msg.max_pid = htonl (ack);
2137
2138   GNUNET_SERVER_notification_context_unicast (nc, c->handle,
2139                                               &msg.header, GNUNET_NO);
2140 }
2141
2142
2143 /**
2144  * Notify all clients (not depending on registration status) that the incoming
2145  * tunnel is no longer valid.
2146  *
2147  * @param t Tunnel that was destroyed.
2148  */
2149 static void
2150 send_clients_tunnel_destroy (struct MeshTunnel *t)
2151 {
2152   struct GNUNET_MESH_TunnelMessage msg;
2153
2154   msg.header.size = htons (sizeof (msg));
2155   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
2156   msg.tunnel_id = htonl (t->local_tid_dest);
2157   GNUNET_SERVER_notification_context_broadcast (nc, &msg.header, GNUNET_NO);
2158 }
2159
2160
2161 /**
2162  * Notify clients of tunnel disconnections, if needed.
2163  * In case the origin disconnects, the destination clients get a tunnel destroy
2164  * notification. If the last destination disconnects (only one remaining client
2165  * in tunnel), the origin gets a (local ID) peer disconnected.
2166  * Note that the function must be called BEFORE removing the client from
2167  * the tunnel.
2168  *
2169  * @param t Tunnel that was destroyed.
2170  * @param c Client that disconnected.
2171  */
2172 static void
2173 send_client_tunnel_disconnect (struct MeshTunnel *t, struct MeshClient *c)
2174 {
2175   unsigned int i;
2176
2177   if (c == t->owner)
2178   {
2179     struct GNUNET_MESH_TunnelMessage msg;
2180
2181     msg.header.size = htons (sizeof (msg));
2182     msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
2183     msg.tunnel_id = htonl (t->local_tid_dest);
2184     for (i = 0; i < t->nclients; i++)
2185       GNUNET_SERVER_notification_context_unicast (nc, t->clients[i]->handle,
2186                                                   &msg.header, GNUNET_NO);
2187   }
2188   // FIXME when to disconnect an incoming tunnel?
2189   else if (1 == t->nclients && NULL != t->owner)
2190   {
2191     struct GNUNET_MESH_PeerControl msg;
2192
2193     msg.header.size = htons (sizeof (msg));
2194     msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL);
2195     msg.tunnel_id = htonl (t->local_tid);
2196     msg.peer = my_full_id;
2197     GNUNET_SERVER_notification_context_unicast (nc, t->owner->handle,
2198                                                 &msg.header, GNUNET_NO);
2199   }
2200 }
2201
2202
2203 /**
2204  * Retrieve the MeshPeerInfo stucture associated with the peer, create one
2205  * and insert it in the appropiate structures if the peer is not known yet.
2206  *
2207  * @param peer Full identity of the peer.
2208  *
2209  * @return Existing or newly created peer info.
2210  */
2211 static struct MeshPeerInfo *
2212 peer_info_get (const struct GNUNET_PeerIdentity *peer)
2213 {
2214   struct MeshPeerInfo *peer_info;
2215
2216   peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
2217   if (NULL == peer_info)
2218   {
2219     peer_info =
2220         (struct MeshPeerInfo *) GNUNET_malloc (sizeof (struct MeshPeerInfo));
2221     GNUNET_CONTAINER_multihashmap_put (peers, &peer->hashPubKey, peer_info,
2222                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2223     peer_info->id = GNUNET_PEER_intern (peer);
2224   }
2225
2226   return peer_info;
2227 }
2228
2229
2230 /**
2231  * Retrieve the MeshPeerInfo stucture associated with the peer, create one
2232  * and insert it in the appropiate structures if the peer is not known yet.
2233  *
2234  * @param peer Short identity of the peer.
2235  *
2236  * @return Existing or newly created peer info.
2237  */
2238 static struct MeshPeerInfo *
2239 peer_info_get_short (const GNUNET_PEER_Id peer)
2240 {
2241   struct GNUNET_PeerIdentity id;
2242
2243   GNUNET_PEER_resolve (peer, &id);
2244   return peer_info_get (&id);
2245 }
2246
2247
2248 /**
2249  * Iterator to remove the tunnel from the list of tunnels a peer participates
2250  * in.
2251  *
2252  * @param cls Closure (tunnel info)
2253  * @param key GNUNET_PeerIdentity of the peer (unused)
2254  * @param value PeerInfo of the peer
2255  *
2256  * @return always GNUNET_YES, to keep iterating
2257  */
2258 static int
2259 peer_info_delete_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
2260 {
2261   struct MeshTunnel *t = cls;
2262   struct MeshPeerInfo *peer = value;
2263   unsigned int i;
2264
2265   for (i = 0; i < peer->ntunnels; i++)
2266   {
2267     if (0 ==
2268         memcmp (&peer->tunnels[i]->id, &t->id, sizeof (struct MESH_TunnelID)))
2269     {
2270       peer->ntunnels--;
2271       peer->tunnels[i] = peer->tunnels[peer->ntunnels];
2272       peer->tunnels = GNUNET_realloc (peer->tunnels, peer->ntunnels);
2273       return GNUNET_YES;
2274     }
2275   }
2276   return GNUNET_YES;
2277 }
2278
2279
2280 /**
2281   * Core callback to write a pre-constructed data packet to core buffer
2282   *
2283   * @param cls Closure (MeshTransmissionDescriptor with data in "data" member).
2284   * @param size Number of bytes available in buf.
2285   * @param buf Where the to write the message.
2286   *
2287   * @return number of bytes written to buf
2288   */
2289 static size_t
2290 send_core_data_raw (void *cls, size_t size, void *buf)
2291 {
2292   struct MeshTransmissionDescriptor *info = cls;
2293   struct GNUNET_MessageHeader *msg;
2294   size_t total_size;
2295
2296   GNUNET_assert (NULL != info);
2297   GNUNET_assert (NULL != info->mesh_data);
2298   msg = (struct GNUNET_MessageHeader *) info->mesh_data->data;
2299   total_size = ntohs (msg->size);
2300
2301   if (total_size > size)
2302   {
2303     GNUNET_break (0);
2304     return 0;
2305   }
2306   memcpy (buf, msg, total_size);
2307   data_descriptor_decrement_rc (info->mesh_data);
2308   GNUNET_free (info);
2309   return total_size;
2310 }
2311
2312
2313 /**
2314  * Sends an already built non-multicast message to a peer,
2315  * properly registrating all used resources.
2316  *
2317  * @param message Message to send. Function makes a copy of it.
2318  * @param peer Short ID of the neighbor whom to send the message.
2319  * @param t Tunnel on which this message is transmitted.
2320  */
2321 static void
2322 send_message (const struct GNUNET_MessageHeader *message,
2323               const struct GNUNET_PeerIdentity *peer,
2324               struct MeshTunnel *t)
2325 {
2326   struct MeshTransmissionDescriptor *info;
2327   struct MeshPeerInfo *neighbor;
2328   struct MeshPeerPath *p;
2329   size_t size;
2330   uint16_t type;
2331
2332 //   GNUNET_TRANSPORT_try_connect(); FIXME use?
2333
2334   size = ntohs (message->size);
2335   info = GNUNET_malloc (sizeof (struct MeshTransmissionDescriptor));
2336   info->mesh_data = GNUNET_malloc (sizeof (struct MeshData));
2337   info->mesh_data->data = GNUNET_malloc (size);
2338   memcpy (info->mesh_data->data, message, size);
2339   type = ntohs(message->type);
2340   if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == type)
2341   {
2342     struct GNUNET_MESH_Unicast *m;
2343
2344     m = (struct GNUNET_MESH_Unicast *) info->mesh_data->data;
2345     m->ttl = htonl (ntohl (m->ttl) - 1);
2346   }
2347   info->mesh_data->data_len = size;
2348   info->mesh_data->reference_counter = GNUNET_malloc (sizeof (unsigned int));
2349   *info->mesh_data->reference_counter = 1;
2350   neighbor = peer_info_get (peer);
2351   for (p = neighbor->path_head; NULL != p; p = p->next)
2352   {
2353     if (2 >= p->length)
2354     {
2355       break;
2356     }
2357   }
2358   if (NULL == p)
2359   {
2360 #if MESH_DEBUG
2361     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2362                 "  %s IS NOT DIRECTLY CONNECTED\n",
2363                 GNUNET_i2s(peer));
2364     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2365                 "  PATHS TO %s:\n",
2366                 GNUNET_i2s(peer));
2367     for (p = neighbor->path_head; NULL != p; p = p->next)
2368     {
2369       struct GNUNET_PeerIdentity debug_id;
2370       unsigned int i;
2371
2372       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2373                   "    path with %u hops through:\n",
2374                   p->length);
2375       for (i = 0; i < p->length; i++)
2376       {
2377         GNUNET_PEER_resolve(p->peers[i], &debug_id);
2378         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2379                     "      hop %u: %s\n",
2380                     i, GNUNET_i2s(&debug_id));
2381       }
2382     }
2383 #endif
2384     GNUNET_break (0); // FIXME sometimes fails (testing disconnect?)
2385     GNUNET_free (info->mesh_data->data);
2386     GNUNET_free (info->mesh_data);
2387     GNUNET_free (info);
2388     return;
2389   }
2390   info->peer = neighbor;
2391   if (GNUNET_MESSAGE_TYPE_MESH_PATH_ACK == type)
2392   {
2393     /*
2394      * TODO: in this case we only need the service to retransmit
2395      * the message down the path. If we pass the real type to queue_add,
2396      * queue_send will try to build the message from scratch. This can
2397      * probably be done by some other way instead of deleteing the type
2398      * info.
2399      */
2400     type = 0;
2401   }
2402   queue_add (info,
2403              type,
2404              size,
2405              neighbor,
2406              t);
2407 }
2408
2409
2410 /**
2411  * Sends a CREATE PATH message for a path to a peer, properly registrating
2412  * all used resources.
2413  *
2414  * @param peer PeerInfo of the final peer for whom this path is being created.
2415  * @param p Path itself.
2416  * @param t Tunnel for which the path is created.
2417  */
2418 static void
2419 send_create_path (struct MeshPeerInfo *peer, struct MeshPeerPath *p,
2420                   struct MeshTunnel *t)
2421 {
2422   struct GNUNET_PeerIdentity id;
2423   struct MeshPathInfo *path_info;
2424   struct MeshPeerInfo *neighbor;
2425
2426   unsigned int i;
2427
2428   if (NULL == p)
2429   {
2430     p = tree_get_path_to_peer (t->tree, peer->id);
2431     if (NULL == p)
2432     {
2433       GNUNET_break (0);
2434       return;
2435     }
2436   }
2437   for (i = 0; i < p->length; i++)
2438   {
2439     if (p->peers[i] == myid)
2440       break;
2441   }
2442   if (i >= p->length - 1)
2443   {
2444     path_destroy (p);
2445     GNUNET_break (0);
2446     return;
2447   }
2448   GNUNET_PEER_resolve (p->peers[i + 1], &id);
2449
2450   path_info = GNUNET_malloc (sizeof (struct MeshPathInfo));
2451   path_info->path = p;
2452   path_info->t = t;
2453   neighbor = peer_info_get (&id);
2454   path_info->peer = neighbor;
2455   queue_add (path_info,
2456              GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE,
2457              sizeof (struct GNUNET_MESH_ManipulatePath) +
2458                 (p->length * sizeof (struct GNUNET_PeerIdentity)),
2459              neighbor,
2460              t);
2461 }
2462
2463
2464 /**
2465  * Sends a DESTROY PATH message to free resources for a path in a tunnel
2466  *
2467  * @param t Tunnel whose path to destroy.
2468  * @param destination Short ID of the peer to whom the path to destroy.
2469  */
2470 static void
2471 send_destroy_path (struct MeshTunnel *t, GNUNET_PEER_Id destination)
2472 {
2473   struct MeshPeerPath *p;
2474   size_t size;
2475
2476   p = tree_get_path_to_peer (t->tree, destination);
2477   if (NULL == p)
2478   {
2479     GNUNET_break (0);
2480     return;
2481   }
2482   size = sizeof (struct GNUNET_MESH_ManipulatePath);
2483   size += p->length * sizeof (struct GNUNET_PeerIdentity);
2484   {
2485     struct GNUNET_MESH_ManipulatePath *msg;
2486     struct GNUNET_PeerIdentity *pi;
2487     char cbuf[size];
2488     unsigned int i;
2489
2490     msg = (struct GNUNET_MESH_ManipulatePath *) cbuf;
2491     msg->header.size = htons (size);
2492     msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY);
2493     msg->tid = htonl (t->id.tid);
2494     pi = (struct GNUNET_PeerIdentity *) &msg[1];
2495     for (i = 0; i < p->length; i++)
2496     {
2497       GNUNET_PEER_resolve (p->peers[i], &pi[i]);
2498     }
2499     send_message (&msg->header, tree_get_first_hop (t->tree, destination), t);
2500   }
2501   path_destroy (p);
2502 }
2503
2504
2505 /**
2506  * Try to establish a new connection to this peer.
2507  * Use the best path for the given tunnel.
2508  * If the peer doesn't have any path to it yet, try to get one.
2509  * If the peer already has some path, send a CREATE PATH towards it.
2510  *
2511  * @param peer PeerInfo of the peer.
2512  * @param t Tunnel for which to create the path, if possible.
2513  */
2514 static void
2515 peer_info_connect (struct MeshPeerInfo *peer, struct MeshTunnel *t)
2516 {
2517   struct MeshPeerPath *p;
2518   struct MeshPathInfo *path_info;
2519
2520   if (NULL != peer->path_head)
2521   {
2522     p = tree_get_path_to_peer (t->tree, peer->id);
2523     if (NULL == p)
2524     {
2525       GNUNET_break (0);
2526       return;
2527     }
2528
2529     // FIXME always send create path to self
2530     if (p->length > 1)
2531     {
2532       send_create_path (peer, p, t);
2533     }
2534     else
2535     {
2536       struct GNUNET_HashCode hash;
2537
2538       path_destroy (p);
2539       send_client_peer_connected (t, myid);
2540       t->local_tid_dest = next_local_tid++;
2541       GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber),
2542                           &hash);
2543       if (GNUNET_OK !=
2544           GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
2545                                              GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2546       {
2547         GNUNET_break (0);
2548         return;
2549       }
2550     }
2551   }
2552   else if (NULL == peer->dhtget)
2553   {
2554     struct GNUNET_PeerIdentity id;
2555
2556     GNUNET_PEER_resolve (peer->id, &id);
2557     path_info = GNUNET_malloc (sizeof (struct MeshPathInfo));
2558     path_info->peer = peer;
2559     path_info->t = t;
2560     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2561                 "  Starting DHT GET for peer %s\n", GNUNET_i2s (&id));
2562     peer->dhtgetcls = path_info;
2563     peer->dhtget = GNUNET_DHT_get_start (dht_handle,    /* handle */
2564                                          GNUNET_BLOCK_TYPE_MESH_PEER, /* type */
2565                                          &id.hashPubKey,     /* key to search */
2566                                          dht_replication_level, /* replication level */
2567                                          GNUNET_DHT_RO_RECORD_ROUTE |
2568                                          GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
2569                                          NULL,       /* xquery */ // FIXME BLOOMFILTER
2570                                          0,     /* xquery bits */ // FIXME BLOOMFILTER SIZE
2571                                          &dht_get_id_handler, path_info);
2572   }
2573   /* Otherwise, there is no path but the DHT get is already started. */
2574 }
2575
2576
2577 /**
2578  * Task to delay the connection of a peer
2579  *
2580  * @param cls Closure (path info with tunnel and peer to connect).
2581  *            Will be free'd on exection.
2582  * @param tc TaskContext
2583  */
2584 static void
2585 peer_info_connect_task (void *cls,
2586                         const struct GNUNET_SCHEDULER_TaskContext *tc)
2587 {
2588   struct MeshPathInfo *path_info = cls;
2589
2590   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2591   {
2592     GNUNET_free (cls);
2593     return;
2594   }
2595   peer_info_connect (path_info->peer, path_info->t);
2596   GNUNET_free (cls);
2597 }
2598
2599
2600 /**
2601  * Destroy the peer_info and free any allocated resources linked to it
2602  *
2603  * @param pi The peer_info to destroy.
2604  *
2605  * @return GNUNET_OK on success
2606  */
2607 static int
2608 peer_info_destroy (struct MeshPeerInfo *pi)
2609 {
2610   struct GNUNET_PeerIdentity id;
2611   struct MeshPeerPath *p;
2612   struct MeshPeerPath *nextp;
2613
2614   GNUNET_PEER_resolve (pi->id, &id);
2615   GNUNET_PEER_change_rc (pi->id, -1);
2616
2617   if (GNUNET_YES !=
2618       GNUNET_CONTAINER_multihashmap_remove (peers, &id.hashPubKey, pi))
2619   {
2620     GNUNET_break (0);
2621     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2622                 "removing peer %s, not in hashmap\n", GNUNET_i2s (&id));
2623   }
2624   if (NULL != pi->dhtget)
2625   {
2626     GNUNET_DHT_get_stop (pi->dhtget);
2627     GNUNET_free (pi->dhtgetcls);
2628   }
2629   p = pi->path_head;
2630   while (NULL != p)
2631   {
2632     nextp = p->next;
2633     GNUNET_CONTAINER_DLL_remove (pi->path_head, pi->path_tail, p);
2634     path_destroy (p);
2635     p = nextp;
2636   }
2637   GNUNET_free (pi);
2638   return GNUNET_OK;
2639 }
2640
2641
2642 /**
2643  * Remove all paths that rely on a direct connection between p1 and p2
2644  * from the peer itself and notify all tunnels about it.
2645  *
2646  * @param peer PeerInfo of affected peer.
2647  * @param p1 GNUNET_PEER_Id of one peer.
2648  * @param p2 GNUNET_PEER_Id of another peer that was connected to the first and
2649  *           no longer is.
2650  *
2651  * TODO: optimize (see below)
2652  */
2653 static void
2654 peer_info_remove_path (struct MeshPeerInfo *peer, GNUNET_PEER_Id p1,
2655                        GNUNET_PEER_Id p2)
2656 {
2657   struct MeshPeerPath *p;
2658   struct MeshPeerPath *aux;
2659   struct MeshPeerInfo *peer_d;
2660   GNUNET_PEER_Id d;
2661   unsigned int destroyed;
2662   unsigned int best;
2663   unsigned int cost;
2664   unsigned int i;
2665
2666   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "peer_info_remove_path\n");
2667   destroyed = 0;
2668   p = peer->path_head;
2669   while (NULL != p)
2670   {
2671     aux = p->next;
2672     for (i = 0; i < (p->length - 1); i++)
2673     {
2674       if ((p->peers[i] == p1 && p->peers[i + 1] == p2) ||
2675           (p->peers[i] == p2 && p->peers[i + 1] == p1))
2676       {
2677         GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, p);
2678         path_destroy (p);
2679         destroyed++;
2680         break;
2681       }
2682     }
2683     p = aux;
2684   }
2685   if (0 == destroyed)
2686     return;
2687
2688   for (i = 0; i < peer->ntunnels; i++)
2689   {
2690     d = tunnel_notify_connection_broken (peer->tunnels[i], p1, p2);
2691     if (0 == d)
2692       continue;
2693     /* TODO
2694      * Problem: one or more peers have been deleted from the tunnel tree.
2695      * We don't know who they are to try to add them again.
2696      * We need to try to find a new path for each of the disconnected peers.
2697      * Some of them might already have a path to reach them that does not
2698      * involve p1 and p2. Adding all anew might render in a better tree than
2699      * the trivial immediate fix.
2700      *
2701      * Trivial immiediate fix: try to reconnect to the disconnected node. All
2702      * its children will be reachable trough him.
2703      */
2704     peer_d = peer_info_get_short (d);
2705     best = UINT_MAX;
2706     aux = NULL;
2707     for (p = peer_d->path_head; NULL != p; p = p->next)
2708     {
2709       if ((cost = tree_get_path_cost (peer->tunnels[i]->tree, p)) < best)
2710       {
2711         best = cost;
2712         aux = p;
2713       }
2714     }
2715     if (NULL != aux)
2716     {
2717       /* No callback, as peer will be already disconnected and a connection
2718        * scheduled by tunnel_notify_connection_broken.
2719        */
2720       tree_add_path (peer->tunnels[i]->tree, aux, NULL, NULL);
2721     }
2722     else
2723     {
2724       peer_info_connect (peer_d, peer->tunnels[i]);
2725     }
2726   }
2727   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "peer_info_remove_path END\n");
2728 }
2729
2730
2731 /**
2732  * Add the path to the peer and update the path used to reach it in case this
2733  * is the shortest.
2734  *
2735  * @param peer_info Destination peer to add the path to.
2736  * @param path New path to add. Last peer must be the peer in arg 1.
2737  *             Path will be either used of freed if already known.
2738  * @param trusted Do we trust that this path is real?
2739  */
2740 void
2741 peer_info_add_path (struct MeshPeerInfo *peer_info, struct MeshPeerPath *path,
2742                     int trusted)
2743 {
2744   struct MeshPeerPath *aux;
2745   unsigned int l;
2746   unsigned int l2;
2747
2748   if ((NULL == peer_info) || (NULL == path))
2749   {
2750     GNUNET_break (0);
2751     path_destroy (path);
2752     return;
2753   }
2754   if (path->peers[path->length - 1] != peer_info->id)
2755   {
2756     GNUNET_break (0);
2757     path_destroy (path);
2758     return;
2759   }
2760   if (path->length <= 2 && GNUNET_NO == trusted)
2761   {
2762     /* Only allow CORE to tell us about direct paths */
2763     path_destroy (path);
2764     return;
2765   }
2766   GNUNET_assert (peer_info->id == path->peers[path->length - 1]);
2767   for (l = 1; l < path->length; l++)
2768   {
2769     if (path->peers[l] == myid)
2770     {
2771       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shortening path by %u\n", l);
2772       for (l2 = 0; l2 < path->length - l; l2++)
2773       {
2774         path->peers[l2] = path->peers[l + l2];
2775       }
2776       path->length -= l;
2777       l = 1;
2778       path->peers =
2779           GNUNET_realloc (path->peers, path->length * sizeof (GNUNET_PEER_Id));
2780     }
2781   }
2782 #if MESH_DEBUG
2783   {
2784     struct GNUNET_PeerIdentity id;
2785
2786     GNUNET_PEER_resolve (peer_info->id, &id);
2787     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "adding path [%u] to peer %s\n",
2788                 path->length, GNUNET_i2s (&id));
2789   }
2790 #endif
2791   l = path_get_length (path);
2792   if (0 == l)
2793   {
2794     GNUNET_free (path);
2795     return;
2796   }
2797
2798   GNUNET_assert (peer_info->id == path->peers[path->length - 1]);
2799   for (aux = peer_info->path_head; aux != NULL; aux = aux->next)
2800   {
2801     l2 = path_get_length (aux);
2802     if (l2 > l)
2803     {
2804       GNUNET_CONTAINER_DLL_insert_before (peer_info->path_head,
2805                                           peer_info->path_tail, aux, path);
2806       return;
2807     }
2808     else
2809     {
2810       if (l2 == l && memcmp (path->peers, aux->peers, l) == 0)
2811       {
2812         path_destroy (path);
2813         return;
2814       }
2815     }
2816   }
2817   GNUNET_CONTAINER_DLL_insert_tail (peer_info->path_head, peer_info->path_tail,
2818                                     path);
2819   return;
2820 }
2821
2822
2823 /**
2824  * Add the path to the origin peer and update the path used to reach it in case
2825  * this is the shortest.
2826  * The path is given in peer_info -> destination, therefore we turn the path
2827  * upside down first.
2828  *
2829  * @param peer_info Peer to add the path to, being the origin of the path.
2830  * @param path New path to add after being inversed.
2831  * @param trusted Do we trust that this path is real?
2832  */
2833 static void
2834 peer_info_add_path_to_origin (struct MeshPeerInfo *peer_info,
2835                               struct MeshPeerPath *path, int trusted)
2836 {
2837   path_invert (path);
2838   peer_info_add_path (peer_info, path, trusted);
2839 }
2840
2841
2842 /**
2843  * Build a PeerPath from the paths returned from the DHT, reversing the paths
2844  * to obtain a local peer -> destination path and interning the peer ids.
2845  *
2846  * @return Newly allocated and created path
2847  */
2848 static struct MeshPeerPath *
2849 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
2850                      unsigned int get_path_length,
2851                      const struct GNUNET_PeerIdentity *put_path,
2852                      unsigned int put_path_length)
2853 {
2854   struct MeshPeerPath *p;
2855   GNUNET_PEER_Id id;
2856   int i;
2857
2858   p = path_new (1);
2859   p->peers[0] = myid;
2860   GNUNET_PEER_change_rc (myid, 1);
2861   i = get_path_length;
2862   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   GET has %d hops.\n", i);
2863   for (i--; i >= 0; i--)
2864   {
2865     id = GNUNET_PEER_intern (&get_path[i]);
2866     if (p->length > 0 && id == p->peers[p->length - 1])
2867     {
2868       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Optimizing 1 hop out.\n");
2869       GNUNET_PEER_change_rc (id, -1);
2870     }
2871     else
2872     {
2873       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Adding from GET: %s.\n",
2874                   GNUNET_i2s (&get_path[i]));
2875       p->length++;
2876       p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
2877       p->peers[p->length - 1] = id;
2878     }
2879   }
2880   i = put_path_length;
2881   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   PUT has %d hops.\n", i);
2882   for (i--; i >= 0; i--)
2883   {
2884     id = GNUNET_PEER_intern (&put_path[i]);
2885     if (id == myid)
2886     {
2887       /* PUT path went through us, so discard the path up until now and start
2888        * from here to get a much shorter (and loop-free) path.
2889        */
2890       path_destroy (p);
2891       p = path_new (0);
2892     }
2893     if (p->length > 0 && id == p->peers[p->length - 1])
2894     {
2895       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Optimizing 1 hop out.\n");
2896       GNUNET_PEER_change_rc (id, -1);
2897     }
2898     else
2899     {
2900       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Adding from PUT: %s.\n",
2901                   GNUNET_i2s (&put_path[i]));
2902       p->length++;
2903       p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
2904       p->peers[p->length - 1] = id;
2905     }
2906   }
2907 #if MESH_DEBUG
2908   if (get_path_length > 0)
2909     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (first of GET: %s)\n",
2910                 GNUNET_i2s (&get_path[0]));
2911   if (put_path_length > 0)
2912     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (first of PUT: %s)\n",
2913                 GNUNET_i2s (&put_path[0]));
2914   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   In total: %d hops\n",
2915               p->length);
2916   for (i = 0; i < p->length; i++)
2917   {
2918     struct GNUNET_PeerIdentity peer_id;
2919
2920     GNUNET_PEER_resolve (p->peers[i], &peer_id);
2921     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "       %u: %s\n", p->peers[i],
2922                 GNUNET_i2s (&peer_id));
2923   }
2924 #endif
2925   return p;
2926 }
2927
2928
2929 /**
2930  * Adds a path to the peer_infos of all the peers in the path
2931  *
2932  * @param p Path to process.
2933  * @param confirmed Whether we know if the path works or not.
2934  */
2935 static void
2936 path_add_to_peers (struct MeshPeerPath *p, int confirmed)
2937 {
2938   unsigned int i;
2939
2940   /* TODO: invert and add */
2941   for (i = 0; i < p->length && p->peers[i] != myid; i++) /* skip'em */ ;
2942   for (i++; i < p->length; i++)
2943   {
2944     struct MeshPeerInfo *aux;
2945     struct MeshPeerPath *copy;
2946
2947     aux = peer_info_get_short (p->peers[i]);
2948     copy = path_duplicate (p);
2949     copy->length = i + 1;
2950     peer_info_add_path (aux, copy, GNUNET_NO);
2951   }
2952 }
2953
2954
2955 /**
2956  * Send keepalive packets for a peer
2957  *
2958  * @param cls Closure (tunnel for which to send the keepalive).
2959  * @param tc Notification context.
2960  *
2961  * TODO: implement explicit multicast keepalive?
2962  */
2963 static void
2964 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
2965
2966
2967 /**
2968  * Search for a tunnel among the incoming tunnels
2969  *
2970  * @param tid the local id of the tunnel
2971  *
2972  * @return tunnel handler, NULL if doesn't exist
2973  */
2974 static struct MeshTunnel *
2975 tunnel_get_incoming (MESH_TunnelNumber tid)
2976 {
2977   struct GNUNET_HashCode hash;
2978
2979   GNUNET_assert (tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV);
2980   GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
2981   return GNUNET_CONTAINER_multihashmap_get (incoming_tunnels, &hash);
2982 }
2983
2984
2985 /**
2986  * Search for a tunnel among the tunnels for a client
2987  *
2988  * @param c the client whose tunnels to search in
2989  * @param tid the local id of the tunnel
2990  *
2991  * @return tunnel handler, NULL if doesn't exist
2992  */
2993 static struct MeshTunnel *
2994 tunnel_get_by_local_id (struct MeshClient *c, MESH_TunnelNumber tid)
2995 {
2996   if (tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
2997   {
2998     return tunnel_get_incoming (tid);
2999   }
3000   else
3001   {
3002     struct GNUNET_HashCode hash;
3003
3004     GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
3005     return GNUNET_CONTAINER_multihashmap_get (c->own_tunnels, &hash);
3006   }
3007 }
3008
3009
3010 /**
3011  * Search for a tunnel by global ID using PEER_ID
3012  *
3013  * @param pi owner of the tunnel
3014  * @param tid global tunnel number
3015  *
3016  * @return tunnel handler, NULL if doesn't exist
3017  */
3018 static struct MeshTunnel *
3019 tunnel_get_by_pi (GNUNET_PEER_Id pi, MESH_TunnelNumber tid)
3020 {
3021   struct MESH_TunnelID id;
3022   struct GNUNET_HashCode hash;
3023
3024   id.oid = pi;
3025   id.tid = tid;
3026
3027   GNUNET_CRYPTO_hash (&id, sizeof (struct MESH_TunnelID), &hash);
3028   return GNUNET_CONTAINER_multihashmap_get (tunnels, &hash);
3029 }
3030
3031
3032 /**
3033  * Search for a tunnel by global ID using full PeerIdentities
3034  *
3035  * @param oid owner of the tunnel
3036  * @param tid global tunnel number
3037  *
3038  * @return tunnel handler, NULL if doesn't exist
3039  */
3040 static struct MeshTunnel *
3041 tunnel_get (struct GNUNET_PeerIdentity *oid, MESH_TunnelNumber tid)
3042 {
3043   return tunnel_get_by_pi (GNUNET_PEER_search (oid), tid);
3044 }
3045
3046
3047 /**
3048  * Delete an active client from the tunnel.
3049  * 
3050  * @param t Tunnel.
3051  * @param c Client.
3052  */
3053 static void
3054 tunnel_delete_active_client (struct MeshTunnel *t, const struct MeshClient *c)
3055 {
3056   unsigned int i;
3057
3058   for (i = 0; i < t->nclients; i++)
3059   {
3060     if (t->clients[i] == c)
3061     {
3062       t->clients[i] = t->clients[t->nclients - 1];
3063       t->clients_fc[i] = t->clients_fc[t->nclients - 1];
3064       GNUNET_array_grow (t->clients, t->nclients, t->nclients - 1);
3065       t->nclients++;
3066       GNUNET_array_grow (t->clients_fc, t->nclients, t->nclients - 1);
3067       break;
3068     }
3069   }
3070 }
3071
3072
3073 /**
3074  * Delete an ignored client from the tunnel.
3075  * 
3076  * @param t Tunnel.
3077  * @param c Client.
3078  */
3079 static void
3080 tunnel_delete_ignored_client (struct MeshTunnel *t, const struct MeshClient *c)
3081 {
3082   unsigned int i;
3083
3084   for (i = 0; i < t->nignore; i++)
3085   {
3086     if (t->ignore[i] == c)
3087     {
3088       t->ignore[i] = t->ignore[t->nignore - 1];
3089       GNUNET_array_grow (t->ignore, t->nignore, t->nignore - 1);
3090       break;
3091     }
3092   }
3093 }
3094
3095
3096 /**
3097  * Delete a client from the tunnel. It should be only done on
3098  * client disconnection, otherwise use client_ignore_tunnel.
3099  * 
3100  * @param t Tunnel.
3101  * @param c Client.
3102  */
3103 static void
3104 tunnel_delete_client (struct MeshTunnel *t, const struct MeshClient *c)
3105 {
3106   tunnel_delete_ignored_client (t, c);
3107   tunnel_delete_active_client (t, c);
3108 }
3109
3110
3111 /**
3112  * Iterator to free MeshTunnelChildInfo of tunnel children.
3113  *
3114  * @param cls Closure (tunnel info).
3115  * @param key Hash of GNUNET_PEER_Id (unused).
3116  * @param value MeshTunnelChildInfo of the child.
3117  *
3118  * @return always GNUNET_YES, to keep iterating
3119  */
3120 static int
3121 tunnel_destroy_child (void *cls,
3122                       const struct GNUNET_HashCode * key,
3123                       void *value)
3124 {
3125   GNUNET_free (value);
3126   return GNUNET_YES;
3127 }
3128
3129
3130 /**
3131  * Callback used to notify a client owner of a tunnel that a peer has
3132  * disconnected, most likely because of a path change.
3133  *
3134  * @param cls Closure (tunnel this notification is about).
3135  * @param peer_id Short ID of disconnected peer.
3136  */
3137 void
3138 tunnel_notify_client_peer_disconnected (void *cls, GNUNET_PEER_Id peer_id)
3139 {
3140   struct MeshTunnel *t = cls;
3141   struct MeshPeerInfo *peer;
3142   struct MeshPathInfo *path_info;
3143
3144   if (NULL != t->owner && NULL != nc)
3145   {
3146     struct GNUNET_MESH_PeerControl msg;
3147
3148     msg.header.size = htons (sizeof (msg));
3149     msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL);
3150     msg.tunnel_id = htonl (t->local_tid);
3151     GNUNET_PEER_resolve (peer_id, &msg.peer);
3152     GNUNET_SERVER_notification_context_unicast (nc, t->owner->handle,
3153                                                 &msg.header, GNUNET_NO);
3154   }
3155   peer = peer_info_get_short (peer_id);
3156   path_info = GNUNET_malloc (sizeof (struct MeshPathInfo));
3157   path_info->peer = peer;
3158   path_info->t = t;
3159   GNUNET_SCHEDULER_add_now (&peer_info_connect_task, path_info);
3160 }
3161
3162
3163 /**
3164  * Add a peer to a tunnel, accomodating paths accordingly and initializing all
3165  * needed rescources.
3166  * If peer already exists, reevaluate shortest path and change if different.
3167  *
3168  * @param t Tunnel we want to add a new peer to
3169  * @param peer PeerInfo of the peer being added
3170  *
3171  */
3172 static void
3173 tunnel_add_peer (struct MeshTunnel *t, struct MeshPeerInfo *peer)
3174 {
3175   struct GNUNET_PeerIdentity id;
3176   struct MeshPeerPath *best_p;
3177   struct MeshPeerPath *p;
3178   unsigned int best_cost;
3179   unsigned int cost;
3180
3181   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "tunnel_add_peer\n");
3182   GNUNET_PEER_resolve (peer->id, &id);
3183   if (GNUNET_NO ==
3184       GNUNET_CONTAINER_multihashmap_contains (t->peers, &id.hashPubKey))
3185   {
3186     t->peers_total++;
3187     GNUNET_array_append (peer->tunnels, peer->ntunnels, t);
3188     GNUNET_assert (GNUNET_OK ==
3189                    GNUNET_CONTAINER_multihashmap_put (t->peers, &id.hashPubKey,
3190                                                       peer,
3191                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
3192   }
3193
3194   if (NULL != (p = peer->path_head))
3195   {
3196     best_p = p;
3197     best_cost = tree_get_path_cost (t->tree, p);
3198     while (NULL != p)
3199     {
3200       if ((cost = tree_get_path_cost (t->tree, p)) < best_cost)
3201       {
3202         best_cost = cost;
3203         best_p = p;
3204       }
3205       p = p->next;
3206     }
3207     tree_add_path (t->tree, best_p, &tunnel_notify_client_peer_disconnected, t);
3208     if (GNUNET_SCHEDULER_NO_TASK == t->path_refresh_task)
3209       t->path_refresh_task =
3210           GNUNET_SCHEDULER_add_delayed (refresh_path_time, &path_refresh, t);
3211   }
3212   else
3213   {
3214     /* Start a DHT get */
3215     peer_info_connect (peer, t);
3216   }
3217   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "tunnel_add_peer END\n");
3218 }
3219
3220 /**
3221  * Add a path to a tunnel which we don't own, just to remember the next hop.
3222  * If destination node was already in the tunnel, the first hop information
3223  * will be replaced with the new path.
3224  *
3225  * @param t Tunnel we want to add a new peer to
3226  * @param p Path to add
3227  * @param own_pos Position of local node in path.
3228  *
3229  */
3230 static void
3231 tunnel_add_path (struct MeshTunnel *t, struct MeshPeerPath *p,
3232                  unsigned int own_pos)
3233 {
3234   struct GNUNET_PeerIdentity id;
3235
3236   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "tunnel_add_path\n");
3237   GNUNET_assert (0 != own_pos);
3238   tree_add_path (t->tree, p, NULL, NULL);
3239   if (own_pos < p->length - 1)
3240   {
3241     GNUNET_PEER_resolve (p->peers[own_pos + 1], &id);
3242     tree_update_first_hops (t->tree, myid, &id);
3243   }
3244   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "tunnel_add_path END\n");
3245 }
3246
3247 /**
3248  * Add a client to a tunnel, initializing all needed data structures.
3249  * 
3250  * @param t Tunnel to which add the client.
3251  * @param c Client which to add to the tunnel.
3252  */
3253 static void
3254 tunnel_add_client (struct MeshTunnel *t, struct MeshClient *c)
3255 {
3256   struct MeshTunnelClientInfo clinfo;
3257
3258   GNUNET_array_append (t->clients, t->nclients, c);
3259   clinfo.fwd_ack = t->fwd_pid + 1;
3260   clinfo.bck_ack = t->nobuffer ? 1 : INITIAL_WINDOW_SIZE;
3261   clinfo.fwd_pid = t->fwd_pid;
3262   clinfo.bck_pid = (uint32_t) -1; // Expected next: 0
3263   t->nclients--;
3264   GNUNET_array_append (t->clients_fc, t->nclients, clinfo);
3265 }
3266
3267
3268 /**
3269  * Notifies a tunnel that a connection has broken that affects at least
3270  * some of its peers. Sends a notification towards the root of the tree.
3271  * In case the peer is the owner of the tree, notifies the client that owns
3272  * the tunnel and tries to reconnect.
3273  *
3274  * @param t Tunnel affected.
3275  * @param p1 Peer that got disconnected from p2.
3276  * @param p2 Peer that got disconnected from p1.
3277  *
3278  * @return Short ID of the peer disconnected (either p1 or p2).
3279  *         0 if the tunnel remained unaffected.
3280  */
3281 static GNUNET_PEER_Id
3282 tunnel_notify_connection_broken (struct MeshTunnel *t, GNUNET_PEER_Id p1,
3283                                  GNUNET_PEER_Id p2)
3284 {
3285   GNUNET_PEER_Id pid;
3286
3287   pid =
3288       tree_notify_connection_broken (t->tree, p1, p2,
3289                                      &tunnel_notify_client_peer_disconnected,
3290                                      t);
3291   if (myid != p1 && myid != p2)
3292   {
3293     return pid;
3294   }
3295   if (pid != myid)
3296   {
3297     if (tree_get_predecessor (t->tree) != 0)
3298     {
3299       /* We are the peer still connected, notify owner of the disconnection. */
3300       struct GNUNET_MESH_PathBroken msg;
3301       struct GNUNET_PeerIdentity neighbor;
3302
3303       msg.header.size = htons (sizeof (msg));
3304       msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN);
3305       GNUNET_PEER_resolve (t->id.oid, &msg.oid);
3306       msg.tid = htonl (t->id.tid);
3307       msg.peer1 = my_full_id;
3308       GNUNET_PEER_resolve (pid, &msg.peer2);
3309       GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &neighbor);
3310       send_message (&msg.header, &neighbor, t);
3311     }
3312   }
3313   return pid;
3314 }
3315
3316
3317 /**
3318  * Send a multicast packet to a neighbor.
3319  *
3320  * @param cls Closure (Info about the multicast packet)
3321  * @param neighbor_id Short ID of the neighbor to send the packet to.
3322  */
3323 static void
3324 tunnel_send_multicast_iterator (void *cls, GNUNET_PEER_Id neighbor_id)
3325 {
3326   struct MeshData *mdata = cls;
3327   struct MeshTransmissionDescriptor *info;
3328   struct GNUNET_PeerIdentity neighbor;
3329
3330   info = GNUNET_malloc (sizeof (struct MeshTransmissionDescriptor));
3331
3332   info->mesh_data = mdata;
3333   (*(mdata->reference_counter)) ++;
3334   info->destination = neighbor_id;
3335   GNUNET_PEER_resolve (neighbor_id, &neighbor);
3336   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   sending to %s...\n",
3337               GNUNET_i2s (&neighbor));
3338   info->peer = peer_info_get (&neighbor);
3339   GNUNET_assert (NULL != info->peer);
3340   queue_add(info,
3341             GNUNET_MESSAGE_TYPE_MESH_MULTICAST,
3342             info->mesh_data->data_len,
3343             info->peer,
3344             mdata->t);
3345 }
3346
3347
3348 /**
3349  * Send a message in a tunnel in multicast, sending a copy to each child node
3350  * down the local one in the tunnel tree.
3351  *
3352  * @param t Tunnel in which to send the data.
3353  * @param msg Message to be sent.
3354  * @param internal Has the service generated this message?
3355  */
3356 static void
3357 tunnel_send_multicast (struct MeshTunnel *t,
3358                        const struct GNUNET_MessageHeader *msg,
3359                        int internal)
3360 {
3361   struct MeshData *mdata;
3362
3363   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3364               " sending a multicast packet...\n");
3365   mdata = GNUNET_malloc (sizeof (struct MeshData));
3366   mdata->data_len = ntohs (msg->size);
3367   mdata->reference_counter = GNUNET_malloc (sizeof (unsigned int));
3368   mdata->t = t;
3369   mdata->data = GNUNET_malloc (mdata->data_len);
3370   memcpy (mdata->data, msg, mdata->data_len);
3371   if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_MESH_MULTICAST)
3372   {
3373     struct GNUNET_MESH_Multicast *mcast;
3374
3375     mcast = (struct GNUNET_MESH_Multicast *) mdata->data;
3376     mcast->ttl = htonl (ntohl (mcast->ttl) - 1);
3377     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  data packet, ttl: %u\n",
3378                 ntohl (mcast->ttl));
3379   }
3380   else
3381   {
3382     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  not a data packet, no ttl\n");
3383   }
3384   if (NULL != t->owner && GNUNET_YES != t->owner->shutting_down
3385       && GNUNET_NO == internal)
3386   {
3387     mdata->task = GNUNET_malloc (sizeof (GNUNET_SCHEDULER_TaskIdentifier));
3388     (*(mdata->task)) =
3389         GNUNET_SCHEDULER_add_delayed (unacknowledged_wait_time, &client_allow_send,
3390                                       mdata);
3391     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "timeout task %u\n",
3392                 *(mdata->task));
3393   }
3394
3395   tree_iterate_children (t->tree, &tunnel_send_multicast_iterator, mdata);
3396   if (*(mdata->reference_counter) == 0)
3397   {
3398     GNUNET_free (mdata->data);
3399     GNUNET_free (mdata->reference_counter);
3400     if (NULL != mdata->task)
3401     {
3402       GNUNET_SCHEDULER_cancel(*(mdata->task));
3403       GNUNET_free (mdata->task);
3404       GNUNET_SERVER_receive_done (t->owner->handle, GNUNET_OK);
3405     }
3406     // FIXME change order?
3407     GNUNET_free (mdata);
3408   }
3409   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3410               " sending a multicast packet done\n");
3411   return;
3412 }
3413
3414
3415 /**
3416  * Increase the SKIP value of all peers that
3417  * have not received a unicast message.
3418  *
3419  * @param cls Closure (ID of the peer that HAS received the message).
3420  * @param key ID of the neighbor.
3421  * @param value Information about the neighbor.
3422  *
3423  * @return GNUNET_YES to keep iterating.
3424  */
3425 static int
3426 tunnel_add_skip (void *cls,
3427                  const struct GNUNET_HashCode * key,
3428                  void *value)
3429 {
3430   struct GNUNET_PeerIdentity *neighbor = cls;
3431   struct MeshTunnelChildInfo *cinfo = value;
3432
3433   /* TODO compare only pointers? key == neighbor? */
3434   if (0 == memcmp (&neighbor->hashPubKey, key, sizeof (struct GNUNET_HashCode)))
3435   {
3436     return GNUNET_YES;
3437   }
3438   cinfo->skip++;
3439   return GNUNET_YES;
3440 }
3441
3442
3443 /**
3444  * @brief Get neighbor's Flow Control information.
3445  *
3446  * Retrieves the MeshTunnelChildInfo containing Flow Control data about a direct
3447  * descendant of the local node in a certain tunnel.
3448  * If the info is not yet there (recently created path), creates the data struct
3449  * and inserts it into the tunnel info, initialized to the current tunnel ACK
3450  * values.
3451  *
3452  * @param t Tunnel related.
3453  * @param peer Neighbor whose Flow Control info is needed.
3454  *
3455  * @return Neighbor's Flow Control info.
3456  */
3457 static struct MeshTunnelChildInfo *
3458 tunnel_get_neighbor_fc (const struct MeshTunnel *t,
3459                         const struct GNUNET_PeerIdentity *peer)
3460 {
3461   struct MeshTunnelChildInfo *cinfo;
3462   cinfo = GNUNET_CONTAINER_multihashmap_get (t->children_fc,
3463                                              &peer->hashPubKey);
3464   if (NULL == cinfo)
3465   {
3466     uint32_t delta;
3467
3468     cinfo = GNUNET_malloc (sizeof (struct MeshTunnelChildInfo));
3469     cinfo->id = GNUNET_PEER_intern (peer);
3470     cinfo->skip = t->fwd_pid;
3471
3472     delta = t->nobuffer ? 1 : INITIAL_WINDOW_SIZE;
3473     cinfo->fwd_ack = t->fwd_pid + delta;
3474     cinfo->bck_ack = delta;
3475
3476     GNUNET_assert (GNUNET_OK ==
3477       GNUNET_CONTAINER_multihashmap_put (t->children_fc,
3478                                          &peer->hashPubKey,
3479                                          cinfo,
3480                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
3481   }
3482   return cinfo;
3483 }
3484
3485
3486 /**
3487  * Get the Flow Control info of a client.
3488  * 
3489  * @param t Tunnel on which to look.
3490  * @param c Client whose ACK to get.
3491  * 
3492  * @return ACK value.
3493  */
3494 static struct MeshTunnelClientInfo *
3495 tunnel_get_client_fc (struct MeshTunnel *t,
3496                       struct MeshClient *c)
3497 {
3498   unsigned int i;
3499
3500   for (i = 0; i < t->nclients; i++)
3501   {
3502     if (t->clients[i] != c)
3503       continue;
3504     return &t->clients_fc[i];
3505   }
3506   GNUNET_assert (0);
3507   return NULL; // avoid compiler / coverity complaints
3508 }
3509
3510
3511 /**
3512  * Iterator to get the appropiate ACK value from all children nodes.
3513  *
3514  * @param cls Closue (tunnel).
3515  * @param id Id of the child node.
3516  */
3517 static void
3518 tunnel_get_child_fwd_ack (void *cls,
3519                           GNUNET_PEER_Id id)
3520 {
3521   struct GNUNET_PeerIdentity peer_id;
3522   struct MeshTunnelChildInfo *cinfo;
3523   struct MeshTunnelChildIteratorContext *ctx = cls;
3524   struct MeshTunnel *t = ctx->t;
3525   uint32_t ack;
3526
3527   GNUNET_PEER_resolve (id, &peer_id);
3528   cinfo = tunnel_get_neighbor_fc (t, &peer_id);
3529   ack = cinfo->fwd_ack;
3530
3531   if (GNUNET_NO == ctx->init)
3532   {
3533     ctx->max_child_ack = ack;
3534     ctx->init = GNUNET_YES;
3535   }
3536
3537   if (GNUNET_YES == t->speed_min)
3538   {
3539     ctx->max_child_ack = ctx->max_child_ack > ack ? ack : ctx->max_child_ack;
3540   }
3541   else
3542   {
3543     ctx->max_child_ack = ctx->max_child_ack > ack ? ctx->max_child_ack : ack;
3544   }
3545
3546 }
3547
3548
3549 /**
3550  * Get the maximum PID allowed to transmit to any
3551  * tunnel child of the local peer, depending on the tunnel
3552  * buffering/speed settings.
3553  *
3554  * @param t Tunnel.
3555  *
3556  * @return Maximum PID allowed (uint32 MAX), -1 if node has no children.
3557  */
3558 static int64_t
3559 tunnel_get_children_fwd_ack (struct MeshTunnel *t)
3560 {
3561   struct MeshTunnelChildIteratorContext ctx;
3562   ctx.t = t;
3563   ctx.max_child_ack = 0;
3564   ctx.nchildren = 0;
3565   tree_iterate_children (t->tree, tunnel_get_child_fwd_ack, &ctx);
3566
3567   if (0 == ctx.nchildren)
3568     return -1LL;
3569
3570   if (GNUNET_YES == t->nobuffer && is_pid_bigger(ctx.max_child_ack, t->fwd_pid))
3571     ctx.max_child_ack = t->fwd_pid + 1; // Might overflow, it's ok.
3572
3573   return (int64_t) ctx.max_child_ack;
3574 }
3575
3576
3577 /**
3578  * Set the FWD ACK value of a client in a particular tunnel.
3579  * 
3580  * @param t Tunnel affected.
3581  * @param c Client whose ACK to set.
3582  * @param ack ACK value.
3583  */
3584 static void
3585 tunnel_set_client_fwd_ack (struct MeshTunnel *t,
3586                            struct MeshClient *c, 
3587                            uint32_t ack)
3588 {
3589   unsigned int i;
3590
3591   for (i = 0; i < t->nclients; i++)
3592   {
3593     if (t->clients[i] != c)
3594       continue;
3595     t->clients_fc[i].fwd_ack = ack;
3596     return;
3597   }
3598   GNUNET_break (0);
3599 }
3600
3601
3602 /**
3603  * Get the highest ACK value of all clients in a particular tunnel,
3604  * according to the buffering/speed settings.
3605  * 
3606  * @param t Tunnel on which to look.
3607  * 
3608  * @return Corresponding ACK value (max uint32_t).
3609  *         If no clients are suscribed, -1.
3610  */
3611 static int64_t
3612 tunnel_get_clients_fwd_ack (struct MeshTunnel *t)
3613 {
3614   unsigned int i;
3615   int64_t ack;
3616
3617   if (0 == t->nclients)
3618     return -1;
3619
3620   for (ack = -1, i = 0; i < t->nclients; i++)
3621   {
3622     if (-1 == ack ||
3623         (GNUNET_YES == t->speed_min &&
3624          GNUNET_YES == is_pid_bigger (ack, t->clients_fc[i].fwd_ack)) ||
3625         (GNUNET_NO == t->speed_min &&
3626          GNUNET_YES == is_pid_bigger (t->clients_fc[i].fwd_ack, ack)))
3627     {
3628       ack = t->clients_fc[i].fwd_ack;
3629     }
3630   }
3631
3632   if (GNUNET_YES == t->nobuffer && is_pid_bigger(ack, t->fwd_pid))
3633     ack = (uint32_t) t->fwd_pid + 1; // Might overflow, it's ok.
3634
3635   return (uint32_t) ack;
3636 }
3637
3638
3639 /**
3640  * Get the current fwd ack value for a tunnel, taking in account the tunnel
3641  * mode and the status of all children nodes.
3642  *
3643  * @param t Tunnel.
3644  *
3645  * @return Maximum PID allowed.
3646  */
3647 static uint32_t
3648 tunnel_get_fwd_ack (struct MeshTunnel *t)
3649 {
3650   uint32_t count;
3651   uint32_t buffer_free;
3652   int64_t child_ack;
3653   int64_t client_ack;
3654   uint32_t ack;
3655
3656   count = t->fwd_pid - t->skip;
3657   buffer_free = t->fwd_queue_max - t->fwd_queue_n;
3658   ack = count + buffer_free; // Might overflow 32 bits, it's ok!
3659   child_ack = tunnel_get_children_fwd_ack (t);
3660   client_ack = tunnel_get_clients_fwd_ack (t);
3661   if (-1 == child_ack)
3662   {
3663     // Node has no children, child_ack AND core buffer are irrelevant.
3664     GNUNET_break (-1 != client_ack); // No children AND no clients? Not good!
3665     return (uint32_t) client_ack;
3666   }
3667
3668   if (GNUNET_YES == t->speed_min)
3669   {
3670     ack = min_pid ((uint32_t) child_ack, ack);
3671     ack = min_pid ((uint32_t) client_ack, ack);
3672   }
3673   else
3674   {
3675     ack = max_pid ((uint32_t) child_ack, ack);
3676     ack = max_pid ((uint32_t) client_ack, ack);
3677   }
3678   if (GNUNET_YES == t->nobuffer && is_pid_bigger(ack, t->fwd_pid))
3679     ack = t->fwd_pid + 1; // Might overflow 32 bits, it's ok!
3680   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "c %u, bf %u, ch %u, cl %u, ACK: %u\n",
3681               count, buffer_free, child_ack, client_ack, ack);
3682   return ack;
3683 }
3684
3685 /**
3686  * Get the current bck ack value for a tunnel, taking in account the tunnel
3687  * mode and the status of all children nodes.
3688  *
3689  * @param t Tunnel.
3690  *
3691  * @return Maximum PID allowed.
3692  */
3693 static uint32_t
3694 tunnel_get_bck_ack (struct MeshTunnel *t)
3695 {
3696   uint32_t ack;
3697
3698   if (GNUNET_YES == t->nobuffer)
3699   {
3700     if (t->bck_ack > t->bck_pid)
3701     {
3702       return t->bck_pid + 1;
3703     }
3704     else
3705     {
3706       return t->bck_pid;
3707     }
3708   }
3709   ack = t->bck_pid + t->bck_queue_max - t->bck_queue_n;
3710
3711   // FIXME fc
3712   return ack;
3713 }
3714
3715 static void
3716 send_local_ack (struct MeshClient *c, struct MeshTunnel *t, uint32_t ack)
3717 {
3718   struct GNUNET_MESH_LocalAck msg;
3719
3720   msg.header.size = htons (sizeof (msg));
3721   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
3722   msg.tunnel_id = htonl (t->local_tid_dest);
3723   msg.max_pid = htonl (ack); 
3724   GNUNET_SERVER_notification_context_unicast(nc,
3725                                               c->handle,
3726                                               &msg.header,
3727                                               GNUNET_NO);
3728 }
3729
3730 /**
3731  * Build an ACK message and send it to the given peer.
3732  */
3733 static void
3734 send_ack (struct MeshTunnel *t, struct GNUNET_PeerIdentity *peer,  uint32_t ack)
3735 {
3736   struct GNUNET_MESH_ACK msg;
3737
3738   GNUNET_PEER_resolve (t->id.oid, &msg.oid);
3739   msg.header.size = htons (sizeof (msg));
3740   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_ACK);
3741   msg.pid = htonl (ack);
3742   msg.tid = htonl (t->id.tid);
3743
3744   send_message (&msg.header, peer, t);
3745 }
3746
3747
3748 /**
3749  * Send an ACK informing the predecessor about the available buffer space.
3750  * In case there is no predecessor, inform the owning client.
3751  * If buffering is off, send only on behalf of children or self if endpoint.
3752  * If buffering is on, send when sent to children and buffer space is free.
3753  * Note that although the name is fwd_ack, the FWD mean forward *traffic*,
3754  * the ACK itself goes "back" (towards root).
3755  * 
3756  * @param t Tunnel on which to send the ACK.
3757  * @param type Type of message that triggered the ACK transmission.
3758  */
3759 static void
3760 tunnel_send_fwd_ack (struct MeshTunnel *t, uint16_t type)
3761 {
3762   struct GNUNET_PeerIdentity id;
3763   uint32_t ack;
3764
3765   if (NULL != t->owner)
3766   {
3767     send_client_tunnel_ack (t->owner, t);
3768     return;
3769   }
3770   /* Is it after unicast / multicast retransmission? */
3771   switch (type)
3772   {
3773     case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
3774     case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
3775       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3776                   "ACK due to FWD DATA retransmission\n");
3777       if (GNUNET_YES == t->nobuffer)
3778       {
3779         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, nobuffer\n");
3780         return;
3781       }
3782       if (t->fwd_queue_max > t->fwd_queue_n * 2)
3783       {
3784         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, buffer free\n");
3785         return;
3786       }
3787       break;
3788     case GNUNET_MESSAGE_TYPE_MESH_ACK:
3789     case GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK:
3790       break;
3791     default:
3792       GNUNET_break (0);
3793   }
3794
3795   /* Ok, ACK might be necessary, what PID to ACK? */
3796   ack = tunnel_get_fwd_ack (t);
3797
3798   /* If speed_min and not all children have ack'd, dont send yet */
3799   if (ack == t->last_fwd_ack)
3800   {
3801     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending FWD ACK, not ready\n");
3802     return;
3803   }
3804
3805   t->last_fwd_ack = ack;
3806   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
3807   send_ack (t, &id, ack);
3808 }
3809
3810
3811 /**
3812  * Iterator to send a child node a BCK ACK to allow him to send more
3813  * to_origin data.
3814  *
3815  * @param cls Closure (tunnel).
3816  * @param id Id of the child node.
3817  */
3818 static void
3819 tunnel_send_child_bck_ack (void *cls,
3820                            GNUNET_PEER_Id id)
3821 {
3822   struct MeshTunnel *t = cls;
3823   struct MeshTunnelChildInfo *cinfo;
3824   struct GNUNET_PeerIdentity peer;
3825
3826   GNUNET_PEER_resolve (id, &peer);
3827   cinfo = tunnel_get_neighbor_fc (t, &peer);
3828
3829   if (cinfo->bck_ack != cinfo->pid &&
3830       GNUNET_NO == is_pid_bigger (cinfo->bck_ack, cinfo->pid))
3831     return;
3832
3833   cinfo->bck_ack++;
3834   send_ack (t, &peer, cinfo->bck_ack);
3835 }
3836
3837
3838 /**
3839  * @brief Send BCK ACKs to clients to allow them more to_origin traffic
3840  * 
3841  * Iterates over all clients and sends BCK ACKs to the ones that need it.
3842  * 
3843  * @param t Tunnel on which to send the BCK ACKs.
3844  */
3845 static void
3846 tunnel_send_clients_bck_ack (struct MeshTunnel *t)
3847 {
3848   unsigned int i;
3849
3850   /* Find client whom to allow to send to origin (with lowest buffer space) */
3851   for (i = 0; i < t->nclients; i++)
3852   {
3853     struct MeshTunnelClientInfo *clinfo;
3854     unsigned int delta;
3855
3856     clinfo = &t->clients_fc[i];
3857     delta = clinfo->bck_ack - clinfo->bck_pid;
3858
3859     if ((GNUNET_NO == t->nobuffer && ACK_THRESHOLD > delta) ||
3860         (GNUNET_YES == t->nobuffer && 0 == delta))
3861     {
3862       uint32_t ack;
3863
3864       ack = clinfo->bck_pid;
3865       ack += t->nobuffer ? 1 : INITIAL_WINDOW_SIZE;
3866       send_local_ack(t->clients[i],  t, ack);
3867       clinfo->bck_ack = ack;
3868     }
3869   }
3870 }
3871
3872
3873 /**
3874  * Send an ACK informing the children nodes and destination clients about
3875  * the available buffer space.
3876  * If buffering is off, send only on behalf of root (can be self).
3877  * If buffering is on, send when sent to predecessor and buffer space is free.
3878  * Note that although the name is bck_ack, the BCK mean backwards *traffic*,
3879  * the ACK itself goes "forward" (towards children/clients).
3880  * 
3881  * @param t Tunnel on which to send the ACK.
3882  * @param type Type of message that triggered the ACK transmission.
3883  */
3884 static void
3885 tunnel_send_bck_ack (struct MeshTunnel *t, uint16_t type)
3886 {
3887   if (NULL != t->owner)
3888   {
3889     send_client_tunnel_ack (t->owner, t);
3890     return;
3891   }
3892   /* Is it after data to_origin retransmission? */
3893   switch (type)
3894   {
3895     case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
3896       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3897                   "ACK due to BCK DATA retransmission\n");
3898       if (GNUNET_YES == t->nobuffer)
3899       {
3900         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, nobuffer\n");
3901         return;
3902       }
3903       if (t->bck_queue_max > t->bck_queue_n * 2)
3904       {
3905         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, buffer free\n");
3906         return;
3907       }
3908       break;
3909     case GNUNET_MESSAGE_TYPE_MESH_ACK:
3910     case GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK:
3911       break;
3912     default:
3913       GNUNET_break (0);
3914   }
3915
3916   tunnel_send_clients_bck_ack (t);
3917   tree_iterate_children (t->tree, &tunnel_send_child_bck_ack, NULL);
3918 }
3919
3920
3921 /**
3922  * Send a message to all peers in this tunnel that the tunnel is no longer
3923  * valid.
3924  *
3925  * @param t The tunnel whose peers to notify.
3926  */
3927 static void
3928 tunnel_send_destroy (struct MeshTunnel *t)
3929 {
3930   struct GNUNET_MESH_TunnelDestroy msg;
3931
3932   msg.header.size = htons (sizeof (msg));
3933   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY);
3934   GNUNET_PEER_resolve (t->id.oid, &msg.oid);
3935   msg.tid = htonl (t->id.tid);
3936   tunnel_send_multicast (t, &msg.header, GNUNET_NO);
3937 }
3938
3939
3940 /**
3941  * Cancel all transmissions towards a neighbor that belong to a certain tunnel.
3942  *
3943  * @param cls Closure (Tunnel which to cancel).
3944  * @param neighbor_id Short ID of the neighbor to whom cancel the transmissions.
3945  */
3946 static void
3947 tunnel_cancel_queues (void *cls, GNUNET_PEER_Id neighbor_id)
3948 {
3949   struct MeshTunnel *t = cls;
3950   struct MeshPeerInfo *peer_info;
3951   struct MeshPeerQueue *pq;
3952   struct MeshPeerQueue *next;
3953
3954   peer_info = peer_info_get_short (neighbor_id);
3955   for (pq = peer_info->queue_head; NULL != pq; pq = next)
3956   {
3957     next = pq->next;
3958     if (pq->tunnel == t)
3959     {
3960       queue_destroy (pq, GNUNET_YES);
3961     }
3962   }
3963   if (NULL == peer_info->queue_head && NULL != peer_info->core_transmit)
3964   {
3965     GNUNET_CORE_notify_transmit_ready_cancel(peer_info->core_transmit);
3966     peer_info->core_transmit = NULL;
3967   }
3968 }
3969
3970 /**
3971  * Destroy the tunnel and free any allocated resources linked to it.
3972  *
3973  * @param t the tunnel to destroy
3974  *
3975  * @return GNUNET_OK on success
3976  */
3977 static int
3978 tunnel_destroy (struct MeshTunnel *t)
3979 {
3980   struct MeshClient *c;
3981   struct GNUNET_HashCode hash;
3982   unsigned int i;
3983   int r;
3984
3985   if (NULL == t)
3986     return GNUNET_OK;
3987
3988   tree_iterate_children (t->tree, &tunnel_cancel_queues, t);
3989
3990   r = GNUNET_OK;
3991   c = t->owner;
3992 #if MESH_DEBUG
3993   {
3994     struct GNUNET_PeerIdentity id;
3995
3996     GNUNET_PEER_resolve (t->id.oid, &id);
3997     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s [%x]\n",
3998                 GNUNET_i2s (&id), t->id.tid);
3999     if (NULL != c)
4000       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
4001   }
4002 #endif
4003
4004   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
4005   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &hash, t))
4006   {
4007     r = GNUNET_SYSERR;
4008   }
4009
4010   GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
4011   if (NULL != c &&
4012       GNUNET_YES !=
4013       GNUNET_CONTAINER_multihashmap_remove (c->own_tunnels, &hash, t))
4014   {
4015     r = GNUNET_SYSERR;
4016   }
4017   GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
4018   for (i = 0; i < t->nclients; i++)
4019   {
4020     c = t->clients[i];
4021     if (GNUNET_YES !=
4022           GNUNET_CONTAINER_multihashmap_remove (c->incoming_tunnels, &hash, t))
4023     {
4024       r = GNUNET_SYSERR;
4025     }
4026   }
4027   for (i = 0; i < t->nignore; i++)
4028   {
4029     c = t->ignore[i];
4030     if (GNUNET_YES !=
4031           GNUNET_CONTAINER_multihashmap_remove (c->ignore_tunnels, &hash, t))
4032     {
4033       r = GNUNET_SYSERR;
4034     }
4035   }
4036   if (t->nclients > 0)
4037   {
4038     if (GNUNET_YES !=
4039         GNUNET_CONTAINER_multihashmap_remove (incoming_tunnels, &hash, t))
4040     {
4041       r = GNUNET_SYSERR;
4042     }
4043     GNUNET_free (t->clients);
4044   }
4045   if (NULL != t->peers)
4046   {
4047     GNUNET_CONTAINER_multihashmap_iterate (t->peers, &peer_info_delete_tunnel,
4048                                            t);
4049     GNUNET_CONTAINER_multihashmap_destroy (t->peers);
4050   }
4051
4052   GNUNET_CONTAINER_multihashmap_iterate (t->children_fc,
4053                                          &tunnel_destroy_child,
4054                                          t);
4055   GNUNET_CONTAINER_multihashmap_destroy (t->children_fc);
4056
4057   tree_destroy (t->tree);
4058
4059   if (NULL != t->regex_ctx)
4060     regex_cancel_search (t->regex_ctx);
4061   if (NULL != t->dht_get_type)
4062     GNUNET_DHT_get_stop (t->dht_get_type);
4063   if (GNUNET_SCHEDULER_NO_TASK != t->timeout_task)
4064     GNUNET_SCHEDULER_cancel (t->timeout_task);
4065   if (GNUNET_SCHEDULER_NO_TASK != t->path_refresh_task)
4066     GNUNET_SCHEDULER_cancel (t->path_refresh_task);
4067
4068   n_tunnels--;
4069   GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
4070   GNUNET_assert (0 <= n_tunnels);
4071   GNUNET_free (t);
4072   return r;
4073 }
4074
4075
4076 /**
4077  * Create a new tunnel
4078  * 
4079  * @param owner Who is the owner of the tunnel (short ID).
4080  * @param tid Tunnel Number of the tunnel.
4081  * @param client Clients that owns the tunnel, NULL for foreign tunnels.
4082  * @param local Tunnel Number for the tunnel, for the client point of view.
4083  * 
4084  * @return A new initialized tunnel. NULL on error.
4085  */
4086 static struct MeshTunnel *
4087 tunnel_new (GNUNET_PEER_Id owner,
4088             MESH_TunnelNumber tid,
4089             struct MeshClient *client,
4090             MESH_TunnelNumber local)
4091 {
4092   struct MeshTunnel *t;
4093   struct GNUNET_HashCode hash;
4094
4095   if (n_tunnels >= max_tunnels && NULL == client)
4096     return NULL;
4097
4098   t = GNUNET_malloc (sizeof (struct MeshTunnel));
4099   t->id.oid = owner;
4100   t->id.tid = tid;
4101   t->fwd_queue_max = (max_msgs_queue / max_tunnels) + 1;
4102   t->bck_queue_max = t->fwd_queue_max;
4103   t->tree = tree_new (owner);
4104   t->owner = client;
4105   t->fwd_pid = (uint32_t) -1; // Next (expected) = 0
4106   t->bck_pid = (uint32_t) -1; // Next (expected) = 0
4107   t->bck_ack = INITIAL_WINDOW_SIZE - 1;
4108   t->last_fwd_ack = INITIAL_WINDOW_SIZE - 1;
4109   t->local_tid = local;
4110   t->children_fc = GNUNET_CONTAINER_multihashmap_create (8);
4111   n_tunnels++;
4112   GNUNET_STATISTICS_update (stats, "# tunnels", 1, GNUNET_NO);
4113
4114   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
4115   if (GNUNET_OK !=
4116       GNUNET_CONTAINER_multihashmap_put (tunnels, &hash, t,
4117                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
4118   {
4119     GNUNET_break (0);
4120     tunnel_destroy (t);
4121     if (NULL != client)
4122     {
4123       GNUNET_break (0);
4124       GNUNET_SERVER_receive_done (client->handle, GNUNET_SYSERR);
4125     }
4126     return NULL;
4127   }
4128
4129   if (NULL != client)
4130   {
4131     GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
4132     if (GNUNET_OK !=
4133         GNUNET_CONTAINER_multihashmap_put (client->own_tunnels, &hash, t,
4134                                           GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
4135     {
4136       tunnel_destroy (t);
4137       GNUNET_break (0);
4138       GNUNET_SERVER_receive_done (client->handle, GNUNET_SYSERR);
4139       return NULL;
4140     }
4141   }
4142
4143   return t;
4144 }
4145
4146
4147 /**
4148  * Removes an explicit path from a tunnel, freeing all intermediate nodes
4149  * that are no longer needed, as well as nodes of no longer reachable peers.
4150  * The tunnel itself is also destoyed if results in a remote empty tunnel.
4151  *
4152  * @param t Tunnel from which to remove the path.
4153  * @param peer Short id of the peer which should be removed.
4154  */
4155 static void
4156 tunnel_delete_peer (struct MeshTunnel *t, GNUNET_PEER_Id peer)
4157 {
4158   if (GNUNET_NO == tree_del_peer (t->tree, peer, NULL, NULL))
4159     tunnel_destroy (t);
4160 }
4161
4162
4163 /**
4164  * tunnel_destroy_iterator: iterator for deleting each tunnel that belongs to a
4165  * client when the client disconnects. If the client is not the owner, the
4166  * owner will get notified if no more clients are in the tunnel and the client
4167  * get removed from the tunnel's list.
4168  *
4169  * @param cls closure (client that is disconnecting)
4170  * @param key the hash of the local tunnel id (used to access the hashmap)
4171  * @param value the value stored at the key (tunnel to destroy)
4172  *
4173  * @return GNUNET_OK on success
4174  */
4175 static int
4176 tunnel_destroy_iterator (void *cls, const struct GNUNET_HashCode * key, void *value)
4177 {
4178   struct MeshTunnel *t = value;
4179   struct MeshClient *c = cls;
4180   int r;
4181
4182   send_client_tunnel_disconnect(t, c);
4183   if (c != t->owner)
4184   {
4185     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4186                 "Client %u is destination, keeping the tunnel alive.\n", c->id);
4187     tunnel_delete_client(t, c);
4188     client_delete_tunnel(c, t);
4189     return GNUNET_OK;
4190   }
4191   tunnel_send_destroy(t);
4192   r = tunnel_destroy (t);
4193   return r;
4194 }
4195
4196
4197 /**
4198  * Timeout function, destroys tunnel if called
4199  *
4200  * @param cls Closure (tunnel to destroy).
4201  * @param tc TaskContext
4202  */
4203 static void
4204 tunnel_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4205 {
4206   struct MeshTunnel *t = cls;
4207
4208   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4209     return;
4210   t->timeout_task = GNUNET_SCHEDULER_NO_TASK;
4211   tunnel_destroy (t);
4212 }
4213
4214 /**
4215  * Resets the tunnel timeout. Starts it if no timeout was running.
4216  *
4217  * @param t Tunnel whose timeout to reset.
4218  *
4219  * TODO use heap to improve efficiency of scheduler.
4220  */
4221 static void
4222 tunnel_reset_timeout (struct MeshTunnel *t)
4223 {
4224   if (GNUNET_SCHEDULER_NO_TASK != t->timeout_task)
4225     GNUNET_SCHEDULER_cancel (t->timeout_task);
4226   t->timeout_task =
4227       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
4228                                     (refresh_path_time, 4), &tunnel_timeout, t);
4229 }
4230
4231
4232 /******************************************************************************/
4233 /****************      MESH NETWORK HANDLER HELPERS     ***********************/
4234 /******************************************************************************/
4235
4236 /**
4237  * Function to send a create path packet to a peer.
4238  *
4239  * @param cls closure
4240  * @param size number of bytes available in buf
4241  * @param buf where the callee should write the message
4242  * @return number of bytes written to buf
4243  */
4244 static size_t
4245 send_core_path_create (void *cls, size_t size, void *buf)
4246 {
4247   struct MeshPathInfo *info = cls;
4248   struct GNUNET_MESH_ManipulatePath *msg;
4249   struct GNUNET_PeerIdentity *peer_ptr;
4250   struct MeshTunnel *t = info->t;
4251   struct MeshPeerPath *p = info->path;
4252   size_t size_needed;
4253   uint32_t opt;
4254   int i;
4255
4256   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATE PATH sending...\n");
4257   size_needed =
4258       sizeof (struct GNUNET_MESH_ManipulatePath) +
4259       p->length * sizeof (struct GNUNET_PeerIdentity);
4260
4261   if (size < size_needed || NULL == buf)
4262   {
4263     GNUNET_break (0);
4264     return 0;
4265   }
4266   msg = (struct GNUNET_MESH_ManipulatePath *) buf;
4267   msg->header.size = htons (size_needed);
4268   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE);
4269   msg->tid = ntohl (t->id.tid);
4270
4271   if (GNUNET_YES == t->speed_min)
4272     opt = MESH_TUNNEL_OPT_SPEED_MIN;
4273   if (GNUNET_YES == t->nobuffer)
4274     opt |= MESH_TUNNEL_OPT_NOBUFFER;
4275   msg->opt = htonl(opt);
4276
4277   peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
4278   for (i = 0; i < p->length; i++)
4279   {
4280     GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
4281   }
4282
4283   path_destroy (p);
4284   GNUNET_free (info);
4285
4286   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4287               "CREATE PATH (%u bytes long) sent!\n", size_needed);
4288   return size_needed;
4289 }
4290
4291
4292 /**
4293  * Fill the core buffer 
4294  *
4295  * @param cls closure (data itself)
4296  * @param size number of bytes available in buf
4297  * @param buf where the callee should write the message
4298  *
4299  * @return number of bytes written to buf
4300  */
4301 static size_t
4302 send_core_data_multicast (void *cls, size_t size, void *buf)
4303 {
4304   struct MeshTransmissionDescriptor *info = cls;
4305   size_t total_size;
4306
4307   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Multicast callback.\n");
4308   GNUNET_assert (NULL != info);
4309   GNUNET_assert (NULL != info->peer);
4310   total_size = info->mesh_data->data_len;
4311   GNUNET_assert (total_size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
4312
4313   if (total_size > size)
4314   {
4315     GNUNET_break (0);
4316     return 0;
4317   }
4318   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " copying data...\n");
4319   memcpy (buf, info->mesh_data->data, total_size);
4320 #if MESH_DEBUG
4321   {
4322     struct GNUNET_MESH_Multicast *mc;
4323     struct GNUNET_MessageHeader *mh;
4324
4325     mh = buf;
4326     if (ntohs (mh->type) == GNUNET_MESSAGE_TYPE_MESH_MULTICAST)
4327     {
4328       mc = (struct GNUNET_MESH_Multicast *) mh;
4329       mh = (struct GNUNET_MessageHeader *) &mc[1];
4330       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4331                   " multicast, payload type %s\n",
4332                   GNUNET_MESH_DEBUG_M2S (ntohs (mh->type)));
4333       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4334                   " multicast, payload size %u\n", ntohs (mh->size));
4335     }
4336     else
4337     {
4338       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " type %s\n",
4339                   GNUNET_MESH_DEBUG_M2S (ntohs (mh->type)));
4340     }
4341   }
4342 #endif
4343   data_descriptor_decrement_rc (info->mesh_data);
4344   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "freeing info...\n");
4345   GNUNET_free (info);
4346   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "return %u\n", total_size);
4347   return total_size;
4348 }
4349
4350
4351 /**
4352  * Creates a path ack message in buf and frees all unused resources.
4353  *
4354  * @param cls closure (MeshTransmissionDescriptor)
4355  * @param size number of bytes available in buf
4356  * @param buf where the callee should write the message
4357  * @return number of bytes written to buf
4358  */
4359 static size_t
4360 send_core_path_ack (void *cls, size_t size, void *buf)
4361 {
4362   struct MeshTransmissionDescriptor *info = cls;
4363   struct GNUNET_MESH_PathACK *msg = buf;
4364
4365   GNUNET_assert (NULL != info);
4366   if (sizeof (struct GNUNET_MESH_PathACK) > size)
4367   {
4368     GNUNET_break (0);
4369     return 0;
4370   }
4371   msg->header.size = htons (sizeof (struct GNUNET_MESH_PathACK));
4372   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_ACK);
4373   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
4374   msg->tid = htonl (info->origin->tid);
4375   msg->peer_id = my_full_id;
4376
4377   GNUNET_free (info);
4378   /* TODO add signature */
4379
4380   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "PATH ACK sent!\n");
4381   return sizeof (struct GNUNET_MESH_PathACK);
4382 }
4383
4384
4385 /**
4386  * Free a transmission that was already queued with all resources
4387  * associated to the request.
4388  *
4389  * @param queue Queue handler to cancel.
4390  * @param clear_cls Is it necessary to free associated cls?
4391  */
4392 static void
4393 queue_destroy (struct MeshPeerQueue *queue, int clear_cls)
4394 {
4395   struct MeshTransmissionDescriptor *dd;
4396   struct MeshPathInfo *path_info;
4397
4398   if (GNUNET_YES == clear_cls)
4399   {
4400     switch (queue->type)
4401     {
4402     case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4403     case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
4404     case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4405         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   type payload\n");
4406         dd = queue->cls;
4407         data_descriptor_decrement_rc (dd->mesh_data);
4408         break;
4409     case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
4410         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   type create path\n");
4411         path_info = queue->cls;
4412         path_destroy (path_info->path);
4413         break;
4414     default:
4415         GNUNET_break (0);
4416         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   type unknown!\n");
4417     }
4418     GNUNET_free_non_null (queue->cls);
4419   }
4420   GNUNET_CONTAINER_DLL_remove (queue->peer->queue_head,
4421                                queue->peer->queue_tail,
4422                                queue);
4423   GNUNET_free (queue);
4424 }
4425
4426
4427 /**
4428   * Core callback to write a queued packet to core buffer
4429   *
4430   * @param cls Closure (peer info).
4431   * @param size Number of bytes available in buf.
4432   * @param buf Where the to write the message.
4433   *
4434   * @return number of bytes written to buf
4435   */
4436 static size_t
4437 queue_send (void *cls, size_t size, void *buf)
4438 {
4439     struct MeshPeerInfo *peer = cls;
4440     struct GNUNET_MessageHeader *msg;
4441     struct MeshPeerQueue *queue;
4442     struct MeshTunnel *t;
4443     size_t data_size;
4444
4445     peer->core_transmit = NULL;
4446     queue = peer->queue_head;
4447
4448     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "********* Queue send\n");
4449
4450     /* If queue is empty, send should have been cancelled */
4451     if (NULL == queue)
4452     {
4453         GNUNET_break(0);
4454         return 0;
4455     }
4456     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   not empty\n");
4457
4458     /* Check if buffer size is enough for the message */
4459     if (queue->size > size)
4460     {
4461         struct GNUNET_PeerIdentity id;
4462
4463         GNUNET_PEER_resolve (peer->id, &id);
4464         peer->core_transmit =
4465             GNUNET_CORE_notify_transmit_ready(core_handle,
4466                                               0,
4467                                               0,
4468                                               GNUNET_TIME_UNIT_FOREVER_REL,
4469                                               &id,
4470                                               queue->size,
4471                                               &queue_send,
4472                                               peer);
4473         return 0;
4474     }
4475     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   size ok\n");
4476
4477     t = queue->tunnel;
4478     if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == queue->type)
4479     {
4480       t->fwd_queue_n--;
4481       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   unicast: %u\n");
4482     }
4483     else if (GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == queue->type)
4484     {
4485       t->bck_queue_n--;
4486       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   to origin\n");
4487     }
4488
4489     /* Fill buf */
4490     switch (queue->type)
4491     {
4492       case 0:
4493       case GNUNET_MESSAGE_TYPE_MESH_ACK:
4494       case GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN:
4495       case GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY:
4496         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4497                     "*********   raw: %u\n",
4498                     queue->type);
4499         /* Fall through */
4500       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4501       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4502         data_size = send_core_data_raw (queue->cls, size, buf);
4503         msg = (struct GNUNET_MessageHeader *) buf;
4504         switch (ntohs (msg->type)) // Type of preconstructed message
4505         {
4506           case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4507             tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_UNICAST);
4508             break;
4509           case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4510             tunnel_send_bck_ack(t, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
4511             break;
4512           default:
4513               break;
4514         }
4515         break;
4516       case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
4517         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   multicast\n");
4518         data_size = send_core_data_multicast(queue->cls, size, buf);
4519         tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
4520         break;
4521       case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
4522         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path create\n");
4523         data_size = send_core_path_create(queue->cls, size, buf);
4524         break;
4525       case GNUNET_MESSAGE_TYPE_MESH_PATH_ACK:
4526         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path ack\n");
4527         data_size = send_core_path_ack(queue->cls, size, buf);
4528         break;
4529       default:
4530         GNUNET_break (0);
4531         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4532                     "*********   type unknown: %u\n",
4533                     queue->type);
4534         data_size = 0;
4535     }
4536
4537     /* Free queue, but cls was freed by send_core_* */
4538     queue_destroy (queue, GNUNET_NO);
4539
4540     if (GNUNET_YES == t->destroy && 0 == t->fwd_queue_n)
4541     {
4542       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********  destroying tunnel!\n");
4543       tunnel_destroy (t);
4544     }
4545
4546     /* If more data in queue, send next */
4547     if (NULL != peer->queue_head)
4548     {
4549         struct GNUNET_PeerIdentity id;
4550
4551         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   more data!\n");
4552         GNUNET_PEER_resolve (peer->id, &id);
4553         peer->core_transmit =
4554             GNUNET_CORE_notify_transmit_ready(core_handle,
4555                                               0,
4556                                               0,
4557                                               GNUNET_TIME_UNIT_FOREVER_REL,
4558                                               &id,
4559                                               peer->queue_head->size,
4560                                               &queue_send,
4561                                               peer);
4562     }
4563     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   return %d\n", data_size);
4564     return data_size;
4565 }
4566
4567
4568 /**
4569  * Queue and pass message to core when possible.
4570  *
4571  * @param cls Closure (type dependant).
4572  * @param type Type of the message, 0 for a raw message.
4573  * @param size Size of the message.
4574  * @param dst Neighbor to send message to.
4575  * @param t Tunnel this message belongs to.
4576  */
4577 static void
4578 queue_add (void *cls, uint16_t type, size_t size,
4579            struct MeshPeerInfo *dst, struct MeshTunnel *t)
4580 {
4581   struct MeshPeerQueue *queue;
4582   unsigned int *max;
4583   unsigned int *n;
4584
4585   n = NULL;
4586   if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == type ||
4587       GNUNET_MESSAGE_TYPE_MESH_MULTICAST == type)
4588   {
4589     n = &t->fwd_queue_n;
4590     max = &t->fwd_queue_max;
4591   }
4592   else if (GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == type)
4593   {
4594     n = &t->bck_queue_n;
4595     max = &t->bck_queue_max;
4596   }
4597   if (NULL != n) {
4598     if (*n >= *max)
4599     {
4600       if (NULL == t->owner)
4601         GNUNET_break_op(0);       // TODO: kill connection?
4602       else
4603         GNUNET_break(0);
4604       return;                       // Drop message
4605     }
4606     (*n)++;
4607   }
4608   queue = GNUNET_malloc (sizeof (struct MeshPeerQueue));
4609   queue->cls = cls;
4610   queue->type = type;
4611   queue->size = size;
4612   queue->peer = dst;
4613   queue->tunnel = t;
4614   GNUNET_CONTAINER_DLL_insert_tail (dst->queue_head, dst->queue_tail, queue);
4615   if (NULL == dst->core_transmit)
4616   {
4617       struct GNUNET_PeerIdentity id;
4618
4619       GNUNET_PEER_resolve (dst->id, &id);
4620       dst->core_transmit =
4621           GNUNET_CORE_notify_transmit_ready(core_handle,
4622                                             0,
4623                                             0,
4624                                             GNUNET_TIME_UNIT_FOREVER_REL,
4625                                             &id,
4626                                             size,
4627                                             &queue_send,
4628                                             dst);
4629   }
4630 }
4631
4632
4633 /******************************************************************************/
4634 /********************      MESH NETWORK HANDLERS     **************************/
4635 /******************************************************************************/
4636
4637
4638 /**
4639  * Core handler for path creation
4640  *
4641  * @param cls closure
4642  * @param message message
4643  * @param peer peer identity this notification is about
4644  * @param atsi performance data
4645  * @param atsi_count number of records in 'atsi'
4646  *
4647  * @return GNUNET_OK to keep the connection open,
4648  *         GNUNET_SYSERR to close it (signal serious error)
4649  */
4650 static int
4651 handle_mesh_path_create (void *cls, const struct GNUNET_PeerIdentity *peer,
4652                          const struct GNUNET_MessageHeader *message,
4653                          const struct GNUNET_ATS_Information *atsi,
4654                          unsigned int atsi_count)
4655 {
4656   unsigned int own_pos;
4657   uint16_t size;
4658   uint16_t i;
4659   MESH_TunnelNumber tid;
4660   struct GNUNET_MESH_ManipulatePath *msg;
4661   struct GNUNET_PeerIdentity *pi;
4662   struct GNUNET_HashCode hash;
4663   struct MeshPeerPath *path;
4664   struct MeshPeerInfo *dest_peer_info;
4665   struct MeshPeerInfo *orig_peer_info;
4666   struct MeshTunnel *t;
4667
4668   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4669               "Received a path create msg [%s]\n",
4670               GNUNET_i2s (&my_full_id));
4671   size = ntohs (message->size);
4672   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
4673   {
4674     GNUNET_break_op (0);
4675     return GNUNET_OK;
4676   }
4677
4678   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
4679   if (size % sizeof (struct GNUNET_PeerIdentity))
4680   {
4681     GNUNET_break_op (0);
4682     return GNUNET_OK;
4683   }
4684   size /= sizeof (struct GNUNET_PeerIdentity);
4685   if (size < 2)
4686   {
4687     GNUNET_break_op (0);
4688     return GNUNET_OK;
4689   }
4690   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
4691   msg = (struct GNUNET_MESH_ManipulatePath *) message;
4692
4693   tid = ntohl (msg->tid);
4694   pi = (struct GNUNET_PeerIdentity *) &msg[1];
4695   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4696               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi), tid);
4697   t = tunnel_get (pi, tid);
4698   if (NULL == t) // FIXME only for INCOMING tunnels?
4699   {
4700     uint32_t opt;
4701
4702     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating tunnel\n");
4703     t = tunnel_new (GNUNET_PEER_intern (pi), tid, NULL, 0);
4704     if (NULL == t)
4705     {
4706       // FIXME notify failure
4707       return GNUNET_OK;
4708     }
4709     opt = ntohl (msg->opt);
4710     t->speed_min = (0 != (opt & MESH_TUNNEL_OPT_SPEED_MIN)) ?
4711                    GNUNET_YES : GNUNET_NO;
4712     t->nobuffer = (0 != (opt & MESH_TUNNEL_OPT_NOBUFFER)) ?
4713                   GNUNET_YES : GNUNET_NO;
4714
4715     if (GNUNET_YES == t->nobuffer)
4716     {
4717       t->bck_queue_max = 1;
4718       t->fwd_queue_max = 1;
4719     }
4720
4721     // FIXME only assign a local tid if a local client is interested (on demand)
4722     while (NULL != tunnel_get_incoming (next_local_tid))
4723       next_local_tid = (next_local_tid + 1) | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
4724     t->local_tid_dest = next_local_tid++;
4725     next_local_tid = next_local_tid | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
4726     // FIXME end
4727
4728     tunnel_reset_timeout (t);
4729     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
4730     if (GNUNET_OK !=
4731         GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
4732                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
4733     {
4734       tunnel_destroy (t);
4735       GNUNET_break (0);
4736       return GNUNET_OK;
4737     }
4738   }
4739   dest_peer_info =
4740       GNUNET_CONTAINER_multihashmap_get (peers, &pi[size - 1].hashPubKey);
4741   if (NULL == dest_peer_info)
4742   {
4743     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4744                 "  Creating PeerInfo for destination.\n");
4745     dest_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
4746     dest_peer_info->id = GNUNET_PEER_intern (&pi[size - 1]);
4747     GNUNET_CONTAINER_multihashmap_put (peers, &pi[size - 1].hashPubKey,
4748                                        dest_peer_info,
4749                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
4750   }
4751   orig_peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &pi->hashPubKey);
4752   if (NULL == orig_peer_info)
4753   {
4754     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4755                 "  Creating PeerInfo for origin.\n");
4756     orig_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
4757     orig_peer_info->id = GNUNET_PEER_intern (pi);
4758     GNUNET_CONTAINER_multihashmap_put (peers, &pi->hashPubKey, orig_peer_info,
4759                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
4760   }
4761   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
4762   path = path_new (size);
4763   own_pos = 0;
4764   for (i = 0; i < size; i++)
4765   {
4766     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
4767                 GNUNET_i2s (&pi[i]));
4768     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
4769     if (path->peers[i] == myid)
4770       own_pos = i;
4771   }
4772   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
4773   if (own_pos == 0)
4774   {
4775     /* cannot be self, must be 'not found' */
4776     /* create path: self not found in path through self */
4777     GNUNET_break_op (0);
4778     path_destroy (path);
4779     tunnel_destroy (t);
4780     return GNUNET_OK;
4781   }
4782   path_add_to_peers (path, GNUNET_NO);
4783   tunnel_add_path (t, path, own_pos);
4784   if (own_pos == size - 1)
4785   {
4786     /* It is for us! Send ack. */
4787     struct MeshTransmissionDescriptor *info;
4788
4789     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
4790     peer_info_add_path_to_origin (orig_peer_info, path, GNUNET_NO);
4791     if (NULL == t->peers)
4792     {
4793       /* New tunnel! Notify clients on data. */
4794       t->peers = GNUNET_CONTAINER_multihashmap_create (4);
4795     }
4796     GNUNET_break (GNUNET_SYSERR !=
4797                   GNUNET_CONTAINER_multihashmap_put (t->peers,
4798                                                      &my_full_id.hashPubKey,
4799                                                      peer_info_get
4800                                                      (&my_full_id),
4801                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE));
4802     info = GNUNET_malloc (sizeof (struct MeshTransmissionDescriptor));
4803     info->origin = &t->id;
4804     info->peer = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
4805     GNUNET_assert (NULL != info->peer);
4806     queue_add(info,
4807               GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
4808               sizeof (struct GNUNET_MESH_PathACK),
4809               info->peer,
4810               t);
4811   }
4812   else
4813   {
4814     struct MeshPeerPath *path2;
4815
4816     /* It's for somebody else! Retransmit. */
4817     path2 = path_duplicate (path);
4818     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Retransmitting.\n");
4819     peer_info_add_path (dest_peer_info, path2, GNUNET_NO);
4820     path2 = path_duplicate (path);
4821     peer_info_add_path_to_origin (orig_peer_info, path2, GNUNET_NO);
4822     send_create_path (dest_peer_info, path, t);
4823   }
4824   return GNUNET_OK;
4825 }
4826
4827
4828 /**
4829  * Core handler for path destruction
4830  *
4831  * @param cls closure
4832  * @param message message
4833  * @param peer peer identity this notification is about
4834  * @param atsi performance data
4835  * @param atsi_count number of records in 'atsi'
4836  *
4837  * @return GNUNET_OK to keep the connection open,
4838  *         GNUNET_SYSERR to close it (signal serious error)
4839  */
4840 static int
4841 handle_mesh_path_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
4842                           const struct GNUNET_MessageHeader *message,
4843                           const struct GNUNET_ATS_Information *atsi,
4844                           unsigned int atsi_count)
4845 {
4846   struct GNUNET_MESH_ManipulatePath *msg;
4847   struct GNUNET_PeerIdentity *pi;
4848   struct MeshPeerPath *path;
4849   struct MeshTunnel *t;
4850   unsigned int own_pos;
4851   unsigned int i;
4852   size_t size;
4853
4854   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4855               "Received a PATH DESTROY msg from %s\n", GNUNET_i2s (peer));
4856   size = ntohs (message->size);
4857   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
4858   {
4859     GNUNET_break_op (0);
4860     return GNUNET_OK;
4861   }
4862
4863   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
4864   if (size % sizeof (struct GNUNET_PeerIdentity))
4865   {
4866     GNUNET_break_op (0);
4867     return GNUNET_OK;
4868   }
4869   size /= sizeof (struct GNUNET_PeerIdentity);
4870   if (size < 2)
4871   {
4872     GNUNET_break_op (0);
4873     return GNUNET_OK;
4874   }
4875   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
4876
4877   msg = (struct GNUNET_MESH_ManipulatePath *) message;
4878   pi = (struct GNUNET_PeerIdentity *) &msg[1];
4879   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4880               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi),
4881               msg->tid);
4882   t = tunnel_get (pi, ntohl (msg->tid));
4883   if (NULL == t)
4884   {
4885     /* TODO notify back: we don't know this tunnel */
4886     GNUNET_break_op (0);
4887     return GNUNET_OK;
4888   }
4889   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
4890   path = path_new (size);
4891   own_pos = 0;
4892   for (i = 0; i < size; i++)
4893   {
4894     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
4895                 GNUNET_i2s (&pi[i]));
4896     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
4897     if (path->peers[i] == myid)
4898       own_pos = i;
4899   }
4900   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
4901   if (own_pos < path->length - 1)
4902     send_message (message, &pi[own_pos + 1], t);
4903   else
4904     send_client_tunnel_disconnect(t, NULL);
4905
4906   tunnel_delete_peer (t, path->peers[path->length - 1]);
4907   path_destroy (path);
4908   return GNUNET_OK;
4909 }
4910
4911
4912 /**
4913  * Core handler for notifications of broken paths
4914  *
4915  * @param cls closure
4916  * @param message message
4917  * @param peer peer identity this notification is about
4918  * @param atsi performance data
4919  * @param atsi_count number of records in 'atsi'
4920  *
4921  * @return GNUNET_OK to keep the connection open,
4922  *         GNUNET_SYSERR to close it (signal serious error)
4923  */
4924 static int
4925 handle_mesh_path_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
4926                          const struct GNUNET_MessageHeader *message,
4927                          const struct GNUNET_ATS_Information *atsi,
4928                          unsigned int atsi_count)
4929 {
4930   struct GNUNET_MESH_PathBroken *msg;
4931   struct MeshTunnel *t;
4932
4933   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4934               "Received a PATH BROKEN msg from %s\n", GNUNET_i2s (peer));
4935   msg = (struct GNUNET_MESH_PathBroken *) message;
4936   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
4937               GNUNET_i2s (&msg->peer1));
4938   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
4939               GNUNET_i2s (&msg->peer2));
4940   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4941   if (NULL == t)
4942   {
4943     GNUNET_break_op (0);
4944     return GNUNET_OK;
4945   }
4946   tunnel_notify_connection_broken (t, GNUNET_PEER_search (&msg->peer1),
4947                                    GNUNET_PEER_search (&msg->peer2));
4948   return GNUNET_OK;
4949
4950 }
4951
4952
4953 /**
4954  * Core handler for tunnel destruction
4955  *
4956  * @param cls closure
4957  * @param message message
4958  * @param peer peer identity this notification is about
4959  * @param atsi performance data
4960  * @param atsi_count number of records in 'atsi'
4961  *
4962  * @return GNUNET_OK to keep the connection open,
4963  *         GNUNET_SYSERR to close it (signal serious error)
4964  */
4965 static int
4966 handle_mesh_tunnel_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
4967                             const struct GNUNET_MessageHeader *message,
4968                             const struct GNUNET_ATS_Information *atsi,
4969                             unsigned int atsi_count)
4970 {
4971   struct GNUNET_MESH_TunnelDestroy *msg;
4972   struct MeshTunnel *t;
4973
4974   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4975               "Got a TUNNEL DESTROY packet from %s\n", GNUNET_i2s (peer));
4976   msg = (struct GNUNET_MESH_TunnelDestroy *) message;
4977   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for tunnel %s [%u]\n",
4978               GNUNET_i2s (&msg->oid), ntohl (msg->tid));
4979   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4980   if (NULL == t)
4981   {
4982     /* Probably already got the message from another path,
4983      * destroyed the tunnel and retransmitted to children.
4984      * Safe to ignore.
4985      */
4986     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel", 1, GNUNET_NO);
4987     return GNUNET_OK;
4988   }
4989   if (t->id.oid == myid)
4990   {
4991     GNUNET_break_op (0);
4992     return GNUNET_OK;
4993   }
4994   if (t->local_tid_dest >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
4995   {
4996     /* Tunnel was incoming, notify clients */
4997     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "INCOMING TUNNEL %X %X\n",
4998                 t->local_tid, t->local_tid_dest);
4999     send_clients_tunnel_destroy (t);
5000   }
5001   tunnel_send_destroy (t);
5002   t->destroy = GNUNET_YES;
5003   // TODO: add timeout to destroy the tunnel anyway
5004   return GNUNET_OK;
5005 }
5006
5007
5008 /**
5009  * Core handler for mesh network traffic going from the origin to a peer
5010  *
5011  * @param cls closure
5012  * @param peer peer identity this notification is about
5013  * @param message message
5014  * @param atsi performance data
5015  * @param atsi_count number of records in 'atsi'
5016  * @return GNUNET_OK to keep the connection open,
5017  *         GNUNET_SYSERR to close it (signal serious error)
5018  */
5019 static int
5020 handle_mesh_data_unicast (void *cls, const struct GNUNET_PeerIdentity *peer,
5021                           const struct GNUNET_MessageHeader *message,
5022                           const struct GNUNET_ATS_Information *atsi,
5023                           unsigned int atsi_count)
5024 {
5025   struct GNUNET_MESH_Unicast *msg;
5026   struct GNUNET_PeerIdentity *neighbor;
5027   struct MeshTunnelChildInfo *cinfo;
5028   struct MeshTunnel *t;
5029   GNUNET_PEER_Id dest_id;
5030   uint32_t pid;
5031   uint32_t ttl;
5032   size_t size;
5033
5034   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a unicast packet from %s\n",
5035               GNUNET_i2s (peer));
5036   /* Check size */
5037   size = ntohs (message->size);
5038   if (size <
5039       sizeof (struct GNUNET_MESH_Unicast) +
5040       sizeof (struct GNUNET_MessageHeader))
5041   {
5042     GNUNET_break (0);
5043     return GNUNET_OK;
5044   }
5045   msg = (struct GNUNET_MESH_Unicast *) message;
5046   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %s\n",
5047               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
5048   /* Check tunnel */
5049   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5050   if (NULL == t)
5051   {
5052     /* TODO notify back: we don't know this tunnel */
5053     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
5054     GNUNET_break_op (0);
5055     return GNUNET_OK;
5056   }
5057   pid = ntohl (msg->pid);
5058   if (t->fwd_pid == pid)
5059   {
5060     GNUNET_STATISTICS_update (stats, "# duplicate PID drops", 1, GNUNET_NO);
5061     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5062                 " Already seen pid %u, DROPPING!\n", pid);
5063     return GNUNET_OK;
5064   }
5065   else
5066   {
5067     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5068                 " pid %u not seen yet, forwarding\n", pid);
5069   }
5070   t->skip += (pid - t->fwd_pid) - 1;
5071   t->fwd_pid = pid;
5072   if (is_pid_bigger (pid, t->last_fwd_ack))
5073   {
5074     GNUNET_STATISTICS_update (stats, "# unsolicited unicast", 1, GNUNET_NO);
5075     GNUNET_break_op (0);
5076     return GNUNET_OK;
5077   }
5078   tunnel_reset_timeout (t);
5079   dest_id = GNUNET_PEER_search (&msg->destination);
5080   if (dest_id == myid)
5081   {
5082     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5083                 "  it's for us! sending to clients...\n");
5084     GNUNET_STATISTICS_update (stats, "# unicast received", 1, GNUNET_NO);
5085     send_subscribed_clients (message, (struct GNUNET_MessageHeader *) &msg[1]);
5086     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_UNICAST);
5087     return GNUNET_OK;
5088   }
5089   ttl = ntohl (msg->ttl);
5090   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ttl);
5091   if (ttl == 0)
5092   {
5093     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
5094     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
5095     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5096     return GNUNET_OK;
5097   }
5098   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5099               "  not for us, retransmitting...\n");
5100
5101   neighbor = tree_get_first_hop (t->tree, dest_id);
5102   cinfo = tunnel_get_neighbor_fc (t, neighbor);
5103   cinfo->pid = pid;
5104   GNUNET_CONTAINER_multihashmap_iterate (t->children_fc,
5105                                          &tunnel_add_skip,
5106                                          &neighbor);
5107   if (is_pid_bigger (pid, cinfo->fwd_ack))
5108   {
5109     GNUNET_STATISTICS_update (stats, "# unsolicited unicast", 1, GNUNET_NO);
5110     GNUNET_break_op (0);
5111     return GNUNET_OK;
5112   }
5113   send_message (message, neighbor, t);
5114   GNUNET_STATISTICS_update (stats, "# unicast forwarded", 1, GNUNET_NO);
5115
5116   return GNUNET_OK;
5117 }
5118
5119
5120 /**
5121  * Core handler for mesh network traffic going from the origin to all peers
5122  *
5123  * @param cls closure
5124  * @param message message
5125  * @param peer peer identity this notification is about
5126  * @param atsi performance data
5127  * @param atsi_count number of records in 'atsi'
5128  * @return GNUNET_OK to keep the connection open,
5129  *         GNUNET_SYSERR to close it (signal serious error)
5130  *
5131  * TODO: Check who we got this from, to validate route.
5132  */
5133 static int
5134 handle_mesh_data_multicast (void *cls, const struct GNUNET_PeerIdentity *peer,
5135                             const struct GNUNET_MessageHeader *message,
5136                             const struct GNUNET_ATS_Information *atsi,
5137                             unsigned int atsi_count)
5138 {
5139   struct GNUNET_MESH_Multicast *msg;
5140   struct MeshTunnel *t;
5141   size_t size;
5142   uint32_t pid;
5143
5144   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a multicast packet from %s\n",
5145               GNUNET_i2s (peer));
5146   size = ntohs (message->size);
5147   if (sizeof (struct GNUNET_MESH_Multicast) +
5148       sizeof (struct GNUNET_MessageHeader) > size)
5149   {
5150     GNUNET_break_op (0);
5151     return GNUNET_OK;
5152   }
5153   msg = (struct GNUNET_MESH_Multicast *) message;
5154   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5155
5156   if (NULL == t)
5157   {
5158     /* TODO notify that we dont know that tunnel */
5159     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
5160     GNUNET_break_op (0);
5161     return GNUNET_OK;
5162   }
5163   pid = ntohl (msg->pid);
5164   if (t->fwd_pid == pid)
5165   {
5166     /* already seen this packet, drop */
5167     GNUNET_STATISTICS_update (stats, "# duplicate PID drops", 1, GNUNET_NO);
5168     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5169                 " Already seen pid %u, DROPPING!\n", pid);
5170     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5171     return GNUNET_OK;
5172   }
5173   else
5174   {
5175     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5176                 " pid %u not seen yet, forwarding\n", pid);
5177   }
5178   t->skip += (pid - t->fwd_pid) - 1;
5179   t->fwd_pid = pid;
5180   tunnel_reset_timeout (t);
5181
5182   /* Transmit to locally interested clients */
5183   if (NULL != t->peers &&
5184       GNUNET_CONTAINER_multihashmap_contains (t->peers, &my_full_id.hashPubKey))
5185   {
5186     GNUNET_STATISTICS_update (stats, "# multicast received", 1, GNUNET_NO);
5187     send_subscribed_clients (message, &msg[1].header);
5188     tunnel_send_fwd_ack(t, GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
5189   }
5190   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ntohl (msg->ttl));
5191   if (ntohl (msg->ttl) == 0)
5192   {
5193     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
5194     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
5195     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5196     return GNUNET_OK;
5197   }
5198   GNUNET_STATISTICS_update (stats, "# multicast forwarded", 1, GNUNET_NO);
5199   tunnel_send_multicast (t, message, GNUNET_NO);
5200   return GNUNET_OK;
5201 }
5202
5203
5204 /**
5205  * Core handler for mesh network traffic toward the owner of a tunnel
5206  *
5207  * @param cls closure
5208  * @param message message
5209  * @param peer peer identity this notification is about
5210  * @param atsi performance data
5211  * @param atsi_count number of records in 'atsi'
5212  *
5213  * @return GNUNET_OK to keep the connection open,
5214  *         GNUNET_SYSERR to close it (signal serious error)
5215  */
5216 static int
5217 handle_mesh_data_to_orig (void *cls, const struct GNUNET_PeerIdentity *peer,
5218                           const struct GNUNET_MessageHeader *message,
5219                           const struct GNUNET_ATS_Information *atsi,
5220                           unsigned int atsi_count)
5221 {
5222   struct GNUNET_MESH_ToOrigin *msg;
5223   struct GNUNET_PeerIdentity id;
5224   struct MeshPeerInfo *peer_info;
5225   struct MeshTunnel *t;
5226   size_t size;
5227
5228   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a ToOrigin packet from %s\n",
5229               GNUNET_i2s (peer));
5230   size = ntohs (message->size);
5231   if (size < sizeof (struct GNUNET_MESH_ToOrigin) +     /* Payload must be */
5232       sizeof (struct GNUNET_MessageHeader))     /* at least a header */
5233   {
5234     GNUNET_break_op (0);
5235     return GNUNET_OK;
5236   }
5237   msg = (struct GNUNET_MESH_ToOrigin *) message;
5238   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %s\n",
5239               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
5240   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5241
5242   if (NULL == t)
5243   {
5244     /* TODO notify that we dont know this tunnel (whom)? */
5245     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
5246     GNUNET_break_op (0);
5247     return GNUNET_OK;
5248   }
5249
5250   if (NULL != t->owner)
5251   {
5252     char cbuf[size];
5253     struct GNUNET_MESH_ToOrigin *copy;
5254
5255     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5256                 "  it's for us! sending to clients...\n");
5257     /* TODO signature verification */
5258     memcpy (cbuf, message, size);
5259     copy = (struct GNUNET_MESH_ToOrigin *) cbuf;
5260     copy->tid = htonl (t->local_tid);
5261     GNUNET_STATISTICS_update (stats, "# to origin received", 1, GNUNET_NO);
5262     GNUNET_SERVER_notification_context_unicast (nc, t->owner->handle,
5263                                                 &copy->header, GNUNET_NO);
5264     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
5265     return GNUNET_OK;
5266   }
5267   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5268               "  not for us, retransmitting...\n");
5269
5270   peer_info = peer_info_get (&msg->oid);
5271   if (NULL == peer_info)
5272   {
5273     /* unknown origin of tunnel */
5274     GNUNET_break (0);
5275     return GNUNET_OK;
5276   }
5277   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
5278   send_message (message, &id, t);
5279   GNUNET_STATISTICS_update (stats, "# to origin forwarded", 1, GNUNET_NO);
5280
5281   return GNUNET_OK;
5282 }
5283
5284
5285 /**
5286  * Core handler for mesh network traffic point-to-point acks.
5287  *
5288  * @param cls closure
5289  * @param message message
5290  * @param peer peer identity this notification is about
5291  * @param atsi performance data
5292  * @param atsi_count number of records in 'atsi'
5293  *
5294  * @return GNUNET_OK to keep the connection open,
5295  *         GNUNET_SYSERR to close it (signal serious error)
5296  */
5297 static int
5298 handle_mesh_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5299                  const struct GNUNET_MessageHeader *message,
5300                  const struct GNUNET_ATS_Information *atsi,
5301                  unsigned int atsi_count)
5302 {
5303   struct GNUNET_MESH_ACK *msg;
5304   struct MeshTunnel *t;
5305   uint32_t ack;
5306
5307   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK packet from %s!\n",
5308               GNUNET_i2s (peer));
5309   msg = (struct GNUNET_MESH_ACK *) message;
5310   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %s\n",
5311               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
5312   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5313
5314   if (NULL == t)
5315   {
5316     /* TODO notify that we dont know this tunnel (whom)? */
5317     GNUNET_STATISTICS_update (stats, "# ack on unknown tunnel", 1, GNUNET_NO);
5318     GNUNET_break_op (0);
5319     return GNUNET_OK;
5320   }
5321   ack = ntohl (msg->pid);
5322
5323   /* Is this a forward or backward ACK? */
5324   if (tree_get_predecessor(t->tree) == GNUNET_PEER_search(peer))
5325   {
5326     struct MeshTunnelChildInfo *cinfo;
5327
5328     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
5329     cinfo = tunnel_get_neighbor_fc (t, peer);
5330     cinfo->fwd_ack = ack;
5331     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5332   }
5333   else
5334   {
5335     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
5336     t->bck_ack = ack;
5337     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5338   }
5339   // FIXME fc Unlock queues?
5340   return GNUNET_OK;
5341 }
5342
5343
5344 /**
5345  * Core handler for path ACKs
5346  *
5347  * @param cls closure
5348  * @param message message
5349  * @param peer peer identity this notification is about
5350  * @param atsi performance data
5351  * @param atsi_count number of records in 'atsi'
5352  *
5353  * @return GNUNET_OK to keep the connection open,
5354  *         GNUNET_SYSERR to close it (signal serious error)
5355  */
5356 static int
5357 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5358                       const struct GNUNET_MessageHeader *message,
5359                       const struct GNUNET_ATS_Information *atsi,
5360                       unsigned int atsi_count)
5361 {
5362   struct GNUNET_MESH_PathACK *msg;
5363   struct GNUNET_PeerIdentity id;
5364   struct MeshPeerInfo *peer_info;
5365   struct MeshPeerPath *p;
5366   struct MeshTunnel *t;
5367
5368   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a path ACK msg [%s]\n",
5369               GNUNET_i2s (&my_full_id));
5370   msg = (struct GNUNET_MESH_PathACK *) message;
5371   t = tunnel_get (&msg->oid, ntohl(msg->tid));
5372   if (NULL == t)
5373   {
5374     /* TODO notify that we don't know the tunnel */
5375     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel", 1, GNUNET_NO);
5376     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  don't know the tunnel %s [%X]!\n",
5377                 GNUNET_i2s (&msg->oid), ntohl(msg->tid));
5378     return GNUNET_OK;
5379   }
5380   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %s [%X]\n",
5381               GNUNET_i2s (&msg->oid), ntohl(msg->tid));
5382
5383   peer_info = peer_info_get (&msg->peer_id);
5384   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by peer %s\n",
5385               GNUNET_i2s (&msg->peer_id));
5386   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  via peer %s\n",
5387               GNUNET_i2s (peer));
5388
5389   if (NULL != t->regex_ctx && t->regex_ctx->info->peer == peer_info->id)
5390   {
5391     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5392                 "connect_by_string completed, stopping search\n");
5393     regex_cancel_search (t->regex_ctx);
5394     t->regex_ctx = NULL;
5395   }
5396
5397   /* Add paths to peers? */
5398   p = tree_get_path_to_peer (t->tree, peer_info->id);
5399   if (NULL != p)
5400   {
5401     path_add_to_peers (p, GNUNET_YES);
5402     path_destroy (p);
5403   }
5404   else
5405   {
5406     GNUNET_break (0);
5407   }
5408
5409   /* Message for us? */
5410   if (0 == memcmp (&msg->oid, &my_full_id, sizeof (struct GNUNET_PeerIdentity)))
5411   {
5412     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
5413     if (NULL == t->owner)
5414     {
5415       GNUNET_break_op (0);
5416       return GNUNET_OK;
5417     }
5418     if (NULL != t->dht_get_type)
5419     {
5420       GNUNET_DHT_get_stop (t->dht_get_type);
5421       t->dht_get_type = NULL;
5422     }
5423     if (tree_get_status (t->tree, peer_info->id) != MESH_PEER_READY)
5424     {
5425       tree_set_status (t->tree, peer_info->id, MESH_PEER_READY);
5426       send_client_peer_connected (t, peer_info->id);
5427     }
5428     return GNUNET_OK;
5429   }
5430
5431   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5432               "  not for us, retransmitting...\n");
5433   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
5434   peer_info = peer_info_get (&msg->oid);
5435   if (NULL == peer_info)
5436   {
5437     /* If we know the tunnel, we should DEFINITELY know the peer */
5438     GNUNET_break (0);
5439     return GNUNET_OK;
5440   }
5441   send_message (message, &id, t);
5442   return GNUNET_OK;
5443 }
5444
5445
5446 /**
5447  * Functions to handle messages from core
5448  */
5449 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
5450   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
5451   {&handle_mesh_path_destroy, GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY, 0},
5452   {&handle_mesh_path_broken, GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN,
5453    sizeof (struct GNUNET_MESH_PathBroken)},
5454   {&handle_mesh_tunnel_destroy, GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY,
5455    sizeof (struct GNUNET_MESH_TunnelDestroy)},
5456   {&handle_mesh_data_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
5457   {&handle_mesh_data_multicast, GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
5458   {&handle_mesh_data_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
5459   {&handle_mesh_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
5460     sizeof (struct GNUNET_MESH_ACK)},
5461   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
5462    sizeof (struct GNUNET_MESH_PathACK)},
5463   {NULL, 0, 0}
5464 };
5465
5466
5467
5468 /******************************************************************************/
5469 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
5470 /******************************************************************************/
5471
5472 /**
5473  * deregister_app: iterator for removing each application registered by a client
5474  *
5475  * @param cls closure
5476  * @param key the hash of the application id (used to access the hashmap)
5477  * @param value the value stored at the key (client)
5478  *
5479  * @return GNUNET_OK on success
5480  */
5481 static int
5482 deregister_app (void *cls, const struct GNUNET_HashCode * key, void *value)
5483 {
5484   struct GNUNET_CONTAINER_MultiHashMap *h = cls;
5485   GNUNET_break (GNUNET_YES ==
5486                 GNUNET_CONTAINER_multihashmap_remove (h, key, value));
5487   return GNUNET_OK;
5488 }
5489
5490 #if LATER
5491 /**
5492  * notify_client_connection_failure: notify a client that the connection to the
5493  * requested remote peer is not possible (for instance, no route found)
5494  * Function called when the socket is ready to queue more data. "buf" will be
5495  * NULL and "size" zero if the socket was closed for writing in the meantime.
5496  *
5497  * @param cls closure
5498  * @param size number of bytes available in buf
5499  * @param buf where the callee should write the message
5500  * @return number of bytes written to buf
5501  */
5502 static size_t
5503 notify_client_connection_failure (void *cls, size_t size, void *buf)
5504 {
5505   int size_needed;
5506   struct MeshPeerInfo *peer_info;
5507   struct GNUNET_MESH_PeerControl *msg;
5508   struct GNUNET_PeerIdentity id;
5509
5510   if (0 == size && NULL == buf)
5511   {
5512     // TODO retry? cancel?
5513     return 0;
5514   }
5515
5516   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
5517   peer_info = (struct MeshPeerInfo *) cls;
5518   msg = (struct GNUNET_MESH_PeerControl *) buf;
5519   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
5520   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
5521 //     msg->tunnel_id = htonl(peer_info->t->tid);
5522   GNUNET_PEER_resolve (peer_info->id, &id);
5523   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
5524
5525   return size_needed;
5526 }
5527 #endif
5528
5529
5530 /**
5531  * Send keepalive packets for a peer
5532  *
5533  * @param cls Closure (tunnel for which to send the keepalive).
5534  * @param tc Notification context.
5535  *
5536  * TODO: implement explicit multicast keepalive?
5537  */
5538 static void
5539 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
5540 {
5541   struct MeshTunnel *t = cls;
5542   struct GNUNET_MessageHeader *payload;
5543   struct GNUNET_MESH_Multicast *msg;
5544   size_t size =
5545       sizeof (struct GNUNET_MESH_Multicast) +
5546       sizeof (struct GNUNET_MessageHeader);
5547   char cbuf[size];
5548
5549   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
5550   {
5551     return;
5552   }
5553   t->path_refresh_task = GNUNET_SCHEDULER_NO_TASK;
5554
5555   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5556               "sending keepalive for tunnel %d\n", t->id.tid);
5557
5558   msg = (struct GNUNET_MESH_Multicast *) cbuf;
5559   msg->header.size = htons (size);
5560   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
5561   msg->oid = my_full_id;
5562   msg->tid = htonl (t->id.tid);
5563   msg->ttl = htonl (default_ttl);
5564   msg->pid = htonl (t->fwd_pid + 1);
5565   t->fwd_pid++;
5566   payload = (struct GNUNET_MessageHeader *) &msg[1];
5567   payload->size = htons (sizeof (struct GNUNET_MessageHeader));
5568   payload->type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE);
5569   tunnel_send_multicast (t, &msg->header, GNUNET_YES);
5570
5571   t->path_refresh_task =
5572       GNUNET_SCHEDULER_add_delayed (refresh_path_time, &path_refresh, t);
5573   return;
5574 }
5575
5576
5577 /**
5578  * Function to process paths received for a new peer addition. The recorded
5579  * paths form the initial tunnel, which can be optimized later.
5580  * Called on each result obtained for the DHT search.
5581  *
5582  * @param cls closure
5583  * @param exp when will this value expire
5584  * @param key key of the result
5585  * @param get_path path of the get request
5586  * @param get_path_length lenght of get_path
5587  * @param put_path path of the put request
5588  * @param put_path_length length of the put_path
5589  * @param type type of the result
5590  * @param size number of bytes in data
5591  * @param data pointer to the result data
5592  *
5593  * TODO: re-issue the request after certain time? cancel after X results?
5594  */
5595 static void
5596 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
5597                     const struct GNUNET_HashCode * key,
5598                     const struct GNUNET_PeerIdentity *get_path,
5599                     unsigned int get_path_length,
5600                     const struct GNUNET_PeerIdentity *put_path,
5601                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
5602                     size_t size, const void *data)
5603 {
5604   struct MeshPathInfo *path_info = cls;
5605   struct MeshPeerPath *p;
5606   struct GNUNET_PeerIdentity pi;
5607   int i;
5608
5609   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
5610   GNUNET_PEER_resolve (path_info->peer->id, &pi);
5611   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", GNUNET_i2s (&pi));
5612
5613   p = path_build_from_dht (get_path, get_path_length, put_path,
5614                            put_path_length);
5615   path_add_to_peers (p, GNUNET_NO);
5616   path_destroy(p);
5617   for (i = 0; i < path_info->peer->ntunnels; i++)
5618   {
5619     tunnel_add_peer (path_info->peer->tunnels[i], path_info->peer);
5620     peer_info_connect (path_info->peer, path_info->t);
5621   }
5622
5623   return;
5624 }
5625
5626
5627 /**
5628  * Function to process paths received for a new peer addition. The recorded
5629  * paths form the initial tunnel, which can be optimized later.
5630  * Called on each result obtained for the DHT search.
5631  *
5632  * @param cls closure
5633  * @param exp when will this value expire
5634  * @param key key of the result
5635  * @param get_path path of the get request
5636  * @param get_path_length lenght of get_path
5637  * @param put_path path of the put request
5638  * @param put_path_length length of the put_path
5639  * @param type type of the result
5640  * @param size number of bytes in data
5641  * @param data pointer to the result data
5642  */
5643 static void
5644 dht_get_type_handler (void *cls, struct GNUNET_TIME_Absolute exp,
5645                       const struct GNUNET_HashCode * key,
5646                       const struct GNUNET_PeerIdentity *get_path,
5647                       unsigned int get_path_length,
5648                       const struct GNUNET_PeerIdentity *put_path,
5649                       unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
5650                       size_t size, const void *data)
5651 {
5652   const struct PBlock *pb = data;
5653   const struct GNUNET_PeerIdentity *pi = &pb->id;
5654   struct MeshTunnel *t = cls;
5655   struct MeshPeerInfo *peer_info;
5656   struct MeshPeerPath *p;
5657
5658   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got type DHT result!\n");
5659   if (size != sizeof (struct PBlock))
5660   {
5661     GNUNET_break_op (0);
5662     return;
5663   }
5664   if (ntohl(pb->type) != t->type)
5665   {
5666     GNUNET_break_op (0);
5667     return;
5668   }
5669   GNUNET_assert (NULL != t->owner);
5670   peer_info = peer_info_get (pi);
5671   (void) GNUNET_CONTAINER_multihashmap_put (t->peers, &pi->hashPubKey,
5672                                             peer_info,
5673                                             GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
5674
5675   p = path_build_from_dht (get_path, get_path_length, put_path,
5676                            put_path_length);
5677   path_add_to_peers (p, GNUNET_NO);
5678   path_destroy(p);
5679   tunnel_add_peer (t, peer_info);
5680   peer_info_connect (peer_info, t);
5681 }
5682
5683
5684 /**
5685  * Function to process DHT string to regex matching.
5686  * Called on each result obtained for the DHT search.
5687  *
5688  * @param cls closure (search context)
5689  * @param exp when will this value expire
5690  * @param key key of the result
5691  * @param get_path path of the get request (not used)
5692  * @param get_path_length lenght of get_path (not used)
5693  * @param put_path path of the put request (not used)
5694  * @param put_path_length length of the put_path (not used)
5695  * @param type type of the result
5696  * @param size number of bytes in data
5697  * @param data pointer to the result data
5698  */
5699 static void
5700 dht_get_string_accept_handler (void *cls, struct GNUNET_TIME_Absolute exp,
5701                                const struct GNUNET_HashCode * key,
5702                                const struct GNUNET_PeerIdentity *get_path,
5703                                unsigned int get_path_length,
5704                                const struct GNUNET_PeerIdentity *put_path,
5705                                unsigned int put_path_length,
5706                                enum GNUNET_BLOCK_Type type,
5707                                size_t size, const void *data)
5708 {
5709   const struct MeshRegexAccept *block = data;
5710   struct MeshRegexSearchContext *ctx = cls;
5711   struct MeshRegexSearchInfo *info = ctx->info;
5712   struct MeshPeerPath *p;
5713   struct MeshPeerInfo *peer_info;
5714
5715   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got regex results from DHT!\n");
5716   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", info->description);
5717
5718   peer_info = peer_info_get(&block->id);
5719   p = path_build_from_dht (get_path, get_path_length, put_path,
5720                            put_path_length);
5721   path_add_to_peers (p, GNUNET_NO);
5722   path_destroy(p);
5723
5724   tunnel_add_peer (info->t, peer_info);
5725   peer_info_connect (peer_info, info->t);
5726   if (0 == info->peer)
5727   {
5728     info->peer = peer_info->id;
5729   }
5730   else
5731   {
5732     GNUNET_array_append (info->peers, info->n_peers, peer_info->id);
5733   }
5734
5735   info->timeout = GNUNET_SCHEDULER_add_delayed (connect_timeout,
5736                                                 &regex_connect_timeout,
5737                                                 info);
5738
5739   return;
5740 }
5741
5742
5743 /**
5744  * Function to process DHT string to regex matching.
5745  * Called on each result obtained for the DHT search.
5746  *
5747  * @param cls closure (search context)
5748  * @param exp when will this value expire
5749  * @param key key of the result
5750  * @param get_path path of the get request (not used)
5751  * @param get_path_length lenght of get_path (not used)
5752  * @param put_path path of the put request (not used)
5753  * @param put_path_length length of the put_path (not used)
5754  * @param type type of the result
5755  * @param size number of bytes in data
5756  * @param data pointer to the result data
5757  *
5758  * TODO: re-issue the request after certain time? cancel after X results?
5759  */
5760 static void
5761 dht_get_string_handler (void *cls, struct GNUNET_TIME_Absolute exp,
5762                         const struct GNUNET_HashCode * key,
5763                         const struct GNUNET_PeerIdentity *get_path,
5764                         unsigned int get_path_length,
5765                         const struct GNUNET_PeerIdentity *put_path,
5766                         unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
5767                         size_t size, const void *data)
5768 {
5769   const struct MeshRegexBlock *block = data;
5770   struct MeshRegexSearchContext *ctx = cls;
5771   struct MeshRegexSearchInfo *info = ctx->info;
5772   void *copy;
5773   size_t len;
5774
5775   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5776               "DHT GET STRING RETURNED RESULTS\n");
5777   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5778               "  key: %s\n", GNUNET_h2s (key));
5779
5780   copy = GNUNET_malloc (size);
5781   memcpy (copy, data, size);
5782   GNUNET_break (GNUNET_OK ==
5783                 GNUNET_CONTAINER_multihashmap_put(info->dht_get_results, key, copy,
5784                                                   GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
5785   len = ntohl (block->n_proof);
5786   {
5787     char proof[len + 1];
5788
5789     memcpy (proof, &block[1], len);
5790     proof[len] = '\0';
5791     if (GNUNET_OK != GNUNET_REGEX_check_proof (proof, key))
5792     {
5793       GNUNET_break_op (0);
5794       return;
5795     }
5796   }
5797   len = strlen (info->description);
5798   if (len == ctx->position) // String processed
5799   {
5800     if (GNUNET_YES == ntohl (block->accepting))
5801     {
5802       regex_find_path(key, ctx);
5803     }
5804     else
5805     {
5806       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  block not accepting!\n");
5807       // FIXME REGEX this block not successful, wait for more? start timeout?
5808     }
5809     return;
5810   }
5811   GNUNET_break (GNUNET_OK ==
5812                 GNUNET_MESH_regex_block_iterate (block, size,
5813                                                  &regex_edge_iterator, ctx));
5814   return;
5815 }
5816
5817 /******************************************************************************/
5818 /*********************       MESH LOCAL HANDLES      **************************/
5819 /******************************************************************************/
5820
5821
5822 /**
5823  * Handler for client disconnection
5824  *
5825  * @param cls closure
5826  * @param client identification of the client; NULL
5827  *        for the last call when the server is destroyed
5828  */
5829 static void
5830 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
5831 {
5832   struct MeshClient *c;
5833   struct MeshClient *next;
5834   unsigned int i;
5835
5836   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected\n");
5837   if (client == NULL)
5838   {
5839     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (SERVER DOWN)\n");
5840     return;
5841   }
5842   c = clients;
5843   while (NULL != c)
5844   {
5845     if (c->handle != client)
5846     {
5847       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ... searching\n");
5848       c = c->next;
5849       continue;
5850     }
5851     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u)\n",
5852                 c->id);
5853     GNUNET_SERVER_client_drop (c->handle);
5854     c->shutting_down = GNUNET_YES;
5855     GNUNET_assert (NULL != c->own_tunnels);
5856     GNUNET_assert (NULL != c->incoming_tunnels);
5857     GNUNET_CONTAINER_multihashmap_iterate (c->own_tunnels,
5858                                            &tunnel_destroy_iterator, c);
5859     GNUNET_CONTAINER_multihashmap_iterate (c->incoming_tunnels,
5860                                            &tunnel_destroy_iterator, c);
5861     GNUNET_CONTAINER_multihashmap_iterate (c->ignore_tunnels,
5862                                            &tunnel_destroy_iterator, c);
5863     GNUNET_CONTAINER_multihashmap_destroy (c->own_tunnels);
5864     GNUNET_CONTAINER_multihashmap_destroy (c->incoming_tunnels);
5865     GNUNET_CONTAINER_multihashmap_destroy (c->ignore_tunnels);
5866
5867     /* deregister clients applications */
5868     if (NULL != c->apps)
5869     {
5870       GNUNET_CONTAINER_multihashmap_iterate (c->apps, &deregister_app, c->apps);
5871       GNUNET_CONTAINER_multihashmap_destroy (c->apps);
5872     }
5873     if (0 == GNUNET_CONTAINER_multihashmap_size (applications) &&
5874         GNUNET_SCHEDULER_NO_TASK != announce_applications_task)
5875     {
5876       GNUNET_SCHEDULER_cancel (announce_applications_task);
5877       announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
5878     }
5879     if (NULL != c->types)
5880       GNUNET_CONTAINER_multihashmap_destroy (c->types);
5881     for (i = 0; i < c->n_regex; i++)
5882     {
5883       GNUNET_free (c->regexes[i]);
5884     }
5885     GNUNET_free_non_null (c->regexes);
5886     if (GNUNET_SCHEDULER_NO_TASK != c->regex_announce_task)
5887       GNUNET_SCHEDULER_cancel (c->regex_announce_task);
5888     next = c->next;
5889     GNUNET_CONTAINER_DLL_remove (clients, clients_tail, c);
5890     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT FREE at %p\n", c);
5891     GNUNET_free (c);
5892     GNUNET_STATISTICS_update (stats, "# clients", -1, GNUNET_NO);
5893     c = next;
5894   }
5895   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   done!\n");
5896   return;
5897 }
5898
5899
5900 /**
5901  * Handler for new clients
5902  *
5903  * @param cls closure
5904  * @param client identification of the client
5905  * @param message the actual message, which includes messages the client wants
5906  */
5907 static void
5908 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
5909                          const struct GNUNET_MessageHeader *message)
5910 {
5911   struct GNUNET_MESH_ClientConnect *cc_msg;
5912   struct MeshClient *c;
5913   GNUNET_MESH_ApplicationType *a;
5914   unsigned int size;
5915   uint16_t ntypes;
5916   uint16_t *t;
5917   uint16_t napps;
5918   uint16_t i;
5919
5920   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected\n");
5921   /* Check data sanity */
5922   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
5923   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
5924   ntypes = ntohs (cc_msg->types);
5925   napps = ntohs (cc_msg->applications);
5926   if (size !=
5927       ntypes * sizeof (uint16_t) + napps * sizeof (GNUNET_MESH_ApplicationType))
5928   {
5929     GNUNET_break (0);
5930     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5931     return;
5932   }
5933
5934   /* Create new client structure */
5935   c = GNUNET_malloc (sizeof (struct MeshClient));
5936   c->id = next_client_id++;
5937   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT NEW %u\n", c->id);
5938   c->handle = client;
5939   GNUNET_SERVER_client_keep (client);
5940   a = (GNUNET_MESH_ApplicationType *) &cc_msg[1];
5941   if (napps > 0)
5942   {
5943     GNUNET_MESH_ApplicationType at;
5944     struct GNUNET_HashCode hc;
5945
5946     c->apps = GNUNET_CONTAINER_multihashmap_create (napps);
5947     for (i = 0; i < napps; i++)
5948     {
5949       at = ntohl (a[i]);
5950       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  app type: %u\n", at);
5951       GNUNET_CRYPTO_hash (&at, sizeof (at), &hc);
5952       /* store in clients hashmap */
5953       GNUNET_CONTAINER_multihashmap_put (c->apps, &hc, (void *) (long) at,
5954                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
5955       /* store in global hashmap, for announcements */
5956       GNUNET_CONTAINER_multihashmap_put (applications, &hc, c,
5957                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
5958     }
5959     if (GNUNET_SCHEDULER_NO_TASK == announce_applications_task)
5960       announce_applications_task =
5961           GNUNET_SCHEDULER_add_now (&announce_applications, NULL);
5962
5963   }
5964   if (ntypes > 0)
5965   {
5966     uint16_t u16;
5967     struct GNUNET_HashCode hc;
5968
5969     t = (uint16_t *) & a[napps];
5970     c->types = GNUNET_CONTAINER_multihashmap_create (ntypes);
5971     for (i = 0; i < ntypes; i++)
5972     {
5973       u16 = ntohs (t[i]);
5974       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  msg type: %u\n", u16);
5975       GNUNET_CRYPTO_hash (&u16, sizeof (u16), &hc);
5976
5977       /* store in clients hashmap */
5978       GNUNET_CONTAINER_multihashmap_put (c->types, &hc, c,
5979                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
5980       /* store in global hashmap */
5981       GNUNET_CONTAINER_multihashmap_put (types, &hc, c,
5982                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
5983     }
5984   }
5985   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5986               " client has %u+%u subscriptions\n", napps, ntypes);
5987
5988   GNUNET_CONTAINER_DLL_insert (clients, clients_tail, c);
5989   c->own_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
5990   c->incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
5991   c->ignore_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
5992   GNUNET_SERVER_notification_context_add (nc, client);
5993   GNUNET_STATISTICS_update (stats, "# clients", 1, GNUNET_NO);
5994
5995   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5996   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
5997 }
5998
5999
6000 /**
6001  * Handler for clients announcing available services by a regular expression.
6002  *
6003  * @param cls closure
6004  * @param client identification of the client
6005  * @param message the actual message, which includes messages the client wants
6006  */
6007 static void
6008 handle_local_announce_regex (void *cls, struct GNUNET_SERVER_Client *client,
6009                              const struct GNUNET_MessageHeader *message)
6010 {
6011   struct MeshClient *c;
6012   char *regex;
6013   size_t len;
6014
6015   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "announce regex started\n");
6016
6017   /* Sanity check for client registration */
6018   if (NULL == (c = client_get (client)))
6019   {
6020     GNUNET_break (0);
6021     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6022     return;
6023   }
6024   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6025
6026   len = ntohs (message->size) - sizeof(struct GNUNET_MessageHeader);
6027   regex = GNUNET_malloc (len + 1);
6028   memcpy (regex, &message[1], len);
6029   regex[len] = '\0';
6030   GNUNET_array_append (c->regexes, c->n_regex, regex);
6031   if (GNUNET_SCHEDULER_NO_TASK == c->regex_announce_task)
6032   {
6033     c->regex_announce_task = GNUNET_SCHEDULER_add_now(&announce_regex, c);
6034   }
6035   else
6036   {
6037     regex_put(regex);
6038   }
6039   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6040   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "announce regex processed\n");
6041 }
6042
6043
6044 /**
6045  * Handler for requests of new tunnels
6046  *
6047  * @param cls closure
6048  * @param client identification of the client
6049  * @param message the actual message
6050  */
6051 static void
6052 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
6053                             const struct GNUNET_MessageHeader *message)
6054 {
6055   struct GNUNET_MESH_TunnelMessage *t_msg;
6056   struct MeshTunnel *t;
6057   struct MeshClient *c;
6058   MESH_TunnelNumber tid;
6059
6060   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel requested\n");
6061
6062   /* Sanity check for client registration */
6063   if (NULL == (c = client_get (client)))
6064   {
6065     GNUNET_break (0);
6066     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6067     return;
6068   }
6069   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6070
6071   /* Message sanity check */
6072   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
6073   {
6074     GNUNET_break (0);
6075     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6076     return;
6077   }
6078
6079   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6080   /* Sanity check for tunnel numbering */
6081   tid = ntohl (t_msg->tunnel_id);
6082   if (0 == (tid & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
6083   {
6084     GNUNET_break (0);
6085     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6086     return;
6087   }
6088   /* Sanity check for duplicate tunnel IDs */
6089   if (NULL != tunnel_get_by_local_id (c, tid))
6090   {
6091     GNUNET_break (0);
6092     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6093     return;
6094   }
6095
6096   while (NULL != tunnel_get_by_pi (myid, next_tid))
6097     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
6098   t = tunnel_new (myid, next_tid++, c, tid);
6099   if (NULL == t)
6100   {
6101     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Tunnel creation failed.\n");
6102     GNUNET_break (0);
6103     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6104     return;
6105   }
6106   next_tid = next_tid & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
6107   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED TUNNEL %s [%x] (%x)\n",
6108               GNUNET_i2s (&my_full_id), t->id.tid, t->local_tid);
6109   t->peers = GNUNET_CONTAINER_multihashmap_create (32);
6110
6111   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel created\n");
6112   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6113   return;
6114 }
6115
6116
6117 /**
6118  * Handler for requests of deleting tunnels
6119  *
6120  * @param cls closure
6121  * @param client identification of the client
6122  * @param message the actual message
6123  */
6124 static void
6125 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
6126                              const struct GNUNET_MessageHeader *message)
6127 {
6128   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
6129   struct MeshClient *c;
6130   struct MeshTunnel *t;
6131   MESH_TunnelNumber tid;
6132
6133   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6134               "Got a DESTROY TUNNEL from client!\n");
6135
6136   /* Sanity check for client registration */
6137   if (NULL == (c = client_get (client)))
6138   {
6139     GNUNET_break (0);
6140     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6141     return;
6142   }
6143   /* Message sanity check */
6144   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
6145   {
6146     GNUNET_break (0);
6147     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6148     return;
6149   }
6150   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6151   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6152
6153   /* Retrieve tunnel */
6154   tid = ntohl (tunnel_msg->tunnel_id);
6155   t = tunnel_get_by_local_id(c, tid);
6156   if (NULL == t)
6157   {
6158     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
6159     GNUNET_break (0);
6160     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6161     return;
6162   }
6163   if (c != t->owner || tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
6164   {
6165     client_ignore_tunnel (c, t);
6166 #if 0
6167     // TODO: when to destroy incoming tunnel?
6168     if (t->nclients == 0)
6169     {
6170       GNUNET_assert (GNUNET_YES ==
6171                      GNUNET_CONTAINER_multihashmap_remove (incoming_tunnels,
6172                                                            &hash, t));
6173       GNUNET_assert (GNUNET_YES ==
6174                      GNUNET_CONTAINER_multihashmap_remove (t->peers,
6175                                                            &my_full_id.hashPubKey,
6176                                                            t));
6177     }
6178 #endif
6179     GNUNET_SERVER_receive_done (client, GNUNET_OK);
6180     return;
6181   }
6182   send_client_tunnel_disconnect(t, c);
6183   client_delete_tunnel(c, t);
6184
6185   /* Don't try to ACK the client about the tunnel_destroy multicast packet */
6186   t->owner = NULL;
6187   tunnel_send_destroy (t);
6188   t->destroy = GNUNET_YES;
6189   // The tunnel will be destroyed when the last message is transmitted.
6190   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6191   return;
6192 }
6193
6194
6195 /**
6196  * Handler for requests of seeting tunnel's speed.
6197  *
6198  * @param cls Closure (unused).
6199  * @param client Identification of the client.
6200  * @param message The actual message.
6201  */
6202 static void
6203 handle_local_tunnel_speed (void *cls, struct GNUNET_SERVER_Client *client,
6204                            const struct GNUNET_MessageHeader *message)
6205 {
6206   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
6207   struct MeshClient *c;
6208   struct MeshTunnel *t;
6209   MESH_TunnelNumber tid;
6210
6211   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6212               "Got a SPEED request from client!\n");
6213
6214   /* Sanity check for client registration */
6215   if (NULL == (c = client_get (client)))
6216   {
6217     GNUNET_break (0);
6218     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6219     return;
6220   }
6221
6222   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6223   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6224
6225   /* Retrieve tunnel */
6226   tid = ntohl (tunnel_msg->tunnel_id);
6227   t = tunnel_get_by_local_id(c, tid);
6228   if (NULL == t)
6229   {
6230     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  tunnel %X not found\n", tid);
6231     GNUNET_break (0);
6232     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6233     return;
6234   }
6235
6236   switch (ntohs(message->type))
6237   {
6238       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MIN:
6239           t->speed_min = GNUNET_YES;
6240           break;
6241       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MAX:
6242           t->speed_min = GNUNET_NO;
6243           break;
6244       default:
6245           GNUNET_break (0);
6246   }
6247   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6248 }
6249
6250
6251 /**
6252  * Handler for requests of seeting tunnel's buffering policy.
6253  *
6254  * @param cls Closure (unused).
6255  * @param client Identification of the client.
6256  * @param message The actual message.
6257  */
6258 static void
6259 handle_local_tunnel_buffer (void *cls, struct GNUNET_SERVER_Client *client,
6260                             const struct GNUNET_MessageHeader *message)
6261 {
6262   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
6263   struct MeshClient *c;
6264   struct MeshTunnel *t;
6265   MESH_TunnelNumber tid;
6266
6267   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6268               "Got a BUFFER request from client!\n");
6269
6270   /* Sanity check for client registration */
6271   if (NULL == (c = client_get (client)))
6272   {
6273     GNUNET_break (0);
6274     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6275     return;
6276   }
6277
6278   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6279   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6280
6281   /* Retrieve tunnel */
6282   tid = ntohl (tunnel_msg->tunnel_id);
6283   t = tunnel_get_by_local_id(c, tid);
6284   if (NULL == t)
6285   {
6286     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
6287     GNUNET_break (0);
6288     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6289     return;
6290   }
6291
6292   switch (ntohs(message->type))
6293   {
6294       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER:
6295           t->nobuffer = GNUNET_NO;
6296           break;
6297       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER:
6298           t->nobuffer = GNUNET_YES;
6299           break;
6300       default:
6301           GNUNET_break (0);
6302   }
6303
6304   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6305 }
6306
6307
6308 /**
6309  * Handler for connection requests to new peers
6310  *
6311  * @param cls closure
6312  * @param client identification of the client
6313  * @param message the actual message (PeerControl)
6314  */
6315 static void
6316 handle_local_connect_add (void *cls, struct GNUNET_SERVER_Client *client,
6317                           const struct GNUNET_MessageHeader *message)
6318 {
6319   struct GNUNET_MESH_PeerControl *peer_msg;
6320   struct MeshPeerInfo *peer_info;
6321   struct MeshClient *c;
6322   struct MeshTunnel *t;
6323   MESH_TunnelNumber tid;
6324
6325   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got connection request\n");
6326   /* Sanity check for client registration */
6327   if (NULL == (c = client_get (client)))
6328   {
6329     GNUNET_break (0);
6330     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6331     return;
6332   }
6333
6334   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6335   /* Sanity check for message size */
6336   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6337   {
6338     GNUNET_break (0);
6339     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6340     return;
6341   }
6342
6343   /* Tunnel exists? */
6344   tid = ntohl (peer_msg->tunnel_id);
6345   t = tunnel_get_by_local_id (c, tid);
6346   if (NULL == t)
6347   {
6348     GNUNET_break (0);
6349     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6350     return;
6351   }
6352
6353   /* Does client own tunnel? */
6354   if (t->owner->handle != client)
6355   {
6356     GNUNET_break (0);
6357     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6358     return;
6359   }
6360   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "     for %s\n",
6361               GNUNET_i2s (&peer_msg->peer));
6362   peer_info = peer_info_get (&peer_msg->peer);
6363
6364   tunnel_add_peer (t, peer_info);
6365   peer_info_connect (peer_info, t);
6366
6367   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6368   return;
6369 }
6370
6371
6372 /**
6373  * Handler for disconnection requests of peers in a tunnel
6374  *
6375  * @param cls closure
6376  * @param client identification of the client
6377  * @param message the actual message (PeerControl)
6378  */
6379 static void
6380 handle_local_connect_del (void *cls, struct GNUNET_SERVER_Client *client,
6381                           const struct GNUNET_MessageHeader *message)
6382 {
6383   struct GNUNET_MESH_PeerControl *peer_msg;
6384   struct MeshPeerInfo *peer_info;
6385   struct MeshClient *c;
6386   struct MeshTunnel *t;
6387   MESH_TunnelNumber tid;
6388
6389   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER DEL request\n");
6390   /* Sanity check for client registration */
6391   if (NULL == (c = client_get (client)))
6392   {
6393     GNUNET_break (0);
6394     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6395     return;
6396   }
6397   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6398   /* Sanity check for message size */
6399   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6400   {
6401     GNUNET_break (0);
6402     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6403     return;
6404   }
6405
6406   /* Tunnel exists? */
6407   tid = ntohl (peer_msg->tunnel_id);
6408   t = tunnel_get_by_local_id (c, tid);
6409   if (NULL == t)
6410   {
6411     GNUNET_break (0);
6412     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6413     return;
6414   }
6415   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
6416
6417   /* Does client own tunnel? */
6418   if (t->owner->handle != client)
6419   {
6420     GNUNET_break (0);
6421     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6422     return;
6423   }
6424
6425   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for peer %s\n",
6426               GNUNET_i2s (&peer_msg->peer));
6427   /* Is the peer in the tunnel? */
6428   peer_info =
6429       GNUNET_CONTAINER_multihashmap_get (t->peers, &peer_msg->peer.hashPubKey);
6430   if (NULL == peer_info)
6431   {
6432     GNUNET_break (0);
6433     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6434     return;
6435   }
6436
6437   /* Ok, delete peer from tunnel */
6438   GNUNET_CONTAINER_multihashmap_remove_all (t->peers,
6439                                             &peer_msg->peer.hashPubKey);
6440
6441   send_destroy_path (t, peer_info->id);
6442   tunnel_delete_peer (t, peer_info->id);
6443   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6444   return;
6445 }
6446
6447 /**
6448  * Handler for blacklist requests of peers in a tunnel
6449  *
6450  * @param cls closure
6451  * @param client identification of the client
6452  * @param message the actual message (PeerControl)
6453  */
6454 static void
6455 handle_local_blacklist (void *cls, struct GNUNET_SERVER_Client *client,
6456                           const struct GNUNET_MessageHeader *message)
6457 {
6458   struct GNUNET_MESH_PeerControl *peer_msg;
6459   struct MeshClient *c;
6460   struct MeshTunnel *t;
6461   MESH_TunnelNumber tid;
6462
6463   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER BLACKLIST request\n");
6464   /* Sanity check for client registration */
6465   if (NULL == (c = client_get (client)))
6466   {
6467     GNUNET_break (0);
6468     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6469     return;
6470   }
6471   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6472
6473   /* Sanity check for message size */
6474   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6475   {
6476     GNUNET_break (0);
6477     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6478     return;
6479   }
6480
6481   /* Tunnel exists? */
6482   tid = ntohl (peer_msg->tunnel_id);
6483   t = tunnel_get_by_local_id (c, tid);
6484   if (NULL == t)
6485   {
6486     GNUNET_break (0);
6487     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6488     return;
6489   }
6490   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
6491
6492   GNUNET_array_append(t->blacklisted, t->nblacklisted,
6493                       GNUNET_PEER_intern(&peer_msg->peer));
6494 }
6495
6496
6497 /**
6498  * Handler for unblacklist requests of peers in a tunnel
6499  *
6500  * @param cls closure
6501  * @param client identification of the client
6502  * @param message the actual message (PeerControl)
6503  */
6504 static void
6505 handle_local_unblacklist (void *cls, struct GNUNET_SERVER_Client *client,
6506                           const struct GNUNET_MessageHeader *message)
6507 {
6508   struct GNUNET_MESH_PeerControl *peer_msg;
6509   struct MeshClient *c;
6510   struct MeshTunnel *t;
6511   MESH_TunnelNumber tid;
6512   GNUNET_PEER_Id pid;
6513   unsigned int i;
6514
6515   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER UNBLACKLIST request\n");
6516   /* Sanity check for client registration */
6517   if (NULL == (c = client_get (client)))
6518   {
6519     GNUNET_break (0);
6520     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6521     return;
6522   }
6523   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6524
6525   /* Sanity check for message size */
6526   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6527   {
6528     GNUNET_break (0);
6529     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6530     return;
6531   }
6532
6533   /* Tunnel exists? */
6534   tid = ntohl (peer_msg->tunnel_id);
6535   t = tunnel_get_by_local_id (c, tid);
6536   if (NULL == t)
6537   {
6538     GNUNET_break (0);
6539     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6540     return;
6541   }
6542   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
6543
6544   /* if peer is not known, complain */
6545   pid = GNUNET_PEER_search (&peer_msg->peer);
6546   if (0 == pid)
6547   {
6548     GNUNET_break (0);
6549     return;
6550   }
6551
6552   /* search and remove from list */
6553   for (i = 0; i < t->nblacklisted; i++)
6554   {
6555     if (t->blacklisted[i] == pid)
6556     {
6557       t->blacklisted[i] = t->blacklisted[t->nblacklisted - 1];
6558       GNUNET_array_grow (t->blacklisted, t->nblacklisted, t->nblacklisted - 1);
6559       return;
6560     }
6561   }
6562
6563   /* if peer hasn't been blacklisted, complain */
6564   GNUNET_break (0);
6565 }
6566
6567
6568 /**
6569  * Handler for connection requests to new peers by type
6570  *
6571  * @param cls closure
6572  * @param client identification of the client
6573  * @param message the actual message (ConnectPeerByType)
6574  */
6575 static void
6576 handle_local_connect_by_type (void *cls, struct GNUNET_SERVER_Client *client,
6577                               const struct GNUNET_MessageHeader *message)
6578 {
6579   struct GNUNET_MESH_ConnectPeerByType *connect_msg;
6580   struct MeshClient *c;
6581   struct MeshTunnel *t;
6582   struct GNUNET_HashCode hash;
6583   MESH_TunnelNumber tid;
6584
6585   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got connect by type request\n");
6586   /* Sanity check for client registration */
6587   if (NULL == (c = client_get (client)))
6588   {
6589     GNUNET_break (0);
6590     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6591     return;
6592   }
6593
6594   connect_msg = (struct GNUNET_MESH_ConnectPeerByType *) message;
6595   /* Sanity check for message size */
6596   if (sizeof (struct GNUNET_MESH_ConnectPeerByType) !=
6597       ntohs (connect_msg->header.size))
6598   {
6599     GNUNET_break (0);
6600     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6601     return;
6602   }
6603
6604   /* Tunnel exists? */
6605   tid = ntohl (connect_msg->tunnel_id);
6606   t = tunnel_get_by_local_id (c, tid);
6607   if (NULL == t)
6608   {
6609     GNUNET_break (0);
6610     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6611     return;
6612   }
6613
6614   /* Does client own tunnel? */
6615   if (t->owner->handle != client)
6616   {
6617     GNUNET_break (0);
6618     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6619     return;
6620   }
6621
6622   /* Do WE have the service? */
6623   t->type = ntohl (connect_msg->type);
6624   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " type requested: %u\n", t->type);
6625   GNUNET_CRYPTO_hash (&t->type, sizeof (GNUNET_MESH_ApplicationType), &hash);
6626   if (GNUNET_CONTAINER_multihashmap_contains (applications, &hash) ==
6627       GNUNET_YES)
6628   {
6629     /* Yes! Fast forward, add ourselves to the tunnel and send the
6630      * good news to the client, and alert the destination client of
6631      * an incoming tunnel.
6632      *
6633      * FIXME send a path create to self, avoid code duplication
6634      */
6635     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " available locally\n");
6636     GNUNET_CONTAINER_multihashmap_put (t->peers, &my_full_id.hashPubKey,
6637                                        peer_info_get (&my_full_id),
6638                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
6639
6640     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " notifying client\n");
6641     send_client_peer_connected (t, myid);
6642     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Done\n");
6643     GNUNET_SERVER_receive_done (client, GNUNET_OK);
6644
6645     t->local_tid_dest = next_local_tid++;
6646     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
6647     GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
6648                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
6649
6650     return;
6651   }
6652   /* Ok, lets find a peer offering the service */
6653   if (NULL != t->dht_get_type)
6654   {
6655     GNUNET_DHT_get_stop (t->dht_get_type);
6656   }
6657   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " looking in DHT for %s\n",
6658               GNUNET_h2s (&hash));
6659   t->dht_get_type =
6660       GNUNET_DHT_get_start (dht_handle, 
6661                             GNUNET_BLOCK_TYPE_MESH_PEER_BY_TYPE,
6662                             &hash,
6663                             dht_replication_level,
6664                             GNUNET_DHT_RO_RECORD_ROUTE |
6665                             GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
6666                             NULL, 0,
6667                             &dht_get_type_handler, t);
6668
6669   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6670   return;
6671 }
6672
6673
6674 /**
6675  * Handler for connection requests to new peers by a string service description.
6676  *
6677  * @param cls closure
6678  * @param client identification of the client
6679  * @param message the actual message, which includes messages the client wants
6680  */
6681 static void
6682 handle_local_connect_by_string (void *cls, struct GNUNET_SERVER_Client *client,
6683                                 const struct GNUNET_MessageHeader *message)
6684 {
6685   struct GNUNET_MESH_ConnectPeerByString *msg;
6686   struct MeshRegexSearchContext *ctx;
6687   struct MeshRegexSearchInfo *info;
6688   struct GNUNET_DHT_GetHandle *get_h;
6689   struct GNUNET_HashCode key;
6690   struct MeshTunnel *t;
6691   struct MeshClient *c;
6692   MESH_TunnelNumber tid;
6693   const char *string;
6694   size_t size;
6695   size_t len;
6696   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6697               "Connect by string started\n");
6698   msg = (struct GNUNET_MESH_ConnectPeerByString *) message;
6699   size = htons (message->size);
6700
6701   /* Sanity check for client registration */
6702   if (NULL == (c = client_get (client)))
6703   {
6704     GNUNET_break (0);
6705     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6706     return;
6707   }
6708
6709   /* Message size sanity check */
6710   if (sizeof(struct GNUNET_MESH_ConnectPeerByString) >= size)
6711   {
6712     GNUNET_break (0);
6713     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6714     return;
6715   }
6716
6717   /* Tunnel exists? */
6718   tid = ntohl (msg->tunnel_id);
6719   t = tunnel_get_by_local_id (c, tid);
6720   if (NULL == t)
6721   {
6722     GNUNET_break (0);
6723     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6724     return;
6725   }
6726
6727   /* Does client own tunnel? */
6728   if (t->owner->handle != client)
6729   {
6730     GNUNET_break (0);
6731     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6732     return;
6733   }
6734
6735   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6736               "  on tunnel %s [%u]\n",
6737               GNUNET_i2s(&my_full_id),
6738               t->id.tid);
6739
6740   /* Only one connect_by_string allowed at the same time! */
6741   /* FIXME: allow more, return handle at api level to cancel, document */
6742   if (NULL != t->regex_ctx)
6743   {
6744     GNUNET_break (0);
6745     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6746     return;
6747   }
6748
6749   /* Find string itself */
6750   len = size - sizeof(struct GNUNET_MESH_ConnectPeerByString);
6751   string = (const char *) &msg[1];
6752
6753   /* Initialize context */
6754   size = GNUNET_REGEX_get_first_key(string, len, &key);
6755   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6756               "  consumed %u bits out of %u\n", size, len);
6757   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6758               "  looking for %s\n", GNUNET_h2s (&key));
6759
6760   info = GNUNET_malloc (sizeof (struct MeshRegexSearchInfo));
6761   info->t = t;
6762   info->description = GNUNET_malloc (len + 1);
6763   memcpy (info->description, string, len);
6764   info->description[len] = '\0';
6765   info->dht_get_handles = GNUNET_CONTAINER_multihashmap_create(32);
6766   info->dht_get_results = GNUNET_CONTAINER_multihashmap_create(32);
6767   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   string: %s\n", info->description);
6768
6769   ctx = GNUNET_malloc (sizeof (struct MeshRegexSearchContext));
6770   ctx->position = size;
6771   ctx->info = info;
6772   t->regex_ctx = ctx;
6773
6774   GNUNET_array_append (info->contexts, info->n_contexts, ctx);
6775
6776   /* Start search in DHT */
6777   get_h = GNUNET_DHT_get_start (dht_handle,    /* handle */
6778                                 GNUNET_BLOCK_TYPE_MESH_REGEX, /* type */
6779                                 &key,     /* key to search */
6780                                 dht_replication_level, /* replication level */
6781                                 GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
6782                                 NULL,       /* xquery */ // FIXME BLOOMFILTER
6783                                 0,     /* xquery bits */ // FIXME BLOOMFILTER SIZE
6784                                 &dht_get_string_handler, ctx);
6785
6786   GNUNET_break (GNUNET_OK ==
6787                 GNUNET_CONTAINER_multihashmap_put(info->dht_get_handles,
6788                                                   &key,
6789                                                   get_h,
6790                                                   GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
6791
6792   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6793   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "connect by string processed\n");
6794 }
6795
6796
6797 /**
6798  * Handler for client traffic directed to one peer
6799  *
6800  * @param cls closure
6801  * @param client identification of the client
6802  * @param message the actual message
6803  */
6804 static void
6805 handle_local_unicast (void *cls, struct GNUNET_SERVER_Client *client,
6806                       const struct GNUNET_MessageHeader *message)
6807 {
6808   struct MeshClient *c;
6809   struct MeshTunnel *t;
6810   struct MeshPeerInfo *pi;
6811   struct GNUNET_MESH_Unicast *data_msg;
6812   MESH_TunnelNumber tid;
6813   size_t size;
6814
6815   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6816               "Got a unicast request from a client!\n");
6817
6818   /* Sanity check for client registration */
6819   if (NULL == (c = client_get (client)))
6820   {
6821     GNUNET_break (0);
6822     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6823     return;
6824   }
6825   data_msg = (struct GNUNET_MESH_Unicast *) message;
6826   /* Sanity check for message size */
6827   size = ntohs (message->size);
6828   if (sizeof (struct GNUNET_MESH_Unicast) +
6829       sizeof (struct GNUNET_MessageHeader) > size)
6830   {
6831     GNUNET_break (0);
6832     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6833     return;
6834   }
6835
6836   /* Tunnel exists? */
6837   tid = ntohl (data_msg->tid);
6838   t = tunnel_get_by_local_id (c, tid);
6839   if (NULL == t)
6840   {
6841     GNUNET_break (0);
6842     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6843     return;
6844   }
6845
6846   /*  Is it a local tunnel? Then, does client own the tunnel? */
6847   if (t->owner->handle != client)
6848   {
6849     GNUNET_break (0);
6850     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6851     return;
6852   }
6853
6854   pi = GNUNET_CONTAINER_multihashmap_get (t->peers,
6855                                           &data_msg->destination.hashPubKey);
6856   /* Is the selected peer in the tunnel? */
6857   if (NULL == pi)
6858   {
6859     GNUNET_break (0);
6860     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6861     return;
6862   }
6863
6864   /* PID should be as expected */
6865   if (ntohl (data_msg->pid) != t->fwd_pid + 1)
6866   {
6867     GNUNET_break (0);
6868     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6869               "Unicast PID, expected %u, got %u\n",
6870               t->fwd_pid + 1, ntohl (data_msg->pid));
6871     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6872     return;
6873   }
6874
6875   /* Ok, everything is correct, send the message
6876    * (pretend we got it from a mesh peer)
6877    */
6878   {
6879     /* Work around const limitation */
6880     char buf[ntohs (message->size)] GNUNET_ALIGN;
6881     struct GNUNET_MESH_Unicast *copy;
6882
6883     copy = (struct GNUNET_MESH_Unicast *) buf;
6884     memcpy (buf, data_msg, size);
6885     copy->oid = my_full_id;
6886     copy->tid = htonl (t->id.tid);
6887     copy->ttl = htonl (default_ttl);
6888     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6889                 "  calling generic handler...\n");
6890     handle_mesh_data_unicast (NULL, &my_full_id, &copy->header, NULL, 0);
6891   }
6892   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "receive done OK\n");
6893   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6894   return;
6895 }
6896
6897
6898 /**
6899  * Handler for client traffic directed to the origin
6900  *
6901  * @param cls closure
6902  * @param client identification of the client
6903  * @param message the actual message
6904  */
6905 static void
6906 handle_local_to_origin (void *cls, struct GNUNET_SERVER_Client *client,
6907                         const struct GNUNET_MessageHeader *message)
6908 {
6909   struct GNUNET_MESH_ToOrigin *data_msg;
6910   struct MeshTunnelClientInfo *clinfo;
6911   struct MeshClient *c;
6912   struct MeshTunnel *t;
6913   MESH_TunnelNumber tid;
6914   size_t size;
6915
6916   /* Sanity check for client registration */
6917   if (NULL == (c = client_get (client)))
6918   {
6919     GNUNET_break (0);
6920     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6921     return;
6922   }
6923   data_msg = (struct GNUNET_MESH_ToOrigin *) message;
6924   /* Sanity check for message size */
6925   size = ntohs (message->size);
6926   if (sizeof (struct GNUNET_MESH_ToOrigin) +
6927       sizeof (struct GNUNET_MessageHeader) > size)
6928   {
6929     GNUNET_break (0);
6930     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6931     return;
6932   }
6933
6934   /* Tunnel exists? */
6935   tid = ntohl (data_msg->tid);
6936   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6937               "Got a ToOrigin request from a client! Tunnel %X\n", tid);
6938   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
6939   {
6940     GNUNET_break (0);
6941     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6942     return;
6943   }
6944   t = tunnel_get_by_local_id (c, tid);
6945   if (NULL == t)
6946   {
6947     GNUNET_break (0);
6948     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6949     return;
6950   }
6951
6952   /*  It should be sent by someone who has this as incoming tunnel. */
6953   if (GNUNET_NO == client_knows_tunnel (c, t))
6954   {
6955     GNUNET_break (0);
6956     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6957     return;
6958   }
6959
6960   /* PID should be as expected */
6961   clinfo = tunnel_get_client_fc (t, c);
6962   if (ntohl (data_msg->pid) != clinfo->bck_pid + 1)
6963   {
6964     GNUNET_break (0);
6965     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6966                 "To Origin PID, expected %u, got %u\n",
6967                 clinfo->bck_pid + 1, ntohl (data_msg->pid));
6968     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6969     return;
6970   }
6971
6972   /* Ok, everything is correct, send the message
6973    * (pretend we got it from a mesh peer)
6974    */
6975   {
6976     char buf[ntohs (message->size)] GNUNET_ALIGN;
6977     struct GNUNET_MESH_ToOrigin *copy;
6978
6979     /* Work around const limitation */
6980     copy = (struct GNUNET_MESH_ToOrigin *) buf;
6981     memcpy (buf, data_msg, size);
6982     GNUNET_PEER_resolve (t->id.oid, &copy->oid);
6983     copy->tid = htonl (t->id.tid);
6984     copy->ttl = htonl (default_ttl);
6985     GNUNET_assert (ntohl (copy->pid) == (t->bck_pid + 1));
6986     copy->sender = my_full_id;
6987     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6988                 "  calling generic handler...\n");
6989     handle_mesh_data_to_orig (NULL, &my_full_id, &copy->header, NULL, 0);
6990   }
6991   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6992   return;
6993 }
6994
6995
6996 /**
6997  * Handler for client traffic directed to all peers in a tunnel
6998  *
6999  * @param cls closure
7000  * @param client identification of the client
7001  * @param message the actual message
7002  */
7003 static void
7004 handle_local_multicast (void *cls, struct GNUNET_SERVER_Client *client,
7005                         const struct GNUNET_MessageHeader *message)
7006 {
7007   struct MeshClient *c;
7008   struct MeshTunnel *t;
7009   struct GNUNET_MESH_Multicast *data_msg;
7010   MESH_TunnelNumber tid;
7011
7012   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7013               "Got a multicast request from a client!\n");
7014
7015   /* Sanity check for client registration */
7016   if (NULL == (c = client_get (client)))
7017   {
7018     GNUNET_break (0);
7019     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7020     return;
7021   }
7022   data_msg = (struct GNUNET_MESH_Multicast *) message;
7023   /* Sanity check for message size */
7024   if (sizeof (struct GNUNET_MESH_Multicast) +
7025       sizeof (struct GNUNET_MessageHeader) > ntohs (data_msg->header.size))
7026   {
7027     GNUNET_break (0);
7028     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7029     return;
7030   }
7031
7032   /* Tunnel exists? */
7033   tid = ntohl (data_msg->tid);
7034   t = tunnel_get_by_local_id (c, tid);
7035   if (NULL == t)
7036   {
7037     GNUNET_break (0);
7038     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7039     return;
7040   }
7041
7042   /* Does client own tunnel? */
7043   if (t->owner->handle != client)
7044   {
7045     GNUNET_break (0);
7046     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7047     return;
7048   }
7049
7050   /* PID should be as expected */
7051   if (ntohl (data_msg->pid) != t->fwd_pid + 1)
7052   {
7053     GNUNET_break (0);
7054     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7055               "Multicast PID, expected %u, got %u\n",
7056               t->fwd_pid + 1, ntohl (data_msg->pid));
7057     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7058     return;
7059   }
7060
7061   {
7062     char buf[ntohs (message->size)] GNUNET_ALIGN;
7063     struct GNUNET_MESH_Multicast *copy;
7064
7065     copy = (struct GNUNET_MESH_Multicast *) buf;
7066     memcpy (buf, message, ntohs (message->size));
7067     copy->oid = my_full_id;
7068     copy->tid = htonl (t->id.tid);
7069     copy->ttl = htonl (default_ttl);
7070     GNUNET_assert (ntohl (copy->pid) == (t->fwd_pid + 1));
7071     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7072                 "  calling generic handler...\n");
7073     handle_mesh_data_multicast (client, &my_full_id, &copy->header, NULL, 0);
7074   }
7075
7076   /* receive done gets called when last copy is sent to a neighbor */
7077   return;
7078 }
7079
7080
7081 /**
7082  * Handler for client's ACKs for payload traffic.
7083  *
7084  * @param cls Closure (unused).
7085  * @param client Identification of the client.
7086  * @param message The actual message.
7087  */
7088 static void
7089 handle_local_ack (void *cls, struct GNUNET_SERVER_Client *client,
7090                   const struct GNUNET_MessageHeader *message)
7091 {
7092   struct GNUNET_MESH_LocalAck *msg;
7093   struct MeshTunnel *t;
7094   struct MeshClient *c;
7095   MESH_TunnelNumber tid;
7096
7097   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a local ACK\n");
7098   /* Sanity check for client registration */
7099   if (NULL == (c = client_get (client)))
7100   {
7101     GNUNET_break (0);
7102     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7103     return;
7104   }
7105
7106   msg = (struct GNUNET_MESH_LocalAck *) message;
7107   /* Tunnel exists? */
7108   tid = ntohl (msg->tunnel_id);
7109   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
7110   t = tunnel_get_by_local_id (c, tid);
7111   if (NULL == t)
7112   {
7113     GNUNET_break (0);
7114     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7115     return;
7116   }
7117
7118   /* Does client own tunnel? I.E: Is this and ACK for BCK traffic? */
7119   if (NULL != t->owner && t->owner->handle == client)
7120   {
7121     /* The client owns the tunnel, ACK is for data to_origin, send BCK ACK. */
7122     t->bck_ack = ntohl(msg->max_pid);
7123     tunnel_send_bck_ack(t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
7124   }
7125   else
7126   {
7127     /* The client doesn't own the tunnel, this ACK is for FWD traffic. */
7128     tunnel_set_client_fwd_ack (t, c, ntohl (msg->max_pid));
7129     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
7130   }
7131
7132   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7133   return;
7134 }
7135
7136
7137 /**
7138  * Functions to handle messages from clients
7139  */
7140 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
7141   {&handle_local_new_client, NULL,
7142    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
7143   {&handle_local_announce_regex, NULL,
7144    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ANNOUNCE_REGEX, 0},
7145   {&handle_local_tunnel_create, NULL,
7146    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
7147    sizeof (struct GNUNET_MESH_TunnelMessage)},
7148   {&handle_local_tunnel_destroy, NULL,
7149    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
7150    sizeof (struct GNUNET_MESH_TunnelMessage)},
7151   {&handle_local_tunnel_speed, NULL,
7152    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MIN,
7153    sizeof (struct GNUNET_MESH_TunnelMessage)},
7154   {&handle_local_tunnel_speed, NULL,
7155    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MAX,
7156    sizeof (struct GNUNET_MESH_TunnelMessage)},
7157   {&handle_local_tunnel_buffer, NULL,
7158    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER,
7159    sizeof (struct GNUNET_MESH_TunnelMessage)},
7160   {&handle_local_tunnel_buffer, NULL,
7161    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER,
7162    sizeof (struct GNUNET_MESH_TunnelMessage)},
7163   {&handle_local_connect_add, NULL,
7164    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD,
7165    sizeof (struct GNUNET_MESH_PeerControl)},
7166   {&handle_local_connect_del, NULL,
7167    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL,
7168    sizeof (struct GNUNET_MESH_PeerControl)},
7169   {&handle_local_blacklist, NULL,
7170    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_BLACKLIST,
7171    sizeof (struct GNUNET_MESH_PeerControl)},
7172   {&handle_local_unblacklist, NULL,
7173    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_UNBLACKLIST,
7174    sizeof (struct GNUNET_MESH_PeerControl)},
7175   {&handle_local_connect_by_type, NULL,
7176    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE,
7177    sizeof (struct GNUNET_MESH_ConnectPeerByType)},
7178   {&handle_local_connect_by_string, NULL,
7179    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_STRING, 0},
7180   {&handle_local_unicast, NULL,
7181    GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
7182   {&handle_local_to_origin, NULL,
7183    GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
7184   {&handle_local_multicast, NULL,
7185    GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
7186   {&handle_local_ack, NULL,
7187    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK,
7188    sizeof (struct GNUNET_MESH_LocalAck)},
7189   {NULL, NULL, 0, 0}
7190 };
7191
7192
7193 /**
7194  * To be called on core init/fail.
7195  *
7196  * @param cls service closure
7197  * @param server handle to the server for this service
7198  * @param identity the public identity of this peer
7199  */
7200 static void
7201 core_init (void *cls, struct GNUNET_CORE_Handle *server,
7202            const struct GNUNET_PeerIdentity *identity)
7203 {
7204   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
7205   core_handle = server;
7206   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)) ||
7207       NULL == server)
7208   {
7209     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
7210     GNUNET_SCHEDULER_shutdown ();
7211   }
7212   return;
7213 }
7214
7215
7216 /**
7217  * Method called whenever a given peer connects.
7218  *
7219  * @param cls closure
7220  * @param peer peer identity this notification is about
7221  * @param atsi performance data for the connection
7222  * @param atsi_count number of records in 'atsi'
7223  */
7224 static void
7225 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
7226               const struct GNUNET_ATS_Information *atsi,
7227               unsigned int atsi_count)
7228 {
7229   struct MeshPeerInfo *peer_info;
7230   struct MeshPeerPath *path;
7231
7232   DEBUG_CONN ("Peer connected\n");
7233   DEBUG_CONN ("     %s\n", GNUNET_i2s (&my_full_id));
7234   peer_info = peer_info_get (peer);
7235   if (myid == peer_info->id)
7236   {
7237     DEBUG_CONN ("     (self)\n");
7238     return;
7239   }
7240   else
7241   {
7242     DEBUG_CONN ("     %s\n", GNUNET_i2s (peer));
7243   }
7244   path = path_new (2);
7245   path->peers[0] = myid;
7246   path->peers[1] = peer_info->id;
7247   GNUNET_PEER_change_rc (myid, 1);
7248   GNUNET_PEER_change_rc (peer_info->id, 1);
7249   peer_info_add_path (peer_info, path, GNUNET_YES);
7250   GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
7251   return;
7252 }
7253
7254
7255 /**
7256  * Method called whenever a peer disconnects.
7257  *
7258  * @param cls closure
7259  * @param peer peer identity this notification is about
7260  */
7261 static void
7262 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
7263 {
7264   struct MeshPeerInfo *pi;
7265   struct MeshPeerQueue *q;
7266   struct MeshPeerQueue *n;
7267
7268   DEBUG_CONN ("Peer disconnected\n");
7269   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
7270   if (NULL == pi)
7271   {
7272     GNUNET_break (0);
7273     return;
7274   }
7275   q = pi->queue_head;
7276   while (NULL != q)
7277   {
7278       n = q->next;
7279       if (q->peer == pi)
7280       {
7281         /* try to reroute this traffic instead */
7282         queue_destroy(q, GNUNET_YES);
7283       }
7284       q = n;
7285   }
7286   peer_info_remove_path (pi, pi->id, myid);
7287   if (myid == pi->id)
7288   {
7289     DEBUG_CONN ("     (self)\n");
7290   }
7291   GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
7292   return;
7293 }
7294
7295
7296 /******************************************************************************/
7297 /************************      MAIN FUNCTIONS      ****************************/
7298 /******************************************************************************/
7299
7300 /**
7301  * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
7302  *
7303  * @param cls closure
7304  * @param key current key code
7305  * @param value value in the hash map
7306  * @return GNUNET_YES if we should continue to iterate,
7307  *         GNUNET_NO if not.
7308  */
7309 static int
7310 shutdown_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
7311 {
7312   struct MeshTunnel *t = value;
7313
7314   tunnel_destroy (t);
7315   return GNUNET_YES;
7316 }
7317
7318 /**
7319  * Iterator over peer hash map entries to destroy the tunnel during shutdown.
7320  *
7321  * @param cls closure
7322  * @param key current key code
7323  * @param value value in the hash map
7324  * @return GNUNET_YES if we should continue to iterate,
7325  *         GNUNET_NO if not.
7326  */
7327 static int
7328 shutdown_peer (void *cls, const struct GNUNET_HashCode * key, void *value)
7329 {
7330   struct MeshPeerInfo *p = value;
7331   struct MeshPeerQueue *q;
7332   struct MeshPeerQueue *n;
7333
7334   q = p->queue_head;
7335   while (NULL != q)
7336   {
7337       n = q->next;
7338       if (q->peer == p)
7339       {
7340         queue_destroy(q, GNUNET_YES);
7341       }
7342       q = n;
7343   }
7344   peer_info_destroy (p);
7345   return GNUNET_YES;
7346 }
7347
7348 /**
7349  * Task run during shutdown.
7350  *
7351  * @param cls unused
7352  * @param tc unused
7353  */
7354 static void
7355 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
7356 {
7357   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
7358
7359   if (core_handle != NULL)
7360   {
7361     GNUNET_CORE_disconnect (core_handle);
7362     core_handle = NULL;
7363   }
7364   GNUNET_CONTAINER_multihashmap_iterate (tunnels, &shutdown_tunnel, NULL);
7365   GNUNET_CONTAINER_multihashmap_iterate (peers, &shutdown_peer, NULL);
7366   if (dht_handle != NULL)
7367   {
7368     GNUNET_DHT_disconnect (dht_handle);
7369     dht_handle = NULL;
7370   }
7371   if (nc != NULL)
7372   {
7373     GNUNET_SERVER_notification_context_destroy (nc);
7374     nc = NULL;
7375   }
7376   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
7377   {
7378     GNUNET_SCHEDULER_cancel (announce_id_task);
7379     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
7380   }
7381   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
7382 }
7383
7384 /**
7385  * Process mesh requests.
7386  *
7387  * @param cls closure
7388  * @param server the initialized server
7389  * @param c configuration to use
7390  */
7391 static void
7392 run (void *cls, struct GNUNET_SERVER_Handle *server,
7393      const struct GNUNET_CONFIGURATION_Handle *c)
7394 {
7395   struct MeshPeerInfo *peer;
7396   struct MeshPeerPath *p;
7397   char *keyfile;
7398
7399   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
7400   server_handle = server;
7401   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
7402                                      NULL,      /* Closure passed to MESH functions */
7403                                      &core_init,        /* Call core_init once connected */
7404                                      &core_connect,     /* Handle connects */
7405                                      &core_disconnect,  /* remove peers on disconnects */
7406                                      NULL,      /* Don't notify about all incoming messages */
7407                                      GNUNET_NO, /* For header only in notification */
7408                                      NULL,      /* Don't notify about all outbound messages */
7409                                      GNUNET_NO, /* For header-only out notification */
7410                                      core_handlers);    /* Register these handlers */
7411
7412   if (core_handle == NULL)
7413   {
7414     GNUNET_break (0);
7415     GNUNET_SCHEDULER_shutdown ();
7416     return;
7417   }
7418
7419   if (GNUNET_OK !=
7420       GNUNET_CONFIGURATION_get_value_filename (c, "GNUNETD", "HOSTKEY",
7421                                                &keyfile))
7422   {
7423     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7424                 _
7425                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7426                 "hostkey");
7427     GNUNET_SCHEDULER_shutdown ();
7428     return;
7429   }
7430
7431   if (GNUNET_OK !=
7432       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_PATH_TIME",
7433                                            &refresh_path_time))
7434   {
7435     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7436                 _
7437                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7438                 "refresh path time");
7439     GNUNET_SCHEDULER_shutdown ();
7440     return;
7441   }
7442
7443   if (GNUNET_OK !=
7444       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "APP_ANNOUNCE_TIME",
7445                                            &app_announce_time))
7446   {
7447     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7448                 _
7449                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7450                 "app announce time");
7451     GNUNET_SCHEDULER_shutdown ();
7452     return;
7453   }
7454
7455   if (GNUNET_OK !=
7456       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "ID_ANNOUNCE_TIME",
7457                                            &id_announce_time))
7458   {
7459     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7460                 _
7461                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7462                 "id announce time");
7463     GNUNET_SCHEDULER_shutdown ();
7464     return;
7465   }
7466
7467   if (GNUNET_OK !=
7468       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "UNACKNOWLEDGED_WAIT",
7469                                            &unacknowledged_wait_time))
7470   {
7471     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7472                 _
7473                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7474                 "unacknowledged wait time");
7475     GNUNET_SCHEDULER_shutdown ();
7476     return;
7477   }
7478
7479   if (GNUNET_OK !=
7480       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "CONNECT_TIMEOUT",
7481                                            &connect_timeout))
7482   {
7483     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7484                 _
7485                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7486                 "connect timeout");
7487     GNUNET_SCHEDULER_shutdown ();
7488     return;
7489   }
7490
7491   if (GNUNET_OK !=
7492       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
7493                                              &max_msgs_queue))
7494   {
7495     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7496                 _
7497                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7498                 "max msgs queue");
7499     GNUNET_SCHEDULER_shutdown ();
7500     return;
7501   }
7502
7503   if (GNUNET_OK !=
7504       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_TUNNELS",
7505                                              &max_tunnels))
7506   {
7507     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7508                 _
7509                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7510                 "max tunnels");
7511     GNUNET_SCHEDULER_shutdown ();
7512     return;
7513   }
7514
7515   if (GNUNET_OK !=
7516       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
7517                                              &default_ttl))
7518   {
7519     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7520                 _
7521                 ("Mesh service is lacking key configuration settings (%s). Using default (%u).\n"),
7522                 "default ttl", 64);
7523     default_ttl = 64;
7524   }
7525
7526   if (GNUNET_OK !=
7527       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DHT_REPLICATION_LEVEL",
7528                                              &dht_replication_level))
7529   {
7530     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7531                 _
7532                 ("Mesh service is lacking key configuration settings (%s). Using default (%u).\n"),
7533                 "dht replication level", 10);
7534     dht_replication_level = 10;
7535   }
7536
7537   
7538   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
7539   GNUNET_free (keyfile);
7540   if (my_private_key == NULL)
7541   {
7542     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7543                 _("Mesh service could not access hostkey.  Exiting.\n"));
7544     GNUNET_SCHEDULER_shutdown ();
7545     return;
7546   }
7547   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
7548   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
7549                       &my_full_id.hashPubKey);
7550   myid = GNUNET_PEER_intern (&my_full_id);
7551
7552 //   transport_handle = GNUNET_TRANSPORT_connect(c,
7553 //                                               &my_full_id,
7554 //                                               NULL,
7555 //                                               NULL,
7556 //                                               NULL,
7557 //                                               NULL);
7558
7559   dht_handle = GNUNET_DHT_connect (c, 64);
7560   if (dht_handle == NULL)
7561   {
7562     GNUNET_break (0);
7563   }
7564
7565   stats = GNUNET_STATISTICS_create ("mesh", c);
7566
7567
7568   next_tid = 0;
7569   next_local_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
7570
7571   tunnels = GNUNET_CONTAINER_multihashmap_create (32);
7572   incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
7573   peers = GNUNET_CONTAINER_multihashmap_create (32);
7574   applications = GNUNET_CONTAINER_multihashmap_create (32);
7575   types = GNUNET_CONTAINER_multihashmap_create (32);
7576
7577   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
7578   nc = GNUNET_SERVER_notification_context_create (server_handle, 1);
7579   GNUNET_SERVER_disconnect_notify (server_handle,
7580                                    &handle_local_client_disconnect, NULL);
7581
7582
7583   clients = NULL;
7584   clients_tail = NULL;
7585   next_client_id = 0;
7586
7587   announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
7588   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
7589
7590   /* Create a peer_info for the local peer */
7591   peer = peer_info_get (&my_full_id);
7592   p = path_new (1);
7593   p->peers[0] = myid;
7594   GNUNET_PEER_change_rc (myid, 1);
7595   peer_info_add_path (peer, p, GNUNET_YES);
7596
7597   /* Scheduled the task to clean up when shutdown is called */
7598   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
7599                                 NULL);
7600
7601   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "end of run()\n");
7602 }
7603
7604 /**
7605  * The main function for the mesh service.
7606  *
7607  * @param argc number of arguments from the command line
7608  * @param argv command line arguments
7609  * @return 0 ok, 1 on error
7610  */
7611 int
7612 main (int argc, char *const *argv)
7613 {
7614   int ret;
7615
7616   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
7617   ret =
7618       (GNUNET_OK ==
7619        GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
7620                            NULL)) ? 0 : 1;
7621   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");
7622
7623   return ret;
7624 }