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