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