- more debug, fixes
[oweals/gnunet.git] / src / mesh / gnunet-service-mesh.c
1 /*
2      This file is part of GNUnet.
3      (C) 2001 - 2011 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file mesh/gnunet-service-mesh.c
23  * @brief GNUnet MESH service
24  * @author Bartlomiej Polot
25  *
26  * STRUCTURE:
27  * - DATA STRUCTURES
28  * - GLOBAL VARIABLES
29  * - GENERAL HELPERS
30  * - PERIODIC FUNCTIONS
31  * - MESH NETWORK HANDLER HELPERS
32  * - MESH NETWORK HANDLES
33  * - MESH LOCAL HANDLER HELPERS
34  * - MESH LOCAL HANDLES
35  * - MAIN FUNCTIONS (main & run)
36  *
37  * TODO:
38  * - error reporting (CREATE/CHANGE/ADD/DEL?) -- new message!
39  * - partial disconnect reporting -- same as error reporting?
40  * - add vs create? change vs. keep-alive? same msg or different ones? -- thinking...
41  * - add ping message
42  * - relay corking down to core
43  * - set ttl relative to tree depth
44  * - Add data ACK count in path ACK
45  * TODO END
46  */
47
48 #include "platform.h"
49 #include "mesh.h"
50 #include "mesh_protocol.h"
51 #include "mesh_tunnel_tree.h"
52 #include "block_mesh.h"
53 #include "mesh_block_lib.h"
54 #include "gnunet_dht_service.h"
55 #include "gnunet_statistics_service.h"
56 #include "gnunet_regex_lib.h"
57
58 #define MESH_BLOOM_SIZE         128
59
60 #define MESH_DEBUG_DHT          GNUNET_YES
61 #define MESH_DEBUG_CONNECTION   GNUNET_NO
62
63 #define INITIAL_WINDOW_SIZE     2
64 #define ACK_THRESHOLD           INITIAL_WINDOW_SIZE / 2
65
66 #if MESH_DEBUG_CONNECTION
67 #define DEBUG_CONN(...) GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
68 #else
69 #define DEBUG_CONN(...)
70 #endif
71
72 #if MESH_DEBUG_DHT
73 #define DEBUG_DHT(...) GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
74 #else
75 #define DEBUG_DHT(...)
76 #endif
77
78 /******************************************************************************/
79 /************************      DATA STRUCTURES     ****************************/
80 /******************************************************************************/
81
82 /** FWD declaration */
83 struct MeshPeerInfo;
84 struct MeshClient;
85
86
87 /**
88  * Struct representing a piece of data being sent to other peers
89  */
90 struct MeshData
91 {
92   /** Tunnel it belongs to. */
93   struct MeshTunnel *t;
94
95   /** In case of a multicast, task to allow a client to send more data if
96    * some neighbor is too slow. */
97   GNUNET_SCHEDULER_TaskIdentifier *task;
98
99   /** How many remaining neighbors we need to send this to. */
100   unsigned int *reference_counter;
101
102   /** Size of the data. */
103   size_t data_len;
104
105   /** Data itself */
106   void *data;
107 };
108
109
110 /**
111  * Struct containing info about a queued transmission to this peer
112  */
113 struct MeshPeerQueue
114 {
115     /**
116       * DLL next
117       */
118   struct MeshPeerQueue *next;
119
120     /**
121       * DLL previous
122       */
123   struct MeshPeerQueue *prev;
124
125     /**
126      * Peer this transmission is directed to.
127      */
128   struct MeshPeerInfo *peer;
129
130     /**
131      * Tunnel this message belongs to.
132      */
133   struct MeshTunnel *tunnel;
134
135     /**
136      * Pointer to info stucture used as cls.
137      */
138   void *cls;
139
140     /**
141      * Type of message
142      */
143   uint16_t type;
144
145     /**
146      * Size of the message
147      */
148   size_t size;
149 };
150
151
152 /**
153  * Struct containing all info possibly needed to build a package when called
154  * back by core.
155  */
156 struct MeshTransmissionDescriptor
157 {
158     /** ID of the tunnel this packet travels in */
159   struct MESH_TunnelID *origin;
160
161     /** Who was this message being sent to */
162   struct MeshPeerInfo *peer;
163
164     /** Ultimate destination of the packet */
165   GNUNET_PEER_Id destination;
166
167     /** Data descriptor */
168   struct MeshData* mesh_data;
169 };
170
171
172 /**
173  * Struct containing all information regarding a given peer
174  */
175 struct MeshPeerInfo
176 {
177     /**
178      * ID of the peer
179      */
180   GNUNET_PEER_Id id;
181
182     /**
183      * Last time we heard from this peer
184      */
185   struct GNUNET_TIME_Absolute last_contact;
186
187     /**
188      * Number of attempts to reconnect so far
189      */
190   int n_reconnect_attempts;
191
192     /**
193      * Paths to reach the peer, ordered by ascending hop count
194      */
195   struct MeshPeerPath *path_head;
196
197     /**
198      * Paths to reach the peer, ordered by ascending hop count
199      */
200   struct MeshPeerPath *path_tail;
201
202     /**
203      * Handle to stop the DHT search for a path to this peer
204      */
205   struct GNUNET_DHT_GetHandle *dhtget;
206
207     /**
208      * Closure given to the DHT GET
209      */
210   struct MeshPathInfo *dhtgetcls;
211
212     /**
213      * Array of tunnels this peer participates in
214      * (most probably a small amount, therefore not a hashmap)
215      * When the path to the peer changes, notify these tunnels to let them
216      * re-adjust their path trees.
217      */
218   struct MeshTunnel **tunnels;
219
220     /**
221      * Number of tunnels this peers participates in
222      */
223   unsigned int ntunnels;
224
225    /**
226     * Transmission queue to core DLL head
227     */
228   struct MeshPeerQueue *queue_head;
229
230    /**
231     * Transmission queue to core DLL tail
232     */
233    struct MeshPeerQueue *queue_tail;
234
235    /**
236     * How many messages are in the queue to this peer.
237     */
238    unsigned int queue_n;
239
240    /**
241     * Handle to for queued transmissions
242     */
243   struct GNUNET_CORE_TransmitHandle *core_transmit;
244 };
245
246
247 /**
248  * Globally unique tunnel identification (owner + number)
249  * DO NOT USE OVER THE NETWORK
250  */
251 struct MESH_TunnelID
252 {
253     /**
254      * Node that owns the tunnel
255      */
256   GNUNET_PEER_Id oid;
257
258     /**
259      * Tunnel number to differentiate all the tunnels owned by the node oid
260      * ( tid < GNUNET_MESH_LOCAL_TUNNEL_ID_CLI )
261      */
262   MESH_TunnelNumber tid;
263 };
264
265
266 /**
267  * Struct containing all information regarding a tunnel
268  * For an intermediate node the improtant info used will be:
269  * - id        Tunnel unique identification
270  * - paths[0]  To know where to send it next
271  * - metainfo: ready, speeds, accounting
272  */
273 struct MeshTunnel
274 {
275     /**
276      * Tunnel ID
277      */
278   struct MESH_TunnelID id;
279
280     /**
281      * Local tunnel number ( >= GNUNET_MESH_LOCAL_TUNNEL_ID_CLI or 0 )
282      */
283   MESH_TunnelNumber local_tid;
284
285     /**
286      * Local tunnel number for local destination clients (incoming number)
287      * ( >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV or 0). All clients share the same
288      * number.
289      */
290   MESH_TunnelNumber local_tid_dest;
291
292     /**
293      * Is the speed on the tunnel limited to the slowest peer?
294      */
295   int speed_min;
296
297     /**
298      * Is the tunnel bufferless (minimum latency)?
299      */
300   int nobuffer;
301
302     /**
303      * Packet ID of the last fwd packet seen (sent/retransmitted/received).
304      */
305   uint32_t fwd_pid;
306
307     /**
308      * Packet ID of the last bck packet sent (unique counter per hop).
309      */
310   uint32_t bck_pid;
311
312   /**
313      * SKIP value for this tunnel.
314      */
315   uint32_t skip;
316
317     /**
318      * MeshTunnelChildInfo of all children, indexed by GNUNET_PEER_Id.
319      * Contains the Flow Control info: FWD ACK value received,
320      * last BCK ACK sent, PID and SKIP values.
321      */
322   struct GNUNET_CONTAINER_MultiHashMap *children_fc;
323
324     /**
325      * Last ACK sent towards the origin (for traffic towards leaf node).
326      */
327   uint32_t last_fwd_ack;
328
329   /**
330    * BCK ACK value received from the hop towards the owner of the tunnel,
331    * (previous node / owner): up to what message PID can we sent back to him.
332    */
333   uint32_t bck_ack;
334
335     /**
336      * How many messages are in the forward queue (towards leaves).
337      */
338   unsigned int fwd_queue_n;
339
340     /**
341      * How many messages do we accept in the forward queue.
342      */
343   unsigned int fwd_queue_max;
344
345     /**
346      * How many messages are in the backward queue (towards origin).
347      */
348   unsigned int bck_queue_n;
349
350     /**
351      * How many messages do we accept in the backward queue.
352     */
353    unsigned int bck_queue_max;
354
355     /**
356      * Last time the tunnel was used
357      */
358   struct GNUNET_TIME_Absolute timestamp;
359
360     /**
361      * Peers in the tunnel, indexed by PeerIdentity -> (MeshPeerInfo)
362      * containing peers added by id or by type, not intermediate peers.
363      */
364   struct GNUNET_CONTAINER_MultiHashMap *peers;
365
366     /**
367      * Number of peers that are connected and potentially ready to receive data
368      */
369   unsigned int peers_ready;
370
371     /**
372      * Number of peers that have been added to the tunnel
373      */
374   unsigned int peers_total;
375
376     /**
377      * Client owner of the tunnel, if any
378      */
379   struct MeshClient *owner;
380
381     /**
382      * Clients that have been informed about and want to stay in the tunnel.
383      */
384   struct MeshClient **clients;
385
386     /**
387      * Flow control info for each client.
388      */
389   struct MeshTunnelClientInfo *clients_fc;
390
391   /**
392      * Number of elements in clients/clients_fc
393      */
394   unsigned int nclients;
395
396     /**
397      * Clients that have been informed but requested to leave the tunnel.
398      */
399   struct MeshClient **ignore;
400
401     /**
402      * Number of elements in clients
403      */
404   unsigned int nignore;
405
406     /**
407      * Blacklisted peers
408      */
409   GNUNET_PEER_Id *blacklisted;
410
411     /**
412      * Number of elements in blacklisted
413      */
414   unsigned int nblacklisted;
415
416   /**
417    * Bloomfilter (for peer identities) to stop circular routes
418    */
419   char bloomfilter[MESH_BLOOM_SIZE];
420
421   /**
422    * Tunnel paths
423    */
424   struct MeshTunnelTree *tree;
425
426   /**
427    * Application type we are looking for in this tunnel
428    */
429   GNUNET_MESH_ApplicationType type;
430
431     /**
432      * Used to search peers offering a service
433      */
434   struct GNUNET_DHT_GetHandle *dht_get_type;
435
436     /**
437      * Initial context of the regex search for a connect_by_string
438      */
439   struct MeshRegexSearchContext *regex_ctx;
440
441     /**
442      * Task to keep the used paths alive
443      */
444   GNUNET_SCHEDULER_TaskIdentifier path_refresh_task;
445
446     /**
447      * Task to destroy the tunnel after timeout
448      *
449      * FIXME: merge the two? a tunnel will have either
450      * a path refresh OR a timeout, never both!
451      */
452   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
453
454     /**
455      * Flag to signal the destruction of the tunnel.
456      * If this is set GNUNET_YES the tunnel will be destroyed
457      * when the queue is empty.
458      */
459   int destroy;
460 };
461
462
463 /**
464  * Info about a child node in a tunnel, needed to perform flow control.
465  */
466 struct MeshTunnelChildInfo
467 {
468     /**
469      * ID of the child node.
470      */
471   GNUNET_PEER_Id id;
472
473     /**
474      * SKIP value.
475      */
476   uint32_t skip;
477
478     /**
479      * Last sent PID.
480      */
481   uint32_t pid;
482
483     /**
484      * Maximum PID allowed (FWD ACK received).
485      */
486   uint32_t fwd_ack;
487
488     /**
489      * Last ACK sent to that child (BCK ACK).
490      */
491   uint32_t bck_ack;
492 };
493
494
495 /**
496  * Info about a leaf client of a tunnel, needed to perform flow control.
497  */
498 struct MeshTunnelClientInfo
499 {
500   /**
501    * PID of the last packet sent to the client (FWD).
502    */
503   uint32_t fwd_pid;
504
505   /**
506    * PID of the last packet received from the client (BCK).
507    */
508   uint32_t bck_pid;
509
510   /**
511    * Maximum PID allowed (FWD ACK received).
512    */
513   uint32_t fwd_ack;
514   
515   /**
516    * Last ACK sent to that child (BCK ACK).
517    */
518   uint32_t bck_ack;
519 };
520
521
522
523 /**
524  * Info collected during iteration of child nodes in order to get the ACK value
525  * for a tunnel.
526  */
527 struct MeshTunnelChildIteratorContext
528 {
529     /**
530      * Tunnel whose info is being collected.
531      */
532   struct MeshTunnel *t;
533
534     /**
535      * Is this context initialized? Is the value in max_child_ack valid?
536      */
537   int init;
538
539     /**
540      * Maximum child ACK so far.
541      */
542   uint32_t max_child_ack;
543
544     /**
545      * Number of children nodes
546      */
547   unsigned int nchildren;
548 };
549
550
551 /**
552  * Info needed to work with tunnel paths and peers
553  */
554 struct MeshPathInfo
555 {
556   /**
557    * Tunnel
558    */
559   struct MeshTunnel *t;
560
561   /**
562    * Neighbouring peer to whom we send the packet to
563    */
564   struct MeshPeerInfo *peer;
565
566   /**
567    * Path itself
568    */
569   struct MeshPeerPath *path;
570 };
571
572
573 /**
574  * Struct containing information about a client of the service
575  */
576 struct MeshClient
577 {
578     /**
579      * Linked list next
580      */
581   struct MeshClient *next;
582
583     /**
584      * Linked list prev
585      */
586   struct MeshClient *prev;
587
588     /**
589      * Tunnels that belong to this client, indexed by local id
590      */
591   struct GNUNET_CONTAINER_MultiHashMap *own_tunnels;
592
593    /**
594      * Tunnels this client has accepted, indexed by incoming local id
595      */
596   struct GNUNET_CONTAINER_MultiHashMap *incoming_tunnels;
597
598    /**
599      * Tunnels this client has rejected, indexed by incoming local id
600      */
601   struct GNUNET_CONTAINER_MultiHashMap *ignore_tunnels;
602     /**
603      * Handle to communicate with the client
604      */
605   struct GNUNET_SERVER_Client *handle;
606
607     /**
608      * Applications that this client has claimed to provide
609      */
610   struct GNUNET_CONTAINER_MultiHashMap *apps;
611
612     /**
613      * Messages that this client has declared interest in
614      */
615   struct GNUNET_CONTAINER_MultiHashMap *types;
616
617     /**
618      * Whether the client is active or shutting down (don't send confirmations
619      * to a client that is shutting down.
620      */
621   int shutting_down;
622
623     /**
624      * ID of the client, mainly for debug messages
625      */
626   unsigned int id;
627   
628     /**
629      * Regular expressions describing the services offered by this client.
630      */
631   char **regexes; // FIXME add timeout? API to remove a regex?
632
633     /**
634      * Number of regular expressions in regexes.
635      */
636   unsigned int n_regex;
637
638     /**
639      * Task to refresh all regular expresions in the DHT.
640      */
641   GNUNET_SCHEDULER_TaskIdentifier regex_announce_task;
642
643 };
644
645
646 /**
647  * Struct to keep information of searches of services described by a regex
648  * using a user-provided string service description.
649  */
650 struct MeshRegexSearchInfo
651 {
652     /**
653      * Which tunnel is this for
654      */
655   struct MeshTunnel *t;
656
657     /**
658      * User provided description of the searched service.
659      */
660   char *description;
661
662     /**
663      * Part of the description already consumed by the search.
664      */
665   size_t position;
666
667     /**
668      * Running DHT GETs.
669      */
670   struct GNUNET_CONTAINER_MultiHashMap *dht_get_handles;
671
672     /**
673      * Results from running DHT GETs.
674      */
675   struct GNUNET_CONTAINER_MultiHashMap *dht_get_results;
676
677     /**
678      * Contexts, for each running DHT GET. Free all on end of search.
679      */
680   struct MeshRegexSearchContext **contexts;
681
682     /**
683      * Number of contexts (branches/steps in search).
684      */
685   unsigned int n_contexts;
686
687     /**
688      * Peer that is connecting via connect_by_string. When connected, free ctx.
689      */
690   GNUNET_PEER_Id peer;
691
692     /**
693      * Other peers that are found but not yet being connected to.
694      */
695   GNUNET_PEER_Id *peers;
696
697     /**
698      * Number of elements in peers.
699      */
700   unsigned int n_peers;
701
702     /**
703      * Next peer to try to connect to.
704      */
705   unsigned int i_peer;
706
707     /**
708      * Timeout for a connect attempt.
709      * When reached, try to connect to a different peer, if any. If not,
710      * try the same peer again.
711      */
712   GNUNET_SCHEDULER_TaskIdentifier timeout;
713
714 };
715
716 /**
717  * Struct to keep state of running searches that have consumed a part of
718  * the inital string.
719  */
720 struct MeshRegexSearchContext
721 {
722     /**
723      * Part of the description already consumed by
724      * this particular search branch.
725      */
726   size_t position;
727
728     /**
729      * Information about the search.
730      */
731   struct MeshRegexSearchInfo *info;
732
733 };
734
735 /******************************************************************************/
736 /************************      DEBUG FUNCTIONS     ****************************/
737 /******************************************************************************/
738
739 #if MESH_DEBUG
740 /**
741  * GNUNET_SCHEDULER_Task for printing a message after some operation is done
742  * @param cls string to print
743  * @param success  GNUNET_OK if the PUT was transmitted,
744  *                GNUNET_NO on timeout,
745  *                GNUNET_SYSERR on disconnect from service
746  *                after the PUT message was transmitted
747  *                (so we don't know if it was received or not)
748  */
749
750 #if 0
751 static void
752 mesh_debug (void *cls, int success)
753 {
754   char *s = cls;
755
756   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s (%d)\n", s, success);
757 }
758 #endif
759
760 #endif
761
762 /******************************************************************************/
763 /***********************      GLOBAL VARIABLES     ****************************/
764 /******************************************************************************/
765
766
767 /**
768  * Configuration parameters
769  */
770 static struct GNUNET_TIME_Relative refresh_path_time;
771 static struct GNUNET_TIME_Relative app_announce_time;
772 static struct GNUNET_TIME_Relative id_announce_time;
773 static struct GNUNET_TIME_Relative unacknowledged_wait_time;
774 static struct GNUNET_TIME_Relative connect_timeout;
775 static long long unsigned int default_ttl;
776 static long long unsigned int dht_replication_level;
777 static long long unsigned int max_tunnels;
778 static long long unsigned int max_msgs_queue;
779
780 /**
781  * DLL with all the clients, head.
782  */
783 static struct MeshClient *clients;
784
785 /**
786  * DLL with all the clients, tail.
787  */
788 static struct MeshClient *clients_tail;
789
790 /**
791  * Tunnels known, indexed by MESH_TunnelID (MeshTunnel).
792  */
793 static struct GNUNET_CONTAINER_MultiHashMap *tunnels;
794
795 /**
796  * Number of tunnels known.
797  */
798 static unsigned long long n_tunnels;
799
800 /**
801  * Tunnels incoming, indexed by MESH_TunnelNumber
802  * (which is greater than GNUNET_MESH_LOCAL_TUNNEL_ID_SERV).
803  */
804 static struct GNUNET_CONTAINER_MultiHashMap *incoming_tunnels;
805
806 /**
807  * Peers known, indexed by PeerIdentity (MeshPeerInfo).
808  */
809 static struct GNUNET_CONTAINER_MultiHashMap *peers;
810
811 /*
812  * Handle to communicate with transport
813  */
814 // static struct GNUNET_TRANSPORT_Handle *transport_handle;
815
816 /**
817  * Handle to communicate with core.
818  */
819 static struct GNUNET_CORE_Handle *core_handle;
820
821 /**
822  * Handle to use DHT.
823  */
824 static struct GNUNET_DHT_Handle *dht_handle;
825
826 /**
827  * Handle to server.
828  */
829 static struct GNUNET_SERVER_Handle *server_handle;
830
831 /**
832  * Handle to the statistics service.
833  */
834 static struct GNUNET_STATISTICS_Handle *stats;
835
836 /**
837  * Notification context, to send messages to local clients.
838  */
839 static struct GNUNET_SERVER_NotificationContext *nc;
840
841 /**
842  * Local peer own ID (memory efficient handle).
843  */
844 static GNUNET_PEER_Id myid;
845
846 /**
847  * Local peer own ID (full value).
848  */
849 static struct GNUNET_PeerIdentity my_full_id;
850
851 /**
852  * Own private key.
853  */
854 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
855
856 /**
857  * Own public key.
858  */
859 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
860
861 /**
862  * Tunnel ID for the next created tunnel (global tunnel number).
863  */
864 static MESH_TunnelNumber next_tid;
865
866 /**
867  * Tunnel ID for the next incoming tunnel (local tunnel number).
868  */
869 static MESH_TunnelNumber next_local_tid;
870
871 /**
872  * All application types provided by this peer.
873  */
874 static struct GNUNET_CONTAINER_MultiHashMap *applications;
875
876 /**
877  * All message types clients of this peer are interested in.
878  */
879 static struct GNUNET_CONTAINER_MultiHashMap *types;
880
881 /**
882  * Task to periodically announce provided applications.
883  */
884 GNUNET_SCHEDULER_TaskIdentifier announce_applications_task;
885
886 /**
887  * Task to periodically announce itself in the network.
888  */
889 GNUNET_SCHEDULER_TaskIdentifier announce_id_task;
890
891 /**
892  * Next ID to assign to a client.
893  */
894 unsigned int next_client_id;
895
896
897 /******************************************************************************/
898 /***********************         DECLARATIONS        **************************/
899 /******************************************************************************/
900
901 /* FIXME move declarations here */
902
903 /**
904  * Function to process paths received for a new peer addition. The recorded
905  * paths form the initial tunnel, which can be optimized later.
906  * Called on each result obtained for the DHT search.
907  *
908  * @param cls closure
909  * @param exp when will this value expire
910  * @param key key of the result
911  * @param type type of the result
912  * @param size number of bytes in data
913  * @param data pointer to the result data
914  */
915 static void
916 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
917                     const struct GNUNET_HashCode * key,
918                     const struct GNUNET_PeerIdentity *get_path,
919                     unsigned int get_path_length,
920                     const struct GNUNET_PeerIdentity *put_path,
921                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
922                     size_t size, const void *data);
923
924
925 /**
926  * Function to process DHT string to regex matching.
927  * Called on each result obtained for the DHT search.
928  *
929  * @param cls closure (search context)
930  * @param exp when will this value expire
931  * @param key key of the result
932  * @param get_path path of the get request (not used)
933  * @param get_path_length lenght of get_path (not used)
934  * @param put_path path of the put request (not used)
935  * @param put_path_length length of the put_path (not used)
936  * @param type type of the result
937  * @param size number of bytes in data
938  * @param data pointer to the result data
939  *
940  * TODO: re-issue the request after certain time? cancel after X results?
941  */
942 static void
943 dht_get_string_handler (void *cls, struct GNUNET_TIME_Absolute exp,
944                         const struct GNUNET_HashCode * key,
945                         const struct GNUNET_PeerIdentity *get_path,
946                         unsigned int get_path_length,
947                         const struct GNUNET_PeerIdentity *put_path,
948                         unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
949                         size_t size, const void *data);
950
951
952 /**
953  * Function to process DHT string to regex matching.
954  * Called on each result obtained for the DHT search.
955  *
956  * @param cls closure (search context)
957  * @param exp when will this value expire
958  * @param key key of the result
959  * @param get_path path of the get request (not used)
960  * @param get_path_length lenght of get_path (not used)
961  * @param put_path path of the put request (not used)
962  * @param put_path_length length of the put_path (not used)
963  * @param type type of the result
964  * @param size number of bytes in data
965  * @param data pointer to the result data
966  */
967 static void
968 dht_get_string_accept_handler (void *cls, struct GNUNET_TIME_Absolute exp,
969                                const struct GNUNET_HashCode * key,
970                                const struct GNUNET_PeerIdentity *get_path,
971                                unsigned int get_path_length,
972                                const struct GNUNET_PeerIdentity *put_path,
973                                unsigned int put_path_length,
974                                enum GNUNET_BLOCK_Type type,
975                                size_t size, const void *data);
976
977
978 /**
979  * Retrieve the MeshPeerInfo stucture associated with the peer, create one
980  * and insert it in the appropiate structures if the peer is not known yet.
981  *
982  * @param peer Short identity of the peer.
983  *
984  * @return Existing or newly created peer info.
985  */
986 static struct MeshPeerInfo *
987 peer_info_get_short (const GNUNET_PEER_Id peer);
988
989
990 /**
991  * Try to establish a new connection to this peer.
992  * Use the best path for the given tunnel.
993  * If the peer doesn't have any path to it yet, try to get one.
994  * If the peer already has some path, send a CREATE PATH towards it.
995  *
996  * @param peer PeerInfo of the peer.
997  * @param t Tunnel for which to create the path, if possible.
998  */
999 static void
1000 peer_info_connect (struct MeshPeerInfo *peer, struct MeshTunnel *t);
1001
1002
1003 /**
1004  * Add a peer to a tunnel, accomodating paths accordingly and initializing all
1005  * needed rescources.
1006  * If peer already exists, reevaluate shortest path and change if different.
1007  *
1008  * @param t Tunnel we want to add a new peer to
1009  * @param peer PeerInfo of the peer being added
1010  *
1011  */
1012 static void
1013 tunnel_add_peer (struct MeshTunnel *t, struct MeshPeerInfo *peer);
1014
1015
1016 /**
1017  * Removes an explicit path from a tunnel, freeing all intermediate nodes
1018  * that are no longer needed, as well as nodes of no longer reachable peers.
1019  * The tunnel itself is also destoyed if results in a remote empty tunnel.
1020  *
1021  * @param t Tunnel from which to remove the path.
1022  * @param peer Short id of the peer which should be removed.
1023  */
1024 static void
1025 tunnel_delete_peer (struct MeshTunnel *t, GNUNET_PEER_Id peer);
1026
1027
1028 /**
1029  * Search for a tunnel by global ID using full PeerIdentities.
1030  *
1031  * @param oid owner of the tunnel.
1032  * @param tid global tunnel number.
1033  *
1034  * @return tunnel handler, NULL if doesn't exist.
1035  */
1036 static struct MeshTunnel *
1037 tunnel_get (struct GNUNET_PeerIdentity *oid, MESH_TunnelNumber tid);
1038
1039
1040 /**
1041  * Delete an active client from the tunnel.
1042  *
1043  * @param t Tunnel.
1044  * @param c Client.
1045  */
1046 static void
1047 tunnel_delete_active_client (struct MeshTunnel *t, const struct MeshClient *c);
1048
1049 /**
1050  * Notify a tunnel that a connection has broken that affects at least
1051  * some of its peers.
1052  *
1053  * @param t Tunnel affected.
1054  * @param p1 Peer that got disconnected from p2.
1055  * @param p2 Peer that got disconnected from p1.
1056  *
1057  * @return Short ID of the peer disconnected (either p1 or p2).
1058  *         0 if the tunnel remained unaffected.
1059  */
1060 static GNUNET_PEER_Id
1061 tunnel_notify_connection_broken (struct MeshTunnel *t, GNUNET_PEER_Id p1,
1062                                  GNUNET_PEER_Id p2);
1063
1064
1065 /**
1066  * Get the current ack value for a tunnel, for data going from root to leaves,
1067  * taking in account the tunnel mode and the status of all children and clients.
1068  *
1069  * @param t Tunnel.
1070  *
1071  * @return Maximum PID allowed.
1072  */
1073 static uint32_t
1074 tunnel_get_fwd_ack (struct MeshTunnel *t);
1075
1076 /**
1077  * Get the current ack value for a tunnel, for data going from leaves to root,
1078  * taking in account the tunnel mode and the status of all children and clients.
1079  *
1080  * @param t Tunnel.
1081  *
1082  * @return Maximum PID allowed.
1083  */
1084 static uint32_t
1085 tunnel_get_bck_ack (struct MeshTunnel *t);
1086
1087 /**
1088  * Add a client to a tunnel, initializing all needed data structures.
1089  * 
1090  * @param t Tunnel to which add the client.
1091  * @param c Client which to add to the tunnel.
1092  */
1093 static void
1094 tunnel_add_client (struct MeshTunnel *t, struct MeshClient *c);
1095
1096
1097 /**
1098  * Iterator over edges in a regex block retrieved from the DHT.
1099  *
1100  * @param cls Closure.
1101  * @param token Token that follows to next state.
1102  * @param len Lenght of token.
1103  * @param key Hash of next state.
1104  *
1105  * @return GNUNET_YES if should keep iterating, GNUNET_NO otherwise.
1106  */
1107 static int
1108 regex_edge_iterator (void *cls,
1109                      const char *token,
1110                      size_t len,
1111                      const struct GNUNET_HashCode *key);
1112
1113
1114 /**
1115  * Find a path to a peer that offers a regex servcie compatible
1116  * with a given string.
1117  * 
1118  * @param key The key of the accepting state.
1119  * @param ctx Context containing info about the string, tunnel, etc.
1120  */
1121 static void
1122 regex_find_path (const struct GNUNET_HashCode *key,
1123                  struct MeshRegexSearchContext *ctx);
1124
1125
1126 /**
1127  * Queue and pass message to core when possible.
1128  *
1129  * @param cls Closure (type dependant).
1130  * @param type Type of the message, 0 for a raw message.
1131  * @param size Size of the message.
1132  * @param dst Neighbor to send message to.
1133  * @param t Tunnel this message belongs to.
1134  */
1135 static void
1136 queue_add (void *cls, uint16_t type, size_t size,
1137            struct MeshPeerInfo *dst, struct MeshTunnel *t);
1138
1139 /**
1140  * Free a transmission that was already queued with all resources
1141  * associated to the request.
1142  *
1143  * @param queue Queue handler to cancel.
1144  * @param clear_cls Is it necessary to free associated cls?
1145  */
1146 static void
1147 queue_destroy (struct MeshPeerQueue *queue, int clear_cls);
1148
1149 /******************************************************************************/
1150 /************************         ITERATORS        ****************************/
1151 /******************************************************************************/
1152
1153 /**
1154  * Iterator over found existing mesh regex blocks that match an ongoing search.
1155  *
1156  * @param cls closure
1157  * @param key current key code
1158  * @param value value in the hash map
1159  * @return GNUNET_YES if we should continue to iterate,
1160  *         GNUNET_NO if not.
1161  */
1162 static int
1163 regex_result_iterator (void *cls,
1164                        const struct GNUNET_HashCode * key,
1165                        void *value)
1166 {
1167   struct MeshRegexBlock *block = value;
1168   struct MeshRegexSearchContext *ctx = cls;
1169
1170   if (GNUNET_YES == ntohl(block->accepting) &&
1171       ctx->position == strlen (ctx->info->description))
1172   {
1173     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* Found accepting known block\n");
1174     regex_find_path (key, ctx);
1175     return GNUNET_YES; // We found an accept state!
1176   }
1177   else
1178   {
1179     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* %u, %u, [%u]\n",
1180                 ctx->position, strlen(ctx->info->description),
1181                 ntohl(block->accepting));
1182
1183   }
1184   (void) GNUNET_MESH_regex_block_iterate (block, SIZE_MAX,
1185                                           &regex_edge_iterator, ctx);
1186
1187   return GNUNET_YES;
1188 }
1189
1190
1191 /**
1192  * Iterator over edges in a regex block retrieved from the DHT.
1193  *
1194  * @param cls Closure (context of the search).
1195  * @param token Token that follows to next state.
1196  * @param len Lenght of token.
1197  * @param key Hash of next state.
1198  *
1199  * @return GNUNET_YES if should keep iterating, GNUNET_NO otherwise.
1200  */
1201 static int
1202 regex_edge_iterator (void *cls,
1203                      const char *token,
1204                      size_t len,
1205                      const struct GNUNET_HashCode *key)
1206 {
1207   struct MeshRegexSearchContext *ctx = cls;
1208   struct MeshRegexSearchContext *new_ctx;
1209   struct MeshRegexSearchInfo *info = ctx->info;
1210   struct GNUNET_DHT_GetHandle *get_h;
1211   char *current;
1212   size_t current_len;
1213
1214   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*    Start of regex edge iterator\n");
1215   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*     descr : %s\n", info->description);
1216   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*     posit : %u\n", ctx->position);
1217   current = &info->description[ctx->position];
1218   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*     currt : %s\n", current);
1219   current_len = strlen (info->description) - ctx->position;
1220   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*     ctlen : %u\n", current_len);
1221   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*     tklen : %u\n", len);
1222   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*     tk[0] : %c\n", token[0]);
1223   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*     nextk : %s\n", GNUNET_h2s(key));
1224   if (len > current_len)
1225   {
1226     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*     Token too long, END\n");
1227     return GNUNET_YES; // Token too long, wont match
1228   }
1229   if (0 != strncmp (current, token, len))
1230   {
1231     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*     Token doesn't match, END\n");
1232     return GNUNET_YES; // Token doesn't match
1233   }
1234   new_ctx = GNUNET_malloc (sizeof (struct MeshRegexSearchContext));
1235   new_ctx->info = info;
1236   new_ctx->position = ctx->position + len;
1237   GNUNET_array_append (info->contexts, info->n_contexts, new_ctx);
1238   if (GNUNET_YES ==
1239       GNUNET_CONTAINER_multihashmap_contains(info->dht_get_handles, key))
1240   {
1241     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*     GET running, END\n");
1242     GNUNET_CONTAINER_multihashmap_get_multiple (info->dht_get_results, key,
1243                                                 &regex_result_iterator,
1244                                                 new_ctx);
1245     return GNUNET_YES; // We are already looking for it
1246   }
1247   /* Start search in DHT */
1248   get_h = 
1249       GNUNET_DHT_get_start (dht_handle,    /* handle */
1250                             GNUNET_BLOCK_TYPE_MESH_REGEX, /* type */
1251                             key,     /* key to search */
1252                             dht_replication_level, /* replication level */
1253                             GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
1254                             NULL,       /* xquery */ // FIXME BLOOMFILTER
1255                             0,     /* xquery bits */ // FIXME BLOOMFILTER SIZE
1256                             &dht_get_string_handler, new_ctx);
1257   if (GNUNET_OK !=
1258       GNUNET_CONTAINER_multihashmap_put(info->dht_get_handles, key, get_h,
1259                                         GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
1260   {
1261     GNUNET_break (0);
1262     return GNUNET_YES;
1263   }
1264   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*    End of regex edge iterator\n");
1265   return GNUNET_YES;
1266 }
1267
1268 /**
1269  * Iterator over hash map entries to cancel DHT GET requests after a
1270  * successful connect_by_string.
1271  *
1272  * @param cls Closure (unused).
1273  * @param key Current key code (unused).
1274  * @param value Value in the hash map (get handle).
1275  * @return GNUNET_YES if we should continue to iterate,
1276  *         GNUNET_NO if not.
1277  */
1278 static int
1279 regex_cancel_dht_get (void *cls,
1280                       const struct GNUNET_HashCode * key,
1281                       void *value)
1282 {
1283   struct GNUNET_DHT_GetHandle *h = value;
1284
1285   GNUNET_DHT_get_stop (h);
1286   return GNUNET_YES;
1287 }
1288
1289
1290 /**
1291  * Iterator over hash map entries to free MeshRegexBlocks stored during the
1292  * search for connect_by_string.
1293  *
1294  * @param cls Closure (unused).
1295  * @param key Current key code (unused).
1296  * @param value MeshRegexBlock in the hash map.
1297  * @return GNUNET_YES if we should continue to iterate,
1298  *         GNUNET_NO if not.
1299  */
1300 static int
1301 regex_free_result (void *cls,
1302                    const struct GNUNET_HashCode * key,
1303                    void *value)
1304 {
1305
1306   GNUNET_free (value);
1307   return GNUNET_YES;
1308 }
1309
1310
1311 /**
1312  * Regex callback iterator to store own service description in the DHT.
1313  *
1314  * @param cls closure.
1315  * @param key hash for current state.
1316  * @param proof proof for current state.
1317  * @param accepting GNUNET_YES if this is an accepting state, GNUNET_NO if not.
1318  * @param num_edges number of edges leaving current state.
1319  * @param edges edges leaving current state.
1320  */
1321 void
1322 regex_iterator (void *cls, const struct GNUNET_HashCode *key, const char *proof,
1323                 int accepting, unsigned int num_edges,
1324                 const struct GNUNET_REGEX_Edge *edges)
1325 {
1326     struct MeshRegexBlock *block;
1327     struct MeshRegexEdge *block_edge;
1328     enum GNUNET_DHT_RouteOption opt;
1329     size_t size;
1330     size_t len;
1331     unsigned int i;
1332     unsigned int offset;
1333     char *aux;
1334
1335     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1336                 "  regex dht put for state %s\n",
1337                 GNUNET_h2s(key));
1338     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1339                 "   proof: %s\n",
1340                 proof);
1341     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1342                 "   num edges: %u\n",
1343                 num_edges);
1344
1345     opt = GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE;
1346     if (GNUNET_YES == accepting)
1347     {
1348         struct MeshRegexAccept block;
1349
1350         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1351                     "   state %s is accepting, putting own id\n",
1352                     GNUNET_h2s(key));
1353         size = sizeof (block);
1354         block.key = *key;
1355         block.id = my_full_id;
1356         (void)
1357         GNUNET_DHT_put(dht_handle, key,
1358                        dht_replication_level,
1359                        opt | GNUNET_DHT_RO_RECORD_ROUTE,
1360                        GNUNET_BLOCK_TYPE_MESH_REGEX_ACCEPT,
1361                        size,
1362                        (char *) &block,
1363                        GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get (),
1364                                                  app_announce_time),
1365                        app_announce_time,
1366                        NULL, NULL);
1367     }
1368     len = strlen(proof);
1369     size = sizeof (struct MeshRegexBlock) + len;
1370     block = GNUNET_malloc (size);
1371
1372     block->key = *key;
1373     block->n_proof = htonl (len);
1374     block->n_edges = htonl (num_edges);
1375     block->accepting = htonl (accepting);
1376
1377     /* Store the proof at the end of the block. */
1378     aux = (char *) &block[1];
1379     memcpy (aux, proof, len);
1380     aux = &aux[len];
1381
1382     /* Store each edge in a variable length MeshEdge struct at the
1383      * very end of the MeshRegexBlock structure.
1384      */
1385     for (i = 0; i < num_edges; i++)
1386     {
1387         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1388                     "    edge %s towards %s\n",
1389                     edges[i].label,
1390                     GNUNET_h2s(&edges[i].destination));
1391
1392         /* aux points at the end of the last block */
1393         len = strlen (edges[i].label);
1394         size += sizeof (struct MeshRegexEdge) + len;
1395         // Calculate offset FIXME is this ok? use size instead?
1396         offset = aux - (char *) block;
1397         block = GNUNET_realloc (block, size);
1398         aux = &((char *) block)[offset];
1399         block_edge = (struct MeshRegexEdge *) aux;
1400         block_edge->key = edges[i].destination;
1401         block_edge->n_token = htonl (len);
1402         aux = (char *) &block_edge[1];
1403         memcpy (aux, edges[i].label, len);
1404         aux = &aux[len];
1405     }
1406     (void)
1407     GNUNET_DHT_put(dht_handle, key,
1408                    dht_replication_level,
1409                    opt,
1410                    GNUNET_BLOCK_TYPE_MESH_REGEX, size,
1411                    (char *) block,
1412                    GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get (),
1413                                             app_announce_time),
1414                    app_announce_time,
1415                    NULL, NULL);
1416     GNUNET_free (block);
1417 }
1418
1419
1420 /**
1421  * Store the regular expression describing a local service into the DHT.
1422  *
1423  * @param regex The regular expresion.
1424  */
1425 static void
1426 regex_put (const char *regex)
1427 {
1428   struct GNUNET_REGEX_Automaton *dfa;
1429
1430   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "regex_put (%s) start\n", regex);
1431   dfa = GNUNET_REGEX_construct_dfa (regex, strlen(regex));
1432   GNUNET_REGEX_iterate_all_edges (dfa, &regex_iterator, NULL);
1433   GNUNET_REGEX_automaton_destroy (dfa);
1434   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "regex_put (%s) end\n", regex);
1435
1436 }
1437
1438 /**
1439  * Find a path to a peer that offers a regex servcie compatible
1440  * with a given string.
1441  * 
1442  * @param key The key of the accepting state.
1443  * @param ctx Context containing info about the string, tunnel, etc.
1444  */
1445 static void
1446 regex_find_path (const struct GNUNET_HashCode *key,
1447                  struct MeshRegexSearchContext *ctx)
1448 {
1449   struct GNUNET_DHT_GetHandle *get_h;
1450
1451   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Found peer by service\n");
1452   get_h = GNUNET_DHT_get_start (dht_handle,    /* handle */
1453                                 GNUNET_BLOCK_TYPE_MESH_REGEX_ACCEPT, /* type */
1454                                 key,     /* key to search */
1455                                 dht_replication_level, /* replication level */
1456                                 GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE |
1457                                 GNUNET_DHT_RO_RECORD_ROUTE,
1458                                 NULL,       /* xquery */ // FIXME BLOOMFILTER
1459                                 0,     /* xquery bits */ // FIXME BLOOMFILTER SIZE
1460                                 &dht_get_string_accept_handler, ctx);
1461   GNUNET_break (GNUNET_OK ==
1462                 GNUNET_CONTAINER_multihashmap_put(ctx->info->dht_get_handles,
1463                                                   key,
1464                                                   get_h,
1465                                                   GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
1466 }
1467
1468
1469 /**
1470  * Function called if the connect attempt to a peer found via
1471  * connect_by_string times out. Try to connect to another peer, if any.
1472  * Otherwise try to reconnect to the same peer.
1473  *
1474  * @param cls Closure (info about regex search).
1475  * @param tc TaskContext.
1476  */
1477 static void
1478 regex_connect_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1479 {
1480   struct MeshRegexSearchInfo *info = cls;
1481   struct MeshPeerInfo *peer_info;
1482   GNUNET_PEER_Id id;
1483   GNUNET_PEER_Id old;
1484
1485   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Regex connect timeout\n");
1486   info->timeout = GNUNET_SCHEDULER_NO_TASK;
1487   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1488   {
1489     return;
1490   }
1491
1492   old = info->peer;
1493   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  timed out: %u\n", old);
1494
1495   if (0 < info->n_peers)
1496   {
1497     // Select next peer, put current in that spot.
1498     id = info->peers[info->i_peer];
1499     info->peers[info->i_peer] = info->peer;
1500     info->i_peer = (info->i_peer + 1) % info->n_peers;
1501   }
1502   else
1503   {
1504     // Try to connect to same peer again.
1505     id = info->peer;
1506   }
1507   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  trying: %u\n", id);
1508
1509   peer_info = peer_info_get_short(id);
1510   tunnel_add_peer (info->t, peer_info);
1511   if (old != id)
1512     tunnel_delete_peer (info->t, old);
1513   peer_info_connect (peer_info, info->t);
1514   info->timeout = GNUNET_SCHEDULER_add_delayed (connect_timeout,
1515                                                 &regex_connect_timeout,
1516                                                 info);
1517   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Regex connect timeout END\n");
1518 }
1519
1520
1521 /**
1522  * Cancel an ongoing regex search in the DHT and free all resources.
1523  *
1524  * @param ctx The search context.
1525  */
1526 static void
1527 regex_cancel_search(struct MeshRegexSearchContext *ctx)
1528 {
1529   struct MeshRegexSearchInfo *info = ctx->info;
1530   int i;
1531
1532   GNUNET_free (info->description);
1533   GNUNET_CONTAINER_multihashmap_iterate (info->dht_get_handles,
1534                                              &regex_cancel_dht_get, NULL);
1535   GNUNET_CONTAINER_multihashmap_iterate (info->dht_get_results,
1536                                          &regex_free_result, NULL);
1537   GNUNET_CONTAINER_multihashmap_destroy (info->dht_get_results);
1538   GNUNET_CONTAINER_multihashmap_destroy (info->dht_get_handles);
1539   info->t->regex_ctx = NULL;
1540   for (i = 0; i < info->n_contexts; i++)
1541   {
1542     GNUNET_free (info->contexts[i]);
1543   }
1544   if (0 < info->n_contexts)
1545     GNUNET_free (info->contexts);
1546   if (0 < info->n_peers)
1547     GNUNET_free (info->peers);
1548   if (GNUNET_SCHEDULER_NO_TASK != info->timeout)
1549   {
1550     GNUNET_SCHEDULER_cancel(info->timeout);
1551   }
1552   GNUNET_free (info);
1553 }
1554
1555
1556 /******************************************************************************/
1557 /************************    PERIODIC FUNCTIONS    ****************************/
1558 /******************************************************************************/
1559
1560 /**
1561  * Announce iterator over for each application provided by the peer
1562  *
1563  * @param cls closure
1564  * @param key current key code
1565  * @param value value in the hash map
1566  * @return GNUNET_YES if we should continue to
1567  *         iterate,
1568  *         GNUNET_NO if not.
1569  */
1570 static int
1571 announce_application (void *cls, const struct GNUNET_HashCode * key, void *value)
1572 {
1573   struct PBlock block;
1574   struct MeshClient *c;
1575
1576   block.id = my_full_id;
1577   c =  GNUNET_CONTAINER_multihashmap_get (applications, key);
1578   block.type = (long) GNUNET_CONTAINER_multihashmap_get (c->apps, key);
1579   if (0 == block.type)
1580   {
1581     GNUNET_break(0);
1582     return GNUNET_YES;
1583   }
1584   block.type = htonl (block.type);
1585
1586   GNUNET_break (NULL != 
1587                 GNUNET_DHT_put (dht_handle, key,
1588                   dht_replication_level,
1589                   GNUNET_DHT_RO_RECORD_ROUTE |
1590                   GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
1591                   GNUNET_BLOCK_TYPE_MESH_PEER_BY_TYPE,
1592                   sizeof (block),
1593                   (const char *) &block,
1594                   GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get (),
1595                                             app_announce_time),
1596                   app_announce_time, NULL, NULL));
1597   return GNUNET_OK;
1598 }
1599
1600
1601 /**
1602  * Periodically announce what applications are provided by local clients
1603  * (by regex)
1604  *
1605  * @param cls closure
1606  * @param tc task context
1607  */
1608 static void
1609 announce_regex (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1610 {
1611   struct MeshClient *c = cls;
1612   unsigned int i;
1613
1614   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1615   {
1616     c->regex_announce_task = GNUNET_SCHEDULER_NO_TASK;
1617     return;
1618   }
1619
1620   DEBUG_DHT ("Starting PUT for regex\n");
1621
1622   for (i = 0; i < c->n_regex; i++)
1623   {
1624     regex_put (c->regexes[i]);
1625   }
1626   c->regex_announce_task =
1627       GNUNET_SCHEDULER_add_delayed (app_announce_time, &announce_regex, cls);
1628   DEBUG_DHT ("Finished PUT for regex\n");
1629
1630   return;
1631 }
1632
1633
1634 /**
1635  * Periodically announce what applications are provided by local clients
1636  * (by type)
1637  *
1638  * @param cls closure
1639  * @param tc task context
1640  */
1641 static void
1642 announce_applications (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1643 {
1644   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1645   {
1646     announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
1647     return;
1648   }
1649  
1650   DEBUG_DHT ("Starting PUT for apps\n");
1651
1652   GNUNET_CONTAINER_multihashmap_iterate (applications, &announce_application,
1653                                          NULL);
1654   announce_applications_task =
1655       GNUNET_SCHEDULER_add_delayed (app_announce_time, &announce_applications,
1656                                     cls);
1657   DEBUG_DHT ("Finished PUT for apps\n");
1658
1659   return;
1660 }
1661
1662
1663 /**
1664  * Periodically announce self id in the DHT
1665  *
1666  * @param cls closure
1667  * @param tc task context
1668  */
1669 static void
1670 announce_id (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1671 {
1672   struct PBlock block;
1673
1674   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1675   {
1676     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
1677     return;
1678   }
1679   /* TODO
1680    * - Set data expiration in function of X
1681    * - Adapt X to churn
1682    */
1683   DEBUG_DHT ("DHT_put for ID %s started.\n", GNUNET_i2s (&my_full_id));
1684
1685   block.id = my_full_id;
1686   block.type = htonl (0);
1687   GNUNET_DHT_put (dht_handle,   /* DHT handle */
1688                   &my_full_id.hashPubKey,       /* Key to use */
1689                   dht_replication_level,     /* Replication level */
1690                   GNUNET_DHT_RO_RECORD_ROUTE | GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,    /* DHT options */
1691                   GNUNET_BLOCK_TYPE_MESH_PEER,       /* Block type */
1692                   sizeof (block),  /* Size of the data */
1693                   (const char *) &block, /* Data itself */
1694                   GNUNET_TIME_UNIT_FOREVER_ABS,  /* Data expiration */
1695                   GNUNET_TIME_UNIT_FOREVER_REL, /* Retry time */
1696                   NULL,         /* Continuation */
1697                   NULL);        /* Continuation closure */
1698   announce_id_task =
1699       GNUNET_SCHEDULER_add_delayed (id_announce_time, &announce_id, cls);
1700 }
1701
1702
1703 /******************************************************************************/
1704 /******************      GENERAL HELPER FUNCTIONS      ************************/
1705 /******************************************************************************/
1706
1707 /**
1708  * Decrements the reference counter and frees all resources if needed
1709  *
1710  * @param mesh_data Data Descriptor used in a multicast message.
1711  *                  Freed no longer needed (last message).
1712  */
1713 static void
1714 data_descriptor_decrement_rc (struct MeshData *mesh_data)
1715 {
1716   /* Make sure it's a multicast packet */
1717   GNUNET_assert (NULL != mesh_data->reference_counter);
1718
1719   if (0 == --(*(mesh_data->reference_counter)))
1720   {
1721     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Last copy!\n");
1722     if (NULL != mesh_data->task)
1723     {
1724       if (GNUNET_SCHEDULER_NO_TASK != *(mesh_data->task))
1725       {
1726         GNUNET_SCHEDULER_cancel (*(mesh_data->task));
1727         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " notifying client...\n");
1728         GNUNET_SERVER_receive_done (mesh_data->t->owner->handle, GNUNET_OK);
1729       }
1730       GNUNET_free (mesh_data->task);
1731     }
1732     GNUNET_free (mesh_data->reference_counter);
1733     GNUNET_free (mesh_data->data);
1734     GNUNET_free (mesh_data);
1735   }
1736 }
1737
1738
1739 /**
1740  * Check if client has registered with the service and has not disconnected
1741  *
1742  * @param client the client to check
1743  *
1744  * @return non-NULL if client exists in the global DLL
1745  */
1746 static struct MeshClient *
1747 client_get (struct GNUNET_SERVER_Client *client)
1748 {
1749   struct MeshClient *c;
1750
1751   c = clients;
1752   while (NULL != c)
1753   {
1754     if (c->handle == client)
1755       return c;
1756     c = c->next;
1757   }
1758   return NULL;
1759 }
1760
1761
1762 /**
1763  * Checks if a given client has subscribed to certain message type
1764  *
1765  * @param message_type Type of message to check
1766  * @param c Client to check
1767  *
1768  * @return GNUNET_YES or GNUNET_NO, depending on subscription status
1769  */
1770 static int
1771 client_is_subscribed (uint16_t message_type, struct MeshClient *c)
1772 {
1773   struct GNUNET_HashCode hc;
1774
1775   if (NULL == c->types)
1776     return GNUNET_NO;
1777   GNUNET_CRYPTO_hash (&message_type, sizeof (uint16_t), &hc);
1778   return GNUNET_CONTAINER_multihashmap_contains (c->types, &hc);
1779 }
1780
1781
1782 /**
1783  * Allow a client to send more data after transmitting a multicast message
1784  * which some neighbor has not yet accepted altough a reasonable time has
1785  * passed.
1786  *
1787  * @param cls Closure (DataDescriptor containing the task identifier)
1788  * @param tc Task Context
1789  * 
1790  * FIXME reference counter cshould be just int
1791  */
1792 static void
1793 client_allow_send (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1794 {
1795   struct MeshData *mdata = cls;
1796
1797   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1798     return;
1799   GNUNET_assert (NULL != mdata->reference_counter);
1800   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1801               "CLIENT ALLOW SEND DESPITE %u COPIES PENDING\n",
1802               *(mdata->reference_counter));
1803   *(mdata->task) = GNUNET_SCHEDULER_NO_TASK;
1804   GNUNET_SERVER_receive_done (mdata->t->owner->handle, GNUNET_OK);
1805 }
1806
1807
1808 /**
1809  * Check whether client wants traffic from a tunnel.
1810  *
1811  * @param c Client to check.
1812  * @param t Tunnel to be found.
1813  *
1814  * @return GNUNET_YES if client knows tunnel.
1815  * 
1816  * TODO look in client hashmap
1817  */
1818 static int
1819 client_wants_tunnel (struct MeshClient *c, struct MeshTunnel *t)
1820 {
1821   unsigned int i;
1822
1823   for (i = 0; i < t->nclients; i++)
1824     if (t->clients[i] == c)
1825       return GNUNET_YES;
1826   return GNUNET_NO;
1827 }
1828
1829
1830 /**
1831  * Check whether client has been informed about a tunnel.
1832  *
1833  * @param c Client to check.
1834  * @param t Tunnel to be found.
1835  *
1836  * @return GNUNET_YES if client knows tunnel.
1837  * 
1838  * TODO look in client hashmap
1839  */
1840 static int
1841 client_knows_tunnel (struct MeshClient *c, struct MeshTunnel *t)
1842 {
1843   unsigned int i;
1844
1845   for (i = 0; i < t->nignore; i++)
1846     if (t->ignore[i] == c)
1847       return GNUNET_YES;
1848   return client_wants_tunnel(c, t);
1849 }
1850
1851
1852 /**
1853  * Marks a client as uninterested in traffic from the tunnel, updating both
1854  * client and tunnel to reflect this.
1855  *
1856  * @param c Client that doesn't want traffic anymore.
1857  * @param t Tunnel which should be ignored.
1858  *
1859  * FIXME when to delete an incoming tunnel?
1860  */
1861 static void
1862 client_ignore_tunnel (struct MeshClient *c, struct MeshTunnel *t)
1863 {
1864   struct GNUNET_HashCode hash;
1865
1866   GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
1867   GNUNET_break (GNUNET_YES ==
1868                 GNUNET_CONTAINER_multihashmap_remove (c->incoming_tunnels,
1869                                                       &hash, t));
1870   GNUNET_break (GNUNET_YES ==
1871                 GNUNET_CONTAINER_multihashmap_put (c->ignore_tunnels, &hash, t,
1872                                                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
1873   tunnel_delete_active_client (t, c);
1874   GNUNET_array_append (t->ignore, t->nignore, c);
1875 }
1876
1877
1878 /**
1879  * Deletes a tunnel from a client (either owner or destination). To be used on
1880  * tunnel destroy, otherwise, use client_ignore_tunnel.
1881  *
1882  * @param c Client whose tunnel to delete.
1883  * @param t Tunnel which should be deleted.
1884  */
1885 static void
1886 client_delete_tunnel (struct MeshClient *c, struct MeshTunnel *t)
1887 {
1888   struct GNUNET_HashCode hash;
1889
1890   if (c == t->owner)
1891   {
1892     GNUNET_CRYPTO_hash(&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
1893     GNUNET_assert (GNUNET_YES ==
1894                    GNUNET_CONTAINER_multihashmap_remove (c->own_tunnels,
1895                                                          &hash,
1896                                                          t));
1897   }
1898   else
1899   {
1900     GNUNET_CRYPTO_hash(&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
1901     // FIXME XOR?
1902     GNUNET_assert (GNUNET_YES ==
1903                    GNUNET_CONTAINER_multihashmap_remove (c->incoming_tunnels,
1904                                                          &hash,
1905                                                          t) ||
1906                    GNUNET_YES ==
1907                    GNUNET_CONTAINER_multihashmap_remove (c->ignore_tunnels,
1908                                                          &hash,
1909                                                          t));
1910   }
1911 }
1912
1913
1914 /**
1915  * Send the message to all clients that have subscribed to its type
1916  *
1917  * @param msg Pointer to the message itself
1918  * @param payload Pointer to the payload of the message.
1919  * @return number of clients this message was sent to
1920  */
1921 static unsigned int
1922 send_subscribed_clients (const struct GNUNET_MessageHeader *msg,
1923                          const struct GNUNET_MessageHeader *payload)
1924 {
1925   struct GNUNET_PeerIdentity *oid;
1926   struct MeshClient *c;
1927   struct MeshTunnel *t;
1928   MESH_TunnelNumber *tid;
1929   unsigned int count;
1930   uint16_t type;
1931   char cbuf[htons (msg->size)];
1932
1933   type = ntohs (payload->type);
1934   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending to clients...\n");
1935   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "message of type %s\n",
1936               GNUNET_MESH_DEBUG_M2S (type));
1937
1938   memcpy (cbuf, msg, sizeof (cbuf));
1939   switch (htons (msg->type))
1940   {
1941     struct GNUNET_MESH_Unicast *uc;
1942     struct GNUNET_MESH_Multicast *mc;
1943     struct GNUNET_MESH_ToOrigin *to;
1944
1945   case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
1946     uc = (struct GNUNET_MESH_Unicast *) cbuf;
1947     tid = &uc->tid;
1948     oid = &uc->oid;
1949     break;
1950   case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
1951     mc = (struct GNUNET_MESH_Multicast *) cbuf;
1952     tid = &mc->tid;
1953     oid = &mc->oid;
1954     break;
1955   case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
1956     to = (struct GNUNET_MESH_ToOrigin *) cbuf;
1957     tid = &to->tid;
1958     oid = &to->oid;
1959     break;
1960   default:
1961     GNUNET_break (0);
1962     return 0;
1963   }
1964   t = tunnel_get (oid, ntohl (*tid));
1965   if (NULL == t)
1966   {
1967     GNUNET_break (0);
1968     return 0;
1969   }
1970
1971   for (count = 0, c = clients; c != NULL; c = c->next)
1972   {
1973     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   client %u\n", c->id);
1974     if (client_is_subscribed (type, c))
1975     {
1976       if (htons (msg->type) == GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN)
1977       {
1978         if (c != t->owner)
1979           continue;
1980         *tid = htonl (t->local_tid);
1981       }
1982       else
1983       {
1984         if (GNUNET_NO == client_knows_tunnel (c, t))
1985         {
1986           /* This client doesn't know the tunnel */
1987           struct GNUNET_MESH_TunnelNotification tmsg;
1988           struct GNUNET_HashCode hash;
1989
1990           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "     sending tunnel create\n");
1991           tmsg.header.size = htons (sizeof (tmsg));
1992           tmsg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
1993           GNUNET_PEER_resolve (t->id.oid, &tmsg.peer);
1994           tmsg.tunnel_id = htonl (t->local_tid_dest);
1995           GNUNET_SERVER_notification_context_unicast (nc, c->handle,
1996                                                       &tmsg.header, GNUNET_NO);
1997           tunnel_add_client (t, c);
1998           GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber),
1999                               &hash);
2000           GNUNET_break (GNUNET_OK == GNUNET_CONTAINER_multihashmap_put (
2001                                        c->incoming_tunnels, &hash, t,
2002                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
2003         }
2004         *tid = htonl (t->local_tid_dest);
2005       }
2006
2007       /* Check if the client wants to get traffic from the tunnel */
2008       if (GNUNET_NO == client_wants_tunnel(c, t))
2009         continue;
2010       count++;
2011       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "     sending\n");
2012       GNUNET_SERVER_notification_context_unicast (nc, c->handle,
2013                                                   (struct GNUNET_MessageHeader
2014                                                    *) cbuf, GNUNET_NO);
2015     }
2016   }
2017   return count;
2018 }
2019
2020
2021 /**
2022  * Notify the client that owns the tunnel that a peer has connected to it
2023  * (the requested path to it has been confirmed).
2024  *
2025  * @param t Tunnel whose owner to notify
2026  * @param id Short id of the peer that has connected
2027  */
2028 static void
2029 send_client_peer_connected (const struct MeshTunnel *t, const GNUNET_PEER_Id id)
2030 {
2031   struct GNUNET_MESH_PeerControl pc;
2032
2033   pc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD);
2034   pc.header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
2035   pc.tunnel_id = htonl (t->local_tid);
2036   GNUNET_PEER_resolve (id, &pc.peer);
2037   GNUNET_SERVER_notification_context_unicast (nc, t->owner->handle, &pc.header,
2038                                               GNUNET_NO);
2039 }
2040
2041
2042 /**
2043  * Notify a client of a tunnel about how many more
2044  * payload packages will we accept on a given tunnel,
2045  * distinguishing between root and leaf clients.
2046  *
2047  * @param c Client whom to send the ACK.
2048  * @param t Tunnel on which to send the ACK.
2049  */
2050 static void
2051 send_client_tunnel_ack (struct MeshClient *c, struct MeshTunnel *t)
2052 {
2053   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! // FIXME fc
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       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3818                   "  sending ack to client %u: %u\n",
3819                   t->clients[i]->id, ack);
3820       send_local_ack(t->clients[i],  t, ack);
3821       clinfo->bck_ack = ack;
3822     }
3823   }
3824 }
3825
3826
3827 /**
3828  * Send an ACK informing the children nodes and destination clients about
3829  * the available buffer space.
3830  * If buffering is off, send only on behalf of root (can be self).
3831  * If buffering is on, send when sent to predecessor and buffer space is free.
3832  * Note that although the name is bck_ack, the BCK mean backwards *traffic*,
3833  * the ACK itself goes "forward" (towards children/clients).
3834  * 
3835  * @param t Tunnel on which to send the ACK.
3836  * @param type Type of message that triggered the ACK transmission.
3837  */
3838 static void
3839 tunnel_send_bck_ack (struct MeshTunnel *t, uint16_t type)
3840 {
3841   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3842               "Sending BCK ACK on tunnel %u [%u]\n",
3843               t->id.oid, t->id.tid);
3844   /* Is it after data to_origin retransmission? */
3845   switch (type)
3846   {
3847     case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
3848       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3849                   "ACK due to BCK DATA retransmission\n");
3850       if (GNUNET_YES == t->nobuffer)
3851       {
3852         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, nobuffer\n");
3853         return;
3854       }
3855       if (t->bck_queue_max > t->bck_queue_n * 2)
3856       {
3857 //         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, buffer free\n");
3858 //         return;
3859       }
3860       break;
3861     case GNUNET_MESSAGE_TYPE_MESH_ACK:
3862     case GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK:
3863       // FIXME fc
3864       break;
3865     default:
3866       GNUNET_break (0);
3867   }
3868
3869   tunnel_send_clients_bck_ack (t);
3870   tree_iterate_children (t->tree, &tunnel_send_child_bck_ack, NULL);
3871 }
3872
3873
3874 /**
3875  * Send a message to all peers in this tunnel that the tunnel is no longer
3876  * valid.
3877  *
3878  * @param t The tunnel whose peers to notify.
3879  */
3880 static void
3881 tunnel_send_destroy (struct MeshTunnel *t)
3882 {
3883   struct GNUNET_MESH_TunnelDestroy msg;
3884
3885   msg.header.size = htons (sizeof (msg));
3886   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY);
3887   GNUNET_PEER_resolve (t->id.oid, &msg.oid);
3888   msg.tid = htonl (t->id.tid);
3889   tunnel_send_multicast (t, &msg.header, GNUNET_NO);
3890 }
3891
3892
3893 /**
3894  * Cancel all transmissions towards a neighbor that belong to a certain tunnel.
3895  *
3896  * @param cls Closure (Tunnel which to cancel).
3897  * @param neighbor_id Short ID of the neighbor to whom cancel the transmissions.
3898  */
3899 static void
3900 tunnel_cancel_queues (void *cls, GNUNET_PEER_Id neighbor_id)
3901 {
3902   struct MeshTunnel *t = cls;
3903   struct MeshPeerInfo *peer_info;
3904   struct MeshPeerQueue *pq;
3905   struct MeshPeerQueue *next;
3906
3907   peer_info = peer_info_get_short (neighbor_id);
3908   for (pq = peer_info->queue_head; NULL != pq; pq = next)
3909   {
3910     next = pq->next;
3911     if (pq->tunnel == t)
3912     {
3913       queue_destroy (pq, GNUNET_YES);
3914     }
3915   }
3916   if (NULL == peer_info->queue_head && NULL != peer_info->core_transmit)
3917   {
3918     GNUNET_CORE_notify_transmit_ready_cancel(peer_info->core_transmit);
3919     peer_info->core_transmit = NULL;
3920   }
3921 }
3922
3923 /**
3924  * Destroy the tunnel and free any allocated resources linked to it.
3925  *
3926  * @param t the tunnel to destroy
3927  *
3928  * @return GNUNET_OK on success
3929  */
3930 static int
3931 tunnel_destroy (struct MeshTunnel *t)
3932 {
3933   struct MeshClient *c;
3934   struct GNUNET_HashCode hash;
3935   unsigned int i;
3936   int r;
3937
3938   if (NULL == t)
3939     return GNUNET_OK;
3940
3941   tree_iterate_children (t->tree, &tunnel_cancel_queues, t);
3942
3943   r = GNUNET_OK;
3944   c = t->owner;
3945 #if MESH_DEBUG
3946   {
3947     struct GNUNET_PeerIdentity id;
3948
3949     GNUNET_PEER_resolve (t->id.oid, &id);
3950     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s [%x]\n",
3951                 GNUNET_i2s (&id), t->id.tid);
3952     if (NULL != c)
3953       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
3954   }
3955 #endif
3956
3957   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
3958   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &hash, t))
3959   {
3960     r = GNUNET_SYSERR;
3961   }
3962
3963   GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
3964   if (NULL != c &&
3965       GNUNET_YES !=
3966       GNUNET_CONTAINER_multihashmap_remove (c->own_tunnels, &hash, t))
3967   {
3968     r = GNUNET_SYSERR;
3969   }
3970   GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
3971   for (i = 0; i < t->nclients; i++)
3972   {
3973     c = t->clients[i];
3974     if (GNUNET_YES !=
3975           GNUNET_CONTAINER_multihashmap_remove (c->incoming_tunnels, &hash, t))
3976     {
3977       r = GNUNET_SYSERR;
3978     }
3979   }
3980   for (i = 0; i < t->nignore; i++)
3981   {
3982     c = t->ignore[i];
3983     if (GNUNET_YES !=
3984           GNUNET_CONTAINER_multihashmap_remove (c->ignore_tunnels, &hash, t))
3985     {
3986       r = GNUNET_SYSERR;
3987     }
3988   }
3989   if (t->nclients > 0)
3990   {
3991     if (GNUNET_YES !=
3992         GNUNET_CONTAINER_multihashmap_remove (incoming_tunnels, &hash, t))
3993     {
3994       r = GNUNET_SYSERR;
3995     }
3996     GNUNET_free (t->clients);
3997   }
3998   if (NULL != t->peers)
3999   {
4000     GNUNET_CONTAINER_multihashmap_iterate (t->peers, &peer_info_delete_tunnel,
4001                                            t);
4002     GNUNET_CONTAINER_multihashmap_destroy (t->peers);
4003   }
4004
4005   GNUNET_CONTAINER_multihashmap_iterate (t->children_fc,
4006                                          &tunnel_destroy_child,
4007                                          t);
4008   GNUNET_CONTAINER_multihashmap_destroy (t->children_fc);
4009
4010   tree_destroy (t->tree);
4011
4012   if (NULL != t->regex_ctx)
4013     regex_cancel_search (t->regex_ctx);
4014   if (NULL != t->dht_get_type)
4015     GNUNET_DHT_get_stop (t->dht_get_type);
4016   if (GNUNET_SCHEDULER_NO_TASK != t->timeout_task)
4017     GNUNET_SCHEDULER_cancel (t->timeout_task);
4018   if (GNUNET_SCHEDULER_NO_TASK != t->path_refresh_task)
4019     GNUNET_SCHEDULER_cancel (t->path_refresh_task);
4020
4021   n_tunnels--;
4022   GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
4023   GNUNET_assert (0 <= n_tunnels);
4024   GNUNET_free (t);
4025   return r;
4026 }
4027
4028
4029 /**
4030  * Create a new tunnel
4031  * 
4032  * @param owner Who is the owner of the tunnel (short ID).
4033  * @param tid Tunnel Number of the tunnel.
4034  * @param client Clients that owns the tunnel, NULL for foreign tunnels.
4035  * @param local Tunnel Number for the tunnel, for the client point of view.
4036  * 
4037  * @return A new initialized tunnel. NULL on error.
4038  */
4039 static struct MeshTunnel *
4040 tunnel_new (GNUNET_PEER_Id owner,
4041             MESH_TunnelNumber tid,
4042             struct MeshClient *client,
4043             MESH_TunnelNumber local)
4044 {
4045   struct MeshTunnel *t;
4046   struct GNUNET_HashCode hash;
4047
4048   if (n_tunnels >= max_tunnels && NULL == client)
4049     return NULL;
4050
4051   t = GNUNET_malloc (sizeof (struct MeshTunnel));
4052   t->id.oid = owner;
4053   t->id.tid = tid;
4054   t->fwd_queue_max = (max_msgs_queue / max_tunnels) + 1;
4055   t->bck_queue_max = t->fwd_queue_max;
4056   t->tree = tree_new (owner);
4057   t->owner = client;
4058   t->fwd_pid = (uint32_t) -1; // Next (expected) = 0
4059   t->bck_pid = (uint32_t) -1; // Next (expected) = 0
4060   t->bck_ack = INITIAL_WINDOW_SIZE - 1;
4061   t->last_fwd_ack = INITIAL_WINDOW_SIZE - 1;
4062   t->local_tid = local;
4063   t->children_fc = GNUNET_CONTAINER_multihashmap_create (8);
4064   n_tunnels++;
4065   GNUNET_STATISTICS_update (stats, "# tunnels", 1, GNUNET_NO);
4066
4067   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
4068   if (GNUNET_OK !=
4069       GNUNET_CONTAINER_multihashmap_put (tunnels, &hash, t,
4070                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
4071   {
4072     GNUNET_break (0);
4073     tunnel_destroy (t);
4074     if (NULL != client)
4075     {
4076       GNUNET_break (0);
4077       GNUNET_SERVER_receive_done (client->handle, GNUNET_SYSERR);
4078     }
4079     return NULL;
4080   }
4081
4082   if (NULL != client)
4083   {
4084     GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
4085     if (GNUNET_OK !=
4086         GNUNET_CONTAINER_multihashmap_put (client->own_tunnels, &hash, t,
4087                                           GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
4088     {
4089       tunnel_destroy (t);
4090       GNUNET_break (0);
4091       GNUNET_SERVER_receive_done (client->handle, GNUNET_SYSERR);
4092       return NULL;
4093     }
4094   }
4095
4096   return t;
4097 }
4098
4099
4100 /**
4101  * Removes an explicit path from a tunnel, freeing all intermediate nodes
4102  * that are no longer needed, as well as nodes of no longer reachable peers.
4103  * The tunnel itself is also destoyed if results in a remote empty tunnel.
4104  *
4105  * @param t Tunnel from which to remove the path.
4106  * @param peer Short id of the peer which should be removed.
4107  */
4108 static void
4109 tunnel_delete_peer (struct MeshTunnel *t, GNUNET_PEER_Id peer)
4110 {
4111   if (GNUNET_NO == tree_del_peer (t->tree, peer, NULL, NULL))
4112     tunnel_destroy (t);
4113 }
4114
4115
4116 /**
4117  * tunnel_destroy_iterator: iterator for deleting each tunnel that belongs to a
4118  * client when the client disconnects. If the client is not the owner, the
4119  * owner will get notified if no more clients are in the tunnel and the client
4120  * get removed from the tunnel's list.
4121  *
4122  * @param cls closure (client that is disconnecting)
4123  * @param key the hash of the local tunnel id (used to access the hashmap)
4124  * @param value the value stored at the key (tunnel to destroy)
4125  *
4126  * @return GNUNET_OK on success
4127  */
4128 static int
4129 tunnel_destroy_iterator (void *cls, const struct GNUNET_HashCode * key, void *value)
4130 {
4131   struct MeshTunnel *t = value;
4132   struct MeshClient *c = cls;
4133   int r;
4134
4135   send_client_tunnel_disconnect(t, c);
4136   if (c != t->owner)
4137   {
4138     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4139                 "Client %u is destination, keeping the tunnel alive.\n", c->id);
4140     tunnel_delete_client(t, c);
4141     client_delete_tunnel(c, t);
4142     return GNUNET_OK;
4143   }
4144   tunnel_send_destroy(t);
4145   r = tunnel_destroy (t);
4146   return r;
4147 }
4148
4149
4150 /**
4151  * Timeout function, destroys tunnel if called
4152  *
4153  * @param cls Closure (tunnel to destroy).
4154  * @param tc TaskContext
4155  */
4156 static void
4157 tunnel_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4158 {
4159   struct MeshTunnel *t = cls;
4160
4161   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4162     return;
4163   t->timeout_task = GNUNET_SCHEDULER_NO_TASK;
4164   tunnel_destroy (t);
4165 }
4166
4167 /**
4168  * Resets the tunnel timeout. Starts it if no timeout was running.
4169  *
4170  * @param t Tunnel whose timeout to reset.
4171  *
4172  * TODO use heap to improve efficiency of scheduler.
4173  */
4174 static void
4175 tunnel_reset_timeout (struct MeshTunnel *t)
4176 {
4177   if (GNUNET_SCHEDULER_NO_TASK != t->timeout_task)
4178     GNUNET_SCHEDULER_cancel (t->timeout_task);
4179   t->timeout_task =
4180       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
4181                                     (refresh_path_time, 4), &tunnel_timeout, t);
4182 }
4183
4184
4185 /******************************************************************************/
4186 /****************      MESH NETWORK HANDLER HELPERS     ***********************/
4187 /******************************************************************************/
4188
4189 /**
4190  * Function to send a create path packet to a peer.
4191  *
4192  * @param cls closure
4193  * @param size number of bytes available in buf
4194  * @param buf where the callee should write the message
4195  * @return number of bytes written to buf
4196  */
4197 static size_t
4198 send_core_path_create (void *cls, size_t size, void *buf)
4199 {
4200   struct MeshPathInfo *info = cls;
4201   struct GNUNET_MESH_ManipulatePath *msg;
4202   struct GNUNET_PeerIdentity *peer_ptr;
4203   struct MeshTunnel *t = info->t;
4204   struct MeshPeerPath *p = info->path;
4205   size_t size_needed;
4206   uint32_t opt;
4207   int i;
4208
4209   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATE PATH sending...\n");
4210   size_needed =
4211       sizeof (struct GNUNET_MESH_ManipulatePath) +
4212       p->length * sizeof (struct GNUNET_PeerIdentity);
4213
4214   if (size < size_needed || NULL == buf)
4215   {
4216     GNUNET_break (0);
4217     return 0;
4218   }
4219   msg = (struct GNUNET_MESH_ManipulatePath *) buf;
4220   msg->header.size = htons (size_needed);
4221   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE);
4222   msg->tid = ntohl (t->id.tid);
4223
4224   if (GNUNET_YES == t->speed_min)
4225     opt = MESH_TUNNEL_OPT_SPEED_MIN;
4226   if (GNUNET_YES == t->nobuffer)
4227     opt |= MESH_TUNNEL_OPT_NOBUFFER;
4228   msg->opt = htonl(opt);
4229
4230   peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
4231   for (i = 0; i < p->length; i++)
4232   {
4233     GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
4234   }
4235
4236   path_destroy (p);
4237   GNUNET_free (info);
4238
4239   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4240               "CREATE PATH (%u bytes long) sent!\n", size_needed);
4241   return size_needed;
4242 }
4243
4244
4245 /**
4246  * Fill the core buffer 
4247  *
4248  * @param cls closure (data itself)
4249  * @param size number of bytes available in buf
4250  * @param buf where the callee should write the message
4251  *
4252  * @return number of bytes written to buf
4253  */
4254 static size_t
4255 send_core_data_multicast (void *cls, size_t size, void *buf)
4256 {
4257   struct MeshTransmissionDescriptor *info = cls;
4258   size_t total_size;
4259
4260   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Multicast callback.\n");
4261   GNUNET_assert (NULL != info);
4262   GNUNET_assert (NULL != info->peer);
4263   total_size = info->mesh_data->data_len;
4264   GNUNET_assert (total_size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
4265
4266   if (total_size > size)
4267   {
4268     GNUNET_break (0);
4269     return 0;
4270   }
4271   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " copying data...\n");
4272   memcpy (buf, info->mesh_data->data, total_size);
4273 #if MESH_DEBUG
4274   {
4275     struct GNUNET_MESH_Multicast *mc;
4276     struct GNUNET_MessageHeader *mh;
4277
4278     mh = buf;
4279     if (ntohs (mh->type) == GNUNET_MESSAGE_TYPE_MESH_MULTICAST)
4280     {
4281       mc = (struct GNUNET_MESH_Multicast *) mh;
4282       mh = (struct GNUNET_MessageHeader *) &mc[1];
4283       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4284                   " multicast, payload type %s\n",
4285                   GNUNET_MESH_DEBUG_M2S (ntohs (mh->type)));
4286       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4287                   " multicast, payload size %u\n", ntohs (mh->size));
4288     }
4289     else
4290     {
4291       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " type %s\n",
4292                   GNUNET_MESH_DEBUG_M2S (ntohs (mh->type)));
4293     }
4294   }
4295 #endif
4296   data_descriptor_decrement_rc (info->mesh_data);
4297   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "freeing info...\n");
4298   GNUNET_free (info);
4299   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "return %u\n", total_size);
4300   return total_size;
4301 }
4302
4303
4304 /**
4305  * Creates a path ack message in buf and frees all unused resources.
4306  *
4307  * @param cls closure (MeshTransmissionDescriptor)
4308  * @param size number of bytes available in buf
4309  * @param buf where the callee should write the message
4310  * @return number of bytes written to buf
4311  */
4312 static size_t
4313 send_core_path_ack (void *cls, size_t size, void *buf)
4314 {
4315   struct MeshTransmissionDescriptor *info = cls;
4316   struct GNUNET_MESH_PathACK *msg = buf;
4317
4318   GNUNET_assert (NULL != info);
4319   if (sizeof (struct GNUNET_MESH_PathACK) > size)
4320   {
4321     GNUNET_break (0);
4322     return 0;
4323   }
4324   msg->header.size = htons (sizeof (struct GNUNET_MESH_PathACK));
4325   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_ACK);
4326   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
4327   msg->tid = htonl (info->origin->tid);
4328   msg->peer_id = my_full_id;
4329
4330   GNUNET_free (info);
4331   /* TODO add signature */
4332
4333   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "PATH ACK sent!\n");
4334   return sizeof (struct GNUNET_MESH_PathACK);
4335 }
4336
4337
4338 /**
4339  * Free a transmission that was already queued with all resources
4340  * associated to the request.
4341  *
4342  * @param queue Queue handler to cancel.
4343  * @param clear_cls Is it necessary to free associated cls?
4344  */
4345 static void
4346 queue_destroy (struct MeshPeerQueue *queue, int clear_cls)
4347 {
4348   struct MeshTransmissionDescriptor *dd;
4349   struct MeshPathInfo *path_info;
4350
4351   if (GNUNET_YES == clear_cls)
4352   {
4353     switch (queue->type)
4354     {
4355     case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4356     case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
4357     case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4358         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   type payload\n");
4359         dd = queue->cls;
4360         data_descriptor_decrement_rc (dd->mesh_data);
4361         break;
4362     case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
4363         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   type create path\n");
4364         path_info = queue->cls;
4365         path_destroy (path_info->path);
4366         break;
4367     default:
4368         GNUNET_break (0);
4369         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   type unknown!\n");
4370     }
4371     GNUNET_free_non_null (queue->cls);
4372   }
4373   GNUNET_CONTAINER_DLL_remove (queue->peer->queue_head,
4374                                queue->peer->queue_tail,
4375                                queue);
4376   GNUNET_free (queue);
4377 }
4378
4379
4380 /**
4381   * Core callback to write a queued packet to core buffer
4382   *
4383   * @param cls Closure (peer info).
4384   * @param size Number of bytes available in buf.
4385   * @param buf Where the to write the message.
4386   *
4387   * @return number of bytes written to buf
4388   */
4389 static size_t
4390 queue_send (void *cls, size_t size, void *buf)
4391 {
4392     struct MeshPeerInfo *peer = cls;
4393     struct GNUNET_MessageHeader *msg;
4394     struct MeshPeerQueue *queue;
4395     struct MeshTunnel *t;
4396     size_t data_size;
4397
4398     peer->core_transmit = NULL;
4399     queue = peer->queue_head;
4400
4401     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "********* Queue send\n");
4402
4403     /* If queue is empty, send should have been cancelled */
4404     if (NULL == queue)
4405     {
4406         GNUNET_break(0);
4407         return 0;
4408     }
4409     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   not empty\n");
4410
4411     /* Check if buffer size is enough for the message */
4412     if (queue->size > size)
4413     {
4414         struct GNUNET_PeerIdentity id;
4415
4416         GNUNET_PEER_resolve (peer->id, &id);
4417         peer->core_transmit =
4418             GNUNET_CORE_notify_transmit_ready(core_handle,
4419                                               0,
4420                                               0,
4421                                               GNUNET_TIME_UNIT_FOREVER_REL,
4422                                               &id,
4423                                               queue->size,
4424                                               &queue_send,
4425                                               peer);
4426         return 0;
4427     }
4428     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   size ok\n");
4429
4430     t = queue->tunnel;
4431     if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == queue->type)
4432     {
4433       t->fwd_queue_n--;
4434       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   unicast: %u\n");
4435     }
4436     else if (GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == queue->type)
4437     {
4438       t->bck_queue_n--;
4439       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   to origin\n");
4440     }
4441
4442     /* Fill buf */
4443     switch (queue->type)
4444     {
4445       case 0:
4446       case GNUNET_MESSAGE_TYPE_MESH_ACK:
4447       case GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN:
4448       case GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY:
4449         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4450                     "*********   raw: %u\n",
4451                     queue->type);
4452         /* Fall through */
4453       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4454       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4455         data_size = send_core_data_raw (queue->cls, size, buf);
4456         msg = (struct GNUNET_MessageHeader *) buf;
4457         switch (ntohs (msg->type)) // Type of preconstructed message
4458         {
4459           case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4460             tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_UNICAST);
4461             break;
4462           case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4463             tunnel_send_bck_ack(t, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
4464             break;
4465           default:
4466               break;
4467         }
4468         break;
4469       case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
4470         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   multicast\n");
4471         data_size = send_core_data_multicast(queue->cls, size, buf);
4472         tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
4473         break;
4474       case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
4475         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path create\n");
4476         data_size = send_core_path_create(queue->cls, size, buf);
4477         break;
4478       case GNUNET_MESSAGE_TYPE_MESH_PATH_ACK:
4479         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path ack\n");
4480         data_size = send_core_path_ack(queue->cls, size, buf);
4481         break;
4482       default:
4483         GNUNET_break (0);
4484         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4485                     "*********   type unknown: %u\n",
4486                     queue->type);
4487         data_size = 0;
4488     }
4489
4490     /* Free queue, but cls was freed by send_core_* */
4491     queue_destroy (queue, GNUNET_NO);
4492
4493     if (GNUNET_YES == t->destroy && 0 == t->fwd_queue_n)
4494     {
4495       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********  destroying tunnel!\n");
4496       tunnel_destroy (t);
4497     }
4498
4499     /* If more data in queue, send next */
4500     if (NULL != peer->queue_head)
4501     {
4502         struct GNUNET_PeerIdentity id;
4503
4504         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   more data!\n");
4505         GNUNET_PEER_resolve (peer->id, &id);
4506         peer->core_transmit =
4507             GNUNET_CORE_notify_transmit_ready(core_handle,
4508                                               0,
4509                                               0,
4510                                               GNUNET_TIME_UNIT_FOREVER_REL,
4511                                               &id,
4512                                               peer->queue_head->size,
4513                                               &queue_send,
4514                                               peer);
4515     }
4516     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   return %d\n", data_size);
4517     return data_size;
4518 }
4519
4520
4521 /**
4522  * Queue and pass message to core when possible.
4523  *
4524  * @param cls Closure (type dependant).
4525  * @param type Type of the message, 0 for a raw message.
4526  * @param size Size of the message.
4527  * @param dst Neighbor to send message to.
4528  * @param t Tunnel this message belongs to.
4529  */
4530 static void
4531 queue_add (void *cls, uint16_t type, size_t size,
4532            struct MeshPeerInfo *dst, struct MeshTunnel *t)
4533 {
4534   struct MeshPeerQueue *queue;
4535   unsigned int *max;
4536   unsigned int *n;
4537
4538   n = NULL;
4539   if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == type ||
4540       GNUNET_MESSAGE_TYPE_MESH_MULTICAST == type)
4541   {
4542     n = &t->fwd_queue_n;
4543     max = &t->fwd_queue_max;
4544   }
4545   else if (GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == type)
4546   {
4547     n = &t->bck_queue_n;
4548     max = &t->bck_queue_max;
4549   }
4550   if (NULL != n) {
4551     if (*n >= *max)
4552     {
4553       if (NULL == t->owner)
4554         GNUNET_break_op(0);       // TODO: kill connection?
4555       else
4556         GNUNET_break(0);
4557       return;                       // Drop message
4558     }
4559     (*n)++;
4560   }
4561   queue = GNUNET_malloc (sizeof (struct MeshPeerQueue));
4562   queue->cls = cls;
4563   queue->type = type;
4564   queue->size = size;
4565   queue->peer = dst;
4566   queue->tunnel = t;
4567   GNUNET_CONTAINER_DLL_insert_tail (dst->queue_head, dst->queue_tail, queue);
4568   if (NULL == dst->core_transmit)
4569   {
4570       struct GNUNET_PeerIdentity id;
4571
4572       GNUNET_PEER_resolve (dst->id, &id);
4573       dst->core_transmit =
4574           GNUNET_CORE_notify_transmit_ready(core_handle,
4575                                             0,
4576                                             0,
4577                                             GNUNET_TIME_UNIT_FOREVER_REL,
4578                                             &id,
4579                                             size,
4580                                             &queue_send,
4581                                             dst);
4582   }
4583 }
4584
4585
4586 /******************************************************************************/
4587 /********************      MESH NETWORK HANDLERS     **************************/
4588 /******************************************************************************/
4589
4590
4591 /**
4592  * Core handler for path creation
4593  *
4594  * @param cls closure
4595  * @param message message
4596  * @param peer peer identity this notification is about
4597  * @param atsi performance data
4598  * @param atsi_count number of records in 'atsi'
4599  *
4600  * @return GNUNET_OK to keep the connection open,
4601  *         GNUNET_SYSERR to close it (signal serious error)
4602  */
4603 static int
4604 handle_mesh_path_create (void *cls, const struct GNUNET_PeerIdentity *peer,
4605                          const struct GNUNET_MessageHeader *message,
4606                          const struct GNUNET_ATS_Information *atsi,
4607                          unsigned int atsi_count)
4608 {
4609   unsigned int own_pos;
4610   uint16_t size;
4611   uint16_t i;
4612   MESH_TunnelNumber tid;
4613   struct GNUNET_MESH_ManipulatePath *msg;
4614   struct GNUNET_PeerIdentity *pi;
4615   struct GNUNET_HashCode hash;
4616   struct MeshPeerPath *path;
4617   struct MeshPeerInfo *dest_peer_info;
4618   struct MeshPeerInfo *orig_peer_info;
4619   struct MeshTunnel *t;
4620
4621   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4622               "Received a path create msg [%s]\n",
4623               GNUNET_i2s (&my_full_id));
4624   size = ntohs (message->size);
4625   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
4626   {
4627     GNUNET_break_op (0);
4628     return GNUNET_OK;
4629   }
4630
4631   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
4632   if (size % sizeof (struct GNUNET_PeerIdentity))
4633   {
4634     GNUNET_break_op (0);
4635     return GNUNET_OK;
4636   }
4637   size /= sizeof (struct GNUNET_PeerIdentity);
4638   if (size < 2)
4639   {
4640     GNUNET_break_op (0);
4641     return GNUNET_OK;
4642   }
4643   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
4644   msg = (struct GNUNET_MESH_ManipulatePath *) message;
4645
4646   tid = ntohl (msg->tid);
4647   pi = (struct GNUNET_PeerIdentity *) &msg[1];
4648   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4649               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi), tid);
4650   t = tunnel_get (pi, tid);
4651   if (NULL == t) // FIXME only for INCOMING tunnels?
4652   {
4653     uint32_t opt;
4654
4655     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating tunnel\n");
4656     t = tunnel_new (GNUNET_PEER_intern (pi), tid, NULL, 0);
4657     if (NULL == t)
4658     {
4659       // FIXME notify failure
4660       return GNUNET_OK;
4661     }
4662     opt = ntohl (msg->opt);
4663     t->speed_min = (0 != (opt & MESH_TUNNEL_OPT_SPEED_MIN)) ?
4664                    GNUNET_YES : GNUNET_NO;
4665     t->nobuffer = (0 != (opt & MESH_TUNNEL_OPT_NOBUFFER)) ?
4666                   GNUNET_YES : GNUNET_NO;
4667
4668     if (GNUNET_YES == t->nobuffer)
4669     {
4670       t->bck_queue_max = 1;
4671       t->fwd_queue_max = 1;
4672     }
4673
4674     // FIXME only assign a local tid if a local client is interested (on demand)
4675     while (NULL != tunnel_get_incoming (next_local_tid))
4676       next_local_tid = (next_local_tid + 1) | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
4677     t->local_tid_dest = next_local_tid++;
4678     next_local_tid = next_local_tid | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
4679     // FIXME end
4680
4681     tunnel_reset_timeout (t);
4682     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
4683     if (GNUNET_OK !=
4684         GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
4685                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
4686     {
4687       tunnel_destroy (t);
4688       GNUNET_break (0);
4689       return GNUNET_OK;
4690     }
4691   }
4692   dest_peer_info =
4693       GNUNET_CONTAINER_multihashmap_get (peers, &pi[size - 1].hashPubKey);
4694   if (NULL == dest_peer_info)
4695   {
4696     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4697                 "  Creating PeerInfo for destination.\n");
4698     dest_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
4699     dest_peer_info->id = GNUNET_PEER_intern (&pi[size - 1]);
4700     GNUNET_CONTAINER_multihashmap_put (peers, &pi[size - 1].hashPubKey,
4701                                        dest_peer_info,
4702                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
4703   }
4704   orig_peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &pi->hashPubKey);
4705   if (NULL == orig_peer_info)
4706   {
4707     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4708                 "  Creating PeerInfo for origin.\n");
4709     orig_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
4710     orig_peer_info->id = GNUNET_PEER_intern (pi);
4711     GNUNET_CONTAINER_multihashmap_put (peers, &pi->hashPubKey, orig_peer_info,
4712                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
4713   }
4714   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
4715   path = path_new (size);
4716   own_pos = 0;
4717   for (i = 0; i < size; i++)
4718   {
4719     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
4720                 GNUNET_i2s (&pi[i]));
4721     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
4722     if (path->peers[i] == myid)
4723       own_pos = i;
4724   }
4725   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
4726   if (own_pos == 0)
4727   {
4728     /* cannot be self, must be 'not found' */
4729     /* create path: self not found in path through self */
4730     GNUNET_break_op (0);
4731     path_destroy (path);
4732     tunnel_destroy (t);
4733     return GNUNET_OK;
4734   }
4735   path_add_to_peers (path, GNUNET_NO);
4736   tunnel_add_path (t, path, own_pos);
4737   if (own_pos == size - 1)
4738   {
4739     /* It is for us! Send ack. */
4740     struct MeshTransmissionDescriptor *info;
4741
4742     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
4743     peer_info_add_path_to_origin (orig_peer_info, path, GNUNET_NO);
4744     if (NULL == t->peers)
4745     {
4746       /* New tunnel! Notify clients on data. */
4747       t->peers = GNUNET_CONTAINER_multihashmap_create (4);
4748     }
4749     GNUNET_break (GNUNET_SYSERR !=
4750                   GNUNET_CONTAINER_multihashmap_put (t->peers,
4751                                                      &my_full_id.hashPubKey,
4752                                                      peer_info_get
4753                                                      (&my_full_id),
4754                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE));
4755     info = GNUNET_malloc (sizeof (struct MeshTransmissionDescriptor));
4756     info->origin = &t->id;
4757     info->peer = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
4758     GNUNET_assert (NULL != info->peer);
4759     queue_add(info,
4760               GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
4761               sizeof (struct GNUNET_MESH_PathACK),
4762               info->peer,
4763               t);
4764   }
4765   else
4766   {
4767     struct MeshPeerPath *path2;
4768
4769     /* It's for somebody else! Retransmit. */
4770     path2 = path_duplicate (path);
4771     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Retransmitting.\n");
4772     peer_info_add_path (dest_peer_info, path2, GNUNET_NO);
4773     path2 = path_duplicate (path);
4774     peer_info_add_path_to_origin (orig_peer_info, path2, GNUNET_NO);
4775     send_create_path (dest_peer_info, path, t);
4776   }
4777   return GNUNET_OK;
4778 }
4779
4780
4781 /**
4782  * Core handler for path destruction
4783  *
4784  * @param cls closure
4785  * @param message message
4786  * @param peer peer identity this notification is about
4787  * @param atsi performance data
4788  * @param atsi_count number of records in 'atsi'
4789  *
4790  * @return GNUNET_OK to keep the connection open,
4791  *         GNUNET_SYSERR to close it (signal serious error)
4792  */
4793 static int
4794 handle_mesh_path_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
4795                           const struct GNUNET_MessageHeader *message,
4796                           const struct GNUNET_ATS_Information *atsi,
4797                           unsigned int atsi_count)
4798 {
4799   struct GNUNET_MESH_ManipulatePath *msg;
4800   struct GNUNET_PeerIdentity *pi;
4801   struct MeshPeerPath *path;
4802   struct MeshTunnel *t;
4803   unsigned int own_pos;
4804   unsigned int i;
4805   size_t size;
4806
4807   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4808               "Received a PATH DESTROY msg from %s\n", GNUNET_i2s (peer));
4809   size = ntohs (message->size);
4810   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
4811   {
4812     GNUNET_break_op (0);
4813     return GNUNET_OK;
4814   }
4815
4816   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
4817   if (size % sizeof (struct GNUNET_PeerIdentity))
4818   {
4819     GNUNET_break_op (0);
4820     return GNUNET_OK;
4821   }
4822   size /= sizeof (struct GNUNET_PeerIdentity);
4823   if (size < 2)
4824   {
4825     GNUNET_break_op (0);
4826     return GNUNET_OK;
4827   }
4828   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
4829
4830   msg = (struct GNUNET_MESH_ManipulatePath *) message;
4831   pi = (struct GNUNET_PeerIdentity *) &msg[1];
4832   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4833               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi),
4834               msg->tid);
4835   t = tunnel_get (pi, ntohl (msg->tid));
4836   if (NULL == t)
4837   {
4838     /* TODO notify back: we don't know this tunnel */
4839     GNUNET_break_op (0);
4840     return GNUNET_OK;
4841   }
4842   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
4843   path = path_new (size);
4844   own_pos = 0;
4845   for (i = 0; i < size; i++)
4846   {
4847     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
4848                 GNUNET_i2s (&pi[i]));
4849     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
4850     if (path->peers[i] == myid)
4851       own_pos = i;
4852   }
4853   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
4854   if (own_pos < path->length - 1)
4855     send_message (message, &pi[own_pos + 1], t);
4856   else
4857     send_client_tunnel_disconnect(t, NULL);
4858
4859   tunnel_delete_peer (t, path->peers[path->length - 1]);
4860   path_destroy (path);
4861   return GNUNET_OK;
4862 }
4863
4864
4865 /**
4866  * Core handler for notifications of broken paths
4867  *
4868  * @param cls closure
4869  * @param message message
4870  * @param peer peer identity this notification is about
4871  * @param atsi performance data
4872  * @param atsi_count number of records in 'atsi'
4873  *
4874  * @return GNUNET_OK to keep the connection open,
4875  *         GNUNET_SYSERR to close it (signal serious error)
4876  */
4877 static int
4878 handle_mesh_path_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
4879                          const struct GNUNET_MessageHeader *message,
4880                          const struct GNUNET_ATS_Information *atsi,
4881                          unsigned int atsi_count)
4882 {
4883   struct GNUNET_MESH_PathBroken *msg;
4884   struct MeshTunnel *t;
4885
4886   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4887               "Received a PATH BROKEN msg from %s\n", GNUNET_i2s (peer));
4888   msg = (struct GNUNET_MESH_PathBroken *) message;
4889   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
4890               GNUNET_i2s (&msg->peer1));
4891   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
4892               GNUNET_i2s (&msg->peer2));
4893   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4894   if (NULL == t)
4895   {
4896     GNUNET_break_op (0);
4897     return GNUNET_OK;
4898   }
4899   tunnel_notify_connection_broken (t, GNUNET_PEER_search (&msg->peer1),
4900                                    GNUNET_PEER_search (&msg->peer2));
4901   return GNUNET_OK;
4902
4903 }
4904
4905
4906 /**
4907  * Core handler for tunnel destruction
4908  *
4909  * @param cls closure
4910  * @param message message
4911  * @param peer peer identity this notification is about
4912  * @param atsi performance data
4913  * @param atsi_count number of records in 'atsi'
4914  *
4915  * @return GNUNET_OK to keep the connection open,
4916  *         GNUNET_SYSERR to close it (signal serious error)
4917  */
4918 static int
4919 handle_mesh_tunnel_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
4920                             const struct GNUNET_MessageHeader *message,
4921                             const struct GNUNET_ATS_Information *atsi,
4922                             unsigned int atsi_count)
4923 {
4924   struct GNUNET_MESH_TunnelDestroy *msg;
4925   struct MeshTunnel *t;
4926
4927   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4928               "Got a TUNNEL DESTROY packet from %s\n", GNUNET_i2s (peer));
4929   msg = (struct GNUNET_MESH_TunnelDestroy *) message;
4930   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for tunnel %s [%u]\n",
4931               GNUNET_i2s (&msg->oid), ntohl (msg->tid));
4932   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4933   if (NULL == t)
4934   {
4935     /* Probably already got the message from another path,
4936      * destroyed the tunnel and retransmitted to children.
4937      * Safe to ignore.
4938      */
4939     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel", 1, GNUNET_NO);
4940     return GNUNET_OK;
4941   }
4942   if (t->id.oid == myid)
4943   {
4944     GNUNET_break_op (0);
4945     return GNUNET_OK;
4946   }
4947   if (t->local_tid_dest >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
4948   {
4949     /* Tunnel was incoming, notify clients */
4950     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "INCOMING TUNNEL %X %X\n",
4951                 t->local_tid, t->local_tid_dest);
4952     send_clients_tunnel_destroy (t);
4953   }
4954   tunnel_send_destroy (t);
4955   t->destroy = GNUNET_YES;
4956   // TODO: add timeout to destroy the tunnel anyway
4957   return GNUNET_OK;
4958 }
4959
4960
4961 /**
4962  * Core handler for mesh network traffic going from the origin to a peer
4963  *
4964  * @param cls closure
4965  * @param peer peer identity this notification is about
4966  * @param message message
4967  * @param atsi performance data
4968  * @param atsi_count number of records in 'atsi'
4969  * @return GNUNET_OK to keep the connection open,
4970  *         GNUNET_SYSERR to close it (signal serious error)
4971  */
4972 static int
4973 handle_mesh_data_unicast (void *cls, const struct GNUNET_PeerIdentity *peer,
4974                           const struct GNUNET_MessageHeader *message,
4975                           const struct GNUNET_ATS_Information *atsi,
4976                           unsigned int atsi_count)
4977 {
4978   struct GNUNET_MESH_Unicast *msg;
4979   struct GNUNET_PeerIdentity *neighbor;
4980   struct MeshTunnelChildInfo *cinfo;
4981   struct MeshTunnel *t;
4982   GNUNET_PEER_Id dest_id;
4983   uint32_t pid;
4984   uint32_t ttl;
4985   size_t size;
4986
4987   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a unicast packet from %s\n",
4988               GNUNET_i2s (peer));
4989   /* Check size */
4990   size = ntohs (message->size);
4991   if (size <
4992       sizeof (struct GNUNET_MESH_Unicast) +
4993       sizeof (struct GNUNET_MessageHeader))
4994   {
4995     GNUNET_break (0);
4996     return GNUNET_OK;
4997   }
4998   msg = (struct GNUNET_MESH_Unicast *) message;
4999   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %s\n",
5000               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
5001   /* Check tunnel */
5002   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5003   if (NULL == t)
5004   {
5005     /* TODO notify back: we don't know this tunnel */
5006     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
5007     GNUNET_break_op (0);
5008     return GNUNET_OK;
5009   }
5010   pid = ntohl (msg->pid);
5011   if (t->fwd_pid == pid)
5012   {
5013     GNUNET_STATISTICS_update (stats, "# duplicate PID drops", 1, GNUNET_NO);
5014     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5015                 " Already seen pid %u, DROPPING!\n", pid);
5016     return GNUNET_OK;
5017   }
5018   else
5019   {
5020     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5021                 " pid %u not seen yet, forwarding\n", pid);
5022   }
5023   t->skip += (pid - t->fwd_pid) - 1;
5024   t->fwd_pid = pid;
5025   if (GMC_is_pid_bigger (pid, t->last_fwd_ack))
5026   {
5027     GNUNET_STATISTICS_update (stats, "# unsolicited unicast", 1, GNUNET_NO);
5028     GNUNET_break_op (0);
5029     return GNUNET_OK;
5030   }
5031   tunnel_reset_timeout (t);
5032   dest_id = GNUNET_PEER_search (&msg->destination);
5033   if (dest_id == myid)
5034   {
5035     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5036                 "  it's for us! sending to clients...\n");
5037     GNUNET_STATISTICS_update (stats, "# unicast received", 1, GNUNET_NO);
5038     send_subscribed_clients (message, (struct GNUNET_MessageHeader *) &msg[1]);
5039     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_UNICAST);
5040     return GNUNET_OK;
5041   }
5042   ttl = ntohl (msg->ttl);
5043   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ttl);
5044   if (ttl == 0)
5045   {
5046     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
5047     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
5048     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5049     return GNUNET_OK;
5050   }
5051   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5052               "  not for us, retransmitting...\n");
5053
5054   neighbor = tree_get_first_hop (t->tree, dest_id);
5055   cinfo = tunnel_get_neighbor_fc (t, neighbor);
5056   cinfo->pid = pid;
5057   GNUNET_CONTAINER_multihashmap_iterate (t->children_fc,
5058                                          &tunnel_add_skip,
5059                                          &neighbor);
5060   if (GMC_is_pid_bigger (pid, cinfo->fwd_ack))
5061   {
5062     GNUNET_STATISTICS_update (stats, "# unsolicited unicast", 1, GNUNET_NO);
5063     GNUNET_break_op (0);
5064     return GNUNET_OK;
5065   }
5066   send_message (message, neighbor, t);
5067   GNUNET_STATISTICS_update (stats, "# unicast forwarded", 1, GNUNET_NO);
5068
5069   return GNUNET_OK;
5070 }
5071
5072
5073 /**
5074  * Core handler for mesh network traffic going from the origin to all peers
5075  *
5076  * @param cls closure
5077  * @param message message
5078  * @param peer peer identity this notification is about
5079  * @param atsi performance data
5080  * @param atsi_count number of records in 'atsi'
5081  * @return GNUNET_OK to keep the connection open,
5082  *         GNUNET_SYSERR to close it (signal serious error)
5083  *
5084  * TODO: Check who we got this from, to validate route.
5085  */
5086 static int
5087 handle_mesh_data_multicast (void *cls, const struct GNUNET_PeerIdentity *peer,
5088                             const struct GNUNET_MessageHeader *message,
5089                             const struct GNUNET_ATS_Information *atsi,
5090                             unsigned int atsi_count)
5091 {
5092   struct GNUNET_MESH_Multicast *msg;
5093   struct MeshTunnel *t;
5094   size_t size;
5095   uint32_t pid;
5096
5097   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a multicast packet from %s\n",
5098               GNUNET_i2s (peer));
5099   size = ntohs (message->size);
5100   if (sizeof (struct GNUNET_MESH_Multicast) +
5101       sizeof (struct GNUNET_MessageHeader) > size)
5102   {
5103     GNUNET_break_op (0);
5104     return GNUNET_OK;
5105   }
5106   msg = (struct GNUNET_MESH_Multicast *) message;
5107   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5108
5109   if (NULL == t)
5110   {
5111     /* TODO notify that we dont know that tunnel */
5112     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
5113     GNUNET_break_op (0);
5114     return GNUNET_OK;
5115   }
5116   pid = ntohl (msg->pid);
5117   if (t->fwd_pid == pid)
5118   {
5119     /* already seen this packet, drop */
5120     GNUNET_STATISTICS_update (stats, "# duplicate PID drops", 1, GNUNET_NO);
5121     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5122                 " Already seen pid %u, DROPPING!\n", pid);
5123     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5124     return GNUNET_OK;
5125   }
5126   else
5127   {
5128     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5129                 " pid %u not seen yet, forwarding\n", pid);
5130   }
5131   t->skip += (pid - t->fwd_pid) - 1;
5132   t->fwd_pid = pid;
5133   tunnel_reset_timeout (t);
5134
5135   /* Transmit to locally interested clients */
5136   if (NULL != t->peers &&
5137       GNUNET_CONTAINER_multihashmap_contains (t->peers, &my_full_id.hashPubKey))
5138   {
5139     GNUNET_STATISTICS_update (stats, "# multicast received", 1, GNUNET_NO);
5140     send_subscribed_clients (message, &msg[1].header);
5141     tunnel_send_fwd_ack(t, GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
5142   }
5143   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ntohl (msg->ttl));
5144   if (ntohl (msg->ttl) == 0)
5145   {
5146     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
5147     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
5148     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5149     return GNUNET_OK;
5150   }
5151   GNUNET_STATISTICS_update (stats, "# multicast forwarded", 1, GNUNET_NO);
5152   tunnel_send_multicast (t, message, GNUNET_NO);
5153   return GNUNET_OK;
5154 }
5155
5156
5157 /**
5158  * Core handler for mesh network traffic toward the owner of a tunnel
5159  *
5160  * @param cls closure
5161  * @param message message
5162  * @param peer peer identity this notification is about
5163  * @param atsi performance data
5164  * @param atsi_count number of records in 'atsi'
5165  *
5166  * @return GNUNET_OK to keep the connection open,
5167  *         GNUNET_SYSERR to close it (signal serious error)
5168  */
5169 static int
5170 handle_mesh_data_to_orig (void *cls, const struct GNUNET_PeerIdentity *peer,
5171                           const struct GNUNET_MessageHeader *message,
5172                           const struct GNUNET_ATS_Information *atsi,
5173                           unsigned int atsi_count)
5174 {
5175   struct GNUNET_MESH_ToOrigin *msg;
5176   struct GNUNET_PeerIdentity id;
5177   struct MeshPeerInfo *peer_info;
5178   struct MeshTunnel *t;
5179   size_t size;
5180
5181   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a ToOrigin packet from %s\n",
5182               GNUNET_i2s (peer));
5183   size = ntohs (message->size);
5184   if (size < sizeof (struct GNUNET_MESH_ToOrigin) +     /* Payload must be */
5185       sizeof (struct GNUNET_MessageHeader))     /* at least a header */
5186   {
5187     GNUNET_break_op (0);
5188     return GNUNET_OK;
5189   }
5190   msg = (struct GNUNET_MESH_ToOrigin *) message;
5191   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %s\n",
5192               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
5193   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5194
5195   if (NULL == t)
5196   {
5197     /* TODO notify that we dont know this tunnel (whom)? */
5198     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
5199     GNUNET_break_op (0);
5200     return GNUNET_OK;
5201   }
5202
5203   if (NULL != t->owner)
5204   {
5205     char cbuf[size];
5206     struct GNUNET_MESH_ToOrigin *copy;
5207
5208     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5209                 "  it's for us! sending to clients...\n");
5210     /* TODO signature verification */
5211     memcpy (cbuf, message, size);
5212     copy = (struct GNUNET_MESH_ToOrigin *) cbuf;
5213     copy->tid = htonl (t->local_tid);
5214     GNUNET_STATISTICS_update (stats, "# to origin received", 1, GNUNET_NO);
5215     GNUNET_SERVER_notification_context_unicast (nc, t->owner->handle,
5216                                                 &copy->header, GNUNET_NO);
5217     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
5218     return GNUNET_OK;
5219   }
5220   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5221               "  not for us, retransmitting...\n");
5222
5223   peer_info = peer_info_get (&msg->oid);
5224   if (NULL == peer_info)
5225   {
5226     /* unknown origin of tunnel */
5227     GNUNET_break (0);
5228     return GNUNET_OK;
5229   }
5230   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
5231   send_message (message, &id, t);
5232   GNUNET_STATISTICS_update (stats, "# to origin forwarded", 1, GNUNET_NO);
5233
5234   return GNUNET_OK;
5235 }
5236
5237
5238 /**
5239  * Core handler for mesh network traffic point-to-point acks.
5240  *
5241  * @param cls closure
5242  * @param message message
5243  * @param peer peer identity this notification is about
5244  * @param atsi performance data
5245  * @param atsi_count number of records in 'atsi'
5246  *
5247  * @return GNUNET_OK to keep the connection open,
5248  *         GNUNET_SYSERR to close it (signal serious error)
5249  */
5250 static int
5251 handle_mesh_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5252                  const struct GNUNET_MessageHeader *message,
5253                  const struct GNUNET_ATS_Information *atsi,
5254                  unsigned int atsi_count)
5255 {
5256   struct GNUNET_MESH_ACK *msg;
5257   struct MeshTunnel *t;
5258   uint32_t ack;
5259
5260   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK packet from %s!\n",
5261               GNUNET_i2s (peer));
5262   msg = (struct GNUNET_MESH_ACK *) message;
5263   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %s\n",
5264               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
5265   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5266
5267   if (NULL == t)
5268   {
5269     /* TODO notify that we dont know this tunnel (whom)? */
5270     GNUNET_STATISTICS_update (stats, "# ack on unknown tunnel", 1, GNUNET_NO);
5271     GNUNET_break_op (0);
5272     return GNUNET_OK;
5273   }
5274   ack = ntohl (msg->pid);
5275
5276   /* Is this a forward or backward ACK? */
5277   if (tree_get_predecessor(t->tree) == GNUNET_PEER_search(peer))
5278   {
5279     struct MeshTunnelChildInfo *cinfo;
5280
5281     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
5282     cinfo = tunnel_get_neighbor_fc (t, peer);
5283     cinfo->fwd_ack = ack;
5284     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5285   }
5286   else
5287   {
5288     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
5289     t->bck_ack = ack;
5290     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5291   }
5292   // FIXME fc Unlock queues?
5293   return GNUNET_OK;
5294 }
5295
5296
5297 /**
5298  * Core handler for path ACKs
5299  *
5300  * @param cls closure
5301  * @param message message
5302  * @param peer peer identity this notification is about
5303  * @param atsi performance data
5304  * @param atsi_count number of records in 'atsi'
5305  *
5306  * @return GNUNET_OK to keep the connection open,
5307  *         GNUNET_SYSERR to close it (signal serious error)
5308  */
5309 static int
5310 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5311                       const struct GNUNET_MessageHeader *message,
5312                       const struct GNUNET_ATS_Information *atsi,
5313                       unsigned int atsi_count)
5314 {
5315   struct GNUNET_MESH_PathACK *msg;
5316   struct GNUNET_PeerIdentity id;
5317   struct MeshPeerInfo *peer_info;
5318   struct MeshPeerPath *p;
5319   struct MeshTunnel *t;
5320
5321   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a path ACK msg [%s]\n",
5322               GNUNET_i2s (&my_full_id));
5323   msg = (struct GNUNET_MESH_PathACK *) message;
5324   t = tunnel_get (&msg->oid, ntohl(msg->tid));
5325   if (NULL == t)
5326   {
5327     /* TODO notify that we don't know the tunnel */
5328     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel", 1, GNUNET_NO);
5329     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  don't know the tunnel %s [%X]!\n",
5330                 GNUNET_i2s (&msg->oid), ntohl(msg->tid));
5331     return GNUNET_OK;
5332   }
5333   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %s [%X]\n",
5334               GNUNET_i2s (&msg->oid), ntohl(msg->tid));
5335
5336   peer_info = peer_info_get (&msg->peer_id);
5337   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by peer %s\n",
5338               GNUNET_i2s (&msg->peer_id));
5339   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  via peer %s\n",
5340               GNUNET_i2s (peer));
5341
5342   if (NULL != t->regex_ctx && t->regex_ctx->info->peer == peer_info->id)
5343   {
5344     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5345                 "connect_by_string completed, stopping search\n");
5346     regex_cancel_search (t->regex_ctx);
5347     t->regex_ctx = NULL;
5348   }
5349
5350   /* Add paths to peers? */
5351   p = tree_get_path_to_peer (t->tree, peer_info->id);
5352   if (NULL != p)
5353   {
5354     path_add_to_peers (p, GNUNET_YES);
5355     path_destroy (p);
5356   }
5357   else
5358   {
5359     GNUNET_break (0);
5360   }
5361
5362   /* Message for us? */
5363   if (0 == memcmp (&msg->oid, &my_full_id, sizeof (struct GNUNET_PeerIdentity)))
5364   {
5365     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
5366     if (NULL == t->owner)
5367     {
5368       GNUNET_break_op (0);
5369       return GNUNET_OK;
5370     }
5371     if (NULL != t->dht_get_type)
5372     {
5373       GNUNET_DHT_get_stop (t->dht_get_type);
5374       t->dht_get_type = NULL;
5375     }
5376     if (tree_get_status (t->tree, peer_info->id) != MESH_PEER_READY)
5377     {
5378       tree_set_status (t->tree, peer_info->id, MESH_PEER_READY);
5379       send_client_peer_connected (t, peer_info->id);
5380     }
5381     return GNUNET_OK;
5382   }
5383
5384   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5385               "  not for us, retransmitting...\n");
5386   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
5387   peer_info = peer_info_get (&msg->oid);
5388   if (NULL == peer_info)
5389   {
5390     /* If we know the tunnel, we should DEFINITELY know the peer */
5391     GNUNET_break (0);
5392     return GNUNET_OK;
5393   }
5394   send_message (message, &id, t);
5395   return GNUNET_OK;
5396 }
5397
5398
5399 /**
5400  * Functions to handle messages from core
5401  */
5402 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
5403   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
5404   {&handle_mesh_path_destroy, GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY, 0},
5405   {&handle_mesh_path_broken, GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN,
5406    sizeof (struct GNUNET_MESH_PathBroken)},
5407   {&handle_mesh_tunnel_destroy, GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY,
5408    sizeof (struct GNUNET_MESH_TunnelDestroy)},
5409   {&handle_mesh_data_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
5410   {&handle_mesh_data_multicast, GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
5411   {&handle_mesh_data_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
5412   {&handle_mesh_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
5413     sizeof (struct GNUNET_MESH_ACK)},
5414   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
5415    sizeof (struct GNUNET_MESH_PathACK)},
5416   {NULL, 0, 0}
5417 };
5418
5419
5420
5421 /******************************************************************************/
5422 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
5423 /******************************************************************************/
5424
5425 /**
5426  * deregister_app: iterator for removing each application registered by a client
5427  *
5428  * @param cls closure
5429  * @param key the hash of the application id (used to access the hashmap)
5430  * @param value the value stored at the key (client)
5431  *
5432  * @return GNUNET_OK on success
5433  */
5434 static int
5435 deregister_app (void *cls, const struct GNUNET_HashCode * key, void *value)
5436 {
5437   struct GNUNET_CONTAINER_MultiHashMap *h = cls;
5438   GNUNET_break (GNUNET_YES ==
5439                 GNUNET_CONTAINER_multihashmap_remove (h, key, value));
5440   return GNUNET_OK;
5441 }
5442
5443 #if LATER
5444 /**
5445  * notify_client_connection_failure: notify a client that the connection to the
5446  * requested remote peer is not possible (for instance, no route found)
5447  * Function called when the socket is ready to queue more data. "buf" will be
5448  * NULL and "size" zero if the socket was closed for writing in the meantime.
5449  *
5450  * @param cls closure
5451  * @param size number of bytes available in buf
5452  * @param buf where the callee should write the message
5453  * @return number of bytes written to buf
5454  */
5455 static size_t
5456 notify_client_connection_failure (void *cls, size_t size, void *buf)
5457 {
5458   int size_needed;
5459   struct MeshPeerInfo *peer_info;
5460   struct GNUNET_MESH_PeerControl *msg;
5461   struct GNUNET_PeerIdentity id;
5462
5463   if (0 == size && NULL == buf)
5464   {
5465     // TODO retry? cancel?
5466     return 0;
5467   }
5468
5469   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
5470   peer_info = (struct MeshPeerInfo *) cls;
5471   msg = (struct GNUNET_MESH_PeerControl *) buf;
5472   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
5473   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
5474 //     msg->tunnel_id = htonl(peer_info->t->tid);
5475   GNUNET_PEER_resolve (peer_info->id, &id);
5476   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
5477
5478   return size_needed;
5479 }
5480 #endif
5481
5482
5483 /**
5484  * Send keepalive packets for a peer
5485  *
5486  * @param cls Closure (tunnel for which to send the keepalive).
5487  * @param tc Notification context.
5488  *
5489  * TODO: implement explicit multicast keepalive?
5490  */
5491 static void
5492 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
5493 {
5494   struct MeshTunnel *t = cls;
5495   struct GNUNET_MessageHeader *payload;
5496   struct GNUNET_MESH_Multicast *msg;
5497   size_t size =
5498       sizeof (struct GNUNET_MESH_Multicast) +
5499       sizeof (struct GNUNET_MessageHeader);
5500   char cbuf[size];
5501
5502   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
5503   {
5504     return;
5505   }
5506   t->path_refresh_task = GNUNET_SCHEDULER_NO_TASK;
5507
5508   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5509               "sending keepalive for tunnel %d\n", t->id.tid);
5510
5511   msg = (struct GNUNET_MESH_Multicast *) cbuf;
5512   msg->header.size = htons (size);
5513   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
5514   msg->oid = my_full_id;
5515   msg->tid = htonl (t->id.tid);
5516   msg->ttl = htonl (default_ttl);
5517   msg->pid = htonl (t->fwd_pid + 1);
5518   t->fwd_pid++;
5519   payload = (struct GNUNET_MessageHeader *) &msg[1];
5520   payload->size = htons (sizeof (struct GNUNET_MessageHeader));
5521   payload->type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE);
5522   tunnel_send_multicast (t, &msg->header, GNUNET_YES);
5523
5524   t->path_refresh_task =
5525       GNUNET_SCHEDULER_add_delayed (refresh_path_time, &path_refresh, t);
5526   return;
5527 }
5528
5529
5530 /**
5531  * Function to process paths received for a new peer addition. The recorded
5532  * paths form the initial tunnel, which can be optimized later.
5533  * Called on each result obtained for the DHT search.
5534  *
5535  * @param cls closure
5536  * @param exp when will this value expire
5537  * @param key key of the result
5538  * @param get_path path of the get request
5539  * @param get_path_length lenght of get_path
5540  * @param put_path path of the put request
5541  * @param put_path_length length of the put_path
5542  * @param type type of the result
5543  * @param size number of bytes in data
5544  * @param data pointer to the result data
5545  *
5546  * TODO: re-issue the request after certain time? cancel after X results?
5547  */
5548 static void
5549 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
5550                     const struct GNUNET_HashCode * key,
5551                     const struct GNUNET_PeerIdentity *get_path,
5552                     unsigned int get_path_length,
5553                     const struct GNUNET_PeerIdentity *put_path,
5554                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
5555                     size_t size, const void *data)
5556 {
5557   struct MeshPathInfo *path_info = cls;
5558   struct MeshPeerPath *p;
5559   struct GNUNET_PeerIdentity pi;
5560   int i;
5561
5562   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
5563   GNUNET_PEER_resolve (path_info->peer->id, &pi);
5564   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", GNUNET_i2s (&pi));
5565
5566   p = path_build_from_dht (get_path, get_path_length, put_path,
5567                            put_path_length);
5568   path_add_to_peers (p, GNUNET_NO);
5569   path_destroy(p);
5570   for (i = 0; i < path_info->peer->ntunnels; i++)
5571   {
5572     tunnel_add_peer (path_info->peer->tunnels[i], path_info->peer);
5573     peer_info_connect (path_info->peer, path_info->t);
5574   }
5575
5576   return;
5577 }
5578
5579
5580 /**
5581  * Function to process paths received for a new peer addition. The recorded
5582  * paths form the initial tunnel, which can be optimized later.
5583  * Called on each result obtained for the DHT search.
5584  *
5585  * @param cls closure
5586  * @param exp when will this value expire
5587  * @param key key of the result
5588  * @param get_path path of the get request
5589  * @param get_path_length lenght of get_path
5590  * @param put_path path of the put request
5591  * @param put_path_length length of the put_path
5592  * @param type type of the result
5593  * @param size number of bytes in data
5594  * @param data pointer to the result data
5595  */
5596 static void
5597 dht_get_type_handler (void *cls, struct GNUNET_TIME_Absolute exp,
5598                       const struct GNUNET_HashCode * key,
5599                       const struct GNUNET_PeerIdentity *get_path,
5600                       unsigned int get_path_length,
5601                       const struct GNUNET_PeerIdentity *put_path,
5602                       unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
5603                       size_t size, const void *data)
5604 {
5605   const struct PBlock *pb = data;
5606   const struct GNUNET_PeerIdentity *pi = &pb->id;
5607   struct MeshTunnel *t = cls;
5608   struct MeshPeerInfo *peer_info;
5609   struct MeshPeerPath *p;
5610
5611   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got type DHT result!\n");
5612   if (size != sizeof (struct PBlock))
5613   {
5614     GNUNET_break_op (0);
5615     return;
5616   }
5617   if (ntohl(pb->type) != t->type)
5618   {
5619     GNUNET_break_op (0);
5620     return;
5621   }
5622   GNUNET_assert (NULL != t->owner);
5623   peer_info = peer_info_get (pi);
5624   (void) GNUNET_CONTAINER_multihashmap_put (t->peers, &pi->hashPubKey,
5625                                             peer_info,
5626                                             GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
5627
5628   p = path_build_from_dht (get_path, get_path_length, put_path,
5629                            put_path_length);
5630   path_add_to_peers (p, GNUNET_NO);
5631   path_destroy(p);
5632   tunnel_add_peer (t, peer_info);
5633   peer_info_connect (peer_info, t);
5634 }
5635
5636
5637 /**
5638  * Function to process DHT string to regex matching.
5639  * Called on each result obtained for the DHT search.
5640  *
5641  * @param cls closure (search context)
5642  * @param exp when will this value expire
5643  * @param key key of the result
5644  * @param get_path path of the get request (not used)
5645  * @param get_path_length lenght of get_path (not used)
5646  * @param put_path path of the put request (not used)
5647  * @param put_path_length length of the put_path (not used)
5648  * @param type type of the result
5649  * @param size number of bytes in data
5650  * @param data pointer to the result data
5651  */
5652 static void
5653 dht_get_string_accept_handler (void *cls, struct GNUNET_TIME_Absolute exp,
5654                                const struct GNUNET_HashCode * key,
5655                                const struct GNUNET_PeerIdentity *get_path,
5656                                unsigned int get_path_length,
5657                                const struct GNUNET_PeerIdentity *put_path,
5658                                unsigned int put_path_length,
5659                                enum GNUNET_BLOCK_Type type,
5660                                size_t size, const void *data)
5661 {
5662   const struct MeshRegexAccept *block = data;
5663   struct MeshRegexSearchContext *ctx = cls;
5664   struct MeshRegexSearchInfo *info = ctx->info;
5665   struct MeshPeerPath *p;
5666   struct MeshPeerInfo *peer_info;
5667
5668   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got regex results from DHT!\n");
5669   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", info->description);
5670
5671   peer_info = peer_info_get(&block->id);
5672   p = path_build_from_dht (get_path, get_path_length, put_path,
5673                            put_path_length);
5674   path_add_to_peers (p, GNUNET_NO);
5675   path_destroy(p);
5676
5677   tunnel_add_peer (info->t, peer_info);
5678   peer_info_connect (peer_info, info->t);
5679   if (0 == info->peer)
5680   {
5681     info->peer = peer_info->id;
5682   }
5683   else
5684   {
5685     GNUNET_array_append (info->peers, info->n_peers, peer_info->id);
5686   }
5687
5688   info->timeout = GNUNET_SCHEDULER_add_delayed (connect_timeout,
5689                                                 &regex_connect_timeout,
5690                                                 info);
5691
5692   return;
5693 }
5694
5695
5696 /**
5697  * Function to process DHT string to regex matching.
5698  * Called on each result obtained for the DHT search.
5699  *
5700  * @param cls closure (search context)
5701  * @param exp when will this value expire
5702  * @param key key of the result
5703  * @param get_path path of the get request (not used)
5704  * @param get_path_length lenght of get_path (not used)
5705  * @param put_path path of the put request (not used)
5706  * @param put_path_length length of the put_path (not used)
5707  * @param type type of the result
5708  * @param size number of bytes in data
5709  * @param data pointer to the result data
5710  *
5711  * TODO: re-issue the request after certain time? cancel after X results?
5712  */
5713 static void
5714 dht_get_string_handler (void *cls, struct GNUNET_TIME_Absolute exp,
5715                         const struct GNUNET_HashCode * key,
5716                         const struct GNUNET_PeerIdentity *get_path,
5717                         unsigned int get_path_length,
5718                         const struct GNUNET_PeerIdentity *put_path,
5719                         unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
5720                         size_t size, const void *data)
5721 {
5722   const struct MeshRegexBlock *block = data;
5723   struct MeshRegexSearchContext *ctx = cls;
5724   struct MeshRegexSearchInfo *info = ctx->info;
5725   void *copy;
5726   size_t len;
5727
5728   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5729               "DHT GET STRING RETURNED RESULTS\n");
5730   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5731               "  key: %s\n", GNUNET_h2s (key));
5732
5733   copy = GNUNET_malloc (size);
5734   memcpy (copy, data, size);
5735   GNUNET_break (GNUNET_OK ==
5736                 GNUNET_CONTAINER_multihashmap_put(info->dht_get_results, key, copy,
5737                                                   GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
5738   len = ntohl (block->n_proof);
5739   {
5740     char proof[len + 1];
5741
5742     memcpy (proof, &block[1], len);
5743     proof[len] = '\0';
5744     if (GNUNET_OK != GNUNET_REGEX_check_proof (proof, key))
5745     {
5746       GNUNET_break_op (0);
5747       return;
5748     }
5749   }
5750   len = strlen (info->description);
5751   if (len == ctx->position) // String processed
5752   {
5753     if (GNUNET_YES == ntohl (block->accepting))
5754     {
5755       regex_find_path(key, ctx);
5756     }
5757     else
5758     {
5759       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  block not accepting!\n");
5760       // FIXME REGEX this block not successful, wait for more? start timeout?
5761     }
5762     return;
5763   }
5764   GNUNET_break (GNUNET_OK ==
5765                 GNUNET_MESH_regex_block_iterate (block, size,
5766                                                  &regex_edge_iterator, ctx));
5767   return;
5768 }
5769
5770 /******************************************************************************/
5771 /*********************       MESH LOCAL HANDLES      **************************/
5772 /******************************************************************************/
5773
5774
5775 /**
5776  * Handler for client disconnection
5777  *
5778  * @param cls closure
5779  * @param client identification of the client; NULL
5780  *        for the last call when the server is destroyed
5781  */
5782 static void
5783 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
5784 {
5785   struct MeshClient *c;
5786   struct MeshClient *next;
5787   unsigned int i;
5788
5789   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected\n");
5790   if (client == NULL)
5791   {
5792     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (SERVER DOWN)\n");
5793     return;
5794   }
5795   c = clients;
5796   while (NULL != c)
5797   {
5798     if (c->handle != client)
5799     {
5800       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ... searching\n");
5801       c = c->next;
5802       continue;
5803     }
5804     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u)\n",
5805                 c->id);
5806     GNUNET_SERVER_client_drop (c->handle);
5807     c->shutting_down = GNUNET_YES;
5808     GNUNET_assert (NULL != c->own_tunnels);
5809     GNUNET_assert (NULL != c->incoming_tunnels);
5810     GNUNET_CONTAINER_multihashmap_iterate (c->own_tunnels,
5811                                            &tunnel_destroy_iterator, c);
5812     GNUNET_CONTAINER_multihashmap_iterate (c->incoming_tunnels,
5813                                            &tunnel_destroy_iterator, c);
5814     GNUNET_CONTAINER_multihashmap_iterate (c->ignore_tunnels,
5815                                            &tunnel_destroy_iterator, c);
5816     GNUNET_CONTAINER_multihashmap_destroy (c->own_tunnels);
5817     GNUNET_CONTAINER_multihashmap_destroy (c->incoming_tunnels);
5818     GNUNET_CONTAINER_multihashmap_destroy (c->ignore_tunnels);
5819
5820     /* deregister clients applications */
5821     if (NULL != c->apps)
5822     {
5823       GNUNET_CONTAINER_multihashmap_iterate (c->apps, &deregister_app, c->apps);
5824       GNUNET_CONTAINER_multihashmap_destroy (c->apps);
5825     }
5826     if (0 == GNUNET_CONTAINER_multihashmap_size (applications) &&
5827         GNUNET_SCHEDULER_NO_TASK != announce_applications_task)
5828     {
5829       GNUNET_SCHEDULER_cancel (announce_applications_task);
5830       announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
5831     }
5832     if (NULL != c->types)
5833       GNUNET_CONTAINER_multihashmap_destroy (c->types);
5834     for (i = 0; i < c->n_regex; i++)
5835     {
5836       GNUNET_free (c->regexes[i]);
5837     }
5838     GNUNET_free_non_null (c->regexes);
5839     if (GNUNET_SCHEDULER_NO_TASK != c->regex_announce_task)
5840       GNUNET_SCHEDULER_cancel (c->regex_announce_task);
5841     next = c->next;
5842     GNUNET_CONTAINER_DLL_remove (clients, clients_tail, c);
5843     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT FREE at %p\n", c);
5844     GNUNET_free (c);
5845     GNUNET_STATISTICS_update (stats, "# clients", -1, GNUNET_NO);
5846     c = next;
5847   }
5848   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   done!\n");
5849   return;
5850 }
5851
5852
5853 /**
5854  * Handler for new clients
5855  *
5856  * @param cls closure
5857  * @param client identification of the client
5858  * @param message the actual message, which includes messages the client wants
5859  */
5860 static void
5861 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
5862                          const struct GNUNET_MessageHeader *message)
5863 {
5864   struct GNUNET_MESH_ClientConnect *cc_msg;
5865   struct MeshClient *c;
5866   GNUNET_MESH_ApplicationType *a;
5867   unsigned int size;
5868   uint16_t ntypes;
5869   uint16_t *t;
5870   uint16_t napps;
5871   uint16_t i;
5872
5873   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected\n");
5874   /* Check data sanity */
5875   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
5876   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
5877   ntypes = ntohs (cc_msg->types);
5878   napps = ntohs (cc_msg->applications);
5879   if (size !=
5880       ntypes * sizeof (uint16_t) + napps * sizeof (GNUNET_MESH_ApplicationType))
5881   {
5882     GNUNET_break (0);
5883     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5884     return;
5885   }
5886
5887   /* Create new client structure */
5888   c = GNUNET_malloc (sizeof (struct MeshClient));
5889   c->id = next_client_id++;
5890   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT NEW %u\n", c->id);
5891   c->handle = client;
5892   GNUNET_SERVER_client_keep (client);
5893   a = (GNUNET_MESH_ApplicationType *) &cc_msg[1];
5894   if (napps > 0)
5895   {
5896     GNUNET_MESH_ApplicationType at;
5897     struct GNUNET_HashCode hc;
5898
5899     c->apps = GNUNET_CONTAINER_multihashmap_create (napps);
5900     for (i = 0; i < napps; i++)
5901     {
5902       at = ntohl (a[i]);
5903       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  app type: %u\n", at);
5904       GNUNET_CRYPTO_hash (&at, sizeof (at), &hc);
5905       /* store in clients hashmap */
5906       GNUNET_CONTAINER_multihashmap_put (c->apps, &hc, (void *) (long) at,
5907                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
5908       /* store in global hashmap, for announcements */
5909       GNUNET_CONTAINER_multihashmap_put (applications, &hc, c,
5910                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
5911     }
5912     if (GNUNET_SCHEDULER_NO_TASK == announce_applications_task)
5913       announce_applications_task =
5914           GNUNET_SCHEDULER_add_now (&announce_applications, NULL);
5915
5916   }
5917   if (ntypes > 0)
5918   {
5919     uint16_t u16;
5920     struct GNUNET_HashCode hc;
5921
5922     t = (uint16_t *) & a[napps];
5923     c->types = GNUNET_CONTAINER_multihashmap_create (ntypes);
5924     for (i = 0; i < ntypes; i++)
5925     {
5926       u16 = ntohs (t[i]);
5927       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  msg type: %u\n", u16);
5928       GNUNET_CRYPTO_hash (&u16, sizeof (u16), &hc);
5929
5930       /* store in clients hashmap */
5931       GNUNET_CONTAINER_multihashmap_put (c->types, &hc, c,
5932                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
5933       /* store in global hashmap */
5934       GNUNET_CONTAINER_multihashmap_put (types, &hc, c,
5935                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
5936     }
5937   }
5938   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5939               " client has %u+%u subscriptions\n", napps, ntypes);
5940
5941   GNUNET_CONTAINER_DLL_insert (clients, clients_tail, c);
5942   c->own_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
5943   c->incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
5944   c->ignore_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
5945   GNUNET_SERVER_notification_context_add (nc, client);
5946   GNUNET_STATISTICS_update (stats, "# clients", 1, GNUNET_NO);
5947
5948   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5949   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
5950 }
5951
5952
5953 /**
5954  * Handler for clients announcing available services by a regular expression.
5955  *
5956  * @param cls closure
5957  * @param client identification of the client
5958  * @param message the actual message, which includes messages the client wants
5959  */
5960 static void
5961 handle_local_announce_regex (void *cls, struct GNUNET_SERVER_Client *client,
5962                              const struct GNUNET_MessageHeader *message)
5963 {
5964   struct MeshClient *c;
5965   char *regex;
5966   size_t len;
5967
5968   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "announce regex started\n");
5969
5970   /* Sanity check for client registration */
5971   if (NULL == (c = client_get (client)))
5972   {
5973     GNUNET_break (0);
5974     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5975     return;
5976   }
5977   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
5978
5979   len = ntohs (message->size) - sizeof(struct GNUNET_MessageHeader);
5980   regex = GNUNET_malloc (len + 1);
5981   memcpy (regex, &message[1], len);
5982   regex[len] = '\0';
5983   GNUNET_array_append (c->regexes, c->n_regex, regex);
5984   if (GNUNET_SCHEDULER_NO_TASK == c->regex_announce_task)
5985   {
5986     c->regex_announce_task = GNUNET_SCHEDULER_add_now(&announce_regex, c);
5987   }
5988   else
5989   {
5990     regex_put(regex);
5991   }
5992   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5993   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "announce regex processed\n");
5994 }
5995
5996
5997 /**
5998  * Handler for requests of new tunnels
5999  *
6000  * @param cls closure
6001  * @param client identification of the client
6002  * @param message the actual message
6003  */
6004 static void
6005 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
6006                             const struct GNUNET_MessageHeader *message)
6007 {
6008   struct GNUNET_MESH_TunnelMessage *t_msg;
6009   struct MeshTunnel *t;
6010   struct MeshClient *c;
6011   MESH_TunnelNumber tid;
6012
6013   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel requested\n");
6014
6015   /* Sanity check for client registration */
6016   if (NULL == (c = client_get (client)))
6017   {
6018     GNUNET_break (0);
6019     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6020     return;
6021   }
6022   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6023
6024   /* Message sanity check */
6025   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
6026   {
6027     GNUNET_break (0);
6028     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6029     return;
6030   }
6031
6032   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6033   /* Sanity check for tunnel numbering */
6034   tid = ntohl (t_msg->tunnel_id);
6035   if (0 == (tid & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
6036   {
6037     GNUNET_break (0);
6038     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6039     return;
6040   }
6041   /* Sanity check for duplicate tunnel IDs */
6042   if (NULL != tunnel_get_by_local_id (c, tid))
6043   {
6044     GNUNET_break (0);
6045     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6046     return;
6047   }
6048
6049   while (NULL != tunnel_get_by_pi (myid, next_tid))
6050     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
6051   t = tunnel_new (myid, next_tid++, c, tid);
6052   if (NULL == t)
6053   {
6054     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Tunnel creation failed.\n");
6055     GNUNET_break (0);
6056     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6057     return;
6058   }
6059   next_tid = next_tid & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
6060   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED TUNNEL %s [%x] (%x)\n",
6061               GNUNET_i2s (&my_full_id), t->id.tid, t->local_tid);
6062   t->peers = GNUNET_CONTAINER_multihashmap_create (32);
6063
6064   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel created\n");
6065   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6066   return;
6067 }
6068
6069
6070 /**
6071  * Handler for requests of deleting tunnels
6072  *
6073  * @param cls closure
6074  * @param client identification of the client
6075  * @param message the actual message
6076  */
6077 static void
6078 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
6079                              const struct GNUNET_MessageHeader *message)
6080 {
6081   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
6082   struct MeshClient *c;
6083   struct MeshTunnel *t;
6084   MESH_TunnelNumber tid;
6085
6086   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6087               "Got a DESTROY TUNNEL from client!\n");
6088
6089   /* Sanity check for client registration */
6090   if (NULL == (c = client_get (client)))
6091   {
6092     GNUNET_break (0);
6093     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6094     return;
6095   }
6096   /* Message sanity check */
6097   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
6098   {
6099     GNUNET_break (0);
6100     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6101     return;
6102   }
6103   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6104   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6105
6106   /* Retrieve tunnel */
6107   tid = ntohl (tunnel_msg->tunnel_id);
6108   t = tunnel_get_by_local_id(c, tid);
6109   if (NULL == t)
6110   {
6111     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
6112     GNUNET_break (0);
6113     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6114     return;
6115   }
6116   if (c != t->owner || tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
6117   {
6118     client_ignore_tunnel (c, t);
6119 #if 0
6120     // TODO: when to destroy incoming tunnel?
6121     if (t->nclients == 0)
6122     {
6123       GNUNET_assert (GNUNET_YES ==
6124                      GNUNET_CONTAINER_multihashmap_remove (incoming_tunnels,
6125                                                            &hash, t));
6126       GNUNET_assert (GNUNET_YES ==
6127                      GNUNET_CONTAINER_multihashmap_remove (t->peers,
6128                                                            &my_full_id.hashPubKey,
6129                                                            t));
6130     }
6131 #endif
6132     GNUNET_SERVER_receive_done (client, GNUNET_OK);
6133     return;
6134   }
6135   send_client_tunnel_disconnect(t, c);
6136   client_delete_tunnel(c, t);
6137
6138   /* Don't try to ACK the client about the tunnel_destroy multicast packet */
6139   t->owner = NULL;
6140   tunnel_send_destroy (t);
6141   t->destroy = GNUNET_YES;
6142   // The tunnel will be destroyed when the last message is transmitted.
6143   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6144   return;
6145 }
6146
6147
6148 /**
6149  * Handler for requests of seeting tunnel's speed.
6150  *
6151  * @param cls Closure (unused).
6152  * @param client Identification of the client.
6153  * @param message The actual message.
6154  */
6155 static void
6156 handle_local_tunnel_speed (void *cls, struct GNUNET_SERVER_Client *client,
6157                            const struct GNUNET_MessageHeader *message)
6158 {
6159   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
6160   struct MeshClient *c;
6161   struct MeshTunnel *t;
6162   MESH_TunnelNumber tid;
6163
6164   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6165               "Got a SPEED request from client!\n");
6166
6167   /* Sanity check for client registration */
6168   if (NULL == (c = client_get (client)))
6169   {
6170     GNUNET_break (0);
6171     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6172     return;
6173   }
6174
6175   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6176   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6177
6178   /* Retrieve tunnel */
6179   tid = ntohl (tunnel_msg->tunnel_id);
6180   t = tunnel_get_by_local_id(c, tid);
6181   if (NULL == t)
6182   {
6183     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  tunnel %X not found\n", tid);
6184     GNUNET_break (0);
6185     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6186     return;
6187   }
6188
6189   switch (ntohs(message->type))
6190   {
6191       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MIN:
6192           t->speed_min = GNUNET_YES;
6193           break;
6194       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MAX:
6195           t->speed_min = GNUNET_NO;
6196           break;
6197       default:
6198           GNUNET_break (0);
6199   }
6200   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6201 }
6202
6203
6204 /**
6205  * Handler for requests of seeting tunnel's buffering policy.
6206  *
6207  * @param cls Closure (unused).
6208  * @param client Identification of the client.
6209  * @param message The actual message.
6210  */
6211 static void
6212 handle_local_tunnel_buffer (void *cls, struct GNUNET_SERVER_Client *client,
6213                             const struct GNUNET_MessageHeader *message)
6214 {
6215   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
6216   struct MeshClient *c;
6217   struct MeshTunnel *t;
6218   MESH_TunnelNumber tid;
6219
6220   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6221               "Got a BUFFER request from client!\n");
6222
6223   /* Sanity check for client registration */
6224   if (NULL == (c = client_get (client)))
6225   {
6226     GNUNET_break (0);
6227     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6228     return;
6229   }
6230
6231   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6232   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6233
6234   /* Retrieve tunnel */
6235   tid = ntohl (tunnel_msg->tunnel_id);
6236   t = tunnel_get_by_local_id(c, tid);
6237   if (NULL == t)
6238   {
6239     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
6240     GNUNET_break (0);
6241     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6242     return;
6243   }
6244
6245   switch (ntohs(message->type))
6246   {
6247       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER:
6248           t->nobuffer = GNUNET_NO;
6249           break;
6250       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER:
6251           t->nobuffer = GNUNET_YES;
6252           break;
6253       default:
6254           GNUNET_break (0);
6255   }
6256
6257   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6258 }
6259
6260
6261 /**
6262  * Handler for connection requests to new peers
6263  *
6264  * @param cls closure
6265  * @param client identification of the client
6266  * @param message the actual message (PeerControl)
6267  */
6268 static void
6269 handle_local_connect_add (void *cls, struct GNUNET_SERVER_Client *client,
6270                           const struct GNUNET_MessageHeader *message)
6271 {
6272   struct GNUNET_MESH_PeerControl *peer_msg;
6273   struct MeshPeerInfo *peer_info;
6274   struct MeshClient *c;
6275   struct MeshTunnel *t;
6276   MESH_TunnelNumber tid;
6277
6278   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got connection request\n");
6279   /* Sanity check for client registration */
6280   if (NULL == (c = client_get (client)))
6281   {
6282     GNUNET_break (0);
6283     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6284     return;
6285   }
6286
6287   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6288   /* Sanity check for message size */
6289   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6290   {
6291     GNUNET_break (0);
6292     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6293     return;
6294   }
6295
6296   /* Tunnel exists? */
6297   tid = ntohl (peer_msg->tunnel_id);
6298   t = tunnel_get_by_local_id (c, tid);
6299   if (NULL == t)
6300   {
6301     GNUNET_break (0);
6302     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6303     return;
6304   }
6305
6306   /* Does client own tunnel? */
6307   if (t->owner->handle != client)
6308   {
6309     GNUNET_break (0);
6310     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6311     return;
6312   }
6313   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "     for %s\n",
6314               GNUNET_i2s (&peer_msg->peer));
6315   peer_info = peer_info_get (&peer_msg->peer);
6316
6317   tunnel_add_peer (t, peer_info);
6318   peer_info_connect (peer_info, t);
6319
6320   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6321   return;
6322 }
6323
6324
6325 /**
6326  * Handler for disconnection requests of peers in a tunnel
6327  *
6328  * @param cls closure
6329  * @param client identification of the client
6330  * @param message the actual message (PeerControl)
6331  */
6332 static void
6333 handle_local_connect_del (void *cls, struct GNUNET_SERVER_Client *client,
6334                           const struct GNUNET_MessageHeader *message)
6335 {
6336   struct GNUNET_MESH_PeerControl *peer_msg;
6337   struct MeshPeerInfo *peer_info;
6338   struct MeshClient *c;
6339   struct MeshTunnel *t;
6340   MESH_TunnelNumber tid;
6341
6342   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER DEL request\n");
6343   /* Sanity check for client registration */
6344   if (NULL == (c = client_get (client)))
6345   {
6346     GNUNET_break (0);
6347     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6348     return;
6349   }
6350   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6351   /* Sanity check for message size */
6352   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6353   {
6354     GNUNET_break (0);
6355     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6356     return;
6357   }
6358
6359   /* Tunnel exists? */
6360   tid = ntohl (peer_msg->tunnel_id);
6361   t = tunnel_get_by_local_id (c, tid);
6362   if (NULL == t)
6363   {
6364     GNUNET_break (0);
6365     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6366     return;
6367   }
6368   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
6369
6370   /* Does client own tunnel? */
6371   if (t->owner->handle != client)
6372   {
6373     GNUNET_break (0);
6374     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6375     return;
6376   }
6377
6378   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for peer %s\n",
6379               GNUNET_i2s (&peer_msg->peer));
6380   /* Is the peer in the tunnel? */
6381   peer_info =
6382       GNUNET_CONTAINER_multihashmap_get (t->peers, &peer_msg->peer.hashPubKey);
6383   if (NULL == peer_info)
6384   {
6385     GNUNET_break (0);
6386     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6387     return;
6388   }
6389
6390   /* Ok, delete peer from tunnel */
6391   GNUNET_CONTAINER_multihashmap_remove_all (t->peers,
6392                                             &peer_msg->peer.hashPubKey);
6393
6394   send_destroy_path (t, peer_info->id);
6395   tunnel_delete_peer (t, peer_info->id);
6396   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6397   return;
6398 }
6399
6400 /**
6401  * Handler for blacklist requests of peers in a tunnel
6402  *
6403  * @param cls closure
6404  * @param client identification of the client
6405  * @param message the actual message (PeerControl)
6406  */
6407 static void
6408 handle_local_blacklist (void *cls, struct GNUNET_SERVER_Client *client,
6409                           const struct GNUNET_MessageHeader *message)
6410 {
6411   struct GNUNET_MESH_PeerControl *peer_msg;
6412   struct MeshClient *c;
6413   struct MeshTunnel *t;
6414   MESH_TunnelNumber tid;
6415
6416   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER BLACKLIST request\n");
6417   /* Sanity check for client registration */
6418   if (NULL == (c = client_get (client)))
6419   {
6420     GNUNET_break (0);
6421     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6422     return;
6423   }
6424   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6425
6426   /* Sanity check for message size */
6427   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6428   {
6429     GNUNET_break (0);
6430     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6431     return;
6432   }
6433
6434   /* Tunnel exists? */
6435   tid = ntohl (peer_msg->tunnel_id);
6436   t = tunnel_get_by_local_id (c, tid);
6437   if (NULL == t)
6438   {
6439     GNUNET_break (0);
6440     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6441     return;
6442   }
6443   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
6444
6445   GNUNET_array_append(t->blacklisted, t->nblacklisted,
6446                       GNUNET_PEER_intern(&peer_msg->peer));
6447 }
6448
6449
6450 /**
6451  * Handler for unblacklist requests of peers in a tunnel
6452  *
6453  * @param cls closure
6454  * @param client identification of the client
6455  * @param message the actual message (PeerControl)
6456  */
6457 static void
6458 handle_local_unblacklist (void *cls, struct GNUNET_SERVER_Client *client,
6459                           const struct GNUNET_MessageHeader *message)
6460 {
6461   struct GNUNET_MESH_PeerControl *peer_msg;
6462   struct MeshClient *c;
6463   struct MeshTunnel *t;
6464   MESH_TunnelNumber tid;
6465   GNUNET_PEER_Id pid;
6466   unsigned int i;
6467
6468   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER UNBLACKLIST request\n");
6469   /* Sanity check for client registration */
6470   if (NULL == (c = client_get (client)))
6471   {
6472     GNUNET_break (0);
6473     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6474     return;
6475   }
6476   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6477
6478   /* Sanity check for message size */
6479   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6480   {
6481     GNUNET_break (0);
6482     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6483     return;
6484   }
6485
6486   /* Tunnel exists? */
6487   tid = ntohl (peer_msg->tunnel_id);
6488   t = tunnel_get_by_local_id (c, tid);
6489   if (NULL == t)
6490   {
6491     GNUNET_break (0);
6492     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6493     return;
6494   }
6495   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
6496
6497   /* if peer is not known, complain */
6498   pid = GNUNET_PEER_search (&peer_msg->peer);
6499   if (0 == pid)
6500   {
6501     GNUNET_break (0);
6502     return;
6503   }
6504
6505   /* search and remove from list */
6506   for (i = 0; i < t->nblacklisted; i++)
6507   {
6508     if (t->blacklisted[i] == pid)
6509     {
6510       t->blacklisted[i] = t->blacklisted[t->nblacklisted - 1];
6511       GNUNET_array_grow (t->blacklisted, t->nblacklisted, t->nblacklisted - 1);
6512       return;
6513     }
6514   }
6515
6516   /* if peer hasn't been blacklisted, complain */
6517   GNUNET_break (0);
6518 }
6519
6520
6521 /**
6522  * Handler for connection requests to new peers by type
6523  *
6524  * @param cls closure
6525  * @param client identification of the client
6526  * @param message the actual message (ConnectPeerByType)
6527  */
6528 static void
6529 handle_local_connect_by_type (void *cls, struct GNUNET_SERVER_Client *client,
6530                               const struct GNUNET_MessageHeader *message)
6531 {
6532   struct GNUNET_MESH_ConnectPeerByType *connect_msg;
6533   struct MeshClient *c;
6534   struct MeshTunnel *t;
6535   struct GNUNET_HashCode hash;
6536   MESH_TunnelNumber tid;
6537
6538   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got connect by type request\n");
6539   /* Sanity check for client registration */
6540   if (NULL == (c = client_get (client)))
6541   {
6542     GNUNET_break (0);
6543     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6544     return;
6545   }
6546
6547   connect_msg = (struct GNUNET_MESH_ConnectPeerByType *) message;
6548   /* Sanity check for message size */
6549   if (sizeof (struct GNUNET_MESH_ConnectPeerByType) !=
6550       ntohs (connect_msg->header.size))
6551   {
6552     GNUNET_break (0);
6553     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6554     return;
6555   }
6556
6557   /* Tunnel exists? */
6558   tid = ntohl (connect_msg->tunnel_id);
6559   t = tunnel_get_by_local_id (c, tid);
6560   if (NULL == t)
6561   {
6562     GNUNET_break (0);
6563     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6564     return;
6565   }
6566
6567   /* Does client own tunnel? */
6568   if (t->owner->handle != client)
6569   {
6570     GNUNET_break (0);
6571     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6572     return;
6573   }
6574
6575   /* Do WE have the service? */
6576   t->type = ntohl (connect_msg->type);
6577   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " type requested: %u\n", t->type);
6578   GNUNET_CRYPTO_hash (&t->type, sizeof (GNUNET_MESH_ApplicationType), &hash);
6579   if (GNUNET_CONTAINER_multihashmap_contains (applications, &hash) ==
6580       GNUNET_YES)
6581   {
6582     /* Yes! Fast forward, add ourselves to the tunnel and send the
6583      * good news to the client, and alert the destination client of
6584      * an incoming tunnel.
6585      *
6586      * FIXME send a path create to self, avoid code duplication
6587      */
6588     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " available locally\n");
6589     GNUNET_CONTAINER_multihashmap_put (t->peers, &my_full_id.hashPubKey,
6590                                        peer_info_get (&my_full_id),
6591                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
6592
6593     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " notifying client\n");
6594     send_client_peer_connected (t, myid);
6595     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Done\n");
6596     GNUNET_SERVER_receive_done (client, GNUNET_OK);
6597
6598     t->local_tid_dest = next_local_tid++;
6599     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
6600     GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
6601                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
6602
6603     return;
6604   }
6605   /* Ok, lets find a peer offering the service */
6606   if (NULL != t->dht_get_type)
6607   {
6608     GNUNET_DHT_get_stop (t->dht_get_type);
6609   }
6610   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " looking in DHT for %s\n",
6611               GNUNET_h2s (&hash));
6612   t->dht_get_type =
6613       GNUNET_DHT_get_start (dht_handle, 
6614                             GNUNET_BLOCK_TYPE_MESH_PEER_BY_TYPE,
6615                             &hash,
6616                             dht_replication_level,
6617                             GNUNET_DHT_RO_RECORD_ROUTE |
6618                             GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
6619                             NULL, 0,
6620                             &dht_get_type_handler, t);
6621
6622   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6623   return;
6624 }
6625
6626
6627 /**
6628  * Handler for connection requests to new peers by a string service description.
6629  *
6630  * @param cls closure
6631  * @param client identification of the client
6632  * @param message the actual message, which includes messages the client wants
6633  */
6634 static void
6635 handle_local_connect_by_string (void *cls, struct GNUNET_SERVER_Client *client,
6636                                 const struct GNUNET_MessageHeader *message)
6637 {
6638   struct GNUNET_MESH_ConnectPeerByString *msg;
6639   struct MeshRegexSearchContext *ctx;
6640   struct MeshRegexSearchInfo *info;
6641   struct GNUNET_DHT_GetHandle *get_h;
6642   struct GNUNET_HashCode key;
6643   struct MeshTunnel *t;
6644   struct MeshClient *c;
6645   MESH_TunnelNumber tid;
6646   const char *string;
6647   size_t size;
6648   size_t len;
6649   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6650               "Connect by string started\n");
6651   msg = (struct GNUNET_MESH_ConnectPeerByString *) message;
6652   size = htons (message->size);
6653
6654   /* Sanity check for client registration */
6655   if (NULL == (c = client_get (client)))
6656   {
6657     GNUNET_break (0);
6658     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6659     return;
6660   }
6661
6662   /* Message size sanity check */
6663   if (sizeof(struct GNUNET_MESH_ConnectPeerByString) >= size)
6664   {
6665     GNUNET_break (0);
6666     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6667     return;
6668   }
6669
6670   /* Tunnel exists? */
6671   tid = ntohl (msg->tunnel_id);
6672   t = tunnel_get_by_local_id (c, tid);
6673   if (NULL == t)
6674   {
6675     GNUNET_break (0);
6676     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6677     return;
6678   }
6679
6680   /* Does client own tunnel? */
6681   if (t->owner->handle != client)
6682   {
6683     GNUNET_break (0);
6684     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6685     return;
6686   }
6687
6688   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6689               "  on tunnel %s [%u]\n",
6690               GNUNET_i2s(&my_full_id),
6691               t->id.tid);
6692
6693   /* Only one connect_by_string allowed at the same time! */
6694   /* FIXME: allow more, return handle at api level to cancel, document */
6695   if (NULL != t->regex_ctx)
6696   {
6697     GNUNET_break (0);
6698     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6699     return;
6700   }
6701
6702   /* Find string itself */
6703   len = size - sizeof(struct GNUNET_MESH_ConnectPeerByString);
6704   string = (const char *) &msg[1];
6705
6706   /* Initialize context */
6707   size = GNUNET_REGEX_get_first_key(string, len, &key);
6708   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6709               "  consumed %u bits out of %u\n", size, len);
6710   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6711               "  looking for %s\n", GNUNET_h2s (&key));
6712
6713   info = GNUNET_malloc (sizeof (struct MeshRegexSearchInfo));
6714   info->t = t;
6715   info->description = GNUNET_malloc (len + 1);
6716   memcpy (info->description, string, len);
6717   info->description[len] = '\0';
6718   info->dht_get_handles = GNUNET_CONTAINER_multihashmap_create(32);
6719   info->dht_get_results = GNUNET_CONTAINER_multihashmap_create(32);
6720   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   string: %s\n", info->description);
6721
6722   ctx = GNUNET_malloc (sizeof (struct MeshRegexSearchContext));
6723   ctx->position = size;
6724   ctx->info = info;
6725   t->regex_ctx = ctx;
6726
6727   GNUNET_array_append (info->contexts, info->n_contexts, ctx);
6728
6729   /* Start search in DHT */
6730   get_h = GNUNET_DHT_get_start (dht_handle,    /* handle */
6731                                 GNUNET_BLOCK_TYPE_MESH_REGEX, /* type */
6732                                 &key,     /* key to search */
6733                                 dht_replication_level, /* replication level */
6734                                 GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
6735                                 NULL,       /* xquery */ // FIXME BLOOMFILTER
6736                                 0,     /* xquery bits */ // FIXME BLOOMFILTER SIZE
6737                                 &dht_get_string_handler, ctx);
6738
6739   GNUNET_break (GNUNET_OK ==
6740                 GNUNET_CONTAINER_multihashmap_put(info->dht_get_handles,
6741                                                   &key,
6742                                                   get_h,
6743                                                   GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
6744
6745   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6746   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "connect by string processed\n");
6747 }
6748
6749
6750 /**
6751  * Handler for client traffic directed to one peer
6752  *
6753  * @param cls closure
6754  * @param client identification of the client
6755  * @param message the actual message
6756  */
6757 static void
6758 handle_local_unicast (void *cls, struct GNUNET_SERVER_Client *client,
6759                       const struct GNUNET_MessageHeader *message)
6760 {
6761   struct MeshClient *c;
6762   struct MeshTunnel *t;
6763   struct MeshPeerInfo *pi;
6764   struct GNUNET_MESH_Unicast *data_msg;
6765   MESH_TunnelNumber tid;
6766   size_t size;
6767
6768   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6769               "Got a unicast request from a client!\n");
6770
6771   /* Sanity check for client registration */
6772   if (NULL == (c = client_get (client)))
6773   {
6774     GNUNET_break (0);
6775     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6776     return;
6777   }
6778   data_msg = (struct GNUNET_MESH_Unicast *) message;
6779   /* Sanity check for message size */
6780   size = ntohs (message->size);
6781   if (sizeof (struct GNUNET_MESH_Unicast) +
6782       sizeof (struct GNUNET_MessageHeader) > size)
6783   {
6784     GNUNET_break (0);
6785     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6786     return;
6787   }
6788
6789   /* Tunnel exists? */
6790   tid = ntohl (data_msg->tid);
6791   t = tunnel_get_by_local_id (c, tid);
6792   if (NULL == t)
6793   {
6794     GNUNET_break (0);
6795     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6796     return;
6797   }
6798
6799   /*  Is it a local tunnel? Then, does client own the tunnel? */
6800   if (t->owner->handle != client)
6801   {
6802     GNUNET_break (0);
6803     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6804     return;
6805   }
6806
6807   pi = GNUNET_CONTAINER_multihashmap_get (t->peers,
6808                                           &data_msg->destination.hashPubKey);
6809   /* Is the selected peer in the tunnel? */
6810   if (NULL == pi)
6811   {
6812     GNUNET_break (0);
6813     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6814     return;
6815   }
6816
6817   /* PID should be as expected */
6818   if (ntohl (data_msg->pid) != t->fwd_pid + 1)
6819   {
6820     GNUNET_break (0);
6821     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6822               "Unicast PID, expected %u, got %u\n",
6823               t->fwd_pid + 1, ntohl (data_msg->pid));
6824     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6825     return;
6826   }
6827
6828   /* Ok, everything is correct, send the message
6829    * (pretend we got it from a mesh peer)
6830    */
6831   {
6832     /* Work around const limitation */
6833     char buf[ntohs (message->size)] GNUNET_ALIGN;
6834     struct GNUNET_MESH_Unicast *copy;
6835
6836     copy = (struct GNUNET_MESH_Unicast *) buf;
6837     memcpy (buf, data_msg, size);
6838     copy->oid = my_full_id;
6839     copy->tid = htonl (t->id.tid);
6840     copy->ttl = htonl (default_ttl);
6841     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6842                 "  calling generic handler...\n");
6843     handle_mesh_data_unicast (NULL, &my_full_id, &copy->header, NULL, 0);
6844   }
6845   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "receive done OK\n");
6846   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6847   return;
6848 }
6849
6850
6851 /**
6852  * Handler for client traffic directed to the origin
6853  *
6854  * @param cls closure
6855  * @param client identification of the client
6856  * @param message the actual message
6857  */
6858 static void
6859 handle_local_to_origin (void *cls, struct GNUNET_SERVER_Client *client,
6860                         const struct GNUNET_MessageHeader *message)
6861 {
6862   struct GNUNET_MESH_ToOrigin *data_msg;
6863   struct MeshTunnelClientInfo *clinfo;
6864   struct MeshClient *c;
6865   struct MeshTunnel *t;
6866   MESH_TunnelNumber tid;
6867   size_t size;
6868
6869   /* Sanity check for client registration */
6870   if (NULL == (c = client_get (client)))
6871   {
6872     GNUNET_break (0);
6873     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6874     return;
6875   }
6876   data_msg = (struct GNUNET_MESH_ToOrigin *) message;
6877   /* Sanity check for message size */
6878   size = ntohs (message->size);
6879   if (sizeof (struct GNUNET_MESH_ToOrigin) +
6880       sizeof (struct GNUNET_MessageHeader) > size)
6881   {
6882     GNUNET_break (0);
6883     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6884     return;
6885   }
6886
6887   /* Tunnel exists? */
6888   tid = ntohl (data_msg->tid);
6889   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6890               "Got a ToOrigin request from a client! Tunnel %X\n", tid);
6891   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
6892   {
6893     GNUNET_break (0);
6894     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6895     return;
6896   }
6897   t = tunnel_get_by_local_id (c, tid);
6898   if (NULL == t)
6899   {
6900     GNUNET_break (0);
6901     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6902     return;
6903   }
6904
6905   /*  It should be sent by someone who has this as incoming tunnel. */
6906   if (GNUNET_NO == client_knows_tunnel (c, t))
6907   {
6908     GNUNET_break (0);
6909     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6910     return;
6911   }
6912
6913   /* PID should be as expected */
6914   clinfo = tunnel_get_client_fc (t, c);
6915   if (ntohl (data_msg->pid) != clinfo->bck_pid + 1)
6916   {
6917     GNUNET_break (0);
6918     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6919                 "To Origin PID, expected %u, got %u\n",
6920                 clinfo->bck_pid + 1, ntohl (data_msg->pid));
6921     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6922     return;
6923   }
6924
6925   /* Ok, everything is correct, send the message
6926    * (pretend we got it from a mesh peer)
6927    */
6928   {
6929     char buf[ntohs (message->size)] GNUNET_ALIGN;
6930     struct GNUNET_MESH_ToOrigin *copy;
6931
6932     /* Work around const limitation */
6933     copy = (struct GNUNET_MESH_ToOrigin *) buf;
6934     memcpy (buf, data_msg, size);
6935     GNUNET_PEER_resolve (t->id.oid, &copy->oid);
6936     copy->tid = htonl (t->id.tid);
6937     copy->ttl = htonl (default_ttl);
6938     GNUNET_assert (ntohl (copy->pid) == (t->bck_pid + 1));
6939     copy->sender = my_full_id;
6940     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6941                 "  calling generic handler...\n");
6942     handle_mesh_data_to_orig (NULL, &my_full_id, &copy->header, NULL, 0);
6943   }
6944   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6945   return;
6946 }
6947
6948
6949 /**
6950  * Handler for client traffic directed to all peers in a tunnel
6951  *
6952  * @param cls closure
6953  * @param client identification of the client
6954  * @param message the actual message
6955  */
6956 static void
6957 handle_local_multicast (void *cls, struct GNUNET_SERVER_Client *client,
6958                         const struct GNUNET_MessageHeader *message)
6959 {
6960   struct MeshClient *c;
6961   struct MeshTunnel *t;
6962   struct GNUNET_MESH_Multicast *data_msg;
6963   MESH_TunnelNumber tid;
6964
6965   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6966               "Got a multicast request from a client!\n");
6967
6968   /* Sanity check for client registration */
6969   if (NULL == (c = client_get (client)))
6970   {
6971     GNUNET_break (0);
6972     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6973     return;
6974   }
6975   data_msg = (struct GNUNET_MESH_Multicast *) message;
6976   /* Sanity check for message size */
6977   if (sizeof (struct GNUNET_MESH_Multicast) +
6978       sizeof (struct GNUNET_MessageHeader) > ntohs (data_msg->header.size))
6979   {
6980     GNUNET_break (0);
6981     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6982     return;
6983   }
6984
6985   /* Tunnel exists? */
6986   tid = ntohl (data_msg->tid);
6987   t = tunnel_get_by_local_id (c, tid);
6988   if (NULL == t)
6989   {
6990     GNUNET_break (0);
6991     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6992     return;
6993   }
6994
6995   /* Does client own tunnel? */
6996   if (t->owner->handle != client)
6997   {
6998     GNUNET_break (0);
6999     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7000     return;
7001   }
7002
7003   /* PID should be as expected */
7004   if (ntohl (data_msg->pid) != t->fwd_pid + 1)
7005   {
7006     GNUNET_break (0);
7007     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7008               "Multicast PID, expected %u, got %u\n",
7009               t->fwd_pid + 1, ntohl (data_msg->pid));
7010     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7011     return;
7012   }
7013
7014   {
7015     char buf[ntohs (message->size)] GNUNET_ALIGN;
7016     struct GNUNET_MESH_Multicast *copy;
7017
7018     copy = (struct GNUNET_MESH_Multicast *) buf;
7019     memcpy (buf, message, ntohs (message->size));
7020     copy->oid = my_full_id;
7021     copy->tid = htonl (t->id.tid);
7022     copy->ttl = htonl (default_ttl);
7023     GNUNET_assert (ntohl (copy->pid) == (t->fwd_pid + 1));
7024     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7025                 "  calling generic handler...\n");
7026     handle_mesh_data_multicast (client, &my_full_id, &copy->header, NULL, 0);
7027   }
7028
7029   /* receive done gets called when last copy is sent to a neighbor */
7030   return;
7031 }
7032
7033
7034 /**
7035  * Handler for client's ACKs for payload traffic.
7036  *
7037  * @param cls Closure (unused).
7038  * @param client Identification of the client.
7039  * @param message The actual message.
7040  */
7041 static void
7042 handle_local_ack (void *cls, struct GNUNET_SERVER_Client *client,
7043                   const struct GNUNET_MessageHeader *message)
7044 {
7045   struct GNUNET_MESH_LocalAck *msg;
7046   struct MeshTunnel *t;
7047   struct MeshClient *c;
7048   MESH_TunnelNumber tid;
7049
7050   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a local ACK\n");
7051   /* Sanity check for client registration */
7052   if (NULL == (c = client_get (client)))
7053   {
7054     GNUNET_break (0);
7055     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7056     return;
7057   }
7058
7059   msg = (struct GNUNET_MESH_LocalAck *) message;
7060   /* Tunnel exists? */
7061   tid = ntohl (msg->tunnel_id);
7062   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
7063   t = tunnel_get_by_local_id (c, tid);
7064   if (NULL == t)
7065   {
7066     GNUNET_break (0); // FIXME fc
7067     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7068     return;
7069   }
7070
7071   /* Does client own tunnel? I.E: Is this and ACK for BCK traffic? */
7072   if (NULL != t->owner && t->owner->handle == client)
7073   {
7074     /* The client owns the tunnel, ACK is for data to_origin, send BCK ACK. */
7075     t->bck_ack = ntohl(msg->max_pid);
7076     tunnel_send_bck_ack(t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
7077   }
7078   else
7079   {
7080     /* The client doesn't own the tunnel, this ACK is for FWD traffic. */
7081     tunnel_set_client_fwd_ack (t, c, ntohl (msg->max_pid));
7082     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
7083   }
7084
7085   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7086   return;
7087 }
7088
7089
7090 /**
7091  * Functions to handle messages from clients
7092  */
7093 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
7094   {&handle_local_new_client, NULL,
7095    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
7096   {&handle_local_announce_regex, NULL,
7097    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ANNOUNCE_REGEX, 0},
7098   {&handle_local_tunnel_create, NULL,
7099    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
7100    sizeof (struct GNUNET_MESH_TunnelMessage)},
7101   {&handle_local_tunnel_destroy, NULL,
7102    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
7103    sizeof (struct GNUNET_MESH_TunnelMessage)},
7104   {&handle_local_tunnel_speed, NULL,
7105    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MIN,
7106    sizeof (struct GNUNET_MESH_TunnelMessage)},
7107   {&handle_local_tunnel_speed, NULL,
7108    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MAX,
7109    sizeof (struct GNUNET_MESH_TunnelMessage)},
7110   {&handle_local_tunnel_buffer, NULL,
7111    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER,
7112    sizeof (struct GNUNET_MESH_TunnelMessage)},
7113   {&handle_local_tunnel_buffer, NULL,
7114    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER,
7115    sizeof (struct GNUNET_MESH_TunnelMessage)},
7116   {&handle_local_connect_add, NULL,
7117    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD,
7118    sizeof (struct GNUNET_MESH_PeerControl)},
7119   {&handle_local_connect_del, NULL,
7120    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL,
7121    sizeof (struct GNUNET_MESH_PeerControl)},
7122   {&handle_local_blacklist, NULL,
7123    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_BLACKLIST,
7124    sizeof (struct GNUNET_MESH_PeerControl)},
7125   {&handle_local_unblacklist, NULL,
7126    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_UNBLACKLIST,
7127    sizeof (struct GNUNET_MESH_PeerControl)},
7128   {&handle_local_connect_by_type, NULL,
7129    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE,
7130    sizeof (struct GNUNET_MESH_ConnectPeerByType)},
7131   {&handle_local_connect_by_string, NULL,
7132    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_STRING, 0},
7133   {&handle_local_unicast, NULL,
7134    GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
7135   {&handle_local_to_origin, NULL,
7136    GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
7137   {&handle_local_multicast, NULL,
7138    GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
7139   {&handle_local_ack, NULL,
7140    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK,
7141    sizeof (struct GNUNET_MESH_LocalAck)},
7142   {NULL, NULL, 0, 0}
7143 };
7144
7145
7146 /**
7147  * To be called on core init/fail.
7148  *
7149  * @param cls service closure
7150  * @param server handle to the server for this service
7151  * @param identity the public identity of this peer
7152  */
7153 static void
7154 core_init (void *cls, struct GNUNET_CORE_Handle *server,
7155            const struct GNUNET_PeerIdentity *identity)
7156 {
7157   static int i = 0;
7158   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
7159   core_handle = server;
7160   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)) ||
7161       NULL == server)
7162   {
7163     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
7164     GNUNET_SCHEDULER_shutdown (); // Try gracefully
7165     if (10 < i++)
7166       GNUNET_abort(); // Try harder
7167   }
7168   return;
7169 }
7170
7171
7172 /**
7173  * Method called whenever a given peer connects.
7174  *
7175  * @param cls closure
7176  * @param peer peer identity this notification is about
7177  * @param atsi performance data for the connection
7178  * @param atsi_count number of records in 'atsi'
7179  */
7180 static void
7181 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
7182               const struct GNUNET_ATS_Information *atsi,
7183               unsigned int atsi_count)
7184 {
7185   struct MeshPeerInfo *peer_info;
7186   struct MeshPeerPath *path;
7187
7188   DEBUG_CONN ("Peer connected\n");
7189   DEBUG_CONN ("     %s\n", GNUNET_i2s (&my_full_id));
7190   peer_info = peer_info_get (peer);
7191   if (myid == peer_info->id)
7192   {
7193     DEBUG_CONN ("     (self)\n");
7194     return;
7195   }
7196   else
7197   {
7198     DEBUG_CONN ("     %s\n", GNUNET_i2s (peer));
7199   }
7200   path = path_new (2);
7201   path->peers[0] = myid;
7202   path->peers[1] = peer_info->id;
7203   GNUNET_PEER_change_rc (myid, 1);
7204   GNUNET_PEER_change_rc (peer_info->id, 1);
7205   peer_info_add_path (peer_info, path, GNUNET_YES);
7206   GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
7207   return;
7208 }
7209
7210
7211 /**
7212  * Method called whenever a peer disconnects.
7213  *
7214  * @param cls closure
7215  * @param peer peer identity this notification is about
7216  */
7217 static void
7218 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
7219 {
7220   struct MeshPeerInfo *pi;
7221   struct MeshPeerQueue *q;
7222   struct MeshPeerQueue *n;
7223
7224   DEBUG_CONN ("Peer disconnected\n");
7225   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
7226   if (NULL == pi)
7227   {
7228     GNUNET_break (0);
7229     return;
7230   }
7231   q = pi->queue_head;
7232   while (NULL != q)
7233   {
7234       n = q->next;
7235       if (q->peer == pi)
7236       {
7237         /* try to reroute this traffic instead */
7238         queue_destroy(q, GNUNET_YES);
7239       }
7240       q = n;
7241   }
7242   peer_info_remove_path (pi, pi->id, myid);
7243   if (myid == pi->id)
7244   {
7245     DEBUG_CONN ("     (self)\n");
7246   }
7247   GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
7248   return;
7249 }
7250
7251
7252 /******************************************************************************/
7253 /************************      MAIN FUNCTIONS      ****************************/
7254 /******************************************************************************/
7255
7256 /**
7257  * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
7258  *
7259  * @param cls closure
7260  * @param key current key code
7261  * @param value value in the hash map
7262  * @return GNUNET_YES if we should continue to iterate,
7263  *         GNUNET_NO if not.
7264  */
7265 static int
7266 shutdown_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
7267 {
7268   struct MeshTunnel *t = value;
7269
7270   tunnel_destroy (t);
7271   return GNUNET_YES;
7272 }
7273
7274 /**
7275  * Iterator over peer hash map entries to destroy the tunnel during shutdown.
7276  *
7277  * @param cls closure
7278  * @param key current key code
7279  * @param value value in the hash map
7280  * @return GNUNET_YES if we should continue to iterate,
7281  *         GNUNET_NO if not.
7282  */
7283 static int
7284 shutdown_peer (void *cls, const struct GNUNET_HashCode * key, void *value)
7285 {
7286   struct MeshPeerInfo *p = value;
7287   struct MeshPeerQueue *q;
7288   struct MeshPeerQueue *n;
7289
7290   q = p->queue_head;
7291   while (NULL != q)
7292   {
7293       n = q->next;
7294       if (q->peer == p)
7295       {
7296         queue_destroy(q, GNUNET_YES);
7297       }
7298       q = n;
7299   }
7300   peer_info_destroy (p);
7301   return GNUNET_YES;
7302 }
7303
7304 /**
7305  * Task run during shutdown.
7306  *
7307  * @param cls unused
7308  * @param tc unused
7309  */
7310 static void
7311 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
7312 {
7313   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
7314
7315   if (core_handle != NULL)
7316   {
7317     GNUNET_CORE_disconnect (core_handle);
7318     core_handle = NULL;
7319   }
7320   GNUNET_CONTAINER_multihashmap_iterate (tunnels, &shutdown_tunnel, NULL);
7321   GNUNET_CONTAINER_multihashmap_iterate (peers, &shutdown_peer, NULL);
7322   if (dht_handle != NULL)
7323   {
7324     GNUNET_DHT_disconnect (dht_handle);
7325     dht_handle = NULL;
7326   }
7327   if (nc != NULL)
7328   {
7329     GNUNET_SERVER_notification_context_destroy (nc);
7330     nc = NULL;
7331   }
7332   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
7333   {
7334     GNUNET_SCHEDULER_cancel (announce_id_task);
7335     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
7336   }
7337   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
7338 }
7339
7340 /**
7341  * Process mesh requests.
7342  *
7343  * @param cls closure
7344  * @param server the initialized server
7345  * @param c configuration to use
7346  */
7347 static void
7348 run (void *cls, struct GNUNET_SERVER_Handle *server,
7349      const struct GNUNET_CONFIGURATION_Handle *c)
7350 {
7351   struct MeshPeerInfo *peer;
7352   struct MeshPeerPath *p;
7353   char *keyfile;
7354
7355   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
7356   server_handle = server;
7357   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
7358                                      NULL,      /* Closure passed to MESH functions */
7359                                      &core_init,        /* Call core_init once connected */
7360                                      &core_connect,     /* Handle connects */
7361                                      &core_disconnect,  /* remove peers on disconnects */
7362                                      NULL,      /* Don't notify about all incoming messages */
7363                                      GNUNET_NO, /* For header only in notification */
7364                                      NULL,      /* Don't notify about all outbound messages */
7365                                      GNUNET_NO, /* For header-only out notification */
7366                                      core_handlers);    /* Register these handlers */
7367
7368   if (core_handle == NULL)
7369   {
7370     GNUNET_break (0);
7371     GNUNET_SCHEDULER_shutdown ();
7372     return;
7373   }
7374
7375   if (GNUNET_OK !=
7376       GNUNET_CONFIGURATION_get_value_filename (c, "GNUNETD", "HOSTKEY",
7377                                                &keyfile))
7378   {
7379     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7380                 _
7381                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7382                 "hostkey");
7383     GNUNET_SCHEDULER_shutdown ();
7384     return;
7385   }
7386
7387   if (GNUNET_OK !=
7388       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_PATH_TIME",
7389                                            &refresh_path_time))
7390   {
7391     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7392                 _
7393                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7394                 "refresh path time");
7395     GNUNET_SCHEDULER_shutdown ();
7396     return;
7397   }
7398
7399   if (GNUNET_OK !=
7400       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "APP_ANNOUNCE_TIME",
7401                                            &app_announce_time))
7402   {
7403     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7404                 _
7405                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7406                 "app announce time");
7407     GNUNET_SCHEDULER_shutdown ();
7408     return;
7409   }
7410
7411   if (GNUNET_OK !=
7412       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "ID_ANNOUNCE_TIME",
7413                                            &id_announce_time))
7414   {
7415     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7416                 _
7417                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7418                 "id announce time");
7419     GNUNET_SCHEDULER_shutdown ();
7420     return;
7421   }
7422
7423   if (GNUNET_OK !=
7424       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "UNACKNOWLEDGED_WAIT",
7425                                            &unacknowledged_wait_time))
7426   {
7427     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7428                 _
7429                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7430                 "unacknowledged wait time");
7431     GNUNET_SCHEDULER_shutdown ();
7432     return;
7433   }
7434
7435   if (GNUNET_OK !=
7436       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "CONNECT_TIMEOUT",
7437                                            &connect_timeout))
7438   {
7439     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7440                 _
7441                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7442                 "connect timeout");
7443     GNUNET_SCHEDULER_shutdown ();
7444     return;
7445   }
7446
7447   if (GNUNET_OK !=
7448       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
7449                                              &max_msgs_queue))
7450   {
7451     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7452                 _
7453                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7454                 "max msgs queue");
7455     GNUNET_SCHEDULER_shutdown ();
7456     return;
7457   }
7458
7459   if (GNUNET_OK !=
7460       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_TUNNELS",
7461                                              &max_tunnels))
7462   {
7463     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7464                 _
7465                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7466                 "max tunnels");
7467     GNUNET_SCHEDULER_shutdown ();
7468     return;
7469   }
7470
7471   if (GNUNET_OK !=
7472       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
7473                                              &default_ttl))
7474   {
7475     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7476                 _
7477                 ("Mesh service is lacking key configuration settings (%s). Using default (%u).\n"),
7478                 "default ttl", 64);
7479     default_ttl = 64;
7480   }
7481
7482   if (GNUNET_OK !=
7483       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DHT_REPLICATION_LEVEL",
7484                                              &dht_replication_level))
7485   {
7486     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7487                 _
7488                 ("Mesh service is lacking key configuration settings (%s). Using default (%u).\n"),
7489                 "dht replication level", 10);
7490     dht_replication_level = 10;
7491   }
7492
7493   
7494   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
7495   GNUNET_free (keyfile);
7496   if (my_private_key == NULL)
7497   {
7498     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7499                 _("Mesh service could not access hostkey.  Exiting.\n"));
7500     GNUNET_SCHEDULER_shutdown ();
7501     return;
7502   }
7503   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
7504   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
7505                       &my_full_id.hashPubKey);
7506   myid = GNUNET_PEER_intern (&my_full_id);
7507
7508 //   transport_handle = GNUNET_TRANSPORT_connect(c,
7509 //                                               &my_full_id,
7510 //                                               NULL,
7511 //                                               NULL,
7512 //                                               NULL,
7513 //                                               NULL);
7514
7515   dht_handle = GNUNET_DHT_connect (c, 64);
7516   if (dht_handle == NULL)
7517   {
7518     GNUNET_break (0);
7519   }
7520
7521   stats = GNUNET_STATISTICS_create ("mesh", c);
7522
7523
7524   next_tid = 0;
7525   next_local_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
7526
7527   tunnels = GNUNET_CONTAINER_multihashmap_create (32);
7528   incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
7529   peers = GNUNET_CONTAINER_multihashmap_create (32);
7530   applications = GNUNET_CONTAINER_multihashmap_create (32);
7531   types = GNUNET_CONTAINER_multihashmap_create (32);
7532
7533   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
7534   nc = GNUNET_SERVER_notification_context_create (server_handle, 1);
7535   GNUNET_SERVER_disconnect_notify (server_handle,
7536                                    &handle_local_client_disconnect, NULL);
7537
7538
7539   clients = NULL;
7540   clients_tail = NULL;
7541   next_client_id = 0;
7542
7543   announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
7544   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
7545
7546   /* Create a peer_info for the local peer */
7547   peer = peer_info_get (&my_full_id);
7548   p = path_new (1);
7549   p->peers[0] = myid;
7550   GNUNET_PEER_change_rc (myid, 1);
7551   peer_info_add_path (peer, p, GNUNET_YES);
7552
7553   /* Scheduled the task to clean up when shutdown is called */
7554   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
7555                                 NULL);
7556
7557   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "end of run()\n");
7558 }
7559
7560 /**
7561  * The main function for the mesh service.
7562  *
7563  * @param argc number of arguments from the command line
7564  * @param argv command line arguments
7565  * @return 0 ok, 1 on error
7566  */
7567 int
7568 main (int argc, char *const *argv)
7569 {
7570   int ret;
7571
7572   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
7573   ret =
7574       (GNUNET_OK ==
7575        GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
7576                            NULL)) ? 0 : 1;
7577   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");
7578
7579   return ret;
7580 }