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