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