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