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