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