- handle errors more gracefully, be more verbose for debug
[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     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
6042                 "unknown to origin at %s\n",
6043                 GNUNET_i2s (&my_full_id));
6044     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
6045                 "from peer %s\n",
6046                 GNUNET_i2s (peer));
6047     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
6048                 "for tunnel %s [%X]\n",
6049                 GNUNET_i2s (&msg->oid), ntohl(msg->tid));
6050     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
6051                 "current tree:\n");
6052     tree_debug (t->tree);
6053     return GNUNET_OK;
6054   }
6055   GNUNET_PEER_resolve (predecessor, &id);
6056   send_prebuilt_message (message, &id, t);
6057   GNUNET_STATISTICS_update (stats, "# to origin forwarded", 1, GNUNET_NO);
6058
6059   return GNUNET_OK;
6060 }
6061
6062
6063 /**
6064  * Core handler for mesh network traffic point-to-point acks.
6065  *
6066  * @param cls closure
6067  * @param message message
6068  * @param peer peer identity this notification is about
6069  * @param atsi performance data
6070  * @param atsi_count number of records in 'atsi'
6071  *
6072  * @return GNUNET_OK to keep the connection open,
6073  *         GNUNET_SYSERR to close it (signal serious error)
6074  */
6075 static int
6076 handle_mesh_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
6077                  const struct GNUNET_MessageHeader *message,
6078                  const struct GNUNET_ATS_Information *atsi,
6079                  unsigned int atsi_count)
6080 {
6081   struct GNUNET_MESH_ACK *msg;
6082   struct MeshTunnel *t;
6083   uint32_t ack;
6084
6085   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK packet from %s!\n",
6086               GNUNET_i2s (peer));
6087   msg = (struct GNUNET_MESH_ACK *) message;
6088
6089   t = tunnel_get (&msg->oid, ntohl (msg->tid));
6090
6091   if (NULL == t)
6092   {
6093     /* TODO notify that we dont know this tunnel (whom)? */
6094     GNUNET_STATISTICS_update (stats, "# ack on unknown tunnel", 1, GNUNET_NO);
6095     return GNUNET_OK;
6096   }
6097   ack = ntohl (msg->pid);
6098   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ACK %u\n", ack);
6099
6100   /* Is this a forward or backward ACK? */
6101   if (tree_get_predecessor(t->tree) != GNUNET_PEER_search(peer))
6102   {
6103     struct MeshTunnelChildInfo *cinfo;
6104
6105     debug_bck_ack++;
6106     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
6107     cinfo = tunnel_get_neighbor_fc (t, peer);
6108     cinfo->fwd_ack = ack;
6109     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
6110     tunnel_unlock_fwd_queues (t);
6111     if (GNUNET_SCHEDULER_NO_TASK != cinfo->fc_poll)
6112     {
6113       GNUNET_SCHEDULER_cancel (cinfo->fc_poll);
6114       cinfo->fc_poll = GNUNET_SCHEDULER_NO_TASK;
6115       cinfo->fc_poll_time = GNUNET_TIME_UNIT_SECONDS;
6116     }
6117   }
6118   else
6119   {
6120     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
6121     t->bck_ack = ack;
6122     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
6123     tunnel_unlock_bck_queue (t);
6124   }
6125   return GNUNET_OK;
6126 }
6127
6128
6129 /**
6130  * Core handler for mesh network traffic point-to-point ack polls.
6131  *
6132  * @param cls closure
6133  * @param message message
6134  * @param peer peer identity this notification is about
6135  * @param atsi performance data
6136  * @param atsi_count number of records in 'atsi'
6137  *
6138  * @return GNUNET_OK to keep the connection open,
6139  *         GNUNET_SYSERR to close it (signal serious error)
6140  */
6141 static int
6142 handle_mesh_poll (void *cls, const struct GNUNET_PeerIdentity *peer,
6143                   const struct GNUNET_MessageHeader *message,
6144                   const struct GNUNET_ATS_Information *atsi,
6145                   unsigned int atsi_count)
6146 {
6147   struct GNUNET_MESH_Poll *msg;
6148   struct MeshTunnel *t;
6149
6150   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an POLL packet from %s!\n",
6151               GNUNET_i2s (peer));
6152
6153   msg = (struct GNUNET_MESH_Poll *) message;
6154
6155   t = tunnel_get (&msg->oid, ntohl (msg->tid));
6156
6157   if (NULL == t)
6158   {
6159     /* TODO notify that we dont know this tunnel (whom)? */
6160     GNUNET_STATISTICS_update (stats, "# poll on unknown tunnel", 1, GNUNET_NO);
6161     GNUNET_break_op (0);
6162     return GNUNET_OK;
6163   }
6164
6165   /* Is this a forward or backward ACK? */
6166   if (tree_get_predecessor(t->tree) != GNUNET_PEER_search(peer))
6167   {
6168     struct MeshTunnelChildInfo *cinfo;
6169
6170     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  from FWD\n");
6171     cinfo = tunnel_get_neighbor_fc (t, peer);
6172     cinfo->bck_ack = cinfo->fwd_pid; // mark as ready to send
6173     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_POLL);
6174   }
6175   else
6176   {
6177     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  from BCK\n");
6178     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_POLL);
6179   }
6180
6181   return GNUNET_OK;
6182 }
6183
6184
6185 /**
6186  * Core handler for path ACKs
6187  *
6188  * @param cls closure
6189  * @param message message
6190  * @param peer peer identity this notification is about
6191  * @param atsi performance data
6192  * @param atsi_count number of records in 'atsi'
6193  *
6194  * @return GNUNET_OK to keep the connection open,
6195  *         GNUNET_SYSERR to close it (signal serious error)
6196  */
6197 static int
6198 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
6199                       const struct GNUNET_MessageHeader *message,
6200                       const struct GNUNET_ATS_Information *atsi,
6201                       unsigned int atsi_count)
6202 {
6203   struct GNUNET_MESH_PathACK *msg;
6204   struct GNUNET_PeerIdentity id;
6205   struct MeshPeerInfo *peer_info;
6206   struct MeshPeerPath *p;
6207   struct MeshTunnel *t;
6208
6209   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a path ACK msg [%s]\n",
6210               GNUNET_i2s (&my_full_id));
6211   msg = (struct GNUNET_MESH_PathACK *) message;
6212   t = tunnel_get (&msg->oid, ntohl(msg->tid));
6213   if (NULL == t)
6214   {
6215     /* TODO notify that we don't know the tunnel */
6216     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel", 1, GNUNET_NO);
6217     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  don't know the tunnel %s [%X]!\n",
6218                 GNUNET_i2s (&msg->oid), ntohl(msg->tid));
6219     return GNUNET_OK;
6220   }
6221   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %s [%X]\n",
6222               GNUNET_i2s (&msg->oid), ntohl(msg->tid));
6223
6224   peer_info = peer_info_get (&msg->peer_id);
6225   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by peer %s\n",
6226               GNUNET_i2s (&msg->peer_id));
6227   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  via peer %s\n",
6228               GNUNET_i2s (peer));
6229
6230   if (NULL != t->regex_ctx && t->regex_ctx->info->peer == peer_info->id)
6231   {
6232     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6233                 "connect_by_string completed, stopping search\n");
6234     regex_cancel_search (t->regex_ctx);
6235     t->regex_ctx = NULL;
6236   }
6237
6238   /* Add paths to peers? */
6239   p = tree_get_path_to_peer (t->tree, peer_info->id);
6240   if (NULL != p)
6241   {
6242     path_add_to_peers (p, GNUNET_YES);
6243     path_destroy (p);
6244   }
6245   else
6246   {
6247     GNUNET_break (0);
6248   }
6249
6250   /* Message for us? */
6251   if (0 == memcmp (&msg->oid, &my_full_id, sizeof (struct GNUNET_PeerIdentity)))
6252   {
6253     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
6254     if (NULL == t->owner)
6255     {
6256       GNUNET_break_op (0);
6257       return GNUNET_OK;
6258     }
6259     if (NULL != t->dht_get_type)
6260     {
6261       GNUNET_DHT_get_stop (t->dht_get_type);
6262       t->dht_get_type = NULL;
6263     }
6264     if (tree_get_status (t->tree, peer_info->id) != MESH_PEER_READY)
6265     {
6266       tree_set_status (t->tree, peer_info->id, MESH_PEER_READY);
6267       send_client_peer_connected (t, peer_info->id);
6268     }
6269     return GNUNET_OK;
6270   }
6271
6272   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6273               "  not for us, retransmitting...\n");
6274   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
6275   peer_info = peer_info_get (&msg->oid);
6276   if (NULL == peer_info)
6277   {
6278     /* If we know the tunnel, we should DEFINITELY know the peer */
6279     GNUNET_break (0);
6280     return GNUNET_OK;
6281   }
6282   send_prebuilt_message (message, &id, t);
6283   return GNUNET_OK;
6284 }
6285
6286
6287 /**
6288  * Core handler for mesh keepalives.
6289  *
6290  * @param cls closure
6291  * @param message message
6292  * @param peer peer identity this notification is about
6293  * @param atsi performance data
6294  * @param atsi_count number of records in 'atsi'
6295  * @return GNUNET_OK to keep the connection open,
6296  *         GNUNET_SYSERR to close it (signal serious error)
6297  *
6298  * TODO: Check who we got this from, to validate route.
6299  */
6300 static int
6301 handle_mesh_keepalive (void *cls, const struct GNUNET_PeerIdentity *peer,
6302                        const struct GNUNET_MessageHeader *message,
6303                        const struct GNUNET_ATS_Information *atsi,
6304                        unsigned int atsi_count)
6305 {
6306   struct GNUNET_MESH_TunnelKeepAlive *msg;
6307   struct MeshTunnel *t;
6308
6309   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a keepalive packet from %s\n",
6310               GNUNET_i2s (peer));
6311
6312   msg = (struct GNUNET_MESH_TunnelKeepAlive *) message;
6313   t = tunnel_get (&msg->oid, ntohl (msg->tid));
6314
6315   if (NULL == t)
6316   {
6317     /* TODO notify that we dont know that tunnel */
6318     GNUNET_STATISTICS_update (stats, "# keepalive on unknown tunnel", 1, GNUNET_NO);
6319     GNUNET_break_op (0);
6320     return GNUNET_OK;
6321   }
6322
6323   tunnel_reset_timeout (t);
6324
6325   GNUNET_STATISTICS_update (stats, "# keepalives forwarded", 1, GNUNET_NO);
6326   tunnel_send_multicast (t, message);
6327   return GNUNET_OK;
6328   }
6329
6330
6331
6332 /**
6333  * Functions to handle messages from core
6334  */
6335 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
6336   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
6337   {&handle_mesh_path_destroy, GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY, 0},
6338   {&handle_mesh_path_broken, GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN,
6339    sizeof (struct GNUNET_MESH_PathBroken)},
6340   {&handle_mesh_tunnel_destroy, GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY,
6341    sizeof (struct GNUNET_MESH_TunnelDestroy)},
6342   {&handle_mesh_data_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
6343   {&handle_mesh_data_multicast, GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
6344   {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE,
6345     sizeof (struct GNUNET_MESH_TunnelKeepAlive)},
6346   {&handle_mesh_data_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
6347   {&handle_mesh_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
6348     sizeof (struct GNUNET_MESH_ACK)},
6349   {&handle_mesh_poll, GNUNET_MESSAGE_TYPE_MESH_POLL,
6350     sizeof (struct GNUNET_MESH_Poll)},
6351   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
6352    sizeof (struct GNUNET_MESH_PathACK)},
6353   {NULL, 0, 0}
6354 };
6355
6356
6357
6358 /******************************************************************************/
6359 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
6360 /******************************************************************************/
6361
6362 /**
6363  * deregister_app: iterator for removing each application registered by a client
6364  *
6365  * @param cls closure
6366  * @param key the hash of the application id (used to access the hashmap)
6367  * @param value the value stored at the key (client)
6368  *
6369  * @return GNUNET_OK on success
6370  */
6371 static int
6372 deregister_app (void *cls, const struct GNUNET_HashCode * key, void *value)
6373 {
6374   struct GNUNET_CONTAINER_MultiHashMap *h = cls;
6375   GNUNET_break (GNUNET_YES ==
6376                 GNUNET_CONTAINER_multihashmap_remove (h, key, value));
6377   return GNUNET_OK;
6378 }
6379
6380 #if LATER
6381 /**
6382  * notify_client_connection_failure: notify a client that the connection to the
6383  * requested remote peer is not possible (for instance, no route found)
6384  * Function called when the socket is ready to queue more data. "buf" will be
6385  * NULL and "size" zero if the socket was closed for writing in the meantime.
6386  *
6387  * @param cls closure
6388  * @param size number of bytes available in buf
6389  * @param buf where the callee should write the message
6390  * @return number of bytes written to buf
6391  */
6392 static size_t
6393 notify_client_connection_failure (void *cls, size_t size, void *buf)
6394 {
6395   int size_needed;
6396   struct MeshPeerInfo *peer_info;
6397   struct GNUNET_MESH_PeerControl *msg;
6398   struct GNUNET_PeerIdentity id;
6399
6400   if (0 == size && NULL == buf)
6401   {
6402     // TODO retry? cancel?
6403     return 0;
6404   }
6405
6406   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
6407   peer_info = (struct MeshPeerInfo *) cls;
6408   msg = (struct GNUNET_MESH_PeerControl *) buf;
6409   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
6410   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
6411 //     msg->tunnel_id = htonl(peer_info->t->tid);
6412   GNUNET_PEER_resolve (peer_info->id, &id);
6413   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
6414
6415   return size_needed;
6416 }
6417 #endif
6418
6419
6420 /**
6421  * Send keepalive packets for a peer
6422  *
6423  * @param cls Closure (tunnel for which to send the keepalive).
6424  * @param tc Notification context.
6425  */
6426 static void
6427 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
6428 {
6429   struct MeshTunnel *t = cls;
6430   struct GNUNET_MESH_TunnelKeepAlive *msg;
6431   size_t size = sizeof (struct GNUNET_MESH_TunnelKeepAlive);
6432   char cbuf[size];
6433
6434   t->path_refresh_task = GNUNET_SCHEDULER_NO_TASK;
6435   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
6436   {
6437     return;
6438   }
6439
6440   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6441               "sending keepalive for tunnel %d\n", t->id.tid);
6442
6443   msg = (struct GNUNET_MESH_TunnelKeepAlive *) cbuf;
6444   msg->header.size = htons (size);
6445   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE);
6446   msg->oid = my_full_id;
6447   msg->tid = htonl (t->id.tid);
6448   tunnel_send_multicast (t, &msg->header);
6449
6450   t->path_refresh_task =
6451       GNUNET_SCHEDULER_add_delayed (refresh_path_time, &path_refresh, t);
6452   tunnel_reset_timeout(t);
6453 }
6454
6455
6456 /**
6457  * Function to process paths received for a new peer addition. The recorded
6458  * paths form the initial tunnel, which can be optimized later.
6459  * Called on each result obtained for the DHT search.
6460  *
6461  * @param cls closure
6462  * @param exp when will this value expire
6463  * @param key key of the result
6464  * @param get_path path of the get request
6465  * @param get_path_length lenght of get_path
6466  * @param put_path path of the put request
6467  * @param put_path_length length of the put_path
6468  * @param type type of the result
6469  * @param size number of bytes in data
6470  * @param data pointer to the result data
6471  *
6472  * TODO: re-issue the request after certain time? cancel after X results?
6473  */
6474 static void
6475 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
6476                     const struct GNUNET_HashCode * key,
6477                     const struct GNUNET_PeerIdentity *get_path,
6478                     unsigned int get_path_length,
6479                     const struct GNUNET_PeerIdentity *put_path,
6480                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
6481                     size_t size, const void *data)
6482 {
6483   struct MeshPathInfo *path_info = cls;
6484   struct MeshPeerPath *p;
6485   struct GNUNET_PeerIdentity pi;
6486   int i;
6487
6488   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
6489   GNUNET_PEER_resolve (path_info->peer->id, &pi);
6490   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", GNUNET_i2s (&pi));
6491
6492   p = path_build_from_dht (get_path, get_path_length, put_path,
6493                            put_path_length);
6494   path_add_to_peers (p, GNUNET_NO);
6495   path_destroy(p);
6496   for (i = 0; i < path_info->peer->ntunnels; i++)
6497   {
6498     tunnel_add_peer (path_info->peer->tunnels[i], path_info->peer);
6499     peer_info_connect (path_info->peer, path_info->t);
6500   }
6501
6502   return;
6503 }
6504
6505
6506 /**
6507  * Function to process paths received for a new peer addition. The recorded
6508  * paths form the initial tunnel, which can be optimized later.
6509  * Called on each result obtained for the DHT search.
6510  *
6511  * @param cls closure
6512  * @param exp when will this value expire
6513  * @param key key of the result
6514  * @param get_path path of the get request
6515  * @param get_path_length lenght of get_path
6516  * @param put_path path of the put request
6517  * @param put_path_length length of the put_path
6518  * @param type type of the result
6519  * @param size number of bytes in data
6520  * @param data pointer to the result data
6521  */
6522 static void
6523 dht_get_type_handler (void *cls, struct GNUNET_TIME_Absolute exp,
6524                       const struct GNUNET_HashCode * key,
6525                       const struct GNUNET_PeerIdentity *get_path,
6526                       unsigned int get_path_length,
6527                       const struct GNUNET_PeerIdentity *put_path,
6528                       unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
6529                       size_t size, const void *data)
6530 {
6531   const struct PBlock *pb = data;
6532   const struct GNUNET_PeerIdentity *pi = &pb->id;
6533   struct MeshTunnel *t = cls;
6534   struct MeshPeerInfo *peer_info;
6535   struct MeshPeerPath *p;
6536
6537   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got type DHT result!\n");
6538   if (size != sizeof (struct PBlock))
6539   {
6540     GNUNET_break_op (0);
6541     return;
6542   }
6543   if (ntohl(pb->type) != t->type)
6544   {
6545     GNUNET_break_op (0);
6546     return;
6547   }
6548   GNUNET_assert (NULL != t->owner);
6549   peer_info = peer_info_get (pi);
6550   (void) GNUNET_CONTAINER_multihashmap_put (t->peers, &pi->hashPubKey,
6551                                             peer_info,
6552                                             GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
6553
6554   p = path_build_from_dht (get_path, get_path_length, put_path,
6555                            put_path_length);
6556   path_add_to_peers (p, GNUNET_NO);
6557   path_destroy(p);
6558   tunnel_add_peer (t, peer_info);
6559   peer_info_connect (peer_info, t);
6560 }
6561
6562
6563 /**
6564  * Function to process DHT string to regex matching.
6565  * Called on each result obtained for the DHT search.
6566  *
6567  * @param cls closure (search context)
6568  * @param exp when will this value expire
6569  * @param key key of the result
6570  * @param get_path path of the get request (not used)
6571  * @param get_path_length lenght of get_path (not used)
6572  * @param put_path path of the put request (not used)
6573  * @param put_path_length length of the put_path (not used)
6574  * @param type type of the result
6575  * @param size number of bytes in data
6576  * @param data pointer to the result data
6577  */
6578 static void
6579 dht_get_string_accept_handler (void *cls, struct GNUNET_TIME_Absolute exp,
6580                                const struct GNUNET_HashCode * key,
6581                                const struct GNUNET_PeerIdentity *get_path,
6582                                unsigned int get_path_length,
6583                                const struct GNUNET_PeerIdentity *put_path,
6584                                unsigned int put_path_length,
6585                                enum GNUNET_BLOCK_Type type,
6586                                size_t size, const void *data)
6587 {
6588   const struct MeshRegexAccept *block = data;
6589   struct MeshRegexSearchContext *ctx = cls;
6590   struct MeshRegexSearchInfo *info = ctx->info;
6591 //   struct MeshPeerPath *p;
6592   struct MeshPeerInfo *peer_info;
6593
6594   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got regex results from DHT!\n");
6595   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", info->description);
6596   GNUNET_STATISTICS_update (stats, "# regex accepting blocks found",
6597                             1, GNUNET_NO);
6598   GNUNET_STATISTICS_update (stats, "# regex accepting block bytes found",
6599                             size, GNUNET_NO);
6600
6601   peer_info = peer_info_get(&block->id);
6602 //   p = path_build_from_dht (get_path, get_path_length, put_path,
6603 //                            put_path_length);
6604 //   path_add_to_peers (p, GNUNET_NO);
6605 //   path_destroy(p);
6606
6607   tunnel_add_peer (info->t, peer_info);
6608   peer_info_connect (peer_info, info->t);
6609   if (0 == info->peer)
6610   {
6611     info->peer = peer_info->id;
6612   }
6613   else
6614   {
6615     GNUNET_array_append (info->peers, info->n_peers, peer_info->id);
6616   }
6617
6618   info->timeout = GNUNET_SCHEDULER_add_delayed (connect_timeout,
6619                                                 &regex_connect_timeout,
6620                                                 info);
6621
6622   return;
6623 }
6624
6625
6626 /**
6627  * Function to process DHT string to regex matching.
6628  * Called on each result obtained for the DHT search.
6629  *
6630  * @param cls closure (search context)
6631  * @param exp when will this value expire
6632  * @param key key of the result
6633  * @param get_path path of the get request (not used)
6634  * @param get_path_length lenght of get_path (not used)
6635  * @param put_path path of the put request (not used)
6636  * @param put_path_length length of the put_path (not used)
6637  * @param type type of the result
6638  * @param size number of bytes in data
6639  * @param data pointer to the result data
6640  *
6641  * TODO: re-issue the request after certain time? cancel after X results?
6642  */
6643 static void
6644 dht_get_string_handler (void *cls, struct GNUNET_TIME_Absolute exp,
6645                         const struct GNUNET_HashCode * key,
6646                         const struct GNUNET_PeerIdentity *get_path,
6647                         unsigned int get_path_length,
6648                         const struct GNUNET_PeerIdentity *put_path,
6649                         unsigned int put_path_length,
6650                         enum GNUNET_BLOCK_Type type,
6651                         size_t size, const void *data)
6652 {
6653   const struct MeshRegexBlock *block = data;
6654   struct MeshRegexSearchContext *ctx = cls;
6655   struct MeshRegexSearchInfo *info = ctx->info;
6656   void *copy;
6657   size_t len;
6658
6659   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6660               "DHT GET STRING RETURNED RESULTS\n");
6661   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6662               "  key: %s\n", GNUNET_h2s (key));
6663
6664   GNUNET_STATISTICS_update (stats, "# regex blocks found",
6665                             1, GNUNET_NO);
6666   GNUNET_STATISTICS_update (stats, "# regex block bytes found",
6667                             size, GNUNET_NO);
6668
6669   copy = GNUNET_malloc (size);
6670   memcpy (copy, data, size);
6671   GNUNET_break (GNUNET_OK ==
6672                 GNUNET_CONTAINER_multihashmap_put(info->dht_get_results, key, copy,
6673                                                   GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
6674   len = ntohl (block->n_proof);
6675   {
6676     char proof[len + 1];
6677
6678     memcpy (proof, &block[1], len);
6679     proof[len] = '\0';
6680     if (GNUNET_OK != GNUNET_REGEX_check_proof (proof, key))
6681     {
6682       GNUNET_break_op (0);
6683       return;
6684     }
6685   }
6686   len = strlen (info->description);
6687   if (len == ctx->position) // String processed
6688   {
6689     if (GNUNET_YES == ntohl (block->accepting))
6690     {
6691       regex_find_path(key, ctx);
6692     }
6693     else
6694     {
6695       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  block not accepting!\n");
6696       // FIXME REGEX this block not successful, wait for more? start timeout?
6697     }
6698     return;
6699   }
6700
6701   regex_next_edge (block, size, ctx);
6702
6703   return;
6704 }
6705
6706 /******************************************************************************/
6707 /*********************       MESH LOCAL HANDLES      **************************/
6708 /******************************************************************************/
6709
6710
6711 /**
6712  * Handler for client disconnection
6713  *
6714  * @param cls closure
6715  * @param client identification of the client; NULL
6716  *        for the last call when the server is destroyed
6717  */
6718 static void
6719 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
6720 {
6721   struct MeshClient *c;
6722   struct MeshClient *next;
6723   unsigned int i;
6724
6725   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected\n");
6726   if (client == NULL)
6727   {
6728     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (SERVER DOWN)\n");
6729     return;
6730   }
6731
6732 //   return; uncomment for regex_profiler
6733   c = clients;
6734   while (NULL != c)
6735   {
6736     if (c->handle != client)
6737     {
6738       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ... searching\n");
6739       c = c->next;
6740       continue;
6741     }
6742     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u)\n",
6743                 c->id);
6744     GNUNET_SERVER_client_drop (c->handle);
6745     c->shutting_down = GNUNET_YES;
6746     GNUNET_assert (NULL != c->own_tunnels);
6747     GNUNET_assert (NULL != c->incoming_tunnels);
6748     GNUNET_CONTAINER_multihashmap_iterate (c->own_tunnels,
6749                                            &tunnel_destroy_iterator, c);
6750     GNUNET_CONTAINER_multihashmap_iterate (c->incoming_tunnels,
6751                                            &tunnel_destroy_iterator, c);
6752     GNUNET_CONTAINER_multihashmap_iterate (c->ignore_tunnels,
6753                                            &tunnel_destroy_iterator, c);
6754     GNUNET_CONTAINER_multihashmap_destroy (c->own_tunnels);
6755     GNUNET_CONTAINER_multihashmap_destroy (c->incoming_tunnels);
6756     GNUNET_CONTAINER_multihashmap_destroy (c->ignore_tunnels);
6757
6758     /* deregister clients applications */
6759     if (NULL != c->apps)
6760     {
6761       GNUNET_CONTAINER_multihashmap_iterate (c->apps, &deregister_app, c->apps);
6762       GNUNET_CONTAINER_multihashmap_destroy (c->apps);
6763     }
6764     if (0 == GNUNET_CONTAINER_multihashmap_size (applications) &&
6765         GNUNET_SCHEDULER_NO_TASK != announce_applications_task)
6766     {
6767       GNUNET_SCHEDULER_cancel (announce_applications_task);
6768       announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
6769     }
6770     if (NULL != c->types)
6771       GNUNET_CONTAINER_multihashmap_destroy (c->types);
6772     for (i = 0; i < c->n_regex; i++)
6773     {
6774       GNUNET_free (c->regexes[i].regex);
6775       if (NULL != c->regexes[i].dfa)
6776         GNUNET_REGEX_automaton_destroy (c->regexes[i].dfa);
6777     }
6778     GNUNET_free_non_null (c->regexes);
6779     if (GNUNET_SCHEDULER_NO_TASK != c->regex_announce_task)
6780       GNUNET_SCHEDULER_cancel (c->regex_announce_task);
6781     next = c->next;
6782     GNUNET_CONTAINER_DLL_remove (clients, clients_tail, c);
6783     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT FREE at %p\n", c);
6784     GNUNET_free (c);
6785     GNUNET_STATISTICS_update (stats, "# clients", -1, GNUNET_NO);
6786     c = next;
6787   }
6788   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   done!\n");
6789   return;
6790 }
6791
6792
6793 /**
6794  * Handler for new clients
6795  *
6796  * @param cls closure
6797  * @param client identification of the client
6798  * @param message the actual message, which includes messages the client wants
6799  */
6800 static void
6801 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
6802                          const struct GNUNET_MessageHeader *message)
6803 {
6804   struct GNUNET_MESH_ClientConnect *cc_msg;
6805   struct MeshClient *c;
6806   GNUNET_MESH_ApplicationType *a;
6807   unsigned int size;
6808   uint16_t ntypes;
6809   uint16_t *t;
6810   uint16_t napps;
6811   uint16_t i;
6812
6813   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected\n");
6814   /* Check data sanity */
6815   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
6816   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
6817   ntypes = ntohs (cc_msg->types);
6818   napps = ntohs (cc_msg->applications);
6819   if (size !=
6820       ntypes * sizeof (uint16_t) + napps * sizeof (GNUNET_MESH_ApplicationType))
6821   {
6822     GNUNET_break (0);
6823     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6824     return;
6825   }
6826
6827   /* Create new client structure */
6828   c = GNUNET_malloc (sizeof (struct MeshClient));
6829   c->id = next_client_id++;
6830   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT NEW %u\n", c->id);
6831   c->handle = client;
6832   GNUNET_SERVER_client_keep (client);
6833   a = (GNUNET_MESH_ApplicationType *) &cc_msg[1];
6834   if (napps > 0)
6835   {
6836     GNUNET_MESH_ApplicationType at;
6837     struct GNUNET_HashCode hc;
6838
6839     c->apps = GNUNET_CONTAINER_multihashmap_create (napps, GNUNET_NO);
6840     for (i = 0; i < napps; i++)
6841     {
6842       at = ntohl (a[i]);
6843       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  app type: %u\n", at);
6844       GNUNET_CRYPTO_hash (&at, sizeof (at), &hc);
6845       /* store in clients hashmap */
6846       GNUNET_CONTAINER_multihashmap_put (c->apps, &hc, (void *) (long) at,
6847                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6848       /* store in global hashmap, for announcements */
6849       GNUNET_CONTAINER_multihashmap_put (applications, &hc, c,
6850                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6851     }
6852     if (GNUNET_SCHEDULER_NO_TASK == announce_applications_task)
6853       announce_applications_task =
6854           GNUNET_SCHEDULER_add_now (&announce_applications, NULL);
6855
6856   }
6857   if (ntypes > 0)
6858   {
6859     uint16_t u16;
6860     struct GNUNET_HashCode hc;
6861
6862     t = (uint16_t *) & a[napps];
6863     c->types = GNUNET_CONTAINER_multihashmap_create (ntypes, GNUNET_NO);
6864     for (i = 0; i < ntypes; i++)
6865     {
6866       u16 = ntohs (t[i]);
6867       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  msg type: %u\n", u16);
6868       GNUNET_CRYPTO_hash (&u16, sizeof (u16), &hc);
6869
6870       /* store in clients hashmap */
6871       GNUNET_CONTAINER_multihashmap_put (c->types, &hc, c,
6872                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6873       /* store in global hashmap */
6874       GNUNET_CONTAINER_multihashmap_put (types, &hc, c,
6875                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6876     }
6877   }
6878   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6879               " client has %u+%u subscriptions\n", napps, ntypes);
6880
6881   GNUNET_CONTAINER_DLL_insert (clients, clients_tail, c);
6882   c->own_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6883   c->incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6884   c->ignore_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6885   GNUNET_SERVER_notification_context_add (nc, client);
6886   GNUNET_STATISTICS_update (stats, "# clients", 1, GNUNET_NO);
6887
6888   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6889   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
6890 }
6891
6892
6893 /**
6894  * Handler for clients announcing available services by a regular expression.
6895  *
6896  * @param cls closure
6897  * @param client identification of the client
6898  * @param message the actual message, which includes messages the client wants
6899  */
6900 static void
6901 handle_local_announce_regex (void *cls, struct GNUNET_SERVER_Client *client,
6902                              const struct GNUNET_MessageHeader *message)
6903 {
6904   const struct GNUNET_MESH_RegexAnnounce *msg;
6905   struct MeshRegexDescriptor rd;
6906   struct MeshClient *c;
6907   char *regex;
6908   size_t len;
6909
6910   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "announce regex started\n");
6911
6912   /* Sanity check for client registration */
6913   if (NULL == (c = client_get (client)))
6914   {
6915     GNUNET_break (0);
6916     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6917     return;
6918   }
6919   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6920
6921   msg = (const struct GNUNET_MESH_RegexAnnounce *) message;
6922   len = ntohs (message->size) - sizeof(struct GNUNET_MESH_RegexAnnounce);
6923   regex = GNUNET_malloc (len + 1);
6924   memcpy (regex, &msg[1], len);
6925   regex[len] = '\0';
6926   rd.regex = regex;
6927   rd.compression = ntohs (msg->compression_characters);
6928   rd.dfa = NULL;
6929   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  length %u\n", len);
6930   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regex %s\n", regex);
6931   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  cm %u\n", ntohs(rd.compression));
6932   GNUNET_array_append (c->regexes, c->n_regex, rd);
6933   if (GNUNET_SCHEDULER_NO_TASK == c->regex_announce_task)
6934   {
6935     c->regex_announce_task = GNUNET_SCHEDULER_add_now(&announce_regex, c);
6936   }
6937   else
6938   {
6939     regex_put(&rd);
6940   }
6941   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6942   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "announce regex processed\n");
6943 }
6944
6945
6946 /**
6947  * Handler for requests of new tunnels
6948  *
6949  * @param cls closure
6950  * @param client identification of the client
6951  * @param message the actual message
6952  */
6953 static void
6954 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
6955                             const struct GNUNET_MessageHeader *message)
6956 {
6957   struct GNUNET_MESH_TunnelMessage *t_msg;
6958   struct MeshTunnel *t;
6959   struct MeshClient *c;
6960   MESH_TunnelNumber tid;
6961
6962   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel requested\n");
6963
6964   /* Sanity check for client registration */
6965   if (NULL == (c = client_get (client)))
6966   {
6967     GNUNET_break (0);
6968     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6969     return;
6970   }
6971   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6972
6973   /* Message sanity check */
6974   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
6975   {
6976     GNUNET_break (0);
6977     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6978     return;
6979   }
6980
6981   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6982   /* Sanity check for tunnel numbering */
6983   tid = ntohl (t_msg->tunnel_id);
6984   if (0 == (tid & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
6985   {
6986     GNUNET_break (0);
6987     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6988     return;
6989   }
6990   /* Sanity check for duplicate tunnel IDs */
6991   if (NULL != tunnel_get_by_local_id (c, tid))
6992   {
6993     GNUNET_break (0);
6994     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6995     return;
6996   }
6997
6998   while (NULL != tunnel_get_by_pi (myid, next_tid))
6999     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
7000   t = tunnel_new (myid, next_tid++, c, tid);
7001   if (NULL == t)
7002   {
7003     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Tunnel creation failed.\n");
7004     GNUNET_break (0);
7005     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7006     return;
7007   }
7008   next_tid = next_tid & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
7009   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED TUNNEL %s [%x] (%x)\n",
7010               GNUNET_i2s (&my_full_id), t->id.tid, t->local_tid);
7011   t->peers = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
7012
7013   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel created\n");
7014   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7015   return;
7016 }
7017
7018
7019 /**
7020  * Handler for requests of deleting tunnels
7021  *
7022  * @param cls closure
7023  * @param client identification of the client
7024  * @param message the actual message
7025  */
7026 static void
7027 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
7028                              const struct GNUNET_MessageHeader *message)
7029 {
7030   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
7031   struct MeshClient *c;
7032   struct MeshTunnel *t;
7033   MESH_TunnelNumber tid;
7034
7035   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7036               "Got a DESTROY TUNNEL from client!\n");
7037
7038   /* Sanity check for client registration */
7039   if (NULL == (c = client_get (client)))
7040   {
7041     GNUNET_break (0);
7042     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7043     return;
7044   }
7045   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7046
7047   /* Message sanity check */
7048   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
7049   {
7050     GNUNET_break (0);
7051     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7052     return;
7053   }
7054
7055   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
7056
7057   /* Retrieve tunnel */
7058   tid = ntohl (tunnel_msg->tunnel_id);
7059   t = tunnel_get_by_local_id(c, tid);
7060   if (NULL == t)
7061   {
7062     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
7063     GNUNET_break (0);
7064     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7065     return;
7066   }
7067   if (c != t->owner || tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
7068   {
7069     client_ignore_tunnel (c, t);
7070 #if 0
7071     // TODO: when to destroy incoming tunnel?
7072     if (t->nclients == 0)
7073     {
7074       GNUNET_assert (GNUNET_YES ==
7075                      GNUNET_CONTAINER_multihashmap_remove (incoming_tunnels,
7076                                                            &hash, t));
7077       GNUNET_assert (GNUNET_YES ==
7078                      GNUNET_CONTAINER_multihashmap_remove (t->peers,
7079                                                            &my_full_id.hashPubKey,
7080                                                            t));
7081     }
7082 #endif
7083     GNUNET_SERVER_receive_done (client, GNUNET_OK);
7084     return;
7085   }
7086   send_client_tunnel_disconnect(t, c);
7087   client_delete_tunnel(c, t);
7088
7089   /* Don't try to ACK the client about the tunnel_destroy multicast packet */
7090   t->owner = NULL;
7091   tunnel_send_destroy (t);
7092   t->destroy = GNUNET_YES;
7093   // The tunnel will be destroyed when the last message is transmitted.
7094   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7095   return;
7096 }
7097
7098
7099 /**
7100  * Handler for requests of seeting tunnel's speed.
7101  *
7102  * @param cls Closure (unused).
7103  * @param client Identification of the client.
7104  * @param message The actual message.
7105  */
7106 static void
7107 handle_local_tunnel_speed (void *cls, struct GNUNET_SERVER_Client *client,
7108                            const struct GNUNET_MessageHeader *message)
7109 {
7110   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
7111   struct MeshClient *c;
7112   struct MeshTunnel *t;
7113   MESH_TunnelNumber tid;
7114
7115   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7116               "Got a SPEED request from client!\n");
7117
7118   /* Sanity check for client registration */
7119   if (NULL == (c = client_get (client)))
7120   {
7121     GNUNET_break (0);
7122     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7123     return;
7124   }
7125
7126   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7127
7128   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
7129
7130   /* Retrieve tunnel */
7131   tid = ntohl (tunnel_msg->tunnel_id);
7132   t = tunnel_get_by_local_id(c, tid);
7133   if (NULL == t)
7134   {
7135     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  tunnel %X not found\n", tid);
7136     GNUNET_break (0);
7137     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7138     return;
7139   }
7140
7141   switch (ntohs(message->type))
7142   {
7143       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MIN:
7144           t->speed_min = GNUNET_YES;
7145           break;
7146       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MAX:
7147           t->speed_min = GNUNET_NO;
7148           break;
7149       default:
7150           GNUNET_break (0);
7151   }
7152   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7153 }
7154
7155
7156 /**
7157  * Handler for requests of seeting tunnel's buffering policy.
7158  *
7159  * @param cls Closure (unused).
7160  * @param client Identification of the client.
7161  * @param message The actual message.
7162  */
7163 static void
7164 handle_local_tunnel_buffer (void *cls, struct GNUNET_SERVER_Client *client,
7165                             const struct GNUNET_MessageHeader *message)
7166 {
7167   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
7168   struct MeshClient *c;
7169   struct MeshTunnel *t;
7170   MESH_TunnelNumber tid;
7171
7172   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7173               "Got a BUFFER request from client!\n");
7174
7175   /* Sanity check for client registration */
7176   if (NULL == (c = client_get (client)))
7177   {
7178     GNUNET_break (0);
7179     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7180     return;
7181   }
7182   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7183
7184   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
7185
7186   /* Retrieve tunnel */
7187   tid = ntohl (tunnel_msg->tunnel_id);
7188   t = tunnel_get_by_local_id(c, tid);
7189   if (NULL == t)
7190   {
7191     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
7192     GNUNET_break (0);
7193     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7194     return;
7195   }
7196
7197   switch (ntohs(message->type))
7198   {
7199       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER:
7200           t->nobuffer = GNUNET_NO;
7201           break;
7202       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER:
7203           t->nobuffer = GNUNET_YES;
7204           break;
7205       default:
7206           GNUNET_break (0);
7207   }
7208
7209   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7210 }
7211
7212
7213 /**
7214  * Handler for connection requests to new peers
7215  *
7216  * @param cls closure
7217  * @param client identification of the client
7218  * @param message the actual message (PeerControl)
7219  */
7220 static void
7221 handle_local_connect_add (void *cls, struct GNUNET_SERVER_Client *client,
7222                           const struct GNUNET_MessageHeader *message)
7223 {
7224   struct GNUNET_MESH_PeerControl *peer_msg;
7225   struct MeshPeerInfo *peer_info;
7226   struct MeshClient *c;
7227   struct MeshTunnel *t;
7228   MESH_TunnelNumber tid;
7229
7230   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got connection request\n");
7231   /* Sanity check for client registration */
7232   if (NULL == (c = client_get (client)))
7233   {
7234     GNUNET_break (0);
7235     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7236     return;
7237   }
7238   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7239
7240   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
7241
7242   /* Sanity check for message size */
7243   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
7244   {
7245     GNUNET_break (0);
7246     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7247     return;
7248   }
7249
7250   /* Tunnel exists? */
7251   tid = ntohl (peer_msg->tunnel_id);
7252   t = tunnel_get_by_local_id (c, tid);
7253   if (NULL == t)
7254   {
7255     GNUNET_break (0);
7256     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7257     return;
7258   }
7259
7260   /* Does client own tunnel? */
7261   if (t->owner->handle != client)
7262   {
7263     GNUNET_break (0);
7264     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7265     return;
7266   }
7267   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "     for %s\n",
7268               GNUNET_i2s (&peer_msg->peer));
7269   peer_info = peer_info_get (&peer_msg->peer);
7270
7271   tunnel_add_peer (t, peer_info);
7272   peer_info_connect (peer_info, t);
7273
7274   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7275   return;
7276 }
7277
7278
7279 /**
7280  * Handler for disconnection requests of peers in a tunnel
7281  *
7282  * @param cls closure
7283  * @param client identification of the client
7284  * @param message the actual message (PeerControl)
7285  */
7286 static void
7287 handle_local_connect_del (void *cls, struct GNUNET_SERVER_Client *client,
7288                           const struct GNUNET_MessageHeader *message)
7289 {
7290   struct GNUNET_MESH_PeerControl *peer_msg;
7291   struct MeshPeerInfo *peer_info;
7292   struct MeshClient *c;
7293   struct MeshTunnel *t;
7294   MESH_TunnelNumber tid;
7295
7296   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER DEL request\n");
7297   /* Sanity check for client registration */
7298   if (NULL == (c = client_get (client)))
7299   {
7300     GNUNET_break (0);
7301     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7302     return;
7303   }
7304   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7305
7306   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
7307
7308   /* Sanity check for message size */
7309   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
7310   {
7311     GNUNET_break (0);
7312     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7313     return;
7314   }
7315
7316   /* Tunnel exists? */
7317   tid = ntohl (peer_msg->tunnel_id);
7318   t = tunnel_get_by_local_id (c, tid);
7319   if (NULL == t)
7320   {
7321     GNUNET_break (0);
7322     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7323     return;
7324   }
7325   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
7326
7327   /* Does client own tunnel? */
7328   if (t->owner->handle != client)
7329   {
7330     GNUNET_break (0);
7331     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7332     return;
7333   }
7334
7335   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for peer %s\n",
7336               GNUNET_i2s (&peer_msg->peer));
7337   /* Is the peer in the tunnel? */
7338   peer_info =
7339       GNUNET_CONTAINER_multihashmap_get (t->peers, &peer_msg->peer.hashPubKey);
7340   if (NULL == peer_info)
7341   {
7342     GNUNET_break (0);
7343     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7344     return;
7345   }
7346
7347   /* Ok, delete peer from tunnel */
7348   GNUNET_CONTAINER_multihashmap_remove_all (t->peers,
7349                                             &peer_msg->peer.hashPubKey);
7350
7351   send_destroy_path (t, peer_info->id);
7352   tunnel_delete_peer (t, peer_info->id);
7353   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7354   return;
7355 }
7356
7357 /**
7358  * Handler for blacklist requests of peers in a tunnel
7359  *
7360  * @param cls closure
7361  * @param client identification of the client
7362  * @param message the actual message (PeerControl)
7363  * 
7364  * FIXME implement DHT block bloomfilter
7365  */
7366 static void
7367 handle_local_blacklist (void *cls, struct GNUNET_SERVER_Client *client,
7368                           const struct GNUNET_MessageHeader *message)
7369 {
7370   struct GNUNET_MESH_PeerControl *peer_msg;
7371   struct MeshClient *c;
7372   struct MeshTunnel *t;
7373   MESH_TunnelNumber tid;
7374
7375   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER BLACKLIST request\n");
7376   /* Sanity check for client registration */
7377   if (NULL == (c = client_get (client)))
7378   {
7379     GNUNET_break (0);
7380     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7381     return;
7382   }
7383   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7384
7385   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
7386
7387   /* Sanity check for message size */
7388   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
7389   {
7390     GNUNET_break (0);
7391     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7392     return;
7393   }
7394
7395   /* Tunnel exists? */
7396   tid = ntohl (peer_msg->tunnel_id);
7397   t = tunnel_get_by_local_id (c, tid);
7398   if (NULL == t)
7399   {
7400     GNUNET_break (0);
7401     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7402     return;
7403   }
7404   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
7405
7406   GNUNET_array_append(t->blacklisted, t->nblacklisted,
7407                       GNUNET_PEER_intern(&peer_msg->peer));
7408 }
7409
7410
7411 /**
7412  * Handler for unblacklist requests of peers in a tunnel
7413  *
7414  * @param cls closure
7415  * @param client identification of the client
7416  * @param message the actual message (PeerControl)
7417  */
7418 static void
7419 handle_local_unblacklist (void *cls, struct GNUNET_SERVER_Client *client,
7420                           const struct GNUNET_MessageHeader *message)
7421 {
7422   struct GNUNET_MESH_PeerControl *peer_msg;
7423   struct MeshClient *c;
7424   struct MeshTunnel *t;
7425   MESH_TunnelNumber tid;
7426   GNUNET_PEER_Id pid;
7427   unsigned int i;
7428
7429   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER UNBLACKLIST request\n");
7430   /* Sanity check for client registration */
7431   if (NULL == (c = client_get (client)))
7432   {
7433     GNUNET_break (0);
7434     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7435     return;
7436   }
7437   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7438
7439   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
7440
7441   /* Sanity check for message size */
7442   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
7443   {
7444     GNUNET_break (0);
7445     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7446     return;
7447   }
7448
7449   /* Tunnel exists? */
7450   tid = ntohl (peer_msg->tunnel_id);
7451   t = tunnel_get_by_local_id (c, tid);
7452   if (NULL == t)
7453   {
7454     GNUNET_break (0);
7455     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7456     return;
7457   }
7458   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
7459
7460   /* if peer is not known, complain */
7461   pid = GNUNET_PEER_search (&peer_msg->peer);
7462   if (0 == pid)
7463   {
7464     GNUNET_break (0);
7465     return;
7466   }
7467
7468   /* search and remove from list */
7469   for (i = 0; i < t->nblacklisted; i++)
7470   {
7471     if (t->blacklisted[i] == pid)
7472     {
7473       t->blacklisted[i] = t->blacklisted[t->nblacklisted - 1];
7474       GNUNET_array_grow (t->blacklisted, t->nblacklisted, t->nblacklisted - 1);
7475       return;
7476     }
7477   }
7478
7479   /* if peer hasn't been blacklisted, complain */
7480   GNUNET_break (0);
7481 }
7482
7483
7484 /**
7485  * Handler for connection requests to new peers by type
7486  *
7487  * @param cls closure
7488  * @param client identification of the client
7489  * @param message the actual message (ConnectPeerByType)
7490  */
7491 static void
7492 handle_local_connect_by_type (void *cls, struct GNUNET_SERVER_Client *client,
7493                               const struct GNUNET_MessageHeader *message)
7494 {
7495   struct GNUNET_MESH_ConnectPeerByType *connect_msg;
7496   struct MeshClient *c;
7497   struct MeshTunnel *t;
7498   struct GNUNET_HashCode hash;
7499   MESH_TunnelNumber tid;
7500
7501   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got connect by type request\n");
7502   /* Sanity check for client registration */
7503   if (NULL == (c = client_get (client)))
7504   {
7505     GNUNET_break (0);
7506     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7507     return;
7508   }
7509   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7510
7511   connect_msg = (struct GNUNET_MESH_ConnectPeerByType *) message;
7512
7513   /* Sanity check for message size */
7514   if (sizeof (struct GNUNET_MESH_ConnectPeerByType) !=
7515       ntohs (connect_msg->header.size))
7516   {
7517     GNUNET_break (0);
7518     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7519     return;
7520   }
7521
7522   /* Tunnel exists? */
7523   tid = ntohl (connect_msg->tunnel_id);
7524   t = tunnel_get_by_local_id (c, tid);
7525   if (NULL == t)
7526   {
7527     GNUNET_break (0);
7528     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7529     return;
7530   }
7531
7532   /* Does client own tunnel? */
7533   if (t->owner->handle != client)
7534   {
7535     GNUNET_break (0);
7536     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7537     return;
7538   }
7539
7540   /* Do WE have the service? */
7541   t->type = ntohl (connect_msg->type);
7542   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " type requested: %u\n", t->type);
7543   GNUNET_CRYPTO_hash (&t->type, sizeof (GNUNET_MESH_ApplicationType), &hash);
7544   if (GNUNET_CONTAINER_multihashmap_contains (applications, &hash) ==
7545       GNUNET_YES)
7546   {
7547     /* Yes! Fast forward, add ourselves to the tunnel and send the
7548      * good news to the client, and alert the destination client of
7549      * an incoming tunnel.
7550      *
7551      * FIXME send a path create to self, avoid code duplication
7552      */
7553     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " available locally\n");
7554     GNUNET_CONTAINER_multihashmap_put (t->peers, &my_full_id.hashPubKey,
7555                                        peer_info_get (&my_full_id),
7556                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
7557
7558     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " notifying client\n");
7559     send_client_peer_connected (t, myid);
7560     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Done\n");
7561     GNUNET_SERVER_receive_done (client, GNUNET_OK);
7562
7563     t->local_tid_dest = next_local_tid++;
7564     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
7565     GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
7566                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
7567
7568     return;
7569   }
7570   /* Ok, lets find a peer offering the service */
7571   if (NULL != t->dht_get_type)
7572   {
7573     GNUNET_DHT_get_stop (t->dht_get_type);
7574   }
7575   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " looking in DHT for %s\n",
7576               GNUNET_h2s (&hash));
7577   t->dht_get_type =
7578       GNUNET_DHT_get_start (dht_handle, 
7579                             GNUNET_BLOCK_TYPE_MESH_PEER_BY_TYPE,
7580                             &hash,
7581                             dht_replication_level,
7582                             GNUNET_DHT_RO_RECORD_ROUTE |
7583                             GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
7584                             NULL, 0,
7585                             &dht_get_type_handler, t);
7586
7587   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7588   return;
7589 }
7590
7591
7592 /**
7593  * Handler for connection requests to new peers by a string service description.
7594  *
7595  * @param cls closure
7596  * @param client identification of the client
7597  * @param message the actual message, which includes messages the client wants
7598  */
7599 static void
7600 handle_local_connect_by_string (void *cls, struct GNUNET_SERVER_Client *client,
7601                                 const struct GNUNET_MessageHeader *message)
7602 {
7603   struct GNUNET_MESH_ConnectPeerByString *msg;
7604   struct MeshRegexSearchContext *ctx;
7605   struct MeshRegexSearchInfo *info;
7606   struct GNUNET_DHT_GetHandle *get_h;
7607   struct GNUNET_HashCode key;
7608   struct MeshTunnel *t;
7609   struct MeshClient *c;
7610   MESH_TunnelNumber tid;
7611   const char *string;
7612   size_t size;
7613   size_t len;
7614
7615   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7616               "Connect by string started\n");
7617   msg = (struct GNUNET_MESH_ConnectPeerByString *) message;
7618   size = htons (message->size);
7619
7620   /* Sanity check for client registration */
7621   if (NULL == (c = client_get (client)))
7622   {
7623     GNUNET_break (0);
7624     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7625     return;
7626   }
7627   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7628
7629   /* Message size sanity check */
7630   if (sizeof(struct GNUNET_MESH_ConnectPeerByString) >= size)
7631   {
7632     GNUNET_break (0);
7633     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7634     return;
7635   }
7636
7637   /* Tunnel exists? */
7638   tid = ntohl (msg->tunnel_id);
7639   t = tunnel_get_by_local_id (c, tid);
7640   if (NULL == t)
7641   {
7642     GNUNET_break (0);
7643     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7644     return;
7645   }
7646
7647   /* Does client own tunnel? */
7648   if (t->owner->handle != client)
7649   {
7650     GNUNET_break (0);
7651     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7652     return;
7653   }
7654
7655   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7656               "  on tunnel %s [%u]\n",
7657               GNUNET_i2s(&my_full_id),
7658               t->id.tid);
7659
7660   /* Only one connect_by_string allowed at the same time! */
7661   /* FIXME: allow more, return handle at api level to cancel, document */
7662   if (NULL != t->regex_ctx)
7663   {
7664     GNUNET_break (0);
7665     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7666     return;
7667   }
7668
7669   /* Find string itself */
7670   len = size - sizeof(struct GNUNET_MESH_ConnectPeerByString);
7671   string = (const char *) &msg[1];
7672
7673   /* Initialize context */
7674   size = GNUNET_REGEX_get_first_key (string, len, &key);
7675   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7676               "  consumed %u bits out of %u\n", size, len);
7677   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7678               "  looking for %s\n", GNUNET_h2s (&key));
7679
7680   info = GNUNET_malloc (sizeof (struct MeshRegexSearchInfo));
7681   info->t = t;
7682   info->description = GNUNET_strndup (string, len);
7683   info->dht_get_handles = GNUNET_CONTAINER_multihashmap_create(32, GNUNET_NO);
7684   info->dht_get_results = GNUNET_CONTAINER_multihashmap_create(32, GNUNET_NO);
7685   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   string: %s\n", info->description);
7686
7687   ctx = GNUNET_malloc (sizeof (struct MeshRegexSearchContext));
7688   ctx->position = size;
7689   ctx->info = info;
7690   t->regex_ctx = ctx;
7691
7692   GNUNET_array_append (info->contexts, info->n_contexts, ctx);
7693
7694   /* Start search in DHT */
7695   get_h = GNUNET_DHT_get_start (dht_handle,    /* handle */
7696                                 GNUNET_BLOCK_TYPE_MESH_REGEX, /* type */
7697                                 &key,     /* key to search */
7698                                 dht_replication_level, /* replication level */
7699                                 GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
7700                                 &info->description[size],           /* xquery */
7701                                 // FIXME add BLOOMFILTER to exclude filtered peers
7702                                 len + 1 - size,                /* xquery bits */
7703                                 // FIXME add BLOOMFILTER SIZE
7704                                 &dht_get_string_handler, ctx);
7705
7706   GNUNET_break (GNUNET_OK ==
7707                 GNUNET_CONTAINER_multihashmap_put(info->dht_get_handles,
7708                                                   &key,
7709                                                   get_h,
7710                                                   GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
7711
7712   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7713   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "connect by string processed\n");
7714 }
7715
7716
7717 /**
7718  * Handler for client traffic directed to one peer
7719  *
7720  * @param cls closure
7721  * @param client identification of the client
7722  * @param message the actual message
7723  */
7724 static void
7725 handle_local_unicast (void *cls, struct GNUNET_SERVER_Client *client,
7726                       const struct GNUNET_MessageHeader *message)
7727 {
7728   struct MeshClient *c;
7729   struct MeshTunnel *t;
7730   struct MeshPeerInfo *pi;
7731   struct GNUNET_MESH_Unicast *data_msg;
7732   MESH_TunnelNumber tid;
7733   size_t size;
7734
7735   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7736               "Got a unicast request from a client!\n");
7737
7738   /* Sanity check for client registration */
7739   if (NULL == (c = client_get (client)))
7740   {
7741     GNUNET_break (0);
7742     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7743     return;
7744   }
7745   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7746
7747   data_msg = (struct GNUNET_MESH_Unicast *) message;
7748
7749   /* Sanity check for message size */
7750   size = ntohs (message->size);
7751   if (sizeof (struct GNUNET_MESH_Unicast) +
7752       sizeof (struct GNUNET_MessageHeader) > size)
7753   {
7754     GNUNET_break (0);
7755     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7756     return;
7757   }
7758
7759   /* Tunnel exists? */
7760   tid = ntohl (data_msg->tid);
7761   t = tunnel_get_by_local_id (c, tid);
7762   if (NULL == t)
7763   {
7764     GNUNET_break (0);
7765     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7766     return;
7767   }
7768
7769   /*  Is it a local tunnel? Then, does client own the tunnel? */
7770   if (t->owner->handle != client)
7771   {
7772     GNUNET_break (0);
7773     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7774     return;
7775   }
7776
7777   pi = GNUNET_CONTAINER_multihashmap_get (t->peers,
7778                                           &data_msg->destination.hashPubKey);
7779   /* Is the selected peer in the tunnel? */
7780   if (NULL == pi)
7781   {
7782     GNUNET_break (0);
7783     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7784     return;
7785   }
7786
7787   /* PID should be as expected */
7788   if (ntohl (data_msg->pid) != t->fwd_pid + 1)
7789   {
7790     GNUNET_break (0);
7791     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7792               "Unicast PID, expected %u, got %u\n",
7793               t->fwd_pid + 1, ntohl (data_msg->pid));
7794     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7795     return;
7796   }
7797
7798   /* Ok, everything is correct, send the message
7799    * (pretend we got it from a mesh peer)
7800    */
7801   {
7802     /* Work around const limitation */
7803     char buf[ntohs (message->size)] GNUNET_ALIGN;
7804     struct GNUNET_MESH_Unicast *copy;
7805
7806     copy = (struct GNUNET_MESH_Unicast *) buf;
7807     memcpy (buf, data_msg, size);
7808     copy->oid = my_full_id;
7809     copy->tid = htonl (t->id.tid);
7810     copy->ttl = htonl (default_ttl);
7811     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7812                 "  calling generic handler...\n");
7813     handle_mesh_data_unicast (NULL, &my_full_id, &copy->header, NULL, 0);
7814   }
7815   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "receive done OK\n");
7816   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7817
7818   return;
7819 }
7820
7821
7822 /**
7823  * Handler for client traffic directed to the origin
7824  *
7825  * @param cls closure
7826  * @param client identification of the client
7827  * @param message the actual message
7828  */
7829 static void
7830 handle_local_to_origin (void *cls, struct GNUNET_SERVER_Client *client,
7831                         const struct GNUNET_MessageHeader *message)
7832 {
7833   struct GNUNET_MESH_ToOrigin *data_msg;
7834   struct MeshTunnelClientInfo *clinfo;
7835   struct MeshClient *c;
7836   struct MeshTunnel *t;
7837   MESH_TunnelNumber tid;
7838   size_t size;
7839
7840   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7841               "Got a ToOrigin request from a client!\n");
7842   /* Sanity check for client registration */
7843   if (NULL == (c = client_get (client)))
7844   {
7845     GNUNET_break (0);
7846     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7847     return;
7848   }
7849   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7850
7851   data_msg = (struct GNUNET_MESH_ToOrigin *) message;
7852
7853   /* Sanity check for message size */
7854   size = ntohs (message->size);
7855   if (sizeof (struct GNUNET_MESH_ToOrigin) +
7856       sizeof (struct GNUNET_MessageHeader) > size)
7857   {
7858     GNUNET_break (0);
7859     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7860     return;
7861   }
7862
7863   /* Tunnel exists? */
7864   tid = ntohl (data_msg->tid);
7865   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
7866   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
7867   {
7868     GNUNET_break (0);
7869     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7870     return;
7871   }
7872   t = tunnel_get_by_local_id (c, tid);
7873   if (NULL == t)
7874   {
7875     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
7876     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
7877     GNUNET_break (0);
7878     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7879     return;
7880   }
7881
7882   /*  It should be sent by someone who has this as incoming tunnel. */
7883   if (GNUNET_NO == client_knows_tunnel (c, t))
7884   {
7885     GNUNET_break (0);
7886     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7887     return;
7888   }
7889
7890   /* PID should be as expected */
7891   clinfo = tunnel_get_client_fc (t, c);
7892   if (ntohl (data_msg->pid) != clinfo->bck_pid + 1)
7893   {
7894     GNUNET_break (0);
7895     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7896                 "To Origin PID, expected %u, got %u\n",
7897                 clinfo->bck_pid + 1,
7898                 ntohl (data_msg->pid));
7899     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7900     return;
7901   }
7902   clinfo->bck_pid++;
7903
7904   /* Ok, everything is correct, send the message
7905    * (pretend we got it from a mesh peer)
7906    */
7907   {
7908     char buf[ntohs (message->size)] GNUNET_ALIGN;
7909     struct GNUNET_MESH_ToOrigin *copy;
7910
7911     /* Work around const limitation */
7912     copy = (struct GNUNET_MESH_ToOrigin *) buf;
7913     memcpy (buf, data_msg, size);
7914     GNUNET_PEER_resolve (t->id.oid, &copy->oid);
7915     copy->tid = htonl (t->id.tid);
7916     copy->ttl = htonl (default_ttl);
7917     copy->pid = htonl (t->bck_pid + 1);
7918
7919     copy->sender = my_full_id;
7920     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7921                 "  calling generic handler...\n");
7922     handle_mesh_data_to_orig (NULL, &my_full_id, &copy->header, NULL, 0);
7923   }
7924   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7925
7926   return;
7927 }
7928
7929
7930 /**
7931  * Handler for client traffic directed to all peers in a tunnel
7932  *
7933  * @param cls closure
7934  * @param client identification of the client
7935  * @param message the actual message
7936  */
7937 static void
7938 handle_local_multicast (void *cls, struct GNUNET_SERVER_Client *client,
7939                         const struct GNUNET_MessageHeader *message)
7940 {
7941   struct MeshClient *c;
7942   struct MeshTunnel *t;
7943   struct GNUNET_MESH_Multicast *data_msg;
7944   MESH_TunnelNumber tid;
7945
7946   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7947               "Got a multicast request from a client!\n");
7948
7949   /* Sanity check for client registration */
7950   if (NULL == (c = client_get (client)))
7951   {
7952     GNUNET_break (0);
7953     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7954     return;
7955   }
7956   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7957
7958   data_msg = (struct GNUNET_MESH_Multicast *) message;
7959
7960   /* Sanity check for message size */
7961   if (sizeof (struct GNUNET_MESH_Multicast) +
7962       sizeof (struct GNUNET_MessageHeader) > ntohs (data_msg->header.size))
7963   {
7964     GNUNET_break (0);
7965     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7966     return;
7967   }
7968
7969   /* Tunnel exists? */
7970   tid = ntohl (data_msg->tid);
7971   t = tunnel_get_by_local_id (c, tid);
7972   if (NULL == t)
7973   {
7974     GNUNET_break (0);
7975     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
7976     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
7977     GNUNET_break (0);
7978     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7979     return;
7980   }
7981
7982   /* Does client own tunnel? */
7983   if (t->owner->handle != client)
7984   {
7985     GNUNET_break (0);
7986     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7987     return;
7988   }
7989
7990   /* PID should be as expected */
7991   if (ntohl (data_msg->pid) != t->fwd_pid + 1)
7992   {
7993     GNUNET_break (0);
7994     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7995               "Multicast PID, expected %u, got %u\n",
7996               t->fwd_pid + 1, ntohl (data_msg->pid));
7997     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7998     return;
7999   }
8000
8001   {
8002     char buf[ntohs (message->size)] GNUNET_ALIGN;
8003     struct GNUNET_MESH_Multicast *copy;
8004
8005     copy = (struct GNUNET_MESH_Multicast *) buf;
8006     memcpy (buf, message, ntohs (message->size));
8007     copy->oid = my_full_id;
8008     copy->tid = htonl (t->id.tid);
8009     copy->ttl = htonl (default_ttl);
8010     GNUNET_assert (ntohl (copy->pid) == (t->fwd_pid + 1));
8011     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
8012                 "  calling generic handler...\n");
8013     handle_mesh_data_multicast (client, &my_full_id, &copy->header, NULL, 0);
8014   }
8015
8016   GNUNET_SERVER_receive_done (t->owner->handle, GNUNET_OK);
8017   return;
8018 }
8019
8020
8021 /**
8022  * Handler for client's ACKs for payload traffic.
8023  *
8024  * @param cls Closure (unused).
8025  * @param client Identification of the client.
8026  * @param message The actual message.
8027  */
8028 static void
8029 handle_local_ack (void *cls, struct GNUNET_SERVER_Client *client,
8030                   const struct GNUNET_MessageHeader *message)
8031 {
8032   struct GNUNET_MESH_LocalAck *msg;
8033   struct MeshTunnel *t;
8034   struct MeshClient *c;
8035   MESH_TunnelNumber tid;
8036   uint32_t ack;
8037
8038   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a local ACK\n");
8039   /* Sanity check for client registration */
8040   if (NULL == (c = client_get (client)))
8041   {
8042     GNUNET_break (0);
8043     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
8044     return;
8045   }
8046   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
8047
8048   msg = (struct GNUNET_MESH_LocalAck *) message;
8049
8050   /* Tunnel exists? */
8051   tid = ntohl (msg->tunnel_id);
8052   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
8053   t = tunnel_get_by_local_id (c, tid);
8054   if (NULL == t)
8055   {
8056     GNUNET_break (0);
8057     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
8058     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
8059     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
8060     return;
8061   }
8062
8063   ack = ntohl (msg->max_pid);
8064   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ack %u\n", ack);
8065
8066   /* Does client own tunnel? I.E: Is this an ACK for BCK traffic? */
8067   if (NULL != t->owner && t->owner->handle == client)
8068   {
8069     /* The client owns the tunnel, ACK is for data to_origin, send BCK ACK. */
8070     t->bck_ack = ack;
8071     tunnel_send_bck_ack(t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
8072   }
8073   else
8074   {
8075     /* The client doesn't own the tunnel, this ACK is for FWD traffic. */
8076     tunnel_set_client_fwd_ack (t, c, ack);
8077     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
8078   }
8079
8080   GNUNET_SERVER_receive_done (client, GNUNET_OK);
8081
8082   return;
8083 }
8084
8085
8086 /**
8087  * Iterator over all peers to send a monitoring client info about a tunnel.
8088  *
8089  * @param cls Closure (message being built).
8090  * @param key Key (hashed tunnel ID, unused).
8091  * @param value Peer info.
8092  *
8093  * @return GNUNET_YES, to keep iterating.
8094  */
8095 static int
8096 monitor_peers_iterator (void *cls,
8097                         const struct GNUNET_HashCode * key,
8098                         void *value)
8099 {
8100   struct GNUNET_MESH_LocalMonitor *msg = cls;
8101   struct GNUNET_PeerIdentity *id;
8102   struct MeshPeerInfo *info = value;
8103
8104   id = (struct GNUNET_PeerIdentity *) &msg[1];
8105   GNUNET_PEER_resolve (info->id, &id[msg->npeers]);
8106   msg->npeers++;
8107
8108   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
8109               "*    sending info about peer %s [%u]\n",
8110               GNUNET_i2s (&id[msg->npeers - 1]), msg->npeers);
8111
8112   return GNUNET_YES;
8113 }
8114
8115
8116
8117 /**
8118  * Iterator over all tunnels to send a monitoring client info about each tunnel.
8119  *
8120  * @param cls Closure (client handle).
8121  * @param key Key (hashed tunnel ID, unused).
8122  * @param value Tunnel info.
8123  *
8124  * @return GNUNET_YES, to keep iterating.
8125  */
8126 static int
8127 monitor_all_tunnels_iterator (void *cls,
8128                               const struct GNUNET_HashCode * key,
8129                               void *value)
8130 {
8131   struct GNUNET_SERVER_Client *client = cls;
8132   struct MeshTunnel *t = value;
8133   struct GNUNET_MESH_LocalMonitor *msg;
8134   uint32_t npeers;
8135   
8136   npeers = GNUNET_CONTAINER_multihashmap_size (t->peers);
8137   msg = GNUNET_malloc (sizeof(struct GNUNET_MESH_LocalMonitor) +
8138   npeers * sizeof (struct GNUNET_PeerIdentity));
8139   GNUNET_PEER_resolve(t->id.oid, &msg->owner);
8140   msg->tunnel_id = htonl (t->id.tid);
8141   msg->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor) +
8142   npeers * sizeof (struct GNUNET_PeerIdentity));
8143   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS);
8144   msg->npeers = 0;
8145   (void) GNUNET_CONTAINER_multihashmap_iterate (t->peers,
8146                                                 monitor_peers_iterator,
8147                                                 msg);
8148   
8149   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
8150               "*  sending info about tunnel %s [%u] (%u peers)\n",
8151               GNUNET_i2s (&msg->owner), t->id.tid, npeers);
8152   
8153   if (msg->npeers != npeers)
8154   {
8155     GNUNET_break (0);
8156     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8157                 "Get tunnels fail: size %u - iter %u\n",
8158                 npeers, msg->npeers);
8159   }
8160   
8161     msg->npeers = htonl (npeers);
8162     GNUNET_SERVER_notification_context_unicast (nc, client,
8163                                                 &msg->header, GNUNET_NO);
8164     return GNUNET_YES;
8165 }
8166
8167
8168 /**
8169  * Handler for client's MONITOR request.
8170  *
8171  * @param cls Closure (unused).
8172  * @param client Identification of the client.
8173  * @param message The actual message.
8174  */
8175 static void
8176 handle_local_get_tunnels (void *cls, struct GNUNET_SERVER_Client *client,
8177                           const struct GNUNET_MessageHeader *message)
8178 {
8179   struct MeshClient *c;
8180
8181   /* Sanity check for client registration */
8182   if (NULL == (c = client_get (client)))
8183   {
8184     GNUNET_break (0);
8185     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
8186     return;
8187   }
8188
8189   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
8190               "Received get tunnels request from client %u\n",
8191               c->id);
8192   GNUNET_CONTAINER_multihashmap_iterate (tunnels,
8193                                          monitor_all_tunnels_iterator,
8194                                          client);
8195   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
8196               "Get tunnels request from client %u completed\n",
8197               c->id);
8198   GNUNET_SERVER_receive_done (client, GNUNET_OK);
8199 }
8200
8201
8202 /**
8203  * Data needed to build a Monitor_Tunnel message.
8204  */
8205 struct MeshMonitorTunnelContext
8206 {
8207   /**
8208    * Partial message, including peer count.
8209    */
8210   struct GNUNET_MESH_LocalMonitor *msg;
8211
8212   /**
8213    * Hashmap with positions: peer->position.
8214    */
8215   struct GNUNET_CONTAINER_MultiHashMap *lookup;
8216
8217   /**
8218    * Index of the parent of each peer in the message, realtive to the absolute
8219    * order in the array (can be in a previous message).
8220    */
8221   uint32_t parents[1024];
8222
8223   /**
8224    * Peers visited so far in the tree, aka position of the current peer.
8225    */
8226   unsigned int npeers;
8227
8228   /**
8229    * Client requesting the info.
8230    */
8231   struct MeshClient *c;
8232 };
8233
8234
8235 /**
8236  * Send a client a message about the structure of a tunnel.
8237  *
8238  * @param ctx Context of the tunnel iteration, with info regarding the state
8239  *            of the execution and the number of peers visited for this message.
8240  */
8241 static void
8242 send_client_tunnel_info (struct MeshMonitorTunnelContext *ctx)
8243 {
8244   struct GNUNET_MESH_LocalMonitor *resp = ctx->msg;
8245   struct GNUNET_PeerIdentity *pid;
8246   unsigned int *parent;
8247   size_t size;
8248
8249   size = sizeof (struct GNUNET_MESH_LocalMonitor);
8250   size += (sizeof (struct GNUNET_PeerIdentity) + sizeof (int)) * resp->npeers;
8251   resp->header.size = htons (size);
8252   pid = (struct GNUNET_PeerIdentity *) &resp[1];
8253   parent = (unsigned int *) &pid[resp->npeers];
8254   memcpy (parent, ctx->parents, sizeof(uint32_t) * resp->npeers);
8255   GNUNET_SERVER_notification_context_unicast (nc, ctx->c->handle,
8256                                               &resp->header, GNUNET_NO);
8257 }
8258
8259 /**
8260  * Iterator over a tunnel tree to build a message containing all peers
8261  * the in the tunnel, including relay nodes.
8262  *
8263  * @param cls Closure (pointer to pointer of message being built).
8264  * @param peer Short ID of a peer.
8265  * @param parent Short ID of the @c peer 's parent.
8266  */
8267 static void
8268 tunnel_tree_iterator (void *cls,
8269                       GNUNET_PEER_Id peer,
8270                       GNUNET_PEER_Id parent)
8271 {
8272   struct MeshMonitorTunnelContext *ctx = cls;
8273   struct GNUNET_MESH_LocalMonitor *msg;
8274   struct GNUNET_PeerIdentity *pid;
8275   struct GNUNET_PeerIdentity ppid;
8276
8277   msg = ctx->msg;
8278   pid = (struct GNUNET_PeerIdentity *) &msg[1];
8279   GNUNET_PEER_resolve (peer, &pid[msg->npeers]);
8280   GNUNET_CONTAINER_multihashmap_put (ctx->lookup,
8281                                      &pid[msg->npeers].hashPubKey,
8282                                      (void *) (long) ctx->npeers,
8283                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
8284   GNUNET_PEER_resolve (parent, &ppid);
8285   ctx->parents[msg->npeers] =
8286       htonl ((long) GNUNET_CONTAINER_multihashmap_get (ctx->lookup,
8287                                                        &ppid.hashPubKey));
8288
8289   ctx->npeers++;
8290   msg->npeers++;
8291
8292   if (sizeof (struct GNUNET_MESH_LocalMonitor) +
8293       (msg->npeers + 1) *
8294       (sizeof (struct GNUNET_PeerIdentity) + sizeof (uint32_t))
8295       > USHRT_MAX)
8296   {
8297     send_client_tunnel_info (ctx);
8298     msg->npeers = 0;
8299   }
8300 }
8301
8302
8303 /**
8304  * Handler for client's MONITOR_TUNNEL request.
8305  *
8306  * @param cls Closure (unused).
8307  * @param client Identification of the client.
8308  * @param message The actual message.
8309  */
8310 static void
8311 handle_local_show_tunnel (void *cls, struct GNUNET_SERVER_Client *client,
8312                           const struct GNUNET_MessageHeader *message)
8313 {
8314   const struct GNUNET_MESH_LocalMonitor *msg;
8315   struct GNUNET_MESH_LocalMonitor *resp;
8316   struct MeshMonitorTunnelContext ctx;
8317   struct MeshClient *c;
8318   struct MeshTunnel *t;
8319
8320   /* Sanity check for client registration */
8321   if (NULL == (c = client_get (client)))
8322   {
8323     GNUNET_break (0);
8324     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
8325     return;
8326   }
8327
8328   msg = (struct GNUNET_MESH_LocalMonitor *) message;
8329   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
8330               "Received tunnel info request from client %u for tunnel %s[%X]\n",
8331               c->id,
8332               &msg->owner,
8333               ntohl (msg->tunnel_id));
8334   t = tunnel_get (&msg->owner, ntohl (msg->tunnel_id));
8335   if (NULL == t)
8336   {
8337     /* We don't know the tunnel */
8338     struct GNUNET_MESH_LocalMonitor warn;
8339
8340     warn = *msg;
8341     warn.npeers = htonl (UINT_MAX);
8342     GNUNET_SERVER_notification_context_unicast (nc, client,
8343                                                 &warn.header,
8344                                                 GNUNET_NO);
8345     GNUNET_SERVER_receive_done (client, GNUNET_OK);
8346     return;
8347   }
8348
8349   /* Initialize context */
8350   resp = GNUNET_malloc (USHRT_MAX); /* avoid realloc'ing on each step */
8351   *resp = *msg;
8352   resp->npeers = 0;
8353   ctx.msg = resp;
8354   ctx.lookup = GNUNET_CONTAINER_multihashmap_create (4 * t->peers_total,
8355                                                      GNUNET_YES);
8356   ctx.c = c;
8357
8358   /* Collect and send information */
8359   tree_iterate_all (t->tree, &tunnel_tree_iterator, &ctx);
8360   send_client_tunnel_info (&ctx);
8361
8362   /* Free context */
8363   GNUNET_CONTAINER_multihashmap_destroy (ctx.lookup);
8364   GNUNET_free (resp);
8365
8366   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
8367               "Monitor tunnel request from client %u completed\n",
8368               c->id);
8369   GNUNET_SERVER_receive_done (client, GNUNET_OK);
8370 }
8371
8372
8373 /**
8374  * Functions to handle messages from clients
8375  */
8376 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
8377   {&handle_local_new_client, NULL,
8378    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
8379   {&handle_local_announce_regex, NULL,
8380    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ANNOUNCE_REGEX, 0},
8381   {&handle_local_tunnel_create, NULL,
8382    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
8383    sizeof (struct GNUNET_MESH_TunnelMessage)},
8384   {&handle_local_tunnel_destroy, NULL,
8385    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
8386    sizeof (struct GNUNET_MESH_TunnelMessage)},
8387   {&handle_local_tunnel_speed, NULL,
8388    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MIN,
8389    sizeof (struct GNUNET_MESH_TunnelMessage)},
8390   {&handle_local_tunnel_speed, NULL,
8391    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MAX,
8392    sizeof (struct GNUNET_MESH_TunnelMessage)},
8393   {&handle_local_tunnel_buffer, NULL,
8394    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER,
8395    sizeof (struct GNUNET_MESH_TunnelMessage)},
8396   {&handle_local_tunnel_buffer, NULL,
8397    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER,
8398    sizeof (struct GNUNET_MESH_TunnelMessage)},
8399   {&handle_local_connect_add, NULL,
8400    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD,
8401    sizeof (struct GNUNET_MESH_PeerControl)},
8402   {&handle_local_connect_del, NULL,
8403    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL,
8404    sizeof (struct GNUNET_MESH_PeerControl)},
8405   {&handle_local_blacklist, NULL,
8406    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_BLACKLIST,
8407    sizeof (struct GNUNET_MESH_PeerControl)},
8408   {&handle_local_unblacklist, NULL,
8409    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_UNBLACKLIST,
8410    sizeof (struct GNUNET_MESH_PeerControl)},
8411   {&handle_local_connect_by_type, NULL,
8412    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE,
8413    sizeof (struct GNUNET_MESH_ConnectPeerByType)},
8414   {&handle_local_connect_by_string, NULL,
8415    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_STRING, 0},
8416   {&handle_local_unicast, NULL,
8417    GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
8418   {&handle_local_to_origin, NULL,
8419    GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
8420   {&handle_local_multicast, NULL,
8421    GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
8422   {&handle_local_ack, NULL,
8423    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK,
8424    sizeof (struct GNUNET_MESH_LocalAck)},
8425   {&handle_local_get_tunnels, NULL,
8426    GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS,
8427    sizeof (struct GNUNET_MessageHeader)},
8428   {&handle_local_show_tunnel, NULL,
8429    GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNEL,
8430      sizeof (struct GNUNET_MESH_LocalMonitor)},
8431   {NULL, NULL, 0, 0}
8432 };
8433
8434
8435 /**
8436  * To be called on core init/fail.
8437  *
8438  * @param cls service closure
8439  * @param server handle to the server for this service
8440  * @param identity the public identity of this peer
8441  */
8442 static void
8443 core_init (void *cls, struct GNUNET_CORE_Handle *server,
8444            const struct GNUNET_PeerIdentity *identity)
8445 {
8446   static int i = 0;
8447   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
8448   core_handle = server;
8449   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)) ||
8450       NULL == server)
8451   {
8452     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
8453     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8454                 " core id %s\n",
8455                 GNUNET_i2s (identity));
8456     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8457                 " my id %s\n",
8458                 GNUNET_i2s (&my_full_id));
8459     GNUNET_SCHEDULER_shutdown (); // Try gracefully
8460     if (10 < i++)
8461       GNUNET_abort(); // Try harder
8462   }
8463   return;
8464 }
8465
8466
8467 /**
8468  * Method called whenever a given peer connects.
8469  *
8470  * @param cls closure
8471  * @param peer peer identity this notification is about
8472  * @param atsi performance data for the connection
8473  * @param atsi_count number of records in 'atsi'
8474  */
8475 static void
8476 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
8477               const struct GNUNET_ATS_Information *atsi,
8478               unsigned int atsi_count)
8479 {
8480   struct MeshPeerInfo *peer_info;
8481   struct MeshPeerPath *path;
8482
8483   DEBUG_CONN ("Peer connected\n");
8484   DEBUG_CONN ("     %s\n", GNUNET_i2s (&my_full_id));
8485   peer_info = peer_info_get (peer);
8486   if (myid == peer_info->id)
8487   {
8488     DEBUG_CONN ("     (self)\n");
8489     return;
8490   }
8491   else
8492   {
8493     DEBUG_CONN ("     %s\n", GNUNET_i2s (peer));
8494   }
8495   path = path_new (2);
8496   path->peers[0] = myid;
8497   path->peers[1] = peer_info->id;
8498   GNUNET_PEER_change_rc (myid, 1);
8499   GNUNET_PEER_change_rc (peer_info->id, 1);
8500   peer_info_add_path (peer_info, path, GNUNET_YES);
8501   GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
8502   return;
8503 }
8504
8505
8506 /**
8507  * Method called whenever a peer disconnects.
8508  *
8509  * @param cls closure
8510  * @param peer peer identity this notification is about
8511  */
8512 static void
8513 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
8514 {
8515   struct MeshPeerInfo *pi;
8516   struct MeshPeerQueue *q;
8517   struct MeshPeerQueue *n;
8518
8519   DEBUG_CONN ("Peer disconnected\n");
8520   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
8521   if (NULL == pi)
8522   {
8523     GNUNET_break (0);
8524     return;
8525   }
8526   q = pi->queue_head;
8527   while (NULL != q)
8528   {
8529       n = q->next;
8530       /* TODO try to reroute this traffic instead */
8531       queue_destroy(q, GNUNET_YES);
8532       q = n;
8533   }
8534   if (NULL != pi->core_transmit)
8535   {
8536     GNUNET_CORE_notify_transmit_ready_cancel(pi->core_transmit);
8537     pi->core_transmit = NULL;
8538   }
8539   peer_info_remove_path (pi, pi->id, myid);
8540   if (myid == pi->id)
8541   {
8542     DEBUG_CONN ("     (self)\n");
8543   }
8544   GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
8545   return;
8546 }
8547
8548
8549 /******************************************************************************/
8550 /************************      MAIN FUNCTIONS      ****************************/
8551 /******************************************************************************/
8552
8553 /**
8554  * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
8555  *
8556  * @param cls closure
8557  * @param key current key code
8558  * @param value value in the hash map
8559  * @return GNUNET_YES if we should continue to iterate,
8560  *         GNUNET_NO if not.
8561  */
8562 static int
8563 shutdown_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
8564 {
8565   struct MeshTunnel *t = value;
8566
8567   tunnel_destroy (t);
8568   return GNUNET_YES;
8569 }
8570
8571 /**
8572  * Iterator over peer hash map entries to destroy the tunnel during shutdown.
8573  *
8574  * @param cls closure
8575  * @param key current key code
8576  * @param value value in the hash map
8577  * @return GNUNET_YES if we should continue to iterate,
8578  *         GNUNET_NO if not.
8579  */
8580 static int
8581 shutdown_peer (void *cls, const struct GNUNET_HashCode * key, void *value)
8582 {
8583   struct MeshPeerInfo *p = value;
8584   struct MeshPeerQueue *q;
8585   struct MeshPeerQueue *n;
8586
8587   q = p->queue_head;
8588   while (NULL != q)
8589   {
8590       n = q->next;
8591       if (q->peer == p)
8592       {
8593         queue_destroy(q, GNUNET_YES);
8594       }
8595       q = n;
8596   }
8597   peer_info_destroy (p);
8598   return GNUNET_YES;
8599 }
8600
8601
8602 /**
8603  * Task run during shutdown.
8604  *
8605  * @param cls unused
8606  * @param tc unused
8607  */
8608 static void
8609 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
8610 {
8611   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
8612
8613   if (core_handle != NULL)
8614   {
8615     GNUNET_CORE_disconnect (core_handle);
8616     core_handle = NULL;
8617   }
8618   if (NULL != keygen)
8619   {
8620     GNUNET_CRYPTO_rsa_key_create_stop (keygen);
8621     keygen = NULL;
8622   }
8623   GNUNET_CONTAINER_multihashmap_iterate (tunnels, &shutdown_tunnel, NULL);
8624   GNUNET_CONTAINER_multihashmap_iterate (peers, &shutdown_peer, NULL);
8625   if (dht_handle != NULL)
8626   {
8627     GNUNET_DHT_disconnect (dht_handle);
8628     dht_handle = NULL;
8629   }
8630   if (nc != NULL)
8631   {
8632     GNUNET_SERVER_notification_context_destroy (nc);
8633     nc = NULL;
8634   }
8635   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
8636   {
8637     GNUNET_SCHEDULER_cancel (announce_id_task);
8638     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
8639   }
8640   if (GNUNET_SCHEDULER_NO_TASK != announce_applications_task)
8641   {
8642     GNUNET_SCHEDULER_cancel (announce_applications_task);
8643     announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
8644   }
8645   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
8646 }
8647
8648
8649 /**
8650  * Callback for hostkey read/generation
8651  *
8652  * @param cls Closure (Configuration handle).
8653  * @param pk the private key
8654  * @param emsg error message
8655  */
8656 static void
8657 key_generation_cb (void *cls,
8658                    struct GNUNET_CRYPTO_RsaPrivateKey *pk,
8659                    const char *emsg)
8660 {
8661   const struct GNUNET_CONFIGURATION_Handle *c = cls;
8662   struct MeshPeerInfo *peer;
8663   struct MeshPeerPath *p;
8664
8665   keygen = NULL;  
8666   if (NULL == pk)
8667   {
8668     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8669                 _("Mesh service could not access hostkey: %s. Exiting.\n"),
8670                 emsg);
8671     GNUNET_SCHEDULER_shutdown ();
8672     return;
8673   }
8674   my_private_key = pk;
8675   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
8676   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
8677                       &my_full_id.hashPubKey);
8678   myid = GNUNET_PEER_intern (&my_full_id);
8679   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
8680               "Mesh for peer [%s] starting\n",
8681               GNUNET_i2s(&my_full_id));
8682
8683 //   transport_handle = GNUNET_TRANSPORT_connect(c,
8684 //                                               &my_full_id,
8685 //                                               NULL,
8686 //                                               NULL,
8687 //                                               NULL,
8688 //                                               NULL);
8689
8690   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
8691                                      NULL,      /* Closure passed to MESH functions */
8692                                      &core_init,        /* Call core_init once connected */
8693                                      &core_connect,     /* Handle connects */
8694                                      &core_disconnect,  /* remove peers on disconnects */
8695                                      NULL,      /* Don't notify about all incoming messages */
8696                                      GNUNET_NO, /* For header only in notification */
8697                                      NULL,      /* Don't notify about all outbound messages */
8698                                      GNUNET_NO, /* For header-only out notification */
8699                                      core_handlers);    /* Register these handlers */
8700   
8701   if (core_handle == NULL)
8702   {
8703     GNUNET_break (0);
8704     GNUNET_SCHEDULER_shutdown ();
8705     return;
8706   }
8707
8708   next_tid = 0;
8709   next_local_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
8710
8711
8712   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
8713   nc = GNUNET_SERVER_notification_context_create (server_handle, 1);
8714   GNUNET_SERVER_disconnect_notify (server_handle,
8715                                    &handle_local_client_disconnect, NULL);
8716
8717
8718   clients = NULL;
8719   clients_tail = NULL;
8720   next_client_id = 0;
8721
8722   announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
8723   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
8724
8725   /* Create a peer_info for the local peer */
8726   peer = peer_info_get (&my_full_id);
8727   p = path_new (1);
8728   p->peers[0] = myid;
8729   GNUNET_PEER_change_rc (myid, 1);
8730   peer_info_add_path (peer, p, GNUNET_YES);
8731   GNUNET_SERVER_resume (server_handle);
8732   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Mesh service running\n");
8733 }
8734
8735
8736 /**
8737  * Process mesh requests.
8738  *
8739  * @param cls closure
8740  * @param server the initialized server
8741  * @param c configuration to use
8742  */
8743 static void
8744 run (void *cls, struct GNUNET_SERVER_Handle *server,
8745      const struct GNUNET_CONFIGURATION_Handle *c)
8746 {
8747   char *keyfile;
8748
8749   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
8750   server_handle = server;
8751
8752   if (GNUNET_OK !=
8753       GNUNET_CONFIGURATION_get_value_filename (c, "GNUNETD", "HOSTKEY",
8754                                                &keyfile))
8755   {
8756     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8757                 _
8758                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8759                 "mesh", "hostkey");
8760     GNUNET_SCHEDULER_shutdown ();
8761     return;
8762   }
8763
8764   if (GNUNET_OK !=
8765       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_PATH_TIME",
8766                                            &refresh_path_time))
8767   {
8768     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8769                 _
8770                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8771                 "mesh", "refresh path time");
8772     GNUNET_SCHEDULER_shutdown ();
8773     return;
8774   }
8775
8776   if (GNUNET_OK !=
8777       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "APP_ANNOUNCE_TIME",
8778                                            &app_announce_time))
8779   {
8780     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8781                 _
8782                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8783                 "mesh", "app announce time");
8784     GNUNET_SCHEDULER_shutdown ();
8785     return;
8786   }
8787   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
8788               "APP_ANNOUNCE_TIME %llu ms\n", 
8789               app_announce_time.rel_value);
8790   if (GNUNET_OK !=
8791       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "ID_ANNOUNCE_TIME",
8792                                            &id_announce_time))
8793   {
8794     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8795                 _
8796                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8797                 "mesh", "id announce time");
8798     GNUNET_SCHEDULER_shutdown ();
8799     return;
8800   }
8801
8802   if (GNUNET_OK !=
8803       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "CONNECT_TIMEOUT",
8804                                            &connect_timeout))
8805   {
8806     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8807                 _
8808                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8809                 "mesh", "connect timeout");
8810     GNUNET_SCHEDULER_shutdown ();
8811     return;
8812   }
8813
8814   if (GNUNET_OK !=
8815       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
8816                                              &max_msgs_queue))
8817   {
8818     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8819                 _
8820                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8821                 "mesh", "max msgs queue");
8822     GNUNET_SCHEDULER_shutdown ();
8823     return;
8824   }
8825
8826   if (GNUNET_OK !=
8827       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_TUNNELS",
8828                                              &max_tunnels))
8829   {
8830     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8831                 _
8832                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8833                 "mesh", "max tunnels");
8834     GNUNET_SCHEDULER_shutdown ();
8835     return;
8836   }
8837
8838   if (GNUNET_OK !=
8839       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
8840                                              &default_ttl))
8841   {
8842     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
8843                 _
8844                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
8845                 "mesh", "default ttl", 64);
8846     default_ttl = 64;
8847   }
8848
8849   if (GNUNET_OK !=
8850       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_PEERS",
8851                                              &max_peers))
8852   {
8853     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
8854                 _("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
8855                 "mesh", "max peers", 1000);
8856     max_peers = 1000;
8857   }
8858
8859   if (GNUNET_OK !=
8860       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DHT_REPLICATION_LEVEL",
8861                                              &dht_replication_level))
8862   {
8863     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
8864                 _
8865                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
8866                 "mesh", "dht replication level", 3);
8867     dht_replication_level = 3;
8868   }
8869
8870   tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
8871   incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
8872   peers = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
8873   applications = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
8874   types = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
8875
8876   dht_handle = GNUNET_DHT_connect (c, 64);
8877   if (NULL == dht_handle)
8878   {
8879     GNUNET_break (0);
8880   }
8881   stats = GNUNET_STATISTICS_create ("mesh", c);
8882
8883   GNUNET_SERVER_suspend (server_handle);
8884   /* Scheduled the task to clean up when shutdown is called */
8885   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
8886                                 NULL);
8887   keygen = GNUNET_CRYPTO_rsa_key_create_start (keyfile,
8888                                                &key_generation_cb,
8889                                                (void *) c);
8890   GNUNET_free (keyfile);
8891 }
8892
8893
8894 /**
8895  * The main function for the mesh service.
8896  *
8897  * @param argc number of arguments from the command line
8898  * @param argv command line arguments
8899  * @return 0 ok, 1 on error
8900  */
8901 int
8902 main (int argc, char *const *argv)
8903 {
8904   int ret;
8905   int r;
8906
8907   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
8908   r = GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
8909                           NULL);
8910   ret = (GNUNET_OK == r) ? 0 : 1;
8911   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");
8912
8913   INTERVAL_SHOW;
8914
8915   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
8916               "Mesh for peer [%s] FWD ACKs %u, BCK ACKs %u\n",
8917               GNUNET_i2s(&my_full_id), debug_fwd_ack, debug_bck_ack);
8918
8919   return ret;
8920 }