- dont destroy tunnels with local clients
[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->clients_fc);
4536
4537   if (NULL != t->peers)
4538   {
4539     GNUNET_CONTAINER_multihashmap_iterate (t->peers, &peer_info_delete_tunnel,
4540                                            t);
4541     GNUNET_CONTAINER_multihashmap_destroy (t->peers);
4542   }
4543
4544   GNUNET_CONTAINER_multihashmap_iterate (t->children_fc,
4545                                          &tunnel_destroy_child,
4546                                          t);
4547   GNUNET_CONTAINER_multihashmap_destroy (t->children_fc);
4548   t->children_fc = NULL;
4549
4550   tree_iterate_children (t->tree, &tunnel_cancel_queues, t);
4551   tree_destroy (t->tree);
4552
4553   if (NULL != t->regex_ctx)
4554     regex_cancel_search (t->regex_ctx);
4555   if (NULL != t->dht_get_type)
4556     GNUNET_DHT_get_stop (t->dht_get_type);
4557   if (GNUNET_SCHEDULER_NO_TASK != t->timeout_task)
4558     GNUNET_SCHEDULER_cancel (t->timeout_task);
4559   if (GNUNET_SCHEDULER_NO_TASK != t->path_refresh_task)
4560     GNUNET_SCHEDULER_cancel (t->path_refresh_task);
4561
4562   n_tunnels--;
4563   GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
4564   GNUNET_free (t);
4565   return r;
4566 }
4567
4568 #define TUNNEL_DESTROY_EMPTY_TIME GNUNET_TIME_UNIT_MILLISECONDS
4569
4570 /**
4571  * Tunnel is empty: destroy it.
4572  * 
4573  * @param cls Closure (Tunnel).
4574  * @param tc TaskContext. 
4575  */
4576 static void
4577 tunnel_destroy_empty_delayed (void *cls,
4578                               const struct GNUNET_SCHEDULER_TaskContext *tc)
4579 {
4580   struct MeshTunnel *t = cls;
4581
4582   t->delayed_destroy = GNUNET_SCHEDULER_NO_TASK;
4583   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4584     return;
4585
4586   if (0 != t->nclients ||
4587       0 != tree_count_children (t->tree))
4588     return;
4589
4590   #if MESH_DEBUG
4591   {
4592     struct GNUNET_PeerIdentity id;
4593
4594     GNUNET_PEER_resolve (t->id.oid, &id);
4595     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4596                 "executing destruction of empty tunnel %s [%X]\n",
4597                 GNUNET_i2s (&id), t->id.tid);
4598   }
4599   #endif
4600
4601   tunnel_send_destroy (t, GNUNET_YES);
4602   if (0 == t->pending_messages)
4603     tunnel_destroy (t);
4604   else
4605     t->destroy = GNUNET_YES;
4606 }
4607
4608
4609 /**
4610  * Schedule tunnel destruction if is empty and no new traffic comes in a time.
4611  * 
4612  * @param t Tunnel to destroy if empty.
4613  */
4614 static void
4615 tunnel_destroy_empty (struct MeshTunnel *t)
4616 {
4617   if (GNUNET_SCHEDULER_NO_TASK != t->delayed_destroy || 
4618       0 != t->nclients ||
4619       0 != tree_count_children (t->tree))
4620   {
4621     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4622                 "%u %u %u\n",
4623                 t->delayed_destroy, t->nclients, tree_count_children(t->tree));
4624     return;
4625   }
4626
4627   #if MESH_DEBUG
4628   {
4629     struct GNUNET_PeerIdentity id;
4630
4631     GNUNET_PEER_resolve (t->id.oid, &id);
4632     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4633                 "scheduling destruction of empty tunnel %s [%X]\n",
4634                 GNUNET_i2s (&id), t->id.tid);
4635   }
4636   #endif
4637
4638   t->delayed_destroy =
4639       GNUNET_SCHEDULER_add_delayed (TUNNEL_DESTROY_EMPTY_TIME,
4640                                     &tunnel_destroy_empty_delayed,
4641                                     t);
4642 }
4643
4644
4645 /**
4646  * Create a new tunnel
4647  * 
4648  * @param owner Who is the owner of the tunnel (short ID).
4649  * @param tid Tunnel Number of the tunnel.
4650  * @param client Clients that owns the tunnel, NULL for foreign tunnels.
4651  * @param local Tunnel Number for the tunnel, for the client point of view.
4652  * 
4653  * @return A new initialized tunnel. NULL on error.
4654  */
4655 static struct MeshTunnel *
4656 tunnel_new (GNUNET_PEER_Id owner,
4657             MESH_TunnelNumber tid,
4658             struct MeshClient *client,
4659             MESH_TunnelNumber local)
4660 {
4661   struct MeshTunnel *t;
4662   struct GNUNET_HashCode hash;
4663
4664   if (n_tunnels >= max_tunnels && NULL == client)
4665     return NULL;
4666
4667   t = GNUNET_malloc (sizeof (struct MeshTunnel));
4668   t->id.oid = owner;
4669   t->id.tid = tid;
4670   t->fwd_queue_max = (max_msgs_queue / max_tunnels) + 1;
4671   t->bck_queue_max = t->fwd_queue_max;
4672   t->tree = tree_new (owner);
4673   t->owner = client;
4674   t->fwd_pid = (uint32_t) -1; // Next (expected) = 0
4675   t->bck_pid = (uint32_t) -1; // Next (expected) = 0
4676   t->bck_ack = INITIAL_WINDOW_SIZE - 1;
4677   t->last_fwd_ack = INITIAL_WINDOW_SIZE - 1;
4678   t->local_tid = local;
4679   t->children_fc = GNUNET_CONTAINER_multihashmap_create (8, GNUNET_NO);
4680   n_tunnels++;
4681   GNUNET_STATISTICS_update (stats, "# tunnels", 1, GNUNET_NO);
4682
4683   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
4684   if (GNUNET_OK !=
4685       GNUNET_CONTAINER_multihashmap_put (tunnels, &hash, t,
4686                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
4687   {
4688     GNUNET_break (0);
4689     tunnel_destroy (t);
4690     if (NULL != client)
4691     {
4692       GNUNET_break (0);
4693       GNUNET_SERVER_receive_done (client->handle, GNUNET_SYSERR);
4694     }
4695     return NULL;
4696   }
4697
4698   if (NULL != client)
4699   {
4700     GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
4701     if (GNUNET_OK !=
4702         GNUNET_CONTAINER_multihashmap_put (client->own_tunnels, &hash, t,
4703                                           GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
4704     {
4705       tunnel_destroy (t);
4706       GNUNET_break (0);
4707       GNUNET_SERVER_receive_done (client->handle, GNUNET_SYSERR);
4708       return NULL;
4709     }
4710   }
4711
4712   return t;
4713 }
4714
4715 /**
4716  * Callback when removing children from a tunnel tree. Notify owner.
4717  *
4718  * @param cls Closure (tunnel).
4719  * @param peer_id Short ID of the peer deleted.
4720  */
4721 void
4722 tunnel_child_removed (void *cls, GNUNET_PEER_Id peer_id)
4723 {
4724   struct MeshTunnel *t = cls;
4725
4726   client_notify_peer_disconnected (t->owner, t, peer_id);
4727 }
4728
4729 /**
4730  * Removes an explicit path from a tunnel, freeing all intermediate nodes
4731  * that are no longer needed, as well as nodes of no longer reachable peers.
4732  * The tunnel itself is also destoyed if results in a remote empty tunnel.
4733  *
4734  * @param t Tunnel from which to remove the path.
4735  * @param peer Short id of the peer which should be removed.
4736  */
4737 static void
4738 tunnel_delete_peer (struct MeshTunnel *t, GNUNET_PEER_Id peer)
4739 {
4740   int r;
4741
4742   r = tree_del_peer (t->tree, peer, &tunnel_child_removed, t);
4743   if (GNUNET_NO == r)
4744   {
4745     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4746                 "Tunnel %u [%u] has no more nodes\n",
4747                 t->id.oid, t->id.tid);
4748   }
4749 }
4750
4751
4752 /**
4753  * tunnel_destroy_iterator: iterator for deleting each tunnel that belongs to a
4754  * client when the client disconnects. If the client is not the owner, the
4755  * owner will get notified if no more clients are in the tunnel and the client
4756  * get removed from the tunnel's list.
4757  *
4758  * @param cls closure (client that is disconnecting)
4759  * @param key the hash of the local tunnel id (used to access the hashmap)
4760  * @param value the value stored at the key (tunnel to destroy)
4761  *
4762  * @return GNUNET_OK, keep iterating.
4763  */
4764 static int
4765 tunnel_destroy_iterator (void *cls,
4766                          const struct GNUNET_HashCode * key,
4767                          void *value)
4768 {
4769   struct MeshTunnel *t = value;
4770   struct MeshClient *c = cls;
4771
4772   send_client_tunnel_disconnect (t, c);
4773   if (c != t->owner)
4774   {
4775     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Client %u is destination.\n", c->id);
4776     tunnel_delete_client (t, c);
4777     client_delete_tunnel (c, t);
4778     tunnel_destroy_empty (t);
4779     return GNUNET_OK;
4780   }
4781   tunnel_send_destroy (t, GNUNET_YES);
4782   t->owner = NULL;
4783   t->destroy = GNUNET_YES;
4784
4785   return GNUNET_OK;
4786 }
4787
4788
4789 /**
4790  * Timeout function, destroys tunnel if called
4791  *
4792  * @param cls Closure (tunnel to destroy).
4793  * @param tc TaskContext
4794  */
4795 static void
4796 tunnel_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4797 {
4798   struct MeshTunnel *t = cls;
4799   struct GNUNET_PeerIdentity id;
4800
4801   t->timeout_task = GNUNET_SCHEDULER_NO_TASK;
4802   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4803     return;
4804   GNUNET_PEER_resolve(t->id.oid, &id);
4805   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4806               "Tunnel %s [%X] timed out. Destroying.\n",
4807               GNUNET_i2s(&id), t->id.tid);
4808   send_clients_tunnel_destroy (t);
4809   tunnel_destroy (t);
4810 }
4811
4812 /**
4813  * Resets the tunnel timeout. Starts it if no timeout was running.
4814  *
4815  * @param t Tunnel whose timeout to reset.
4816  *
4817  * TODO use heap to improve efficiency of scheduler.
4818  */
4819 static void
4820 tunnel_reset_timeout (struct MeshTunnel *t)
4821 {
4822   if (GNUNET_SCHEDULER_NO_TASK != t->timeout_task)
4823     GNUNET_SCHEDULER_cancel (t->timeout_task);
4824   t->timeout_task =
4825       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
4826                                     (refresh_path_time, 4), &tunnel_timeout, t);
4827 }
4828
4829
4830 /******************************************************************************/
4831 /****************      MESH NETWORK HANDLER HELPERS     ***********************/
4832 /******************************************************************************/
4833
4834 /**
4835  * Function to send a create path packet to a peer.
4836  *
4837  * @param cls closure
4838  * @param size number of bytes available in buf
4839  * @param buf where the callee should write the message
4840  * @return number of bytes written to buf
4841  */
4842 static size_t
4843 send_core_path_create (void *cls, size_t size, void *buf)
4844 {
4845   struct MeshPathInfo *info = cls;
4846   struct GNUNET_MESH_ManipulatePath *msg;
4847   struct GNUNET_PeerIdentity *peer_ptr;
4848   struct MeshTunnel *t = info->t;
4849   struct MeshPeerPath *p = info->path;
4850   size_t size_needed;
4851   uint32_t opt;
4852   int i;
4853
4854   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATE PATH sending...\n");
4855   size_needed =
4856       sizeof (struct GNUNET_MESH_ManipulatePath) +
4857       p->length * sizeof (struct GNUNET_PeerIdentity);
4858
4859   if (size < size_needed || NULL == buf)
4860   {
4861     GNUNET_break (0);
4862     return 0;
4863   }
4864   msg = (struct GNUNET_MESH_ManipulatePath *) buf;
4865   msg->header.size = htons (size_needed);
4866   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE);
4867   msg->tid = ntohl (t->id.tid);
4868
4869   opt = 0;
4870   if (GNUNET_YES == t->speed_min)
4871     opt |= MESH_TUNNEL_OPT_SPEED_MIN;
4872   if (GNUNET_YES == t->nobuffer)
4873     opt |= MESH_TUNNEL_OPT_NOBUFFER;
4874   msg->opt = htonl(opt);
4875   msg->reserved = 0;
4876
4877   peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
4878   for (i = 0; i < p->length; i++)
4879   {
4880     GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
4881   }
4882
4883   path_destroy (p);
4884   GNUNET_free (info);
4885
4886   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4887               "CREATE PATH (%u bytes long) sent!\n", size_needed);
4888   return size_needed;
4889 }
4890
4891
4892 /**
4893  * Fill the core buffer 
4894  *
4895  * @param cls closure (data itself)
4896  * @param size number of bytes available in buf
4897  * @param buf where the callee should write the message
4898  *
4899  * @return number of bytes written to buf
4900  */
4901 static size_t
4902 send_core_data_multicast (void *cls, size_t size, void *buf)
4903 {
4904   struct MeshTransmissionDescriptor *info = cls;
4905   size_t total_size;
4906
4907   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Multicast callback.\n");
4908   GNUNET_assert (NULL != info);
4909   GNUNET_assert (NULL != info->peer);
4910   total_size = info->mesh_data->data_len;
4911   GNUNET_assert (total_size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
4912
4913   if (total_size > size)
4914   {
4915     GNUNET_break (0);
4916     return 0;
4917   }
4918   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " copying data...\n");
4919   memcpy (buf, info->mesh_data->data, total_size);
4920 #if MESH_DEBUG
4921   {
4922     struct GNUNET_MESH_Multicast *mc;
4923     struct GNUNET_MessageHeader *mh;
4924
4925     mh = buf;
4926     if (ntohs (mh->type) == GNUNET_MESSAGE_TYPE_MESH_MULTICAST)
4927     {
4928       mc = (struct GNUNET_MESH_Multicast *) mh;
4929       mh = (struct GNUNET_MessageHeader *) &mc[1];
4930       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4931                   " multicast, payload type %s\n",
4932                   GNUNET_MESH_DEBUG_M2S (ntohs (mh->type)));
4933       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4934                   " multicast, payload size %u\n", ntohs (mh->size));
4935     }
4936     else
4937     {
4938       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " type %s\n",
4939                   GNUNET_MESH_DEBUG_M2S (ntohs (mh->type)));
4940     }
4941   }
4942 #endif
4943   data_descriptor_decrement_rc (info->mesh_data);
4944   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "freeing info...\n");
4945   GNUNET_free (info);
4946   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "return %u\n", total_size);
4947   return total_size;
4948 }
4949
4950
4951 /**
4952  * Creates a path ack message in buf and frees all unused resources.
4953  *
4954  * @param cls closure (MeshTransmissionDescriptor)
4955  * @param size number of bytes available in buf
4956  * @param buf where the callee should write the message
4957  * @return number of bytes written to buf
4958  */
4959 static size_t
4960 send_core_path_ack (void *cls, size_t size, void *buf)
4961 {
4962   struct MeshTransmissionDescriptor *info = cls;
4963   struct GNUNET_MESH_PathACK *msg = buf;
4964
4965   GNUNET_assert (NULL != info);
4966   if (sizeof (struct GNUNET_MESH_PathACK) > size)
4967   {
4968     GNUNET_break (0);
4969     return 0;
4970   }
4971   msg->header.size = htons (sizeof (struct GNUNET_MESH_PathACK));
4972   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_ACK);
4973   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
4974   msg->tid = htonl (info->origin->tid);
4975   msg->peer_id = my_full_id;
4976
4977   GNUNET_free (info);
4978   /* TODO add signature */
4979
4980   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "PATH ACK sent!\n");
4981   return sizeof (struct GNUNET_MESH_PathACK);
4982 }
4983
4984
4985 /**
4986  * Free a transmission that was already queued with all resources
4987  * associated to the request.
4988  *
4989  * @param queue Queue handler to cancel.
4990  * @param clear_cls Is it necessary to free associated cls?
4991  */
4992 static void
4993 queue_destroy (struct MeshPeerQueue *queue, int clear_cls)
4994 {
4995   struct MeshTransmissionDescriptor *dd;
4996   struct MeshPathInfo *path_info;
4997   struct MeshTunnelChildInfo *cinfo;
4998   struct GNUNET_PeerIdentity id;
4999   unsigned int i;
5000   unsigned int max;
5001
5002   if (GNUNET_YES == clear_cls)
5003   {
5004     switch (queue->type)
5005     {
5006       case GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY:
5007         GNUNET_log (GNUNET_ERROR_TYPE_INFO, "   cancelling TUNNEL_DESTROY\n");
5008         GNUNET_break (GNUNET_YES == queue->tunnel->destroy);
5009         /* fall through */
5010       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
5011       case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
5012       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
5013       case GNUNET_MESSAGE_TYPE_MESH_ACK:
5014       case GNUNET_MESSAGE_TYPE_MESH_POLL:
5015       case GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE:
5016         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5017                     "   prebuilt message\n");
5018         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5019                     "   type %s\n",
5020                     GNUNET_MESH_DEBUG_M2S(queue->type));
5021         dd = queue->cls;
5022         data_descriptor_decrement_rc (dd->mesh_data);
5023         break;
5024       case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
5025         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   type create path\n");
5026         path_info = queue->cls;
5027         path_destroy (path_info->path);
5028         break;
5029       default:
5030         GNUNET_break (0);
5031         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5032                     "   type %s unknown!\n",
5033                     GNUNET_MESH_DEBUG_M2S(queue->type));
5034     }
5035     GNUNET_free_non_null (queue->cls);
5036   }
5037   GNUNET_CONTAINER_DLL_remove (queue->peer->queue_head,
5038                                queue->peer->queue_tail,
5039                                queue);
5040
5041   /* Delete from child_fc in the appropiate tunnel */
5042   max = queue->tunnel->fwd_queue_max;
5043   GNUNET_PEER_resolve (queue->peer->id, &id);
5044   cinfo = tunnel_get_neighbor_fc (queue->tunnel, &id);
5045   if (NULL != cinfo)
5046   {
5047     for (i = 0; i < cinfo->send_buffer_n; i++)
5048     {
5049       unsigned int i2;
5050       i2 = (cinfo->send_buffer_start + i) % max;
5051       if (cinfo->send_buffer[i2] == queue)
5052       {
5053         /* Found corresponding entry in the send_buffer. Move all others back. */
5054         unsigned int j;
5055         unsigned int j2;
5056         unsigned int j3;
5057
5058         for (j = i, j2 = 0, j3 = 0; j < cinfo->send_buffer_n - 1; j++)
5059         {
5060           j2 = (cinfo->send_buffer_start + j) % max;
5061           j3 = (cinfo->send_buffer_start + j + 1) % max;
5062           cinfo->send_buffer[j2] = cinfo->send_buffer[j3];
5063         }
5064
5065         cinfo->send_buffer[j3] = NULL;
5066         cinfo->send_buffer_n--;
5067       }
5068     }
5069   }
5070
5071   GNUNET_free (queue);
5072 }
5073
5074
5075 /**
5076  * @brief Get the next transmittable message from the queue.
5077  *
5078  * This will be the head, except in the case of being a data packet
5079  * not allowed by the destination peer.
5080  *
5081  * @param peer Destination peer.
5082  *
5083  * @return The next viable MeshPeerQueue element to send to that peer.
5084  *         NULL when there are no transmittable messages.
5085  */
5086 struct MeshPeerQueue *
5087 queue_get_next (const struct MeshPeerInfo *peer)
5088 {
5089   struct MeshPeerQueue *q;
5090   struct MeshTunnel *t;
5091   struct MeshTransmissionDescriptor *info;
5092   struct MeshTunnelChildInfo *cinfo;
5093   struct GNUNET_MESH_Unicast *ucast;
5094   struct GNUNET_MESH_ToOrigin *to_orig;
5095   struct GNUNET_MESH_Multicast *mcast;
5096   struct GNUNET_PeerIdentity id;
5097   uint32_t pid;
5098   uint32_t ack;
5099
5100   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   selecting message\n");
5101   for (q = peer->queue_head; NULL != q; q = q->next)
5102   {
5103     t = q->tunnel;
5104     info = q->cls;
5105     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5106                 "*********     %s\n",
5107                 GNUNET_MESH_DEBUG_M2S(q->type));
5108     switch (q->type)
5109     {
5110       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
5111         ucast = (struct GNUNET_MESH_Unicast *) info->mesh_data->data;
5112         pid = ntohl (ucast->pid);
5113         GNUNET_PEER_resolve (info->peer->id, &id);
5114         cinfo = tunnel_get_neighbor_fc(t, &id);
5115         ack = cinfo->fwd_ack;
5116         break;
5117       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
5118         to_orig = (struct GNUNET_MESH_ToOrigin *) info->mesh_data->data;
5119         pid = ntohl (to_orig->pid);
5120         ack = t->bck_ack;
5121         break;
5122       case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
5123         mcast = (struct GNUNET_MESH_Multicast *) info->mesh_data->data;
5124         if (GNUNET_MESSAGE_TYPE_MESH_MULTICAST != ntohs(mcast->header.type)) 
5125         {
5126           // Not a multicast payload: multicast control traffic (destroy, etc)
5127           return q;
5128         }
5129         pid = ntohl (mcast->pid);
5130         GNUNET_PEER_resolve (info->peer->id, &id);
5131         cinfo = tunnel_get_neighbor_fc(t, &id);
5132         ack = cinfo->fwd_ack;
5133         break;
5134       default:
5135         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5136                     "*********   OK!\n");
5137         return q;
5138     }
5139         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5140                     "*********     ACK: %u, PID: %u\n",
5141                     ack, pid);
5142     if (GNUNET_NO == GMC_is_pid_bigger(pid, ack))
5143     {
5144       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5145                   "*********   OK!\n");
5146       return q;
5147     }
5148     else
5149     {
5150       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5151                   "*********     NEXT!\n");
5152     }
5153   }
5154   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5155                 "*********   nothing found\n");
5156   return NULL;
5157 }
5158
5159
5160 /**
5161   * Core callback to write a queued packet to core buffer
5162   *
5163   * @param cls Closure (peer info).
5164   * @param size Number of bytes available in buf.
5165   * @param buf Where the to write the message.
5166   *
5167   * @return number of bytes written to buf
5168   */
5169 static size_t
5170 queue_send (void *cls, size_t size, void *buf)
5171 {
5172     struct MeshPeerInfo *peer = cls;
5173     struct GNUNET_MessageHeader *msg;
5174     struct MeshPeerQueue *queue;
5175     struct MeshTunnel *t;
5176     struct MeshTunnelChildInfo *cinfo;
5177     struct GNUNET_PeerIdentity dst_id;
5178     size_t data_size;
5179
5180     peer->core_transmit = NULL;
5181     cinfo = NULL;
5182
5183     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "********* Queue send\n");
5184     queue = queue_get_next (peer);
5185
5186     /* Queue has no internal mesh traffic nor sendable payload */
5187     if (NULL == queue)
5188     {
5189       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   not ready, return\n");
5190       if (NULL == peer->queue_head)
5191         GNUNET_break (0); // Should've been canceled
5192       return 0;
5193     }
5194     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   not empty\n");
5195
5196     GNUNET_PEER_resolve (peer->id, &dst_id);
5197     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5198                 "*********   towards %s\n",
5199                 GNUNET_i2s(&dst_id));
5200     /* Check if buffer size is enough for the message */
5201     if (queue->size > size)
5202     {
5203         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5204                     "*********   not enough room, reissue\n");
5205         peer->core_transmit =
5206             GNUNET_CORE_notify_transmit_ready (core_handle,
5207                                                0,
5208                                                0,
5209                                                GNUNET_TIME_UNIT_FOREVER_REL,
5210                                                &dst_id,
5211                                                queue->size,
5212                                                &queue_send,
5213                                                peer);
5214         return 0;
5215     }
5216     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   size ok\n");
5217
5218     t = queue->tunnel;
5219     GNUNET_assert (0 < t->pending_messages);
5220     t->pending_messages--;
5221     if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == queue->type)
5222     {
5223       t->fwd_queue_n--;
5224       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5225                   "*********   unicast: t->q (%u/%u)\n",
5226                   t->fwd_queue_n, t->fwd_queue_max);
5227     }
5228     else if (GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == queue->type)
5229     {
5230       t->bck_queue_n--;
5231       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   to origin\n");
5232     }
5233
5234     /* Fill buf */
5235     switch (queue->type)
5236     {
5237       case 0:
5238       case GNUNET_MESSAGE_TYPE_MESH_ACK:
5239       case GNUNET_MESSAGE_TYPE_MESH_POLL:
5240       case GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN:
5241       case GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY:
5242       case GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY:
5243         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5244                     "*********   raw: %s\n",
5245                     GNUNET_MESH_DEBUG_M2S (queue->type));
5246         /* Fall through */
5247       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
5248       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
5249         data_size = send_core_data_raw (queue->cls, size, buf);
5250         msg = (struct GNUNET_MessageHeader *) buf;
5251         switch (ntohs (msg->type)) // Type of preconstructed message
5252         {
5253           case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
5254             tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_UNICAST);
5255             break;
5256           case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
5257             tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
5258             break;
5259           default:
5260               break;
5261         }
5262         break;
5263       case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
5264         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   multicast\n");
5265         {
5266           struct MeshTransmissionDescriptor *info = queue->cls;
5267
5268           if ((1 == info->mesh_data->reference_counter
5269               && GNUNET_YES == t->speed_min)
5270               ||
5271               (info->mesh_data->total_out == info->mesh_data->reference_counter
5272               && GNUNET_NO == t->speed_min))
5273           {
5274             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5275                         "*********   considered sent\n");
5276             t->fwd_queue_n--;
5277           }
5278           else
5279           {
5280             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5281                         "*********   NOT considered sent yet\n");
5282             t->pending_messages++;
5283           }
5284         }
5285         data_size = send_core_data_multicast(queue->cls, size, buf);
5286         tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
5287         break;
5288       case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
5289         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path create\n");
5290         data_size = send_core_path_create (queue->cls, size, buf);
5291         break;
5292       case GNUNET_MESSAGE_TYPE_MESH_PATH_ACK:
5293         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path ack\n");
5294         data_size = send_core_path_ack (queue->cls, size, buf);
5295         break;
5296       case GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE:
5297         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path keepalive\n");
5298         data_size = send_core_data_multicast (queue->cls, size, buf);
5299         break;
5300       default:
5301         GNUNET_break (0);
5302         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5303                     "*********   type unknown: %u\n",
5304                     queue->type);
5305         data_size = 0;
5306     }
5307     switch (queue->type)
5308     {
5309       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
5310       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
5311       case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
5312         cinfo = tunnel_get_neighbor_fc (t, &dst_id);
5313         if (cinfo->send_buffer[cinfo->send_buffer_start] != queue)
5314         {
5315           GNUNET_break (0);
5316           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5317                       "at pos %u (%p) != %p\n",
5318                       cinfo->send_buffer_start,
5319                       cinfo->send_buffer[cinfo->send_buffer_start],
5320                       queue);
5321         }
5322         if (cinfo->send_buffer_n > 0)
5323         {
5324           cinfo->send_buffer[cinfo->send_buffer_start] = NULL;
5325           cinfo->send_buffer_n--;
5326           cinfo->send_buffer_start++;
5327           cinfo->send_buffer_start %= t->fwd_queue_max;
5328         }
5329         else
5330         {
5331           GNUNET_break (0);
5332         }
5333         break;
5334       default:
5335         break;
5336     }
5337
5338     /* Free queue, but cls was freed by send_core_* */
5339     queue_destroy (queue, GNUNET_NO);
5340
5341     if (GNUNET_YES == t->destroy && 0 == t->pending_messages)
5342     {
5343       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********  destroying tunnel!\n");
5344       tunnel_destroy (t);
5345     }
5346
5347     /* If more data in queue, send next */
5348     queue = queue_get_next(peer);
5349     if (NULL != queue)
5350     {
5351         struct GNUNET_PeerIdentity id;
5352
5353         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   more data!\n");
5354         GNUNET_PEER_resolve (peer->id, &id);
5355         peer->core_transmit =
5356             GNUNET_CORE_notify_transmit_ready(core_handle,
5357                                               0,
5358                                               0,
5359                                               GNUNET_TIME_UNIT_FOREVER_REL,
5360                                               &id,
5361                                               queue->size,
5362                                               &queue_send,
5363                                               peer);
5364     }
5365     else
5366     {
5367       if (NULL != peer->queue_head)
5368       {
5369         GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5370                     "*********   %s stalled\n",
5371                     GNUNET_i2s(&my_full_id));
5372         if (NULL == cinfo)
5373           cinfo = tunnel_get_neighbor_fc (t, &dst_id);
5374         // FIXME unify bck/fwd structures, bck does not have cinfo right now
5375         if (NULL != cinfo && GNUNET_SCHEDULER_NO_TASK == cinfo->fc_poll)
5376         {
5377           cinfo->fc_poll = GNUNET_SCHEDULER_add_delayed (cinfo->fc_poll_time,
5378                                                          &tunnel_poll, cinfo);
5379         }
5380       }
5381     }
5382     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   return %d\n", data_size);
5383     return data_size;
5384 }
5385
5386
5387 /**
5388  * @brief Queue and pass message to core when possible.
5389  * 
5390  * If type is payload (UNICAST, TO_ORIGIN, MULTICAST) checks for queue status
5391  * and accounts for it. In case the queue is full, the message is dropped and
5392  * a break issued.
5393  * 
5394  * Otherwise, message is treated as internal and allowed to go regardless of 
5395  * queue status.
5396  *
5397  * @param cls Closure (@c type dependant). It will be used by queue_send to
5398  *            build the message to be sent if not already prebuilt.
5399  * @param type Type of the message, 0 for a raw message.
5400  * @param size Size of the message.
5401  * @param dst Neighbor to send message to.
5402  * @param t Tunnel this message belongs to.
5403  */
5404 static void
5405 queue_add (void *cls, uint16_t type, size_t size,
5406            struct MeshPeerInfo *dst, struct MeshTunnel *t)
5407 {
5408   struct MeshPeerQueue *queue;
5409   struct MeshTunnelChildInfo *cinfo;
5410   struct GNUNET_PeerIdentity id;
5411   unsigned int *max;
5412   unsigned int *n;
5413   unsigned int i;
5414
5415   n = NULL;
5416   if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == type ||
5417       GNUNET_MESSAGE_TYPE_MESH_MULTICAST == type)
5418   {
5419     n = &t->fwd_queue_n;
5420     max = &t->fwd_queue_max;
5421   }
5422   else if (GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == type)
5423   {
5424     n = &t->bck_queue_n;
5425     max = &t->bck_queue_max;
5426   }
5427   if (NULL != n)
5428   {
5429     if (*n >= *max)
5430     {
5431       GNUNET_break(0);
5432       GNUNET_STATISTICS_update(stats,
5433                                "# messages dropped (buffer full)",
5434                                1, GNUNET_NO);
5435       return; // Drop message
5436     }
5437     (*n)++;
5438   }
5439   queue = GNUNET_malloc (sizeof (struct MeshPeerQueue));
5440   queue->cls = cls;
5441   queue->type = type;
5442   queue->size = size;
5443   queue->peer = dst;
5444   queue->tunnel = t;
5445   GNUNET_CONTAINER_DLL_insert_tail (dst->queue_head, dst->queue_tail, queue);
5446   GNUNET_PEER_resolve (dst->id, &id);
5447   if (NULL == dst->core_transmit)
5448   {
5449       dst->core_transmit =
5450           GNUNET_CORE_notify_transmit_ready (core_handle,
5451                                              0,
5452                                              0,
5453                                              GNUNET_TIME_UNIT_FOREVER_REL,
5454                                              &id,
5455                                              size,
5456                                              &queue_send,
5457                                              dst);
5458   }
5459   t->pending_messages++;
5460   if (NULL == n) // Is this internal mesh traffic?
5461     return;
5462
5463   // It's payload, keep track of buffer per peer.
5464   cinfo = tunnel_get_neighbor_fc(t, &id);
5465   i = (cinfo->send_buffer_start + cinfo->send_buffer_n) % t->fwd_queue_max;
5466   if (NULL != cinfo->send_buffer[i])
5467   {
5468     GNUNET_break (cinfo->send_buffer_n == t->fwd_queue_max); // aka i == start
5469     queue_destroy (cinfo->send_buffer[cinfo->send_buffer_start], GNUNET_YES);
5470     cinfo->send_buffer_start++;
5471     cinfo->send_buffer_start %= t->fwd_queue_max;
5472   }
5473   else
5474   {
5475     cinfo->send_buffer_n++;
5476   }
5477   cinfo->send_buffer[i] = queue;
5478   if (cinfo->send_buffer_n > t->fwd_queue_max)
5479   {
5480     GNUNET_break (0);
5481     cinfo->send_buffer_n = t->fwd_queue_max;
5482   }
5483 }
5484
5485
5486 /******************************************************************************/
5487 /********************      MESH NETWORK HANDLERS     **************************/
5488 /******************************************************************************/
5489
5490
5491 /**
5492  * Core handler for path creation
5493  *
5494  * @param cls closure
5495  * @param message message
5496  * @param peer peer identity this notification is about
5497  * @param atsi performance data
5498  * @param atsi_count number of records in 'atsi'
5499  *
5500  * @return GNUNET_OK to keep the connection open,
5501  *         GNUNET_SYSERR to close it (signal serious error)
5502  */
5503 static int
5504 handle_mesh_path_create (void *cls, const struct GNUNET_PeerIdentity *peer,
5505                          const struct GNUNET_MessageHeader *message,
5506                          const struct GNUNET_ATS_Information *atsi,
5507                          unsigned int atsi_count)
5508 {
5509   unsigned int own_pos;
5510   uint16_t size;
5511   uint16_t i;
5512   MESH_TunnelNumber tid;
5513   struct GNUNET_MESH_ManipulatePath *msg;
5514   struct GNUNET_PeerIdentity *pi;
5515   struct GNUNET_HashCode hash;
5516   struct MeshPeerPath *path;
5517   struct MeshPeerInfo *dest_peer_info;
5518   struct MeshPeerInfo *orig_peer_info;
5519   struct MeshTunnel *t;
5520
5521   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5522               "Received a path create msg [%s]\n",
5523               GNUNET_i2s (&my_full_id));
5524   size = ntohs (message->size);
5525   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
5526   {
5527     GNUNET_break_op (0);
5528     return GNUNET_OK;
5529   }
5530
5531   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
5532   if (size % sizeof (struct GNUNET_PeerIdentity))
5533   {
5534     GNUNET_break_op (0);
5535     return GNUNET_OK;
5536   }
5537   size /= sizeof (struct GNUNET_PeerIdentity);
5538   if (size < 2)
5539   {
5540     GNUNET_break_op (0);
5541     return GNUNET_OK;
5542   }
5543   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
5544   msg = (struct GNUNET_MESH_ManipulatePath *) message;
5545
5546   tid = ntohl (msg->tid);
5547   pi = (struct GNUNET_PeerIdentity *) &msg[1];
5548   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5549               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi), tid);
5550   t = tunnel_get (pi, tid);
5551   if (NULL == t) // FIXME only for INCOMING tunnels?
5552   {
5553     uint32_t opt;
5554
5555     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating tunnel\n");
5556     t = tunnel_new (GNUNET_PEER_intern (pi), tid, NULL, 0);
5557     if (NULL == t)
5558     {
5559       // FIXME notify failure
5560       return GNUNET_OK;
5561     }
5562     opt = ntohl (msg->opt);
5563     t->speed_min = (0 != (opt & MESH_TUNNEL_OPT_SPEED_MIN)) ?
5564                    GNUNET_YES : GNUNET_NO;
5565     if (0 != (opt & MESH_TUNNEL_OPT_NOBUFFER))
5566     {
5567       t->nobuffer = GNUNET_YES;
5568       t->last_fwd_ack = t->fwd_pid + 1;
5569     }
5570     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5571                 "  speed_min: %d, nobuffer:%d\n",
5572                 t->speed_min, t->nobuffer);
5573
5574     if (GNUNET_YES == t->nobuffer)
5575     {
5576       t->bck_queue_max = 1;
5577       t->fwd_queue_max = 1;
5578     }
5579
5580     // FIXME only assign a local tid if a local client is interested (on demand)
5581     while (NULL != tunnel_get_incoming (next_local_tid))
5582       next_local_tid = (next_local_tid + 1) | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
5583     t->local_tid_dest = next_local_tid++;
5584     next_local_tid = next_local_tid | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
5585     // FIXME end
5586
5587     tunnel_reset_timeout (t);
5588     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
5589     if (GNUNET_OK !=
5590         GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
5591                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
5592     {
5593       tunnel_destroy (t);
5594       GNUNET_break (0);
5595       return GNUNET_OK;
5596     }
5597   }
5598   dest_peer_info =
5599       GNUNET_CONTAINER_multihashmap_get (peers, &pi[size - 1].hashPubKey);
5600   if (NULL == dest_peer_info)
5601   {
5602     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5603                 "  Creating PeerInfo for destination.\n");
5604     dest_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
5605     dest_peer_info->id = GNUNET_PEER_intern (&pi[size - 1]);
5606     GNUNET_CONTAINER_multihashmap_put (peers, &pi[size - 1].hashPubKey,
5607                                        dest_peer_info,
5608                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
5609   }
5610   orig_peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &pi->hashPubKey);
5611   if (NULL == orig_peer_info)
5612   {
5613     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5614                 "  Creating PeerInfo for origin.\n");
5615     orig_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
5616     orig_peer_info->id = GNUNET_PEER_intern (pi);
5617     GNUNET_CONTAINER_multihashmap_put (peers, &pi->hashPubKey, orig_peer_info,
5618                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
5619   }
5620   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
5621   path = path_new (size);
5622   own_pos = 0;
5623   for (i = 0; i < size; i++)
5624   {
5625     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
5626                 GNUNET_i2s (&pi[i]));
5627     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
5628     if (path->peers[i] == myid)
5629       own_pos = i;
5630   }
5631   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
5632   if (own_pos == 0)
5633   {
5634     /* cannot be self, must be 'not found' */
5635     /* create path: self not found in path through self */
5636     GNUNET_break_op (0);
5637     path_destroy (path);
5638     tunnel_destroy (t);
5639     return GNUNET_OK;
5640   }
5641   path_add_to_peers (path, GNUNET_NO);
5642   tunnel_add_path (t, path, own_pos);
5643   if (own_pos == size - 1)
5644   {
5645     /* It is for us! Send ack. */
5646     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
5647     peer_info_add_path_to_origin (orig_peer_info, path, GNUNET_NO);
5648     if (NULL == t->peers)
5649     {
5650       /* New tunnel! Notify clients on first payload message. */
5651       t->peers = GNUNET_CONTAINER_multihashmap_create (4, GNUNET_NO);
5652     }
5653     GNUNET_break (GNUNET_SYSERR !=
5654                   GNUNET_CONTAINER_multihashmap_put (t->peers,
5655                                                      &my_full_id.hashPubKey,
5656                                                      peer_info_get
5657                                                      (&my_full_id),
5658                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE));
5659     send_path_ack (t);
5660   }
5661   else
5662   {
5663     struct MeshPeerPath *path2;
5664
5665     /* It's for somebody else! Retransmit. */
5666     path2 = path_duplicate (path);
5667     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Retransmitting.\n");
5668     peer_info_add_path (dest_peer_info, path2, GNUNET_NO);
5669     path2 = path_duplicate (path);
5670     peer_info_add_path_to_origin (orig_peer_info, path2, GNUNET_NO);
5671     send_create_path (dest_peer_info, path, t);
5672   }
5673   return GNUNET_OK;
5674 }
5675
5676
5677 /**
5678  * Core handler for path destruction
5679  *
5680  * @param cls closure
5681  * @param message message
5682  * @param peer peer identity this notification is about
5683  * @param atsi performance data
5684  * @param atsi_count number of records in 'atsi'
5685  *
5686  * @return GNUNET_OK to keep the connection open,
5687  *         GNUNET_SYSERR to close it (signal serious error)
5688  */
5689 static int
5690 handle_mesh_path_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
5691                           const struct GNUNET_MessageHeader *message,
5692                           const struct GNUNET_ATS_Information *atsi,
5693                           unsigned int atsi_count)
5694 {
5695   struct GNUNET_MESH_ManipulatePath *msg;
5696   struct GNUNET_PeerIdentity *pi;
5697   struct MeshPeerPath *path;
5698   struct MeshTunnel *t;
5699   unsigned int own_pos;
5700   unsigned int i;
5701   size_t size;
5702
5703   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5704               "Received a PATH DESTROY msg from %s\n", GNUNET_i2s (peer));
5705   size = ntohs (message->size);
5706   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
5707   {
5708     GNUNET_break_op (0);
5709     return GNUNET_OK;
5710   }
5711
5712   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
5713   if (size % sizeof (struct GNUNET_PeerIdentity))
5714   {
5715     GNUNET_break_op (0);
5716     return GNUNET_OK;
5717   }
5718   size /= sizeof (struct GNUNET_PeerIdentity);
5719   if (size < 2)
5720   {
5721     GNUNET_break_op (0);
5722     return GNUNET_OK;
5723   }
5724   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
5725
5726   msg = (struct GNUNET_MESH_ManipulatePath *) message;
5727   pi = (struct GNUNET_PeerIdentity *) &msg[1];
5728   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5729               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi),
5730               msg->tid);
5731   t = tunnel_get (pi, ntohl (msg->tid));
5732   if (NULL == t)
5733   {
5734     /* TODO notify back: we don't know this tunnel */
5735     GNUNET_break_op (0);
5736     return GNUNET_OK;
5737   }
5738   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
5739   path = path_new (size);
5740   own_pos = 0;
5741   for (i = 0; i < size; i++)
5742   {
5743     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
5744                 GNUNET_i2s (&pi[i]));
5745     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
5746     if (path->peers[i] == myid)
5747       own_pos = i;
5748   }
5749   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
5750   if (own_pos < path->length - 1)
5751     send_prebuilt_message (message, &pi[own_pos + 1], t);
5752   else
5753     send_client_tunnel_disconnect(t, NULL);
5754
5755   tunnel_delete_peer (t, path->peers[path->length - 1]);
5756   path_destroy (path);
5757   return GNUNET_OK;
5758 }
5759
5760
5761 /**
5762  * Core handler for notifications of broken paths
5763  *
5764  * @param cls closure
5765  * @param message message
5766  * @param peer peer identity this notification is about
5767  * @param atsi performance data
5768  * @param atsi_count number of records in 'atsi'
5769  *
5770  * @return GNUNET_OK to keep the connection open,
5771  *         GNUNET_SYSERR to close it (signal serious error)
5772  */
5773 static int
5774 handle_mesh_path_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
5775                          const struct GNUNET_MessageHeader *message,
5776                          const struct GNUNET_ATS_Information *atsi,
5777                          unsigned int atsi_count)
5778 {
5779   struct GNUNET_MESH_PathBroken *msg;
5780   struct MeshTunnel *t;
5781
5782   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5783               "Received a PATH BROKEN msg from %s\n", GNUNET_i2s (peer));
5784   msg = (struct GNUNET_MESH_PathBroken *) message;
5785   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
5786               GNUNET_i2s (&msg->peer1));
5787   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
5788               GNUNET_i2s (&msg->peer2));
5789   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5790   if (NULL == t)
5791   {
5792     GNUNET_break_op (0);
5793     return GNUNET_OK;
5794   }
5795   tunnel_notify_connection_broken (t, GNUNET_PEER_search (&msg->peer1),
5796                                    GNUNET_PEER_search (&msg->peer2));
5797   return GNUNET_OK;
5798
5799 }
5800
5801
5802 /**
5803  * Core handler for tunnel destruction
5804  *
5805  * @param cls closure
5806  * @param message message
5807  * @param peer peer identity this notification is about
5808  * @param atsi performance data
5809  * @param atsi_count number of records in 'atsi'
5810  *
5811  * @return GNUNET_OK to keep the connection open,
5812  *         GNUNET_SYSERR to close it (signal serious error)
5813  */
5814 static int
5815 handle_mesh_tunnel_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
5816                             const struct GNUNET_MessageHeader *message,
5817                             const struct GNUNET_ATS_Information *atsi,
5818                             unsigned int atsi_count)
5819 {
5820   struct GNUNET_MESH_TunnelDestroy *msg;
5821   struct MeshTunnel *t;
5822   GNUNET_PEER_Id parent;
5823   GNUNET_PEER_Id pid;
5824
5825   msg = (struct GNUNET_MESH_TunnelDestroy *) message;
5826   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5827               "Got a TUNNEL DESTROY packet from %s\n",
5828               GNUNET_i2s (peer));
5829   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5830               "  for tunnel %s [%u]\n",
5831               GNUNET_i2s (&msg->oid), ntohl (msg->tid));
5832   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5833   /* Check signature */
5834   if (NULL == t)
5835   {
5836     /* Probably already got the message from another path,
5837      * destroyed the tunnel and retransmitted to children.
5838      * Safe to ignore.
5839      */
5840     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel",
5841                               1, GNUNET_NO);
5842     return GNUNET_OK;
5843   }
5844   parent = tree_get_predecessor(t->tree);
5845   pid = GNUNET_PEER_search (peer);
5846   if (pid != parent)
5847   {
5848     tree_del_peer (t->tree, pid, &tunnel_child_removed, t);
5849     if (tree_count_children(t->tree) > 0 ||
5850       NULL != t->owner ||
5851       t->nclients > 0)
5852       return GNUNET_OK;
5853   }
5854   if (t->local_tid_dest >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
5855   {
5856     /* Tunnel was incoming, notify clients */
5857     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "INCOMING TUNNEL %X %X\n",
5858                 t->local_tid, t->local_tid_dest);
5859     send_clients_tunnel_destroy (t);
5860   }
5861   tunnel_send_destroy (t, GNUNET_YES);
5862   t->destroy = GNUNET_YES;
5863   // TODO: add timeout to destroy the tunnel anyway
5864   return GNUNET_OK;
5865 }
5866
5867
5868 /**
5869  * Core handler for mesh network traffic going from the origin to a peer
5870  *
5871  * @param cls closure
5872  * @param peer peer identity this notification is about
5873  * @param message message
5874  * @param atsi performance data
5875  * @param atsi_count number of records in 'atsi'
5876  * @return GNUNET_OK to keep the connection open,
5877  *         GNUNET_SYSERR to close it (signal serious error)
5878  */
5879 static int
5880 handle_mesh_data_unicast (void *cls, const struct GNUNET_PeerIdentity *peer,
5881                           const struct GNUNET_MessageHeader *message,
5882                           const struct GNUNET_ATS_Information *atsi,
5883                           unsigned int atsi_count)
5884 {
5885   struct GNUNET_MESH_Unicast *msg;
5886   struct GNUNET_PeerIdentity *neighbor;
5887   struct MeshTunnelChildInfo *cinfo;
5888   struct MeshTunnel *t;
5889   GNUNET_PEER_Id dest_id;
5890   uint32_t pid;
5891   uint32_t ttl;
5892   size_t size;
5893
5894   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a unicast packet from %s\n",
5895               GNUNET_i2s (peer));
5896   /* Check size */
5897   size = ntohs (message->size);
5898   if (size <
5899       sizeof (struct GNUNET_MESH_Unicast) +
5900       sizeof (struct GNUNET_MessageHeader))
5901   {
5902     GNUNET_break (0);
5903     return GNUNET_OK;
5904   }
5905   msg = (struct GNUNET_MESH_Unicast *) message;
5906   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %s\n",
5907               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
5908   /* Check tunnel */
5909   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5910   if (NULL == t)
5911   {
5912     /* TODO notify back: we don't know this tunnel */
5913     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
5914     GNUNET_break_op (0);
5915     return GNUNET_OK;
5916   }
5917   pid = ntohl (msg->pid);
5918   if (t->fwd_pid == pid)
5919   {
5920     GNUNET_STATISTICS_update (stats, "# duplicate PID drops", 1, GNUNET_NO);
5921     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5922                 " Already seen pid %u, DROPPING!\n", pid);
5923     return GNUNET_OK;
5924   }
5925   else
5926   {
5927     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5928                 " pid %u not seen yet, forwarding\n", pid);
5929   }
5930
5931   t->skip += (pid - t->fwd_pid) - 1;
5932   t->fwd_pid = pid;
5933
5934   if (GMC_is_pid_bigger (pid, t->last_fwd_ack))
5935   {
5936     GNUNET_STATISTICS_update (stats, "# unsolicited unicast", 1, GNUNET_NO);
5937     GNUNET_break_op (0);
5938     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5939                 "Received PID %u, ACK %u\n",
5940                 pid, t->last_fwd_ack);
5941     return GNUNET_OK;
5942   }
5943
5944   tunnel_reset_timeout (t);
5945   dest_id = GNUNET_PEER_search (&msg->destination);
5946   if (dest_id == myid)
5947   {
5948     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5949                 "  it's for us! sending to clients...\n");
5950     GNUNET_STATISTICS_update (stats, "# unicast received", 1, GNUNET_NO);
5951     send_subscribed_clients (message, &msg[1].header, t);
5952     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_UNICAST);
5953     return GNUNET_OK;
5954   }
5955   ttl = ntohl (msg->ttl);
5956   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ttl);
5957   if (ttl == 0)
5958   {
5959     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
5960     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
5961     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5962     return GNUNET_OK;
5963   }
5964   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5965               "  not for us, retransmitting...\n");
5966
5967   neighbor = tree_get_first_hop (t->tree, dest_id);
5968   cinfo = tunnel_get_neighbor_fc (t, neighbor);
5969   cinfo->fwd_pid = pid;
5970   GNUNET_CONTAINER_multihashmap_iterate (t->children_fc,
5971                                          &tunnel_add_skip,
5972                                          &neighbor);
5973   if (GNUNET_YES == t->nobuffer &&
5974       GNUNET_YES == GMC_is_pid_bigger (pid, cinfo->fwd_ack))
5975   {
5976     GNUNET_STATISTICS_update (stats, "# unsolicited unicast", 1, GNUNET_NO);
5977     GNUNET_log (GNUNET_ERROR_TYPE_INFO, "  %u > %u\n", pid, cinfo->fwd_ack);
5978     GNUNET_break_op (0);
5979     return GNUNET_OK;
5980   }
5981   send_prebuilt_message (message, neighbor, t);
5982   GNUNET_STATISTICS_update (stats, "# unicast forwarded", 1, GNUNET_NO);
5983   return GNUNET_OK;
5984 }
5985
5986
5987 /**
5988  * Core handler for mesh network traffic going from the origin to all peers
5989  *
5990  * @param cls closure
5991  * @param message message
5992  * @param peer peer identity this notification is about
5993  * @param atsi performance data
5994  * @param atsi_count number of records in 'atsi'
5995  * @return GNUNET_OK to keep the connection open,
5996  *         GNUNET_SYSERR to close it (signal serious error)
5997  *
5998  * TODO: Check who we got this from, to validate route.
5999  */
6000 static int
6001 handle_mesh_data_multicast (void *cls, const struct GNUNET_PeerIdentity *peer,
6002                             const struct GNUNET_MessageHeader *message,
6003                             const struct GNUNET_ATS_Information *atsi,
6004                             unsigned int atsi_count)
6005 {
6006   struct GNUNET_MESH_Multicast *msg;
6007   struct MeshTunnel *t;
6008   size_t size;
6009   uint32_t pid;
6010
6011   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a multicast packet from %s\n",
6012               GNUNET_i2s (peer));
6013   size = ntohs (message->size);
6014   if (sizeof (struct GNUNET_MESH_Multicast) +
6015       sizeof (struct GNUNET_MessageHeader) > size)
6016   {
6017     GNUNET_break_op (0);
6018     return GNUNET_OK;
6019   }
6020   msg = (struct GNUNET_MESH_Multicast *) message;
6021   t = tunnel_get (&msg->oid, ntohl (msg->tid));
6022
6023   if (NULL == t)
6024   {
6025     /* TODO notify that we dont know that tunnel */
6026     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
6027     GNUNET_break_op (0);
6028     return GNUNET_OK;
6029   }
6030   pid = ntohl (msg->pid);
6031   if (t->fwd_pid == pid)
6032   {
6033     /* already seen this packet, drop */
6034     GNUNET_STATISTICS_update (stats, "# duplicate PID drops", 1, GNUNET_NO);
6035     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6036                 " Already seen pid %u, DROPPING!\n", pid);
6037     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
6038     return GNUNET_OK;
6039   }
6040   else
6041   {
6042     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6043                 " pid %u not seen yet, forwarding\n", pid);
6044   }
6045   t->skip += (pid - t->fwd_pid) - 1;
6046   t->fwd_pid = pid;
6047   tunnel_reset_timeout (t);
6048
6049   /* Transmit to locally interested clients */
6050   if (NULL != t->peers &&
6051       GNUNET_CONTAINER_multihashmap_contains (t->peers, &my_full_id.hashPubKey))
6052   {
6053     GNUNET_STATISTICS_update (stats, "# multicast received", 1, GNUNET_NO);
6054     send_subscribed_clients (message, &msg[1].header, t);
6055     tunnel_send_fwd_ack(t, GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
6056   }
6057   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ntohl (msg->ttl));
6058   if (ntohl (msg->ttl) == 0)
6059   {
6060     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
6061     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
6062     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
6063     return GNUNET_OK;
6064   }
6065   GNUNET_STATISTICS_update (stats, "# multicast forwarded", 1, GNUNET_NO);
6066   tunnel_send_multicast (t, message);
6067   return GNUNET_OK;
6068 }
6069
6070
6071 /**
6072  * Core handler for mesh network traffic toward the owner of a tunnel
6073  *
6074  * @param cls closure
6075  * @param message message
6076  * @param peer peer identity this notification is about
6077  * @param atsi performance data
6078  * @param atsi_count number of records in 'atsi'
6079  *
6080  * @return GNUNET_OK to keep the connection open,
6081  *         GNUNET_SYSERR to close it (signal serious error)
6082  */
6083 static int
6084 handle_mesh_data_to_orig (void *cls, const struct GNUNET_PeerIdentity *peer,
6085                           const struct GNUNET_MessageHeader *message,
6086                           const struct GNUNET_ATS_Information *atsi,
6087                           unsigned int atsi_count)
6088 {
6089   struct GNUNET_MESH_ToOrigin *msg;
6090   struct GNUNET_PeerIdentity id;
6091   struct MeshPeerInfo *peer_info;
6092   struct MeshTunnel *t;
6093   struct MeshTunnelChildInfo *cinfo;
6094   GNUNET_PEER_Id predecessor;
6095   size_t size;
6096   uint32_t pid;
6097
6098   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a ToOrigin packet from %s\n",
6099               GNUNET_i2s (peer));
6100   size = ntohs (message->size);
6101   if (size < sizeof (struct GNUNET_MESH_ToOrigin) +     /* Payload must be */
6102       sizeof (struct GNUNET_MessageHeader))     /* at least a header */
6103   {
6104     GNUNET_break_op (0);
6105     return GNUNET_OK;
6106   }
6107   msg = (struct GNUNET_MESH_ToOrigin *) message;
6108   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %s\n",
6109               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
6110   t = tunnel_get (&msg->oid, ntohl (msg->tid));
6111   pid = ntohl (msg->pid);
6112
6113   if (NULL == t)
6114   {
6115     /* TODO notify that we dont know this tunnel (whom)? */
6116     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
6117     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6118                 "Received to_origin with PID %u on unknown tunnel %s [%u]\n",
6119                 pid, GNUNET_i2s (&msg->oid), ntohl (msg->tid));
6120     return GNUNET_OK;
6121   }
6122
6123   cinfo = tunnel_get_neighbor_fc(t, peer);
6124   if (NULL == cinfo)
6125   {
6126     GNUNET_break (0);
6127     return GNUNET_OK;
6128   }
6129
6130   if (cinfo->bck_pid == pid)
6131   {
6132     /* already seen this packet, drop */
6133     GNUNET_STATISTICS_update (stats, "# duplicate PID drops BCK", 1, GNUNET_NO);
6134     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6135                 " Already seen pid %u, DROPPING!\n", pid);
6136     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
6137     return GNUNET_OK;
6138   }
6139
6140   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6141               " pid %u not seen yet, forwarding\n", pid);
6142   cinfo->bck_pid = pid;
6143
6144   if (NULL != t->owner)
6145   {
6146     char cbuf[size];
6147     struct GNUNET_MESH_ToOrigin *copy;
6148
6149     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6150                 "  it's for us! sending to clients...\n");
6151     /* TODO signature verification */
6152     memcpy (cbuf, message, size);
6153     copy = (struct GNUNET_MESH_ToOrigin *) cbuf;
6154     copy->tid = htonl (t->local_tid);
6155     t->bck_pid++;
6156     copy->pid = htonl (t->bck_pid);
6157     GNUNET_STATISTICS_update (stats, "# to origin received", 1, GNUNET_NO);
6158     GNUNET_SERVER_notification_context_unicast (nc, t->owner->handle,
6159                                                 &copy->header, GNUNET_NO);
6160     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
6161     return GNUNET_OK;
6162   }
6163   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6164               "  not for us, retransmitting...\n");
6165
6166   peer_info = peer_info_get (&msg->oid);
6167   if (NULL == peer_info)
6168   {
6169     /* unknown origin of tunnel */
6170     GNUNET_break (0);
6171     return GNUNET_OK;
6172   }
6173   predecessor = tree_get_predecessor (t->tree);
6174   if (0 == predecessor)
6175   {
6176     if (GNUNET_YES == t->destroy)
6177     {
6178       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6179                   "to orig received on a dying tunnel %s [%X]\n",
6180                   GNUNET_i2s (&msg->oid), ntohl(msg->tid));
6181       return GNUNET_OK;
6182     }
6183     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
6184                 "unknown to origin at %s\n",
6185                 GNUNET_i2s (&my_full_id));
6186     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
6187                 "from peer %s\n",
6188                 GNUNET_i2s (peer));
6189     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
6190                 "for tunnel %s [%X]\n",
6191                 GNUNET_i2s (&msg->oid), ntohl(msg->tid));
6192     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
6193                 "current tree:\n");
6194     tree_debug (t->tree);
6195     return GNUNET_OK;
6196   }
6197   GNUNET_PEER_resolve (predecessor, &id);
6198   send_prebuilt_message (message, &id, t);
6199   GNUNET_STATISTICS_update (stats, "# to origin forwarded", 1, GNUNET_NO);
6200
6201   return GNUNET_OK;
6202 }
6203
6204
6205 /**
6206  * Core handler for mesh network traffic point-to-point acks.
6207  *
6208  * @param cls closure
6209  * @param message message
6210  * @param peer peer identity this notification is about
6211  * @param atsi performance data
6212  * @param atsi_count number of records in 'atsi'
6213  *
6214  * @return GNUNET_OK to keep the connection open,
6215  *         GNUNET_SYSERR to close it (signal serious error)
6216  */
6217 static int
6218 handle_mesh_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
6219                  const struct GNUNET_MessageHeader *message,
6220                  const struct GNUNET_ATS_Information *atsi,
6221                  unsigned int atsi_count)
6222 {
6223   struct GNUNET_MESH_ACK *msg;
6224   struct MeshTunnel *t;
6225   uint32_t ack;
6226
6227   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK packet from %s!\n",
6228               GNUNET_i2s (peer));
6229   msg = (struct GNUNET_MESH_ACK *) message;
6230
6231   t = tunnel_get (&msg->oid, ntohl (msg->tid));
6232
6233   if (NULL == t)
6234   {
6235     /* TODO notify that we dont know this tunnel (whom)? */
6236     GNUNET_STATISTICS_update (stats, "# ack on unknown tunnel", 1, GNUNET_NO);
6237     return GNUNET_OK;
6238   }
6239   ack = ntohl (msg->pid);
6240   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ACK %u\n", ack);
6241
6242   /* Is this a forward or backward ACK? */
6243   if (tree_get_predecessor(t->tree) != GNUNET_PEER_search(peer))
6244   {
6245     struct MeshTunnelChildInfo *cinfo;
6246
6247     debug_bck_ack++;
6248     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
6249     cinfo = tunnel_get_neighbor_fc (t, peer);
6250     cinfo->fwd_ack = ack;
6251     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
6252     tunnel_unlock_fwd_queues (t);
6253     if (GNUNET_SCHEDULER_NO_TASK != cinfo->fc_poll)
6254     {
6255       GNUNET_SCHEDULER_cancel (cinfo->fc_poll);
6256       cinfo->fc_poll = GNUNET_SCHEDULER_NO_TASK;
6257       cinfo->fc_poll_time = GNUNET_TIME_UNIT_SECONDS;
6258     }
6259   }
6260   else
6261   {
6262     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
6263     t->bck_ack = ack;
6264     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
6265     tunnel_unlock_bck_queue (t);
6266   }
6267   return GNUNET_OK;
6268 }
6269
6270
6271 /**
6272  * Core handler for mesh network traffic point-to-point ack polls.
6273  *
6274  * @param cls closure
6275  * @param message message
6276  * @param peer peer identity this notification is about
6277  * @param atsi performance data
6278  * @param atsi_count number of records in 'atsi'
6279  *
6280  * @return GNUNET_OK to keep the connection open,
6281  *         GNUNET_SYSERR to close it (signal serious error)
6282  */
6283 static int
6284 handle_mesh_poll (void *cls, const struct GNUNET_PeerIdentity *peer,
6285                   const struct GNUNET_MessageHeader *message,
6286                   const struct GNUNET_ATS_Information *atsi,
6287                   unsigned int atsi_count)
6288 {
6289   struct GNUNET_MESH_Poll *msg;
6290   struct MeshTunnel *t;
6291
6292   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an POLL packet from %s!\n",
6293               GNUNET_i2s (peer));
6294
6295   msg = (struct GNUNET_MESH_Poll *) message;
6296
6297   t = tunnel_get (&msg->oid, ntohl (msg->tid));
6298
6299   if (NULL == t)
6300   {
6301     /* TODO notify that we dont know this tunnel (whom)? */
6302     GNUNET_STATISTICS_update (stats, "# poll on unknown tunnel", 1, GNUNET_NO);
6303     GNUNET_break_op (0);
6304     return GNUNET_OK;
6305   }
6306
6307   /* Is this a forward or backward ACK? */
6308   if (tree_get_predecessor(t->tree) != GNUNET_PEER_search(peer))
6309   {
6310     struct MeshTunnelChildInfo *cinfo;
6311
6312     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  from FWD\n");
6313     cinfo = tunnel_get_neighbor_fc (t, peer);
6314     cinfo->bck_ack = cinfo->fwd_pid; // mark as ready to send
6315     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_POLL);
6316   }
6317   else
6318   {
6319     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  from BCK\n");
6320     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_POLL);
6321   }
6322
6323   return GNUNET_OK;
6324 }
6325
6326
6327 /**
6328  * Core handler for path ACKs
6329  *
6330  * @param cls closure
6331  * @param message message
6332  * @param peer peer identity this notification is about
6333  * @param atsi performance data
6334  * @param atsi_count number of records in 'atsi'
6335  *
6336  * @return GNUNET_OK to keep the connection open,
6337  *         GNUNET_SYSERR to close it (signal serious error)
6338  */
6339 static int
6340 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
6341                       const struct GNUNET_MessageHeader *message,
6342                       const struct GNUNET_ATS_Information *atsi,
6343                       unsigned int atsi_count)
6344 {
6345   struct GNUNET_MESH_PathACK *msg;
6346   struct GNUNET_PeerIdentity id;
6347   struct MeshPeerInfo *peer_info;
6348   struct MeshPeerPath *p;
6349   struct MeshTunnel *t;
6350
6351   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a path ACK msg [%s]\n",
6352               GNUNET_i2s (&my_full_id));
6353   msg = (struct GNUNET_MESH_PathACK *) message;
6354   t = tunnel_get (&msg->oid, ntohl(msg->tid));
6355   if (NULL == t)
6356   {
6357     /* TODO notify that we don't know the tunnel */
6358     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel", 1, GNUNET_NO);
6359     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  don't know the tunnel %s [%X]!\n",
6360                 GNUNET_i2s (&msg->oid), ntohl(msg->tid));
6361     return GNUNET_OK;
6362   }
6363   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %s [%X]\n",
6364               GNUNET_i2s (&msg->oid), ntohl(msg->tid));
6365
6366   peer_info = peer_info_get (&msg->peer_id);
6367   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by peer %s\n",
6368               GNUNET_i2s (&msg->peer_id));
6369   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  via peer %s\n",
6370               GNUNET_i2s (peer));
6371
6372   if (NULL != t->regex_ctx && t->regex_ctx->info->peer == peer_info->id)
6373   {
6374     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6375                 "connect_by_string completed, stopping search\n");
6376     regex_cancel_search (t->regex_ctx);
6377     t->regex_ctx = NULL;
6378   }
6379
6380   /* Add paths to peers? */
6381   p = tree_get_path_to_peer (t->tree, peer_info->id);
6382   if (NULL != p)
6383   {
6384     path_add_to_peers (p, GNUNET_YES);
6385     path_destroy (p);
6386   }
6387   else
6388   {
6389     GNUNET_break (0);
6390   }
6391
6392   /* Message for us? */
6393   if (0 == memcmp (&msg->oid, &my_full_id, sizeof (struct GNUNET_PeerIdentity)))
6394   {
6395     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
6396     if (NULL == t->owner)
6397     {
6398       GNUNET_break_op (0);
6399       return GNUNET_OK;
6400     }
6401     if (NULL != t->dht_get_type)
6402     {
6403       GNUNET_DHT_get_stop (t->dht_get_type);
6404       t->dht_get_type = NULL;
6405     }
6406     if (tree_get_status (t->tree, peer_info->id) != MESH_PEER_READY)
6407     {
6408       tree_set_status (t->tree, peer_info->id, MESH_PEER_READY);
6409       send_client_peer_connected (t, peer_info->id);
6410     }
6411     return GNUNET_OK;
6412   }
6413
6414   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6415               "  not for us, retransmitting...\n");
6416   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
6417   peer_info = peer_info_get (&msg->oid);
6418   if (NULL == peer_info)
6419   {
6420     /* If we know the tunnel, we should DEFINITELY know the peer */
6421     GNUNET_break (0);
6422     return GNUNET_OK;
6423   }
6424   send_prebuilt_message (message, &id, t);
6425   return GNUNET_OK;
6426 }
6427
6428
6429 /**
6430  * Core handler for mesh keepalives.
6431  *
6432  * @param cls closure
6433  * @param message message
6434  * @param peer peer identity this notification is about
6435  * @param atsi performance data
6436  * @param atsi_count number of records in 'atsi'
6437  * @return GNUNET_OK to keep the connection open,
6438  *         GNUNET_SYSERR to close it (signal serious error)
6439  *
6440  * TODO: Check who we got this from, to validate route.
6441  */
6442 static int
6443 handle_mesh_keepalive (void *cls, const struct GNUNET_PeerIdentity *peer,
6444                        const struct GNUNET_MessageHeader *message,
6445                        const struct GNUNET_ATS_Information *atsi,
6446                        unsigned int atsi_count)
6447 {
6448   struct GNUNET_MESH_TunnelKeepAlive *msg;
6449   struct MeshTunnel *t;
6450
6451   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a keepalive packet from %s\n",
6452               GNUNET_i2s (peer));
6453
6454   msg = (struct GNUNET_MESH_TunnelKeepAlive *) message;
6455   t = tunnel_get (&msg->oid, ntohl (msg->tid));
6456
6457   if (NULL == t)
6458   {
6459     /* TODO notify that we dont know that tunnel */
6460     GNUNET_STATISTICS_update (stats, "# keepalive on unknown tunnel", 1,
6461                               GNUNET_NO);
6462     return GNUNET_OK;
6463   }
6464
6465   tunnel_reset_timeout (t);
6466
6467   GNUNET_STATISTICS_update (stats, "# keepalives forwarded", 1, GNUNET_NO);
6468   tunnel_send_multicast (t, message);
6469   return GNUNET_OK;
6470   }
6471
6472
6473
6474 /**
6475  * Functions to handle messages from core
6476  */
6477 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
6478   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
6479   {&handle_mesh_path_destroy, GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY, 0},
6480   {&handle_mesh_path_broken, GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN,
6481    sizeof (struct GNUNET_MESH_PathBroken)},
6482   {&handle_mesh_tunnel_destroy, GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY,
6483    sizeof (struct GNUNET_MESH_TunnelDestroy)},
6484   {&handle_mesh_data_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
6485   {&handle_mesh_data_multicast, GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
6486   {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE,
6487     sizeof (struct GNUNET_MESH_TunnelKeepAlive)},
6488   {&handle_mesh_data_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
6489   {&handle_mesh_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
6490     sizeof (struct GNUNET_MESH_ACK)},
6491   {&handle_mesh_poll, GNUNET_MESSAGE_TYPE_MESH_POLL,
6492     sizeof (struct GNUNET_MESH_Poll)},
6493   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
6494    sizeof (struct GNUNET_MESH_PathACK)},
6495   {NULL, 0, 0}
6496 };
6497
6498
6499
6500 /******************************************************************************/
6501 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
6502 /******************************************************************************/
6503
6504 /**
6505  * deregister_app: iterator for removing each application registered by a client
6506  *
6507  * @param cls closure
6508  * @param key the hash of the application id (used to access the hashmap)
6509  * @param value the value stored at the key (client)
6510  *
6511  * @return GNUNET_OK on success
6512  */
6513 static int
6514 deregister_app (void *cls, const struct GNUNET_HashCode * key, void *value)
6515 {
6516   struct GNUNET_CONTAINER_MultiHashMap *h = cls;
6517   GNUNET_break (GNUNET_YES ==
6518                 GNUNET_CONTAINER_multihashmap_remove (h, key, value));
6519   return GNUNET_OK;
6520 }
6521
6522 #if LATER
6523 /**
6524  * notify_client_connection_failure: notify a client that the connection to the
6525  * requested remote peer is not possible (for instance, no route found)
6526  * Function called when the socket is ready to queue more data. "buf" will be
6527  * NULL and "size" zero if the socket was closed for writing in the meantime.
6528  *
6529  * @param cls closure
6530  * @param size number of bytes available in buf
6531  * @param buf where the callee should write the message
6532  * @return number of bytes written to buf
6533  */
6534 static size_t
6535 notify_client_connection_failure (void *cls, size_t size, void *buf)
6536 {
6537   int size_needed;
6538   struct MeshPeerInfo *peer_info;
6539   struct GNUNET_MESH_PeerControl *msg;
6540   struct GNUNET_PeerIdentity id;
6541
6542   if (0 == size && NULL == buf)
6543   {
6544     // TODO retry? cancel?
6545     return 0;
6546   }
6547
6548   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
6549   peer_info = (struct MeshPeerInfo *) cls;
6550   msg = (struct GNUNET_MESH_PeerControl *) buf;
6551   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
6552   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
6553 //     msg->tunnel_id = htonl(peer_info->t->tid);
6554   GNUNET_PEER_resolve (peer_info->id, &id);
6555   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
6556
6557   return size_needed;
6558 }
6559 #endif
6560
6561
6562 /**
6563  * Send keepalive packets for a peer
6564  *
6565  * @param cls Closure (tunnel for which to send the keepalive).
6566  * @param tc Notification context.
6567  */
6568 static void
6569 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
6570 {
6571   struct MeshTunnel *t = cls;
6572   struct GNUNET_MESH_TunnelKeepAlive *msg;
6573   size_t size = sizeof (struct GNUNET_MESH_TunnelKeepAlive);
6574   char cbuf[size];
6575
6576   t->path_refresh_task = GNUNET_SCHEDULER_NO_TASK;
6577   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
6578   {
6579     return;
6580   }
6581
6582   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6583               "sending keepalive for tunnel %d\n", t->id.tid);
6584
6585   msg = (struct GNUNET_MESH_TunnelKeepAlive *) cbuf;
6586   msg->header.size = htons (size);
6587   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE);
6588   msg->oid = my_full_id;
6589   msg->tid = htonl (t->id.tid);
6590   tunnel_send_multicast (t, &msg->header);
6591
6592   t->path_refresh_task =
6593       GNUNET_SCHEDULER_add_delayed (refresh_path_time, &path_refresh, t);
6594   tunnel_reset_timeout(t);
6595 }
6596
6597
6598 /**
6599  * Function to process paths received for a new peer addition. The recorded
6600  * paths form the initial tunnel, which can be optimized later.
6601  * Called on each result obtained for the DHT search.
6602  *
6603  * @param cls closure
6604  * @param exp when will this value expire
6605  * @param key key of the result
6606  * @param get_path path of the get request
6607  * @param get_path_length lenght of get_path
6608  * @param put_path path of the put request
6609  * @param put_path_length length of the put_path
6610  * @param type type of the result
6611  * @param size number of bytes in data
6612  * @param data pointer to the result data
6613  *
6614  * TODO: re-issue the request after certain time? cancel after X results?
6615  */
6616 static void
6617 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
6618                     const struct GNUNET_HashCode * key,
6619                     const struct GNUNET_PeerIdentity *get_path,
6620                     unsigned int get_path_length,
6621                     const struct GNUNET_PeerIdentity *put_path,
6622                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
6623                     size_t size, const void *data)
6624 {
6625   struct MeshPathInfo *path_info = cls;
6626   struct MeshPeerPath *p;
6627   struct GNUNET_PeerIdentity pi;
6628   int i;
6629
6630   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
6631   GNUNET_PEER_resolve (path_info->peer->id, &pi);
6632   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", GNUNET_i2s (&pi));
6633
6634   p = path_build_from_dht (get_path, get_path_length, put_path,
6635                            put_path_length);
6636   path_add_to_peers (p, GNUNET_NO);
6637   path_destroy(p);
6638   for (i = 0; i < path_info->peer->ntunnels; i++)
6639   {
6640     tunnel_add_peer (path_info->peer->tunnels[i], path_info->peer);
6641     peer_info_connect (path_info->peer, path_info->t);
6642   }
6643
6644   return;
6645 }
6646
6647
6648 /**
6649  * Function to process paths received for a new peer addition. The recorded
6650  * paths form the initial tunnel, which can be optimized later.
6651  * Called on each result obtained for the DHT search.
6652  *
6653  * @param cls closure
6654  * @param exp when will this value expire
6655  * @param key key of the result
6656  * @param get_path path of the get request
6657  * @param get_path_length lenght of get_path
6658  * @param put_path path of the put request
6659  * @param put_path_length length of the put_path
6660  * @param type type of the result
6661  * @param size number of bytes in data
6662  * @param data pointer to the result data
6663  */
6664 static void
6665 dht_get_type_handler (void *cls, struct GNUNET_TIME_Absolute exp,
6666                       const struct GNUNET_HashCode * key,
6667                       const struct GNUNET_PeerIdentity *get_path,
6668                       unsigned int get_path_length,
6669                       const struct GNUNET_PeerIdentity *put_path,
6670                       unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
6671                       size_t size, const void *data)
6672 {
6673   const struct PBlock *pb = data;
6674   const struct GNUNET_PeerIdentity *pi = &pb->id;
6675   struct MeshTunnel *t = cls;
6676   struct MeshPeerInfo *peer_info;
6677   struct MeshPeerPath *p;
6678
6679   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got type DHT result!\n");
6680   if (size != sizeof (struct PBlock))
6681   {
6682     GNUNET_break_op (0);
6683     return;
6684   }
6685   if (ntohl(pb->type) != t->type)
6686   {
6687     GNUNET_break_op (0);
6688     return;
6689   }
6690   GNUNET_assert (NULL != t->owner);
6691   peer_info = peer_info_get (pi);
6692   (void) GNUNET_CONTAINER_multihashmap_put (t->peers, &pi->hashPubKey,
6693                                             peer_info,
6694                                             GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
6695
6696   p = path_build_from_dht (get_path, get_path_length, put_path,
6697                            put_path_length);
6698   path_add_to_peers (p, GNUNET_NO);
6699   path_destroy(p);
6700   tunnel_add_peer (t, peer_info);
6701   peer_info_connect (peer_info, t);
6702 }
6703
6704
6705 /**
6706  * Function to process DHT string to regex matching.
6707  * Called on each result obtained for the DHT search.
6708  *
6709  * @param cls closure (search context)
6710  * @param exp when will this value expire
6711  * @param key key of the result
6712  * @param get_path path of the get request (not used)
6713  * @param get_path_length lenght of get_path (not used)
6714  * @param put_path path of the put request (not used)
6715  * @param put_path_length length of the put_path (not used)
6716  * @param type type of the result
6717  * @param size number of bytes in data
6718  * @param data pointer to the result data
6719  */
6720 static void
6721 dht_get_string_accept_handler (void *cls, struct GNUNET_TIME_Absolute exp,
6722                                const struct GNUNET_HashCode * key,
6723                                const struct GNUNET_PeerIdentity *get_path,
6724                                unsigned int get_path_length,
6725                                const struct GNUNET_PeerIdentity *put_path,
6726                                unsigned int put_path_length,
6727                                enum GNUNET_BLOCK_Type type,
6728                                size_t size, const void *data)
6729 {
6730   const struct MeshRegexAccept *block = data;
6731   struct MeshRegexSearchContext *ctx = cls;
6732   struct MeshRegexSearchInfo *info = ctx->info;
6733 //   struct MeshPeerPath *p;
6734   struct MeshPeerInfo *peer_info;
6735
6736   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got regex results from DHT!\n");
6737   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", info->description);
6738   GNUNET_STATISTICS_update (stats, "# regex accepting blocks found",
6739                             1, GNUNET_NO);
6740   GNUNET_STATISTICS_update (stats, "# regex accepting block bytes found",
6741                             size, GNUNET_NO);
6742
6743   peer_info = peer_info_get(&block->id);
6744 //   p = path_build_from_dht (get_path, get_path_length, put_path,
6745 //                            put_path_length);
6746 //   path_add_to_peers (p, GNUNET_NO);
6747 //   path_destroy(p);
6748
6749   tunnel_add_peer (info->t, peer_info);
6750   peer_info_connect (peer_info, info->t);
6751   if (0 == info->peer)
6752   {
6753     info->peer = peer_info->id;
6754   }
6755   else
6756   {
6757     GNUNET_array_append (info->peers, info->n_peers, peer_info->id);
6758   }
6759
6760   if (GNUNET_SCHEDULER_NO_TASK != info->timeout)
6761     return;
6762
6763   info->timeout = GNUNET_SCHEDULER_add_delayed (connect_timeout,
6764                                                 &regex_connect_timeout,
6765                                                 info);
6766
6767   return;
6768 }
6769
6770
6771 /**
6772  * Function to process DHT string to regex matching.
6773  * Called on each result obtained for the DHT search.
6774  *
6775  * @param cls closure (search context)
6776  * @param exp when will this value expire
6777  * @param key key of the result
6778  * @param get_path path of the get request (not used)
6779  * @param get_path_length lenght of get_path (not used)
6780  * @param put_path path of the put request (not used)
6781  * @param put_path_length length of the put_path (not used)
6782  * @param type type of the result
6783  * @param size number of bytes in data
6784  * @param data pointer to the result data
6785  *
6786  * TODO: re-issue the request after certain time? cancel after X results?
6787  */
6788 static void
6789 dht_get_string_handler (void *cls, struct GNUNET_TIME_Absolute exp,
6790                         const struct GNUNET_HashCode * key,
6791                         const struct GNUNET_PeerIdentity *get_path,
6792                         unsigned int get_path_length,
6793                         const struct GNUNET_PeerIdentity *put_path,
6794                         unsigned int put_path_length,
6795                         enum GNUNET_BLOCK_Type type,
6796                         size_t size, const void *data)
6797 {
6798   const struct MeshRegexBlock *block = data;
6799   struct MeshRegexSearchContext *ctx = cls;
6800   struct MeshRegexSearchInfo *info = ctx->info;
6801   void *copy;
6802   size_t len;
6803
6804   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6805               "DHT GET STRING RETURNED RESULTS\n");
6806   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6807               "  key: %s\n", GNUNET_h2s (key));
6808
6809   GNUNET_STATISTICS_update (stats, "# regex blocks found",
6810                             1, GNUNET_NO);
6811   GNUNET_STATISTICS_update (stats, "# regex block bytes found",
6812                             size, GNUNET_NO);
6813
6814   copy = GNUNET_malloc (size);
6815   memcpy (copy, data, size);
6816   GNUNET_break (GNUNET_OK ==
6817                 GNUNET_CONTAINER_multihashmap_put(info->dht_get_results, key, copy,
6818                                                   GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
6819   len = ntohl (block->n_proof);
6820   {
6821     char proof[len + 1];
6822
6823     memcpy (proof, &block[1], len);
6824     proof[len] = '\0';
6825     if (GNUNET_OK != GNUNET_REGEX_check_proof (proof, key))
6826     {
6827       GNUNET_break_op (0);
6828       return;
6829     }
6830   }
6831   len = strlen (info->description);
6832   if (len == ctx->position) // String processed
6833   {
6834     if (GNUNET_YES == ntohl (block->accepting))
6835     {
6836       regex_find_path(key, ctx);
6837     }
6838     else
6839     {
6840       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  block not accepting!\n");
6841       // FIXME REGEX this block not successful, wait for more? start timeout?
6842     }
6843     return;
6844   }
6845
6846   regex_next_edge (block, size, ctx);
6847
6848   return;
6849 }
6850
6851 /******************************************************************************/
6852 /*********************       MESH LOCAL HANDLES      **************************/
6853 /******************************************************************************/
6854
6855
6856 /**
6857  * Handler for client disconnection
6858  *
6859  * @param cls closure
6860  * @param client identification of the client; NULL
6861  *        for the last call when the server is destroyed
6862  */
6863 static void
6864 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
6865 {
6866   struct MeshClient *c;
6867   struct MeshClient *next;
6868   unsigned int i;
6869
6870   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected\n");
6871   if (client == NULL)
6872   {
6873     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (SERVER DOWN)\n");
6874     return;
6875   }
6876
6877   c = clients;
6878   while (NULL != c)
6879   {
6880     if (c->handle != client)
6881     {
6882       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ... searching\n");
6883       c = c->next;
6884       continue;
6885     }
6886     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u)\n",
6887                 c->id);
6888     GNUNET_SERVER_client_drop (c->handle);
6889     c->shutting_down = GNUNET_YES;
6890     GNUNET_assert (NULL != c->own_tunnels);
6891     GNUNET_assert (NULL != c->incoming_tunnels);
6892     GNUNET_CONTAINER_multihashmap_iterate (c->own_tunnels,
6893                                            &tunnel_destroy_iterator, c);
6894     GNUNET_CONTAINER_multihashmap_iterate (c->incoming_tunnels,
6895                                            &tunnel_destroy_iterator, c);
6896     GNUNET_CONTAINER_multihashmap_iterate (c->ignore_tunnels,
6897                                            &tunnel_destroy_iterator, c);
6898     GNUNET_CONTAINER_multihashmap_destroy (c->own_tunnels);
6899     GNUNET_CONTAINER_multihashmap_destroy (c->incoming_tunnels);
6900     GNUNET_CONTAINER_multihashmap_destroy (c->ignore_tunnels);
6901
6902     /* deregister clients applications */
6903     if (NULL != c->apps)
6904     {
6905       GNUNET_CONTAINER_multihashmap_iterate (c->apps, &deregister_app, c->apps);
6906       GNUNET_CONTAINER_multihashmap_destroy (c->apps);
6907     }
6908     if (0 == GNUNET_CONTAINER_multihashmap_size (applications) &&
6909         GNUNET_SCHEDULER_NO_TASK != announce_applications_task)
6910     {
6911       GNUNET_SCHEDULER_cancel (announce_applications_task);
6912       announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
6913     }
6914     if (NULL != c->types)
6915       GNUNET_CONTAINER_multihashmap_destroy (c->types);
6916     for (i = 0; i < c->n_regex; i++)
6917     {
6918       GNUNET_free (c->regexes[i].regex);
6919       if (NULL != c->regexes[i].dfa)
6920         GNUNET_REGEX_automaton_destroy (c->regexes[i].dfa);
6921     }
6922     GNUNET_free_non_null (c->regexes);
6923     if (GNUNET_SCHEDULER_NO_TASK != c->regex_announce_task)
6924       GNUNET_SCHEDULER_cancel (c->regex_announce_task);
6925     next = c->next;
6926     GNUNET_CONTAINER_DLL_remove (clients, clients_tail, c);
6927     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT FREE at %p\n", c);
6928     GNUNET_free (c);
6929     GNUNET_STATISTICS_update (stats, "# clients", -1, GNUNET_NO);
6930     c = next;
6931   }
6932   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   done!\n");
6933   return;
6934 }
6935
6936
6937 /**
6938  * Handler for new clients
6939  *
6940  * @param cls closure
6941  * @param client identification of the client
6942  * @param message the actual message, which includes messages the client wants
6943  */
6944 static void
6945 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
6946                          const struct GNUNET_MessageHeader *message)
6947 {
6948   struct GNUNET_MESH_ClientConnect *cc_msg;
6949   struct MeshClient *c;
6950   GNUNET_MESH_ApplicationType *a;
6951   unsigned int size;
6952   uint16_t ntypes;
6953   uint16_t *t;
6954   uint16_t napps;
6955   uint16_t i;
6956
6957   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected\n");
6958   /* Check data sanity */
6959   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
6960   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
6961   ntypes = ntohs (cc_msg->types);
6962   napps = ntohs (cc_msg->applications);
6963   if (size !=
6964       ntypes * sizeof (uint16_t) + napps * sizeof (GNUNET_MESH_ApplicationType))
6965   {
6966     GNUNET_break (0);
6967     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6968     return;
6969   }
6970
6971   /* Create new client structure */
6972   c = GNUNET_malloc (sizeof (struct MeshClient));
6973   c->id = next_client_id++;
6974   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT NEW %u\n", c->id);
6975   c->handle = client;
6976   GNUNET_SERVER_client_keep (client);
6977   a = (GNUNET_MESH_ApplicationType *) &cc_msg[1];
6978   if (napps > 0)
6979   {
6980     GNUNET_MESH_ApplicationType at;
6981     struct GNUNET_HashCode hc;
6982
6983     c->apps = GNUNET_CONTAINER_multihashmap_create (napps, GNUNET_NO);
6984     for (i = 0; i < napps; i++)
6985     {
6986       at = ntohl (a[i]);
6987       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  app type: %u\n", at);
6988       GNUNET_CRYPTO_hash (&at, sizeof (at), &hc);
6989       /* store in clients hashmap */
6990       GNUNET_CONTAINER_multihashmap_put (c->apps, &hc, (void *) (long) at,
6991                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6992       /* store in global hashmap, for announcements */
6993       GNUNET_CONTAINER_multihashmap_put (applications, &hc, c,
6994                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6995     }
6996     if (GNUNET_SCHEDULER_NO_TASK == announce_applications_task)
6997       announce_applications_task =
6998           GNUNET_SCHEDULER_add_now (&announce_applications, NULL);
6999
7000   }
7001   if (ntypes > 0)
7002   {
7003     uint16_t u16;
7004     struct GNUNET_HashCode hc;
7005
7006     t = (uint16_t *) & a[napps];
7007     c->types = GNUNET_CONTAINER_multihashmap_create (ntypes, GNUNET_NO);
7008     for (i = 0; i < ntypes; i++)
7009     {
7010       u16 = ntohs (t[i]);
7011       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  msg type: %u\n", u16);
7012       GNUNET_CRYPTO_hash (&u16, sizeof (u16), &hc);
7013
7014       /* store in clients hashmap */
7015       GNUNET_CONTAINER_multihashmap_put (c->types, &hc, c,
7016                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
7017       /* store in global hashmap */
7018       GNUNET_CONTAINER_multihashmap_put (types, &hc, c,
7019                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
7020     }
7021   }
7022   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7023               " client has %u+%u subscriptions\n", napps, ntypes);
7024
7025   GNUNET_CONTAINER_DLL_insert (clients, clients_tail, c);
7026   c->own_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
7027   c->incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
7028   c->ignore_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
7029   GNUNET_SERVER_notification_context_add (nc, client);
7030   GNUNET_STATISTICS_update (stats, "# clients", 1, GNUNET_NO);
7031
7032   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7033   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
7034 }
7035
7036
7037 /**
7038  * Handler for clients announcing available services by a regular expression.
7039  *
7040  * @param cls closure
7041  * @param client identification of the client
7042  * @param message the actual message, which includes messages the client wants
7043  */
7044 static void
7045 handle_local_announce_regex (void *cls, struct GNUNET_SERVER_Client *client,
7046                              const struct GNUNET_MessageHeader *message)
7047 {
7048   const struct GNUNET_MESH_RegexAnnounce *msg;
7049   struct MeshRegexDescriptor rd;
7050   struct MeshClient *c;
7051   char *regex;
7052   size_t len;
7053   size_t offset;
7054
7055   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "announce regex started\n");
7056
7057   /* Sanity check for client registration */
7058   if (NULL == (c = client_get (client)))
7059   {
7060     GNUNET_break (0);
7061     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7062     return;
7063   }
7064   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7065
7066   msg = (const struct GNUNET_MESH_RegexAnnounce *) message;
7067
7068   len = ntohs (message->size) - sizeof(struct GNUNET_MESH_RegexAnnounce);
7069   if (NULL != c->partial_regex)
7070   {
7071     regex = c->partial_regex;
7072     offset = strlen (c->partial_regex);
7073     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7074                 "  continuation, already have %u bytes\n",
7075                 offset);
7076   }
7077   else
7078   {
7079     regex = NULL;
7080     offset = 0;
7081   }
7082
7083   regex = GNUNET_realloc (regex, offset + len + 1);
7084   memcpy (&regex[offset], &msg[1], len);
7085   regex[offset + len] = '\0';
7086   if (0 == ntohs (msg->last))
7087   {
7088     c->partial_regex = regex;
7089     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7090                 "  not ended, stored %u bytes for later\n",
7091                 len);
7092     GNUNET_SERVER_receive_done (client, GNUNET_OK);
7093     return;
7094   }
7095   rd.regex = regex;
7096   rd.compression = ntohs (msg->compression_characters);
7097   rd.dfa = NULL;
7098   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  length %u\n", len);
7099   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regex %s\n", regex);
7100   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  cm %u\n", ntohs(rd.compression));
7101   GNUNET_array_append (c->regexes, c->n_regex, rd);
7102   c->partial_regex = NULL;
7103   if (GNUNET_SCHEDULER_NO_TASK == c->regex_announce_task)
7104   {
7105     c->regex_announce_task = GNUNET_SCHEDULER_add_now(&announce_regex, c);
7106   }
7107   else
7108   {
7109     regex_put(&rd);
7110   }
7111   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7112   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "announce regex processed\n");
7113 }
7114
7115
7116 /**
7117  * Handler for requests of new tunnels
7118  *
7119  * @param cls closure
7120  * @param client identification of the client
7121  * @param message the actual message
7122  */
7123 static void
7124 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
7125                             const struct GNUNET_MessageHeader *message)
7126 {
7127   struct GNUNET_MESH_TunnelMessage *t_msg;
7128   struct MeshTunnel *t;
7129   struct MeshClient *c;
7130   MESH_TunnelNumber tid;
7131
7132   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel requested\n");
7133
7134   /* Sanity check for client registration */
7135   if (NULL == (c = client_get (client)))
7136   {
7137     GNUNET_break (0);
7138     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7139     return;
7140   }
7141   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7142
7143   /* Message sanity check */
7144   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
7145   {
7146     GNUNET_break (0);
7147     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7148     return;
7149   }
7150
7151   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
7152   /* Sanity check for tunnel numbering */
7153   tid = ntohl (t_msg->tunnel_id);
7154   if (0 == (tid & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
7155   {
7156     GNUNET_break (0);
7157     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7158     return;
7159   }
7160   /* Sanity check for duplicate tunnel IDs */
7161   if (NULL != tunnel_get_by_local_id (c, tid))
7162   {
7163     GNUNET_break (0);
7164     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7165     return;
7166   }
7167
7168   while (NULL != tunnel_get_by_pi (myid, next_tid))
7169     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
7170   t = tunnel_new (myid, next_tid++, c, tid);
7171   if (NULL == t)
7172   {
7173     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Tunnel creation failed.\n");
7174     GNUNET_break (0);
7175     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7176     return;
7177   }
7178   next_tid = next_tid & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
7179   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED TUNNEL %s [%x] (%x)\n",
7180               GNUNET_i2s (&my_full_id), t->id.tid, t->local_tid);
7181   t->peers = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
7182
7183   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel created\n");
7184   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7185   return;
7186 }
7187
7188
7189 /**
7190  * Handler for requests of deleting tunnels
7191  *
7192  * @param cls closure
7193  * @param client identification of the client
7194  * @param message the actual message
7195  */
7196 static void
7197 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
7198                              const struct GNUNET_MessageHeader *message)
7199 {
7200   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
7201   struct MeshClient *c;
7202   struct MeshTunnel *t;
7203   MESH_TunnelNumber tid;
7204
7205   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7206               "Got a DESTROY TUNNEL from client!\n");
7207
7208   /* Sanity check for client registration */
7209   if (NULL == (c = client_get (client)))
7210   {
7211     GNUNET_break (0);
7212     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7213     return;
7214   }
7215   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7216
7217   /* Message sanity check */
7218   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
7219   {
7220     GNUNET_break (0);
7221     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7222     return;
7223   }
7224
7225   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
7226
7227   /* Retrieve tunnel */
7228   tid = ntohl (tunnel_msg->tunnel_id);
7229   t = tunnel_get_by_local_id(c, tid);
7230   if (NULL == t)
7231   {
7232     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
7233     GNUNET_break (0);
7234     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7235     return;
7236   }
7237   if (c != t->owner || tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
7238   {
7239     client_ignore_tunnel (c, t);
7240     tunnel_destroy_empty (t);
7241     GNUNET_SERVER_receive_done (client, GNUNET_OK);
7242     return;
7243   }
7244   send_client_tunnel_disconnect(t, c);
7245   client_delete_tunnel(c, t);
7246
7247   /* Don't try to ACK the client about the tunnel_destroy multicast packet */
7248   t->owner = NULL;
7249   tunnel_send_destroy (t, GNUNET_YES);
7250   t->destroy = GNUNET_YES;
7251   // The tunnel will be destroyed when the last message is transmitted.
7252   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7253   return;
7254 }
7255
7256
7257 /**
7258  * Handler for requests of seeting tunnel's speed.
7259  *
7260  * @param cls Closure (unused).
7261  * @param client Identification of the client.
7262  * @param message The actual message.
7263  */
7264 static void
7265 handle_local_tunnel_speed (void *cls, struct GNUNET_SERVER_Client *client,
7266                            const struct GNUNET_MessageHeader *message)
7267 {
7268   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
7269   struct MeshClient *c;
7270   struct MeshTunnel *t;
7271   MESH_TunnelNumber tid;
7272
7273   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7274               "Got a SPEED request from client!\n");
7275
7276   /* Sanity check for client registration */
7277   if (NULL == (c = client_get (client)))
7278   {
7279     GNUNET_break (0);
7280     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7281     return;
7282   }
7283
7284   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7285
7286   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
7287
7288   /* Retrieve tunnel */
7289   tid = ntohl (tunnel_msg->tunnel_id);
7290   t = tunnel_get_by_local_id(c, tid);
7291   if (NULL == t)
7292   {
7293     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  tunnel %X not found\n", tid);
7294     GNUNET_break (0);
7295     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7296     return;
7297   }
7298
7299   switch (ntohs(message->type))
7300   {
7301       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MIN:
7302           t->speed_min = GNUNET_YES;
7303           break;
7304       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MAX:
7305           t->speed_min = GNUNET_NO;
7306           break;
7307       default:
7308           GNUNET_break (0);
7309   }
7310   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7311 }
7312
7313
7314 /**
7315  * Handler for requests of seeting tunnel's buffering policy.
7316  *
7317  * @param cls Closure (unused).
7318  * @param client Identification of the client.
7319  * @param message The actual message.
7320  */
7321 static void
7322 handle_local_tunnel_buffer (void *cls, struct GNUNET_SERVER_Client *client,
7323                             const struct GNUNET_MessageHeader *message)
7324 {
7325   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
7326   struct MeshClient *c;
7327   struct MeshTunnel *t;
7328   MESH_TunnelNumber tid;
7329
7330   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7331               "Got a BUFFER request from client!\n");
7332
7333   /* Sanity check for client registration */
7334   if (NULL == (c = client_get (client)))
7335   {
7336     GNUNET_break (0);
7337     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7338     return;
7339   }
7340   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7341
7342   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
7343
7344   /* Retrieve tunnel */
7345   tid = ntohl (tunnel_msg->tunnel_id);
7346   t = tunnel_get_by_local_id(c, tid);
7347   if (NULL == t)
7348   {
7349     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
7350     GNUNET_break (0);
7351     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7352     return;
7353   }
7354
7355   switch (ntohs(message->type))
7356   {
7357       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER:
7358           t->nobuffer = GNUNET_NO;
7359           break;
7360       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER:
7361           t->nobuffer = GNUNET_YES;
7362           break;
7363       default:
7364           GNUNET_break (0);
7365   }
7366
7367   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7368 }
7369
7370
7371 /**
7372  * Handler for connection requests to new peers
7373  *
7374  * @param cls closure
7375  * @param client identification of the client
7376  * @param message the actual message (PeerControl)
7377  */
7378 static void
7379 handle_local_connect_add (void *cls, struct GNUNET_SERVER_Client *client,
7380                           const struct GNUNET_MessageHeader *message)
7381 {
7382   struct GNUNET_MESH_PeerControl *peer_msg;
7383   struct MeshPeerInfo *peer_info;
7384   struct MeshClient *c;
7385   struct MeshTunnel *t;
7386   MESH_TunnelNumber tid;
7387
7388   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got connection request\n");
7389   /* Sanity check for client registration */
7390   if (NULL == (c = client_get (client)))
7391   {
7392     GNUNET_break (0);
7393     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7394     return;
7395   }
7396   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7397
7398   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
7399
7400   /* Sanity check for message size */
7401   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
7402   {
7403     GNUNET_break (0);
7404     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7405     return;
7406   }
7407
7408   /* Tunnel exists? */
7409   tid = ntohl (peer_msg->tunnel_id);
7410   t = tunnel_get_by_local_id (c, tid);
7411   if (NULL == t)
7412   {
7413     GNUNET_break (0);
7414     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7415     return;
7416   }
7417
7418   /* Does client own tunnel? */
7419   if (t->owner->handle != client)
7420   {
7421     GNUNET_break (0);
7422     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7423     return;
7424   }
7425   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "     for %s\n",
7426               GNUNET_i2s (&peer_msg->peer));
7427   peer_info = peer_info_get (&peer_msg->peer);
7428
7429   tunnel_add_peer (t, peer_info);
7430   peer_info_connect (peer_info, t);
7431
7432   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7433   return;
7434 }
7435
7436
7437 /**
7438  * Handler for disconnection requests of peers in a tunnel
7439  *
7440  * @param cls closure
7441  * @param client identification of the client
7442  * @param message the actual message (PeerControl)
7443  */
7444 static void
7445 handle_local_connect_del (void *cls, struct GNUNET_SERVER_Client *client,
7446                           const struct GNUNET_MessageHeader *message)
7447 {
7448   struct GNUNET_MESH_PeerControl *peer_msg;
7449   struct MeshPeerInfo *peer_info;
7450   struct MeshClient *c;
7451   struct MeshTunnel *t;
7452   MESH_TunnelNumber tid;
7453
7454   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER DEL request\n");
7455   /* Sanity check for client registration */
7456   if (NULL == (c = client_get (client)))
7457   {
7458     GNUNET_break (0);
7459     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7460     return;
7461   }
7462   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7463
7464   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
7465
7466   /* Sanity check for message size */
7467   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
7468   {
7469     GNUNET_break (0);
7470     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7471     return;
7472   }
7473
7474   /* Tunnel exists? */
7475   tid = ntohl (peer_msg->tunnel_id);
7476   t = tunnel_get_by_local_id (c, tid);
7477   if (NULL == t)
7478   {
7479     GNUNET_break (0);
7480     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7481     return;
7482   }
7483   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
7484
7485   /* Does client own tunnel? */
7486   if (t->owner->handle != client)
7487   {
7488     GNUNET_break (0);
7489     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7490     return;
7491   }
7492
7493   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for peer %s\n",
7494               GNUNET_i2s (&peer_msg->peer));
7495   /* Is the peer in the tunnel? */
7496   peer_info =
7497       GNUNET_CONTAINER_multihashmap_get (t->peers, &peer_msg->peer.hashPubKey);
7498   if (NULL == peer_info)
7499   {
7500     GNUNET_break (0);
7501     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7502     return;
7503   }
7504
7505   /* Ok, delete peer from tunnel */
7506   GNUNET_CONTAINER_multihashmap_remove_all (t->peers,
7507                                             &peer_msg->peer.hashPubKey);
7508
7509   send_destroy_path (t, peer_info->id);
7510   tunnel_delete_peer (t, peer_info->id);
7511   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7512   return;
7513 }
7514
7515 /**
7516  * Handler for blacklist requests of peers in a tunnel
7517  *
7518  * @param cls closure
7519  * @param client identification of the client
7520  * @param message the actual message (PeerControl)
7521  * 
7522  * FIXME implement DHT block bloomfilter
7523  */
7524 static void
7525 handle_local_blacklist (void *cls, struct GNUNET_SERVER_Client *client,
7526                           const struct GNUNET_MessageHeader *message)
7527 {
7528   struct GNUNET_MESH_PeerControl *peer_msg;
7529   struct MeshClient *c;
7530   struct MeshTunnel *t;
7531   MESH_TunnelNumber tid;
7532
7533   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER BLACKLIST request\n");
7534   /* Sanity check for client registration */
7535   if (NULL == (c = client_get (client)))
7536   {
7537     GNUNET_break (0);
7538     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7539     return;
7540   }
7541   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7542
7543   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
7544
7545   /* Sanity check for message size */
7546   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
7547   {
7548     GNUNET_break (0);
7549     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7550     return;
7551   }
7552
7553   /* Tunnel exists? */
7554   tid = ntohl (peer_msg->tunnel_id);
7555   t = tunnel_get_by_local_id (c, tid);
7556   if (NULL == t)
7557   {
7558     GNUNET_break (0);
7559     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7560     return;
7561   }
7562   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
7563
7564   GNUNET_array_append(t->blacklisted, t->nblacklisted,
7565                       GNUNET_PEER_intern(&peer_msg->peer));
7566 }
7567
7568
7569 /**
7570  * Handler for unblacklist requests of peers in a tunnel
7571  *
7572  * @param cls closure
7573  * @param client identification of the client
7574  * @param message the actual message (PeerControl)
7575  */
7576 static void
7577 handle_local_unblacklist (void *cls, struct GNUNET_SERVER_Client *client,
7578                           const struct GNUNET_MessageHeader *message)
7579 {
7580   struct GNUNET_MESH_PeerControl *peer_msg;
7581   struct MeshClient *c;
7582   struct MeshTunnel *t;
7583   MESH_TunnelNumber tid;
7584   GNUNET_PEER_Id pid;
7585   unsigned int i;
7586
7587   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER UNBLACKLIST request\n");
7588   /* Sanity check for client registration */
7589   if (NULL == (c = client_get (client)))
7590   {
7591     GNUNET_break (0);
7592     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7593     return;
7594   }
7595   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7596
7597   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
7598
7599   /* Sanity check for message size */
7600   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
7601   {
7602     GNUNET_break (0);
7603     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7604     return;
7605   }
7606
7607   /* Tunnel exists? */
7608   tid = ntohl (peer_msg->tunnel_id);
7609   t = tunnel_get_by_local_id (c, tid);
7610   if (NULL == t)
7611   {
7612     GNUNET_break (0);
7613     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7614     return;
7615   }
7616   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
7617
7618   /* if peer is not known, complain */
7619   pid = GNUNET_PEER_search (&peer_msg->peer);
7620   if (0 == pid)
7621   {
7622     GNUNET_break (0);
7623     return;
7624   }
7625
7626   /* search and remove from list */
7627   for (i = 0; i < t->nblacklisted; i++)
7628   {
7629     if (t->blacklisted[i] == pid)
7630     {
7631       t->blacklisted[i] = t->blacklisted[t->nblacklisted - 1];
7632       GNUNET_array_grow (t->blacklisted, t->nblacklisted, t->nblacklisted - 1);
7633       return;
7634     }
7635   }
7636
7637   /* if peer hasn't been blacklisted, complain */
7638   GNUNET_break (0);
7639 }
7640
7641
7642 /**
7643  * Handler for connection requests to new peers by type
7644  *
7645  * @param cls closure
7646  * @param client identification of the client
7647  * @param message the actual message (ConnectPeerByType)
7648  */
7649 static void
7650 handle_local_connect_by_type (void *cls, struct GNUNET_SERVER_Client *client,
7651                               const struct GNUNET_MessageHeader *message)
7652 {
7653   struct GNUNET_MESH_ConnectPeerByType *connect_msg;
7654   struct MeshClient *c;
7655   struct MeshTunnel *t;
7656   struct GNUNET_HashCode hash;
7657   MESH_TunnelNumber tid;
7658
7659   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got connect by type request\n");
7660   /* Sanity check for client registration */
7661   if (NULL == (c = client_get (client)))
7662   {
7663     GNUNET_break (0);
7664     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7665     return;
7666   }
7667   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7668
7669   connect_msg = (struct GNUNET_MESH_ConnectPeerByType *) message;
7670
7671   /* Sanity check for message size */
7672   if (sizeof (struct GNUNET_MESH_ConnectPeerByType) !=
7673       ntohs (connect_msg->header.size))
7674   {
7675     GNUNET_break (0);
7676     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7677     return;
7678   }
7679
7680   /* Tunnel exists? */
7681   tid = ntohl (connect_msg->tunnel_id);
7682   t = tunnel_get_by_local_id (c, tid);
7683   if (NULL == t)
7684   {
7685     GNUNET_break (0);
7686     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7687     return;
7688   }
7689
7690   /* Does client own tunnel? */
7691   if (t->owner->handle != client)
7692   {
7693     GNUNET_break (0);
7694     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7695     return;
7696   }
7697
7698   /* Do WE have the service? */
7699   t->type = ntohl (connect_msg->type);
7700   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " type requested: %u\n", t->type);
7701   GNUNET_CRYPTO_hash (&t->type, sizeof (GNUNET_MESH_ApplicationType), &hash);
7702   if (GNUNET_CONTAINER_multihashmap_contains (applications, &hash) ==
7703       GNUNET_YES)
7704   {
7705     /* Yes! Fast forward, add ourselves to the tunnel and send the
7706      * good news to the client, and alert the destination client of
7707      * an incoming tunnel.
7708      *
7709      * FIXME send a path create to self, avoid code duplication
7710      */
7711     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " available locally\n");
7712     GNUNET_CONTAINER_multihashmap_put (t->peers, &my_full_id.hashPubKey,
7713                                        peer_info_get (&my_full_id),
7714                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
7715
7716     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " notifying client\n");
7717     send_client_peer_connected (t, myid);
7718     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Done\n");
7719     GNUNET_SERVER_receive_done (client, GNUNET_OK);
7720
7721     t->local_tid_dest = next_local_tid++;
7722     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
7723     GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
7724                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
7725
7726     return;
7727   }
7728   /* Ok, lets find a peer offering the service */
7729   if (NULL != t->dht_get_type)
7730   {
7731     GNUNET_DHT_get_stop (t->dht_get_type);
7732   }
7733   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " looking in DHT for %s\n",
7734               GNUNET_h2s (&hash));
7735   t->dht_get_type =
7736       GNUNET_DHT_get_start (dht_handle, 
7737                             GNUNET_BLOCK_TYPE_MESH_PEER_BY_TYPE,
7738                             &hash,
7739                             dht_replication_level,
7740                             GNUNET_DHT_RO_RECORD_ROUTE |
7741                             GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
7742                             NULL, 0,
7743                             &dht_get_type_handler, t);
7744
7745   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7746   return;
7747 }
7748
7749
7750 /**
7751  * Handler for connection requests to new peers by a string service description.
7752  *
7753  * @param cls closure
7754  * @param client identification of the client
7755  * @param message the actual message, which includes messages the client wants
7756  */
7757 static void
7758 handle_local_connect_by_string (void *cls, struct GNUNET_SERVER_Client *client,
7759                                 const struct GNUNET_MessageHeader *message)
7760 {
7761   struct GNUNET_MESH_ConnectPeerByString *msg;
7762   struct MeshRegexSearchContext *ctx;
7763   struct MeshRegexSearchInfo *info;
7764   struct GNUNET_DHT_GetHandle *get_h;
7765   struct GNUNET_HashCode key;
7766   struct MeshTunnel *t;
7767   struct MeshClient *c;
7768   MESH_TunnelNumber tid;
7769   const char *string;
7770   size_t size;
7771   size_t len;
7772
7773   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7774               "Connect by string started\n");
7775   msg = (struct GNUNET_MESH_ConnectPeerByString *) message;
7776   size = htons (message->size);
7777
7778   /* Sanity check for client registration */
7779   if (NULL == (c = client_get (client)))
7780   {
7781     GNUNET_break (0);
7782     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7783     return;
7784   }
7785   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7786
7787   /* Message size sanity check */
7788   if (sizeof(struct GNUNET_MESH_ConnectPeerByString) >= size)
7789   {
7790     GNUNET_break (0);
7791     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7792     return;
7793   }
7794
7795   /* Tunnel exists? */
7796   tid = ntohl (msg->tunnel_id);
7797   t = tunnel_get_by_local_id (c, tid);
7798   if (NULL == t)
7799   {
7800     GNUNET_break (0);
7801     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7802     return;
7803   }
7804
7805   /* Does client own tunnel? */
7806   if (t->owner->handle != client)
7807   {
7808     GNUNET_break (0);
7809     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7810     return;
7811   }
7812
7813   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7814               "  on tunnel %s [%u]\n",
7815               GNUNET_i2s(&my_full_id),
7816               t->id.tid);
7817
7818   /* Only one connect_by_string allowed at the same time! */
7819   /* FIXME: allow more, return handle at api level to cancel, document */
7820   if (NULL != t->regex_ctx)
7821   {
7822     GNUNET_break (0);
7823     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7824     return;
7825   }
7826
7827   /* Find string itself */
7828   len = size - sizeof(struct GNUNET_MESH_ConnectPeerByString);
7829   string = (const char *) &msg[1];
7830
7831   /* Initialize context */
7832   size = GNUNET_REGEX_get_first_key (string, len, &key);
7833   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7834               "  consumed %u bits out of %u\n", size, len);
7835   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7836               "  looking for %s\n", GNUNET_h2s (&key));
7837
7838   info = GNUNET_malloc (sizeof (struct MeshRegexSearchInfo));
7839   info->t = t;
7840   info->description = GNUNET_strndup (string, len);
7841   info->dht_get_handles = GNUNET_CONTAINER_multihashmap_create(32, GNUNET_NO);
7842   info->dht_get_results = GNUNET_CONTAINER_multihashmap_create(32, GNUNET_NO);
7843   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   string: %s\n", info->description);
7844
7845   ctx = GNUNET_malloc (sizeof (struct MeshRegexSearchContext));
7846   ctx->position = size;
7847   ctx->info = info;
7848   t->regex_ctx = ctx;
7849
7850   GNUNET_array_append (info->contexts, info->n_contexts, ctx);
7851
7852   /* Start search in DHT */
7853   get_h = GNUNET_DHT_get_start (dht_handle,    /* handle */
7854                                 GNUNET_BLOCK_TYPE_MESH_REGEX, /* type */
7855                                 &key,     /* key to search */
7856                                 dht_replication_level, /* replication level */
7857                                 GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
7858                                 &info->description[size],           /* xquery */
7859                                 // FIXME add BLOOMFILTER to exclude filtered peers
7860                                 len + 1 - size,                /* xquery bits */
7861                                 // FIXME add BLOOMFILTER SIZE
7862                                 &dht_get_string_handler, ctx);
7863
7864   GNUNET_break (GNUNET_OK ==
7865                 GNUNET_CONTAINER_multihashmap_put(info->dht_get_handles,
7866                                                   &key,
7867                                                   get_h,
7868                                                   GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
7869
7870   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7871   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "connect by string processed\n");
7872 }
7873
7874
7875 /**
7876  * Handler for client traffic directed to one peer
7877  *
7878  * @param cls closure
7879  * @param client identification of the client
7880  * @param message the actual message
7881  */
7882 static void
7883 handle_local_unicast (void *cls, struct GNUNET_SERVER_Client *client,
7884                       const struct GNUNET_MessageHeader *message)
7885 {
7886   struct MeshClient *c;
7887   struct MeshTunnel *t;
7888   struct MeshPeerInfo *pi;
7889   struct GNUNET_MESH_Unicast *data_msg;
7890   MESH_TunnelNumber tid;
7891   size_t size;
7892
7893   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7894               "Got a unicast request from a client!\n");
7895
7896   /* Sanity check for client registration */
7897   if (NULL == (c = client_get (client)))
7898   {
7899     GNUNET_break (0);
7900     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7901     return;
7902   }
7903   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7904
7905   data_msg = (struct GNUNET_MESH_Unicast *) message;
7906
7907   /* Sanity check for message size */
7908   size = ntohs (message->size);
7909   if (sizeof (struct GNUNET_MESH_Unicast) +
7910       sizeof (struct GNUNET_MessageHeader) > size)
7911   {
7912     GNUNET_break (0);
7913     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7914     return;
7915   }
7916
7917   /* Tunnel exists? */
7918   tid = ntohl (data_msg->tid);
7919   t = tunnel_get_by_local_id (c, tid);
7920   if (NULL == t)
7921   {
7922     GNUNET_break (0);
7923     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7924     return;
7925   }
7926
7927   /*  Is it a local tunnel? Then, does client own the tunnel? */
7928   if (t->owner->handle != client)
7929   {
7930     GNUNET_break (0);
7931     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7932     return;
7933   }
7934
7935   pi = GNUNET_CONTAINER_multihashmap_get (t->peers,
7936                                           &data_msg->destination.hashPubKey);
7937   /* Is the selected peer in the tunnel? */
7938   if (NULL == pi)
7939   {
7940     GNUNET_break (0);
7941     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7942     return;
7943   }
7944
7945   /* PID should be as expected */
7946   if (ntohl (data_msg->pid) != t->fwd_pid + 1)
7947   {
7948     GNUNET_break (0);
7949     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7950               "Unicast PID, expected %u, got %u\n",
7951               t->fwd_pid + 1, ntohl (data_msg->pid));
7952     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7953     return;
7954   }
7955
7956   /* Ok, everything is correct, send the message
7957    * (pretend we got it from a mesh peer)
7958    */
7959   {
7960     /* Work around const limitation */
7961     char buf[ntohs (message->size)] GNUNET_ALIGN;
7962     struct GNUNET_MESH_Unicast *copy;
7963
7964     copy = (struct GNUNET_MESH_Unicast *) buf;
7965     memcpy (buf, data_msg, size);
7966     copy->oid = my_full_id;
7967     copy->tid = htonl (t->id.tid);
7968     copy->ttl = htonl (default_ttl);
7969     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7970                 "  calling generic handler...\n");
7971     handle_mesh_data_unicast (NULL, &my_full_id, &copy->header, NULL, 0);
7972   }
7973   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "receive done OK\n");
7974   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7975
7976   return;
7977 }
7978
7979
7980 /**
7981  * Handler for client traffic directed to the origin
7982  *
7983  * @param cls closure
7984  * @param client identification of the client
7985  * @param message the actual message
7986  */
7987 static void
7988 handle_local_to_origin (void *cls, struct GNUNET_SERVER_Client *client,
7989                         const struct GNUNET_MessageHeader *message)
7990 {
7991   struct GNUNET_MESH_ToOrigin *data_msg;
7992   struct MeshTunnelClientInfo *clinfo;
7993   struct MeshClient *c;
7994   struct MeshTunnel *t;
7995   MESH_TunnelNumber tid;
7996   size_t size;
7997
7998   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7999               "Got a ToOrigin request from a client!\n");
8000   /* Sanity check for client registration */
8001   if (NULL == (c = client_get (client)))
8002   {
8003     GNUNET_break (0);
8004     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
8005     return;
8006   }
8007   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
8008
8009   data_msg = (struct GNUNET_MESH_ToOrigin *) message;
8010
8011   /* Sanity check for message size */
8012   size = ntohs (message->size);
8013   if (sizeof (struct GNUNET_MESH_ToOrigin) +
8014       sizeof (struct GNUNET_MessageHeader) > size)
8015   {
8016     GNUNET_break (0);
8017     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
8018     return;
8019   }
8020
8021   /* Tunnel exists? */
8022   tid = ntohl (data_msg->tid);
8023   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
8024   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
8025   {
8026     GNUNET_break (0);
8027     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
8028     return;
8029   }
8030   t = tunnel_get_by_local_id (c, tid);
8031   if (NULL == t)
8032   {
8033     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
8034     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
8035     GNUNET_break (0);
8036     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
8037     return;
8038   }
8039
8040   /*  It should be sent by someone who has this as incoming tunnel. */
8041   if (GNUNET_NO == client_knows_tunnel (c, t))
8042   {
8043     GNUNET_break (0);
8044     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
8045     return;
8046   }
8047
8048   /* PID should be as expected */
8049   clinfo = tunnel_get_client_fc (t, c);
8050   if (ntohl (data_msg->pid) != clinfo->bck_pid + 1)
8051   {
8052     GNUNET_break (0);
8053     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
8054                 "To Origin PID, expected %u, got %u\n",
8055                 clinfo->bck_pid + 1,
8056                 ntohl (data_msg->pid));
8057     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
8058     return;
8059   }
8060   clinfo->bck_pid++;
8061
8062   /* Ok, everything is correct, send the message
8063    * (pretend we got it from a mesh peer)
8064    */
8065   {
8066     char buf[ntohs (message->size)] GNUNET_ALIGN;
8067     struct GNUNET_MESH_ToOrigin *copy;
8068
8069     /* Work around const limitation */
8070     copy = (struct GNUNET_MESH_ToOrigin *) buf;
8071     memcpy (buf, data_msg, size);
8072     GNUNET_PEER_resolve (t->id.oid, &copy->oid);
8073     copy->tid = htonl (t->id.tid);
8074     copy->ttl = htonl (default_ttl);
8075     copy->pid = htonl (t->bck_pid + 1);
8076
8077     copy->sender = my_full_id;
8078     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
8079                 "  calling generic handler...\n");
8080     handle_mesh_data_to_orig (NULL, &my_full_id, &copy->header, NULL, 0);
8081   }
8082   GNUNET_SERVER_receive_done (client, GNUNET_OK);
8083
8084   return;
8085 }
8086
8087
8088 /**
8089  * Handler for client traffic directed to all peers in a tunnel
8090  *
8091  * @param cls closure
8092  * @param client identification of the client
8093  * @param message the actual message
8094  */
8095 static void
8096 handle_local_multicast (void *cls, struct GNUNET_SERVER_Client *client,
8097                         const struct GNUNET_MessageHeader *message)
8098 {
8099   struct MeshClient *c;
8100   struct MeshTunnel *t;
8101   struct GNUNET_MESH_Multicast *data_msg;
8102   MESH_TunnelNumber tid;
8103
8104   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
8105               "Got a multicast request from a client!\n");
8106
8107   /* Sanity check for client registration */
8108   if (NULL == (c = client_get (client)))
8109   {
8110     GNUNET_break (0);
8111     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
8112     return;
8113   }
8114   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
8115
8116   data_msg = (struct GNUNET_MESH_Multicast *) message;
8117
8118   /* Sanity check for message size */
8119   if (sizeof (struct GNUNET_MESH_Multicast) +
8120       sizeof (struct GNUNET_MessageHeader) > ntohs (data_msg->header.size))
8121   {
8122     GNUNET_break (0);
8123     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
8124     return;
8125   }
8126
8127   /* Tunnel exists? */
8128   tid = ntohl (data_msg->tid);
8129   t = tunnel_get_by_local_id (c, tid);
8130   if (NULL == t)
8131   {
8132     GNUNET_break (0);
8133     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
8134     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
8135     GNUNET_break (0);
8136     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
8137     return;
8138   }
8139
8140   /* Does client own tunnel? */
8141   if (t->owner->handle != client)
8142   {
8143     GNUNET_break (0);
8144     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
8145     return;
8146   }
8147
8148   /* PID should be as expected */
8149   if (ntohl (data_msg->pid) != t->fwd_pid + 1)
8150   {
8151     GNUNET_break (0);
8152     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
8153               "Multicast PID, expected %u, got %u\n",
8154               t->fwd_pid + 1, ntohl (data_msg->pid));
8155     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
8156     return;
8157   }
8158
8159   {
8160     char buf[ntohs (message->size)] GNUNET_ALIGN;
8161     struct GNUNET_MESH_Multicast *copy;
8162
8163     copy = (struct GNUNET_MESH_Multicast *) buf;
8164     memcpy (buf, message, ntohs (message->size));
8165     copy->oid = my_full_id;
8166     copy->tid = htonl (t->id.tid);
8167     copy->ttl = htonl (default_ttl);
8168     GNUNET_assert (ntohl (copy->pid) == (t->fwd_pid + 1));
8169     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
8170                 "  calling generic handler...\n");
8171     handle_mesh_data_multicast (client, &my_full_id, &copy->header, NULL, 0);
8172   }
8173
8174   GNUNET_SERVER_receive_done (t->owner->handle, GNUNET_OK);
8175   return;
8176 }
8177
8178
8179 /**
8180  * Handler for client's ACKs for payload traffic.
8181  *
8182  * @param cls Closure (unused).
8183  * @param client Identification of the client.
8184  * @param message The actual message.
8185  */
8186 static void
8187 handle_local_ack (void *cls, struct GNUNET_SERVER_Client *client,
8188                   const struct GNUNET_MessageHeader *message)
8189 {
8190   struct GNUNET_MESH_LocalAck *msg;
8191   struct MeshTunnel *t;
8192   struct MeshClient *c;
8193   MESH_TunnelNumber tid;
8194   uint32_t ack;
8195
8196   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a local ACK\n");
8197   /* Sanity check for client registration */
8198   if (NULL == (c = client_get (client)))
8199   {
8200     GNUNET_break (0);
8201     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
8202     return;
8203   }
8204   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
8205
8206   msg = (struct GNUNET_MESH_LocalAck *) message;
8207
8208   /* Tunnel exists? */
8209   tid = ntohl (msg->tunnel_id);
8210   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
8211   t = tunnel_get_by_local_id (c, tid);
8212   if (NULL == t)
8213   {
8214     GNUNET_break (0);
8215     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
8216     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
8217     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
8218     return;
8219   }
8220
8221   ack = ntohl (msg->max_pid);
8222   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ack %u\n", ack);
8223
8224   /* Does client own tunnel? I.E: Is this an ACK for BCK traffic? */
8225   if (NULL != t->owner && t->owner->handle == client)
8226   {
8227     /* The client owns the tunnel, ACK is for data to_origin, send BCK ACK. */
8228     t->bck_ack = ack;
8229     tunnel_send_bck_ack(t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
8230   }
8231   else
8232   {
8233     /* The client doesn't own the tunnel, this ACK is for FWD traffic. */
8234     tunnel_set_client_fwd_ack (t, c, ack);
8235     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
8236   }
8237
8238   GNUNET_SERVER_receive_done (client, GNUNET_OK);
8239
8240   return;
8241 }
8242
8243
8244 /**
8245  * Iterator over all peers to send a monitoring client info about a tunnel.
8246  *
8247  * @param cls Closure (message being built).
8248  * @param key Key (hashed tunnel ID, unused).
8249  * @param value Peer info.
8250  *
8251  * @return GNUNET_YES, to keep iterating.
8252  */
8253 static int
8254 monitor_peers_iterator (void *cls,
8255                         const struct GNUNET_HashCode * key,
8256                         void *value)
8257 {
8258   struct GNUNET_MESH_LocalMonitor *msg = cls;
8259   struct GNUNET_PeerIdentity *id;
8260   struct MeshPeerInfo *info = value;
8261
8262   id = (struct GNUNET_PeerIdentity *) &msg[1];
8263   GNUNET_PEER_resolve (info->id, &id[msg->npeers]);
8264   msg->npeers++;
8265
8266   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
8267               "*    sending info about peer %s [%u]\n",
8268               GNUNET_i2s (&id[msg->npeers - 1]), msg->npeers);
8269
8270   return GNUNET_YES;
8271 }
8272
8273
8274
8275 /**
8276  * Iterator over all tunnels to send a monitoring client info about each tunnel.
8277  *
8278  * @param cls Closure (client handle).
8279  * @param key Key (hashed tunnel ID, unused).
8280  * @param value Tunnel info.
8281  *
8282  * @return GNUNET_YES, to keep iterating.
8283  */
8284 static int
8285 monitor_all_tunnels_iterator (void *cls,
8286                               const struct GNUNET_HashCode * key,
8287                               void *value)
8288 {
8289   struct GNUNET_SERVER_Client *client = cls;
8290   struct MeshTunnel *t = value;
8291   struct GNUNET_MESH_LocalMonitor *msg;
8292   uint32_t npeers;
8293   
8294   npeers = GNUNET_CONTAINER_multihashmap_size (t->peers);
8295   msg = GNUNET_malloc (sizeof(struct GNUNET_MESH_LocalMonitor) +
8296   npeers * sizeof (struct GNUNET_PeerIdentity));
8297   GNUNET_PEER_resolve(t->id.oid, &msg->owner);
8298   msg->tunnel_id = htonl (t->id.tid);
8299   msg->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor) +
8300   npeers * sizeof (struct GNUNET_PeerIdentity));
8301   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS);
8302   msg->npeers = 0;
8303   (void) GNUNET_CONTAINER_multihashmap_iterate (t->peers,
8304                                                 monitor_peers_iterator,
8305                                                 msg);
8306   
8307   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
8308               "*  sending info about tunnel %s [%u] (%u peers)\n",
8309               GNUNET_i2s (&msg->owner), t->id.tid, npeers);
8310   
8311   if (msg->npeers != npeers)
8312   {
8313     GNUNET_break (0);
8314     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8315                 "Get tunnels fail: size %u - iter %u\n",
8316                 npeers, msg->npeers);
8317   }
8318   
8319     msg->npeers = htonl (npeers);
8320     GNUNET_SERVER_notification_context_unicast (nc, client,
8321                                                 &msg->header, GNUNET_NO);
8322     return GNUNET_YES;
8323 }
8324
8325
8326 /**
8327  * Handler for client's MONITOR request.
8328  *
8329  * @param cls Closure (unused).
8330  * @param client Identification of the client.
8331  * @param message The actual message.
8332  */
8333 static void
8334 handle_local_get_tunnels (void *cls, struct GNUNET_SERVER_Client *client,
8335                           const struct GNUNET_MessageHeader *message)
8336 {
8337   struct MeshClient *c;
8338
8339   /* Sanity check for client registration */
8340   if (NULL == (c = client_get (client)))
8341   {
8342     GNUNET_break (0);
8343     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
8344     return;
8345   }
8346
8347   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
8348               "Received get tunnels request from client %u\n",
8349               c->id);
8350   GNUNET_CONTAINER_multihashmap_iterate (tunnels,
8351                                          monitor_all_tunnels_iterator,
8352                                          client);
8353   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
8354               "Get tunnels request from client %u completed\n",
8355               c->id);
8356   GNUNET_SERVER_receive_done (client, GNUNET_OK);
8357 }
8358
8359
8360 /**
8361  * Data needed to build a Monitor_Tunnel message.
8362  */
8363 struct MeshMonitorTunnelContext
8364 {
8365   /**
8366    * Partial message, including peer count.
8367    */
8368   struct GNUNET_MESH_LocalMonitor *msg;
8369
8370   /**
8371    * Hashmap with positions: peer->position.
8372    */
8373   struct GNUNET_CONTAINER_MultiHashMap *lookup;
8374
8375   /**
8376    * Index of the parent of each peer in the message, realtive to the absolute
8377    * order in the array (can be in a previous message).
8378    */
8379   uint32_t parents[1024];
8380
8381   /**
8382    * Peers visited so far in the tree, aka position of the current peer.
8383    */
8384   unsigned int npeers;
8385
8386   /**
8387    * Client requesting the info.
8388    */
8389   struct MeshClient *c;
8390 };
8391
8392
8393 /**
8394  * Send a client a message about the structure of a tunnel.
8395  *
8396  * @param ctx Context of the tunnel iteration, with info regarding the state
8397  *            of the execution and the number of peers visited for this message.
8398  */
8399 static void
8400 send_client_tunnel_info (struct MeshMonitorTunnelContext *ctx)
8401 {
8402   struct GNUNET_MESH_LocalMonitor *resp = ctx->msg;
8403   struct GNUNET_PeerIdentity *pid;
8404   unsigned int *parent;
8405   size_t size;
8406
8407   size = sizeof (struct GNUNET_MESH_LocalMonitor);
8408   size += (sizeof (struct GNUNET_PeerIdentity) + sizeof (int)) * resp->npeers;
8409   resp->header.size = htons (size);
8410   pid = (struct GNUNET_PeerIdentity *) &resp[1];
8411   parent = (unsigned int *) &pid[resp->npeers];
8412   memcpy (parent, ctx->parents, sizeof(uint32_t) * resp->npeers);
8413   GNUNET_SERVER_notification_context_unicast (nc, ctx->c->handle,
8414                                               &resp->header, GNUNET_NO);
8415 }
8416
8417 /**
8418  * Iterator over a tunnel tree to build a message containing all peers
8419  * the in the tunnel, including relay nodes.
8420  *
8421  * @param cls Closure (pointer to pointer of message being built).
8422  * @param peer Short ID of a peer.
8423  * @param parent Short ID of the @c peer 's parent.
8424  */
8425 static void
8426 tunnel_tree_iterator (void *cls,
8427                       GNUNET_PEER_Id peer,
8428                       GNUNET_PEER_Id parent)
8429 {
8430   struct MeshMonitorTunnelContext *ctx = cls;
8431   struct GNUNET_MESH_LocalMonitor *msg;
8432   struct GNUNET_PeerIdentity *pid;
8433   struct GNUNET_PeerIdentity ppid;
8434
8435   msg = ctx->msg;
8436   pid = (struct GNUNET_PeerIdentity *) &msg[1];
8437   GNUNET_PEER_resolve (peer, &pid[msg->npeers]);
8438   GNUNET_CONTAINER_multihashmap_put (ctx->lookup,
8439                                      &pid[msg->npeers].hashPubKey,
8440                                      (void *) (long) ctx->npeers,
8441                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
8442   GNUNET_PEER_resolve (parent, &ppid);
8443   ctx->parents[msg->npeers] =
8444       htonl ((long) GNUNET_CONTAINER_multihashmap_get (ctx->lookup,
8445                                                        &ppid.hashPubKey));
8446
8447   ctx->npeers++;
8448   msg->npeers++;
8449
8450   if (sizeof (struct GNUNET_MESH_LocalMonitor) +
8451       (msg->npeers + 1) *
8452       (sizeof (struct GNUNET_PeerIdentity) + sizeof (uint32_t))
8453       > USHRT_MAX)
8454   {
8455     send_client_tunnel_info (ctx);
8456     msg->npeers = 0;
8457   }
8458 }
8459
8460
8461 /**
8462  * Handler for client's MONITOR_TUNNEL request.
8463  *
8464  * @param cls Closure (unused).
8465  * @param client Identification of the client.
8466  * @param message The actual message.
8467  */
8468 static void
8469 handle_local_show_tunnel (void *cls, struct GNUNET_SERVER_Client *client,
8470                           const struct GNUNET_MessageHeader *message)
8471 {
8472   const struct GNUNET_MESH_LocalMonitor *msg;
8473   struct GNUNET_MESH_LocalMonitor *resp;
8474   struct MeshMonitorTunnelContext ctx;
8475   struct MeshClient *c;
8476   struct MeshTunnel *t;
8477
8478   /* Sanity check for client registration */
8479   if (NULL == (c = client_get (client)))
8480   {
8481     GNUNET_break (0);
8482     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
8483     return;
8484   }
8485
8486   msg = (struct GNUNET_MESH_LocalMonitor *) message;
8487   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
8488               "Received tunnel info request from client %u for tunnel %s[%X]\n",
8489               c->id,
8490               &msg->owner,
8491               ntohl (msg->tunnel_id));
8492   t = tunnel_get (&msg->owner, ntohl (msg->tunnel_id));
8493   if (NULL == t)
8494   {
8495     /* We don't know the tunnel */
8496     struct GNUNET_MESH_LocalMonitor warn;
8497
8498     warn = *msg;
8499     warn.npeers = htonl (UINT_MAX);
8500     GNUNET_SERVER_notification_context_unicast (nc, client,
8501                                                 &warn.header,
8502                                                 GNUNET_NO);
8503     GNUNET_SERVER_receive_done (client, GNUNET_OK);
8504     return;
8505   }
8506
8507   /* Initialize context */
8508   resp = GNUNET_malloc (USHRT_MAX); /* avoid realloc'ing on each step */
8509   *resp = *msg;
8510   resp->npeers = 0;
8511   ctx.msg = resp;
8512   ctx.lookup = GNUNET_CONTAINER_multihashmap_create (4 * t->peers_total,
8513                                                      GNUNET_YES);
8514   ctx.c = c;
8515
8516   /* Collect and send information */
8517   tree_iterate_all (t->tree, &tunnel_tree_iterator, &ctx);
8518   send_client_tunnel_info (&ctx);
8519
8520   /* Free context */
8521   GNUNET_CONTAINER_multihashmap_destroy (ctx.lookup);
8522   GNUNET_free (resp);
8523
8524   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
8525               "Monitor tunnel request from client %u completed\n",
8526               c->id);
8527   GNUNET_SERVER_receive_done (client, GNUNET_OK);
8528 }
8529
8530
8531 /**
8532  * Functions to handle messages from clients
8533  */
8534 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
8535   {&handle_local_new_client, NULL,
8536    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
8537   {&handle_local_announce_regex, NULL,
8538    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ANNOUNCE_REGEX, 0},
8539   {&handle_local_tunnel_create, NULL,
8540    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
8541    sizeof (struct GNUNET_MESH_TunnelMessage)},
8542   {&handle_local_tunnel_destroy, NULL,
8543    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
8544    sizeof (struct GNUNET_MESH_TunnelMessage)},
8545   {&handle_local_tunnel_speed, NULL,
8546    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MIN,
8547    sizeof (struct GNUNET_MESH_TunnelMessage)},
8548   {&handle_local_tunnel_speed, NULL,
8549    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MAX,
8550    sizeof (struct GNUNET_MESH_TunnelMessage)},
8551   {&handle_local_tunnel_buffer, NULL,
8552    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER,
8553    sizeof (struct GNUNET_MESH_TunnelMessage)},
8554   {&handle_local_tunnel_buffer, NULL,
8555    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER,
8556    sizeof (struct GNUNET_MESH_TunnelMessage)},
8557   {&handle_local_connect_add, NULL,
8558    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD,
8559    sizeof (struct GNUNET_MESH_PeerControl)},
8560   {&handle_local_connect_del, NULL,
8561    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL,
8562    sizeof (struct GNUNET_MESH_PeerControl)},
8563   {&handle_local_blacklist, NULL,
8564    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_BLACKLIST,
8565    sizeof (struct GNUNET_MESH_PeerControl)},
8566   {&handle_local_unblacklist, NULL,
8567    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_UNBLACKLIST,
8568    sizeof (struct GNUNET_MESH_PeerControl)},
8569   {&handle_local_connect_by_type, NULL,
8570    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE,
8571    sizeof (struct GNUNET_MESH_ConnectPeerByType)},
8572   {&handle_local_connect_by_string, NULL,
8573    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_STRING, 0},
8574   {&handle_local_unicast, NULL,
8575    GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
8576   {&handle_local_to_origin, NULL,
8577    GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
8578   {&handle_local_multicast, NULL,
8579    GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
8580   {&handle_local_ack, NULL,
8581    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK,
8582    sizeof (struct GNUNET_MESH_LocalAck)},
8583   {&handle_local_get_tunnels, NULL,
8584    GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS,
8585    sizeof (struct GNUNET_MessageHeader)},
8586   {&handle_local_show_tunnel, NULL,
8587    GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNEL,
8588      sizeof (struct GNUNET_MESH_LocalMonitor)},
8589   {NULL, NULL, 0, 0}
8590 };
8591
8592
8593 /**
8594  * To be called on core init/fail.
8595  *
8596  * @param cls service closure
8597  * @param server handle to the server for this service
8598  * @param identity the public identity of this peer
8599  */
8600 static void
8601 core_init (void *cls, struct GNUNET_CORE_Handle *server,
8602            const struct GNUNET_PeerIdentity *identity)
8603 {
8604   static int i = 0;
8605   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
8606   core_handle = server;
8607   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)) ||
8608       NULL == server)
8609   {
8610     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
8611     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8612                 " core id %s\n",
8613                 GNUNET_i2s (identity));
8614     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8615                 " my id %s\n",
8616                 GNUNET_i2s (&my_full_id));
8617     GNUNET_SCHEDULER_shutdown (); // Try gracefully
8618     if (10 < i++)
8619       GNUNET_abort(); // Try harder
8620   }
8621   return;
8622 }
8623
8624
8625 /**
8626  * Method called whenever a given peer connects.
8627  *
8628  * @param cls closure
8629  * @param peer peer identity this notification is about
8630  * @param atsi performance data for the connection
8631  * @param atsi_count number of records in 'atsi'
8632  */
8633 static void
8634 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
8635               const struct GNUNET_ATS_Information *atsi,
8636               unsigned int atsi_count)
8637 {
8638   struct MeshPeerInfo *peer_info;
8639   struct MeshPeerPath *path;
8640
8641   DEBUG_CONN ("Peer connected\n");
8642   DEBUG_CONN ("     %s\n", GNUNET_i2s (&my_full_id));
8643   peer_info = peer_info_get (peer);
8644   if (myid == peer_info->id)
8645   {
8646     DEBUG_CONN ("     (self)\n");
8647     return;
8648   }
8649   else
8650   {
8651     DEBUG_CONN ("     %s\n", GNUNET_i2s (peer));
8652   }
8653   path = path_new (2);
8654   path->peers[0] = myid;
8655   path->peers[1] = peer_info->id;
8656   GNUNET_PEER_change_rc (myid, 1);
8657   GNUNET_PEER_change_rc (peer_info->id, 1);
8658   peer_info_add_path (peer_info, path, GNUNET_YES);
8659   GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
8660   return;
8661 }
8662
8663
8664 /**
8665  * Method called whenever a peer disconnects.
8666  *
8667  * @param cls closure
8668  * @param peer peer identity this notification is about
8669  */
8670 static void
8671 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
8672 {
8673   struct MeshPeerInfo *pi;
8674   struct MeshPeerQueue *q;
8675   struct MeshPeerQueue *n;
8676
8677   DEBUG_CONN ("Peer disconnected\n");
8678   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
8679   if (NULL == pi)
8680   {
8681     GNUNET_break (0);
8682     return;
8683   }
8684   q = pi->queue_head;
8685   while (NULL != q)
8686   {
8687       n = q->next;
8688       /* TODO try to reroute this traffic instead */
8689       queue_destroy(q, GNUNET_YES);
8690       q = n;
8691   }
8692   if (NULL != pi->core_transmit)
8693   {
8694     GNUNET_CORE_notify_transmit_ready_cancel(pi->core_transmit);
8695     pi->core_transmit = NULL;
8696   }
8697   peer_info_remove_path (pi, pi->id, myid);
8698   if (myid == pi->id)
8699   {
8700     DEBUG_CONN ("     (self)\n");
8701   }
8702   GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
8703   return;
8704 }
8705
8706
8707 /******************************************************************************/
8708 /************************      MAIN FUNCTIONS      ****************************/
8709 /******************************************************************************/
8710
8711 /**
8712  * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
8713  *
8714  * @param cls closure
8715  * @param key current key code
8716  * @param value value in the hash map
8717  * @return GNUNET_YES if we should continue to iterate,
8718  *         GNUNET_NO if not.
8719  */
8720 static int
8721 shutdown_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
8722 {
8723   struct MeshTunnel *t = value;
8724
8725   tunnel_destroy (t);
8726   return GNUNET_YES;
8727 }
8728
8729 /**
8730  * Iterator over peer hash map entries to destroy the tunnel during shutdown.
8731  *
8732  * @param cls closure
8733  * @param key current key code
8734  * @param value value in the hash map
8735  * @return GNUNET_YES if we should continue to iterate,
8736  *         GNUNET_NO if not.
8737  */
8738 static int
8739 shutdown_peer (void *cls, const struct GNUNET_HashCode * key, void *value)
8740 {
8741   struct MeshPeerInfo *p = value;
8742   struct MeshPeerQueue *q;
8743   struct MeshPeerQueue *n;
8744
8745   q = p->queue_head;
8746   while (NULL != q)
8747   {
8748       n = q->next;
8749       if (q->peer == p)
8750       {
8751         queue_destroy(q, GNUNET_YES);
8752       }
8753       q = n;
8754   }
8755   peer_info_destroy (p);
8756   return GNUNET_YES;
8757 }
8758
8759
8760 /**
8761  * Task run during shutdown.
8762  *
8763  * @param cls unused
8764  * @param tc unused
8765  */
8766 static void
8767 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
8768 {
8769   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
8770
8771   if (core_handle != NULL)
8772   {
8773     GNUNET_CORE_disconnect (core_handle);
8774     core_handle = NULL;
8775   }
8776   if (NULL != keygen)
8777   {
8778     GNUNET_CRYPTO_rsa_key_create_stop (keygen);
8779     keygen = NULL;
8780   }
8781   GNUNET_CONTAINER_multihashmap_iterate (tunnels, &shutdown_tunnel, NULL);
8782   GNUNET_CONTAINER_multihashmap_iterate (peers, &shutdown_peer, NULL);
8783   if (dht_handle != NULL)
8784   {
8785     GNUNET_DHT_disconnect (dht_handle);
8786     dht_handle = NULL;
8787   }
8788   if (nc != NULL)
8789   {
8790     GNUNET_SERVER_notification_context_destroy (nc);
8791     nc = NULL;
8792   }
8793   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
8794   {
8795     GNUNET_SCHEDULER_cancel (announce_id_task);
8796     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
8797   }
8798   if (GNUNET_SCHEDULER_NO_TASK != announce_applications_task)
8799   {
8800     GNUNET_SCHEDULER_cancel (announce_applications_task);
8801     announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
8802   }
8803   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
8804 }
8805
8806
8807 /**
8808  * Callback for hostkey read/generation
8809  *
8810  * @param cls Closure (Configuration handle).
8811  * @param pk the private key
8812  * @param emsg error message
8813  */
8814 static void
8815 key_generation_cb (void *cls,
8816                    struct GNUNET_CRYPTO_RsaPrivateKey *pk,
8817                    const char *emsg)
8818 {
8819   const struct GNUNET_CONFIGURATION_Handle *c = cls;
8820   struct MeshPeerInfo *peer;
8821   struct MeshPeerPath *p;
8822
8823   keygen = NULL;  
8824   if (NULL == pk)
8825   {
8826     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8827                 _("Mesh service could not access hostkey: %s. Exiting.\n"),
8828                 emsg);
8829     GNUNET_SCHEDULER_shutdown ();
8830     return;
8831   }
8832   my_private_key = pk;
8833   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
8834   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
8835                       &my_full_id.hashPubKey);
8836   myid = GNUNET_PEER_intern (&my_full_id);
8837   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
8838               "Mesh for peer [%s] starting\n",
8839               GNUNET_i2s(&my_full_id));
8840
8841 //   transport_handle = GNUNET_TRANSPORT_connect(c,
8842 //                                               &my_full_id,
8843 //                                               NULL,
8844 //                                               NULL,
8845 //                                               NULL,
8846 //                                               NULL);
8847
8848   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
8849                                      NULL,      /* Closure passed to MESH functions */
8850                                      &core_init,        /* Call core_init once connected */
8851                                      &core_connect,     /* Handle connects */
8852                                      &core_disconnect,  /* remove peers on disconnects */
8853                                      NULL,      /* Don't notify about all incoming messages */
8854                                      GNUNET_NO, /* For header only in notification */
8855                                      NULL,      /* Don't notify about all outbound messages */
8856                                      GNUNET_NO, /* For header-only out notification */
8857                                      core_handlers);    /* Register these handlers */
8858   
8859   if (core_handle == NULL)
8860   {
8861     GNUNET_break (0);
8862     GNUNET_SCHEDULER_shutdown ();
8863     return;
8864   }
8865
8866   next_tid = 0;
8867   next_local_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
8868
8869
8870   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
8871   nc = GNUNET_SERVER_notification_context_create (server_handle, 1);
8872   GNUNET_SERVER_disconnect_notify (server_handle,
8873                                    &handle_local_client_disconnect, NULL);
8874
8875
8876   clients = NULL;
8877   clients_tail = NULL;
8878   next_client_id = 0;
8879
8880   announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
8881   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
8882
8883   /* Create a peer_info for the local peer */
8884   peer = peer_info_get (&my_full_id);
8885   p = path_new (1);
8886   p->peers[0] = myid;
8887   GNUNET_PEER_change_rc (myid, 1);
8888   peer_info_add_path (peer, p, GNUNET_YES);
8889   GNUNET_SERVER_resume (server_handle);
8890   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Mesh service running\n");
8891 }
8892
8893
8894 /**
8895  * Process mesh requests.
8896  *
8897  * @param cls closure
8898  * @param server the initialized server
8899  * @param c configuration to use
8900  */
8901 static void
8902 run (void *cls, struct GNUNET_SERVER_Handle *server,
8903      const struct GNUNET_CONFIGURATION_Handle *c)
8904 {
8905   char *keyfile;
8906
8907   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
8908   server_handle = server;
8909
8910   if (GNUNET_OK !=
8911       GNUNET_CONFIGURATION_get_value_filename (c, "GNUNETD", "HOSTKEY",
8912                                                &keyfile))
8913   {
8914     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8915                 _
8916                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8917                 "mesh", "hostkey");
8918     GNUNET_SCHEDULER_shutdown ();
8919     return;
8920   }
8921
8922   if (GNUNET_OK !=
8923       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_PATH_TIME",
8924                                            &refresh_path_time))
8925   {
8926     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8927                 _
8928                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8929                 "mesh", "refresh path time");
8930     GNUNET_SCHEDULER_shutdown ();
8931     return;
8932   }
8933
8934   if (GNUNET_OK !=
8935       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "APP_ANNOUNCE_TIME",
8936                                            &app_announce_time))
8937   {
8938     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8939                 _
8940                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8941                 "mesh", "app announce time");
8942     GNUNET_SCHEDULER_shutdown ();
8943     return;
8944   }
8945   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
8946               "APP_ANNOUNCE_TIME %llu ms\n", 
8947               app_announce_time.rel_value);
8948   if (GNUNET_OK !=
8949       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "ID_ANNOUNCE_TIME",
8950                                            &id_announce_time))
8951   {
8952     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8953                 _
8954                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8955                 "mesh", "id announce time");
8956     GNUNET_SCHEDULER_shutdown ();
8957     return;
8958   }
8959
8960   if (GNUNET_OK !=
8961       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "CONNECT_TIMEOUT",
8962                                            &connect_timeout))
8963   {
8964     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8965                 _
8966                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8967                 "mesh", "connect timeout");
8968     GNUNET_SCHEDULER_shutdown ();
8969     return;
8970   }
8971
8972   if (GNUNET_OK !=
8973       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
8974                                              &max_msgs_queue))
8975   {
8976     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8977                 _
8978                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8979                 "mesh", "max msgs queue");
8980     GNUNET_SCHEDULER_shutdown ();
8981     return;
8982   }
8983
8984   if (GNUNET_OK !=
8985       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_TUNNELS",
8986                                              &max_tunnels))
8987   {
8988     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8989                 _
8990                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8991                 "mesh", "max tunnels");
8992     GNUNET_SCHEDULER_shutdown ();
8993     return;
8994   }
8995
8996   if (GNUNET_OK !=
8997       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
8998                                              &default_ttl))
8999   {
9000     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
9001                 _
9002                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
9003                 "mesh", "default ttl", 64);
9004     default_ttl = 64;
9005   }
9006
9007   if (GNUNET_OK !=
9008       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_PEERS",
9009                                              &max_peers))
9010   {
9011     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
9012                 _("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
9013                 "mesh", "max peers", 1000);
9014     max_peers = 1000;
9015   }
9016
9017   if (GNUNET_OK !=
9018       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DHT_REPLICATION_LEVEL",
9019                                              &dht_replication_level))
9020   {
9021     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
9022                 _
9023                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
9024                 "mesh", "dht replication level", 3);
9025     dht_replication_level = 3;
9026   }
9027
9028   tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
9029   incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
9030   peers = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
9031   applications = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
9032   types = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
9033
9034   dht_handle = GNUNET_DHT_connect (c, 64);
9035   if (NULL == dht_handle)
9036   {
9037     GNUNET_break (0);
9038   }
9039   stats = GNUNET_STATISTICS_create ("mesh", c);
9040
9041   GNUNET_SERVER_suspend (server_handle);
9042   /* Scheduled the task to clean up when shutdown is called */
9043   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
9044                                 NULL);
9045   keygen = GNUNET_CRYPTO_rsa_key_create_start (keyfile,
9046                                                &key_generation_cb,
9047                                                (void *) c);
9048   GNUNET_free (keyfile);
9049 }
9050
9051
9052 /**
9053  * The main function for the mesh service.
9054  *
9055  * @param argc number of arguments from the command line
9056  * @param argv command line arguments
9057  * @return 0 ok, 1 on error
9058  */
9059 int
9060 main (int argc, char *const *argv)
9061 {
9062   int ret;
9063   int r;
9064
9065   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
9066   r = GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
9067                           NULL);
9068   ret = (GNUNET_OK == r) ? 0 : 1;
9069   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");
9070
9071   INTERVAL_SHOW;
9072
9073   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
9074               "Mesh for peer [%s] FWD ACKs %u, BCK ACKs %u\n",
9075               GNUNET_i2s(&my_full_id), debug_fwd_ack, debug_bck_ack);
9076
9077   return ret;
9078 }