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