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