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