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