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