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