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