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