- cancel dht get for peers when done, style
[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     if (NULL != peer_info->dhtget)
5987     {
5988       GNUNET_DHT_get_stop (peer_info->dhtget);
5989       peer_info->dhtget = NULL;
5990     }
5991     return GNUNET_OK;
5992   }
5993
5994   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5995               "  not for us, retransmitting...\n");
5996   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
5997   peer_info = peer_info_get (&msg->oid);
5998   send_prebuilt_message (message, &id, t);
5999   return GNUNET_OK;
6000 }
6001
6002
6003 /**
6004  * Core handler for mesh keepalives.
6005  *
6006  * @param cls closure
6007  * @param message message
6008  * @param peer peer identity this notification is about
6009  * @param atsi performance data
6010  * @param atsi_count number of records in 'atsi'
6011  * @return GNUNET_OK to keep the connection open,
6012  *         GNUNET_SYSERR to close it (signal serious error)
6013  *
6014  * TODO: Check who we got this from, to validate route.
6015  */
6016 static int
6017 handle_mesh_keepalive (void *cls, const struct GNUNET_PeerIdentity *peer,
6018                        const struct GNUNET_MessageHeader *message,
6019                        const struct GNUNET_ATS_Information *atsi,
6020                        unsigned int atsi_count)
6021 {
6022   struct GNUNET_MESH_TunnelKeepAlive *msg;
6023   struct MeshTunnel *t;
6024
6025   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a keepalive packet from %s\n",
6026               GNUNET_i2s (peer));
6027
6028   msg = (struct GNUNET_MESH_TunnelKeepAlive *) message;
6029   t = tunnel_get (&msg->oid, ntohl (msg->tid));
6030
6031   if (NULL == t)
6032   {
6033     /* TODO notify that we dont know that tunnel */
6034     GNUNET_STATISTICS_update (stats, "# keepalive on unknown tunnel", 1,
6035                               GNUNET_NO);
6036     return GNUNET_OK;
6037   }
6038
6039   tunnel_reset_timeout (t);
6040
6041   GNUNET_STATISTICS_update (stats, "# keepalives forwarded", 1, GNUNET_NO);
6042   tunnel_send_multicast (t, message);
6043   return GNUNET_OK;
6044   }
6045
6046
6047
6048 /**
6049  * Functions to handle messages from core
6050  */
6051 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
6052   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
6053   {&handle_mesh_path_destroy, GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY, 0},
6054   {&handle_mesh_path_broken, GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN,
6055    sizeof (struct GNUNET_MESH_PathBroken)},
6056   {&handle_mesh_tunnel_destroy, GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY,
6057    sizeof (struct GNUNET_MESH_TunnelDestroy)},
6058   {&handle_mesh_data_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
6059   {&handle_mesh_data_multicast, GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
6060   {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE,
6061     sizeof (struct GNUNET_MESH_TunnelKeepAlive)},
6062   {&handle_mesh_data_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
6063   {&handle_mesh_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
6064     sizeof (struct GNUNET_MESH_ACK)},
6065   {&handle_mesh_poll, GNUNET_MESSAGE_TYPE_MESH_POLL,
6066     sizeof (struct GNUNET_MESH_Poll)},
6067   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
6068    sizeof (struct GNUNET_MESH_PathACK)},
6069   {NULL, 0, 0}
6070 };
6071
6072
6073
6074 /******************************************************************************/
6075 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
6076 /******************************************************************************/
6077
6078 /**
6079  * deregister_app: iterator for removing each application registered by a client
6080  *
6081  * @param cls closure
6082  * @param key the hash of the application id (used to access the hashmap)
6083  * @param value the value stored at the key (client)
6084  *
6085  * @return GNUNET_OK on success
6086  */
6087 static int
6088 deregister_app (void *cls, const struct GNUNET_HashCode * key, void *value)
6089 {
6090   struct MeshClient *c = cls;
6091
6092   GNUNET_break (GNUNET_YES ==
6093                 GNUNET_CONTAINER_multihashmap_remove (applications, key, c));
6094   return GNUNET_OK;
6095 }
6096
6097 #if LATER
6098 /**
6099  * notify_client_connection_failure: notify a client that the connection to the
6100  * requested remote peer is not possible (for instance, no route found)
6101  * Function called when the socket is ready to queue more data. "buf" will be
6102  * NULL and "size" zero if the socket was closed for writing in the meantime.
6103  *
6104  * @param cls closure
6105  * @param size number of bytes available in buf
6106  * @param buf where the callee should write the message
6107  * @return number of bytes written to buf
6108  */
6109 static size_t
6110 notify_client_connection_failure (void *cls, size_t size, void *buf)
6111 {
6112   int size_needed;
6113   struct MeshPeerInfo *peer_info;
6114   struct GNUNET_MESH_PeerControl *msg;
6115   struct GNUNET_PeerIdentity id;
6116
6117   if (0 == size && NULL == buf)
6118   {
6119     // TODO retry? cancel?
6120     return 0;
6121   }
6122
6123   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
6124   peer_info = (struct MeshPeerInfo *) cls;
6125   msg = (struct GNUNET_MESH_PeerControl *) buf;
6126   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
6127   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
6128 //     msg->tunnel_id = htonl(peer_info->t->tid);
6129   GNUNET_PEER_resolve (peer_info->id, &id);
6130   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
6131
6132   return size_needed;
6133 }
6134 #endif
6135
6136
6137 /**
6138  * Send keepalive packets for a peer
6139  *
6140  * @param cls Closure (tunnel for which to send the keepalive).
6141  * @param tc Notification context.
6142  */
6143 static void
6144 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
6145 {
6146   struct MeshTunnel *t = cls;
6147   struct GNUNET_MESH_TunnelKeepAlive *msg;
6148   size_t size = sizeof (struct GNUNET_MESH_TunnelKeepAlive);
6149   char cbuf[size];
6150
6151   t->path_refresh_task = GNUNET_SCHEDULER_NO_TASK;
6152   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
6153   {
6154     return;
6155   }
6156
6157   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6158               "sending keepalive for tunnel %d\n", t->id.tid);
6159
6160   msg = (struct GNUNET_MESH_TunnelKeepAlive *) cbuf;
6161   msg->header.size = htons (size);
6162   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE);
6163   msg->oid = my_full_id;
6164   msg->tid = htonl (t->id.tid);
6165   tunnel_send_multicast (t, &msg->header);
6166
6167   t->path_refresh_task =
6168       GNUNET_SCHEDULER_add_delayed (refresh_path_time, &path_refresh, t);
6169   tunnel_reset_timeout(t);
6170 }
6171
6172
6173 /**
6174  * Function to process paths received for a new peer addition. The recorded
6175  * paths form the initial tunnel, which can be optimized later.
6176  * Called on each result obtained for the DHT search.
6177  *
6178  * @param cls closure
6179  * @param exp when will this value expire
6180  * @param key key of the result
6181  * @param get_path path of the get request
6182  * @param get_path_length lenght of get_path
6183  * @param put_path path of the put request
6184  * @param put_path_length length of the put_path
6185  * @param type type of the result
6186  * @param size number of bytes in data
6187  * @param data pointer to the result data
6188  *
6189  * TODO: re-issue the request after certain time? cancel after X results?
6190  */
6191 static void
6192 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
6193                     const struct GNUNET_HashCode * key,
6194                     const struct GNUNET_PeerIdentity *get_path,
6195                     unsigned int get_path_length,
6196                     const struct GNUNET_PeerIdentity *put_path,
6197                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
6198                     size_t size, const void *data)
6199 {
6200   struct MeshPathInfo *path_info = cls;
6201   struct MeshPeerPath *p;
6202   struct GNUNET_PeerIdentity pi;
6203   int i;
6204
6205   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
6206   GNUNET_PEER_resolve (path_info->peer->id, &pi);
6207   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", GNUNET_i2s (&pi));
6208
6209   p = path_build_from_dht (get_path, get_path_length,
6210                            put_path, put_path_length);
6211   path_add_to_peers (p, GNUNET_NO);
6212   path_destroy (p);
6213   for (i = 0; i < path_info->peer->ntunnels; i++)
6214   {
6215     tunnel_add_peer (path_info->peer->tunnels[i], path_info->peer);
6216     peer_info_connect (path_info->peer, path_info->t);
6217   }
6218
6219   return;
6220 }
6221
6222
6223 /**
6224  * Function to process paths received for a new peer addition. The recorded
6225  * paths form the initial tunnel, which can be optimized later.
6226  * Called on each result obtained for the DHT search.
6227  *
6228  * @param cls closure
6229  * @param exp when will this value expire
6230  * @param key key of the result
6231  * @param get_path path of the get request
6232  * @param get_path_length lenght of get_path
6233  * @param put_path path of the put request
6234  * @param put_path_length length of the put_path
6235  * @param type type of the result
6236  * @param size number of bytes in data
6237  * @param data pointer to the result data
6238  */
6239 static void
6240 dht_get_type_handler (void *cls, struct GNUNET_TIME_Absolute exp,
6241                       const struct GNUNET_HashCode * key,
6242                       const struct GNUNET_PeerIdentity *get_path,
6243                       unsigned int get_path_length,
6244                       const struct GNUNET_PeerIdentity *put_path,
6245                       unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
6246                       size_t size, const void *data)
6247 {
6248   const struct PBlock *pb = data;
6249   const struct GNUNET_PeerIdentity *pi = &pb->id;
6250   struct MeshTunnel *t = cls;
6251   struct MeshPeerInfo *peer_info;
6252   struct MeshPeerPath *p;
6253
6254   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got type DHT result!\n");
6255   if (size != sizeof (struct PBlock))
6256   {
6257     GNUNET_break_op (0);
6258     return;
6259   }
6260   if (ntohl(pb->type) != t->type)
6261   {
6262     GNUNET_break_op (0);
6263     return;
6264   }
6265   GNUNET_assert (NULL != t->owner);
6266   peer_info = peer_info_get (pi);
6267   (void) GNUNET_CONTAINER_multihashmap_put (t->peers, &pi->hashPubKey,
6268                                             peer_info,
6269                                             GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
6270
6271   p = path_build_from_dht (get_path, get_path_length, put_path,
6272                            put_path_length);
6273   path_add_to_peers (p, GNUNET_NO);
6274   path_destroy(p);
6275   tunnel_add_peer (t, peer_info);
6276   peer_info_connect (peer_info, t);
6277 }
6278
6279
6280 /******************************************************************************/
6281 /*********************       MESH LOCAL HANDLES      **************************/
6282 /******************************************************************************/
6283
6284
6285 /**
6286  * Handler for client disconnection
6287  *
6288  * @param cls closure
6289  * @param client identification of the client; NULL
6290  *        for the last call when the server is destroyed
6291  */
6292 static void
6293 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
6294 {
6295   struct MeshClient *c;
6296   struct MeshClient *next;
6297   unsigned int i;
6298
6299   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected\n");
6300   if (client == NULL)
6301   {
6302     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (SERVER DOWN)\n");
6303     return;
6304   }
6305
6306   c = clients;
6307   while (NULL != c)
6308   {
6309     if (c->handle != client)
6310     {
6311       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ... searching\n");
6312       c = c->next;
6313       continue;
6314     }
6315     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u)\n",
6316                 c->id);
6317     GNUNET_SERVER_client_drop (c->handle);
6318     c->shutting_down = GNUNET_YES;
6319     GNUNET_assert (NULL != c->own_tunnels);
6320     GNUNET_assert (NULL != c->incoming_tunnels);
6321     GNUNET_CONTAINER_multihashmap_iterate (c->own_tunnels,
6322                                            &tunnel_destroy_iterator, c);
6323     GNUNET_CONTAINER_multihashmap_iterate (c->incoming_tunnels,
6324                                            &tunnel_destroy_iterator, c);
6325     GNUNET_CONTAINER_multihashmap_iterate (c->ignore_tunnels,
6326                                            &tunnel_destroy_iterator, c);
6327     GNUNET_CONTAINER_multihashmap_destroy (c->own_tunnels);
6328     GNUNET_CONTAINER_multihashmap_destroy (c->incoming_tunnels);
6329     GNUNET_CONTAINER_multihashmap_destroy (c->ignore_tunnels);
6330
6331     /* deregister clients applications */
6332     if (NULL != c->apps)
6333     {
6334       GNUNET_CONTAINER_multihashmap_iterate (c->apps, &deregister_app, c);
6335       GNUNET_CONTAINER_multihashmap_destroy (c->apps);
6336     }
6337     if (0 == GNUNET_CONTAINER_multihashmap_size (applications) &&
6338         GNUNET_SCHEDULER_NO_TASK != announce_applications_task)
6339     {
6340       GNUNET_SCHEDULER_cancel (announce_applications_task);
6341       announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
6342     }
6343     if (NULL != c->types)
6344       GNUNET_CONTAINER_multihashmap_destroy (c->types);
6345     for (i = 0; i < c->n_regex; i++)
6346     {
6347       GNUNET_free (c->regexes[i].regex);
6348       if (NULL != c->regexes[i].h)
6349         GNUNET_REGEX_announce_cancel (c->regexes[i].h);
6350     }
6351     GNUNET_free_non_null (c->regexes);
6352     if (GNUNET_SCHEDULER_NO_TASK != c->regex_announce_task)
6353       GNUNET_SCHEDULER_cancel (c->regex_announce_task);
6354     next = c->next;
6355     GNUNET_CONTAINER_DLL_remove (clients, clients_tail, c);
6356     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT FREE at %p\n", c);
6357     GNUNET_free (c);
6358     GNUNET_STATISTICS_update (stats, "# clients", -1, GNUNET_NO);
6359     c = next;
6360   }
6361   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   done!\n");
6362   return;
6363 }
6364
6365
6366 /**
6367  * Handler for new clients
6368  *
6369  * @param cls closure
6370  * @param client identification of the client
6371  * @param message the actual message, which includes messages the client wants
6372  */
6373 static void
6374 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
6375                          const struct GNUNET_MessageHeader *message)
6376 {
6377   struct GNUNET_MESH_ClientConnect *cc_msg;
6378   struct MeshClient *c;
6379   GNUNET_MESH_ApplicationType *a;
6380   unsigned int size;
6381   uint16_t ntypes;
6382   uint16_t *t;
6383   uint16_t napps;
6384   uint16_t i;
6385
6386   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected\n");
6387   /* Check data sanity */
6388   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
6389   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
6390   ntypes = ntohs (cc_msg->types);
6391   napps = ntohs (cc_msg->applications);
6392   if (size !=
6393       ntypes * sizeof (uint16_t) + napps * sizeof (GNUNET_MESH_ApplicationType))
6394   {
6395     GNUNET_break (0);
6396     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6397     return;
6398   }
6399
6400   /* Create new client structure */
6401   c = GNUNET_malloc (sizeof (struct MeshClient));
6402   c->id = next_client_id++;
6403   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT NEW %u\n", c->id);
6404   c->handle = client;
6405   GNUNET_SERVER_client_keep (client);
6406   a = (GNUNET_MESH_ApplicationType *) &cc_msg[1];
6407   if (napps > 0)
6408   {
6409     GNUNET_MESH_ApplicationType at;
6410     struct GNUNET_HashCode hc;
6411
6412     c->apps = GNUNET_CONTAINER_multihashmap_create (napps, GNUNET_NO);
6413     for (i = 0; i < napps; i++)
6414     {
6415       at = ntohl (a[i]);
6416       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  app type: %u\n", at);
6417       GNUNET_CRYPTO_hash (&at, sizeof (at), &hc);
6418       /* store in clients hashmap */
6419       GNUNET_CONTAINER_multihashmap_put (c->apps, &hc, (void *) (long) at,
6420                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6421       /* store in global hashmap, for announcements */
6422       GNUNET_CONTAINER_multihashmap_put (applications, &hc, c,
6423                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6424     }
6425     if (GNUNET_SCHEDULER_NO_TASK == announce_applications_task)
6426       announce_applications_task =
6427           GNUNET_SCHEDULER_add_now (&announce_applications, NULL);
6428
6429   }
6430   if (ntypes > 0)
6431   {
6432     uint16_t u16;
6433     struct GNUNET_HashCode hc;
6434
6435     t = (uint16_t *) & a[napps];
6436     c->types = GNUNET_CONTAINER_multihashmap_create (ntypes, GNUNET_NO);
6437     for (i = 0; i < ntypes; i++)
6438     {
6439       u16 = ntohs (t[i]);
6440       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  msg type: %u\n", u16);
6441       GNUNET_CRYPTO_hash (&u16, sizeof (u16), &hc);
6442
6443       /* store in clients hashmap */
6444       GNUNET_CONTAINER_multihashmap_put (c->types, &hc, c,
6445                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6446       /* store in global hashmap */
6447       GNUNET_CONTAINER_multihashmap_put (types, &hc, c,
6448                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6449     }
6450   }
6451   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6452               " client has %u+%u subscriptions\n", napps, ntypes);
6453
6454   GNUNET_CONTAINER_DLL_insert (clients, clients_tail, c);
6455   c->own_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6456   c->incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6457   c->ignore_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6458   GNUNET_SERVER_notification_context_add (nc, client);
6459   GNUNET_STATISTICS_update (stats, "# clients", 1, GNUNET_NO);
6460
6461   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6462   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
6463 }
6464
6465
6466 /**
6467  * Handler for clients announcing available services by a regular expression.
6468  *
6469  * @param cls closure
6470  * @param client identification of the client
6471  * @param message the actual message, which includes messages the client wants
6472  */
6473 static void
6474 handle_local_announce_regex (void *cls, struct GNUNET_SERVER_Client *client,
6475                              const struct GNUNET_MessageHeader *message)
6476 {
6477   const struct GNUNET_MESH_RegexAnnounce *msg;
6478   struct MeshRegexDescriptor rd;
6479   struct MeshClient *c;
6480   char *regex;
6481   size_t len;
6482   size_t offset;
6483
6484   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "announce regex started\n");
6485
6486   /* Sanity check for client registration */
6487   if (NULL == (c = client_get (client)))
6488   {
6489     GNUNET_break (0);
6490     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6491     return;
6492   }
6493   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6494
6495   msg = (const struct GNUNET_MESH_RegexAnnounce *) message;
6496
6497   len = ntohs (message->size) - sizeof(struct GNUNET_MESH_RegexAnnounce);
6498   if (NULL != c->partial_regex)
6499   {
6500     regex = c->partial_regex;
6501     offset = strlen (c->partial_regex);
6502     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6503                 "  continuation, already have %u bytes\n",
6504                 offset);
6505   }
6506   else
6507   {
6508     regex = NULL;
6509     offset = 0;
6510   }
6511
6512   regex = GNUNET_realloc (regex, offset + len + 1);
6513   memcpy (&regex[offset], &msg[1], len);
6514   regex[offset + len] = '\0';
6515   if (0 == ntohs (msg->last))
6516   {
6517     c->partial_regex = regex;
6518     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6519                 "  not ended, stored %u bytes for later\n",
6520                 len);
6521     GNUNET_SERVER_receive_done (client, GNUNET_OK);
6522     return;
6523   }
6524   rd.regex = regex;
6525   rd.compression = ntohs (msg->compression_characters);
6526   rd.h = NULL;
6527   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  length %u\n", len);
6528   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regex %s\n", regex);
6529   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  compr %u\n", ntohs (rd.compression));
6530   GNUNET_array_append (c->regexes, c->n_regex, rd);
6531   c->partial_regex = NULL;
6532   if (GNUNET_SCHEDULER_NO_TASK == c->regex_announce_task)
6533   {
6534     c->regex_announce_task = GNUNET_SCHEDULER_add_now (&regex_announce, c);
6535   }
6536   else
6537   {
6538     regex_put (&rd);
6539   }
6540   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6541   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "announce regex processed\n");
6542 }
6543
6544
6545 /**
6546  * Handler for requests of new tunnels
6547  *
6548  * @param cls closure
6549  * @param client identification of the client
6550  * @param message the actual message
6551  */
6552 static void
6553 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
6554                             const struct GNUNET_MessageHeader *message)
6555 {
6556   struct GNUNET_MESH_TunnelMessage *t_msg;
6557   struct MeshTunnel *t;
6558   struct MeshClient *c;
6559   MESH_TunnelNumber tid;
6560
6561   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel requested\n");
6562
6563   /* Sanity check for client registration */
6564   if (NULL == (c = client_get (client)))
6565   {
6566     GNUNET_break (0);
6567     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6568     return;
6569   }
6570   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6571
6572   /* Message sanity check */
6573   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
6574   {
6575     GNUNET_break (0);
6576     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6577     return;
6578   }
6579
6580   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6581   /* Sanity check for tunnel numbering */
6582   tid = ntohl (t_msg->tunnel_id);
6583   if (0 == (tid & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
6584   {
6585     GNUNET_break (0);
6586     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6587     return;
6588   }
6589   /* Sanity check for duplicate tunnel IDs */
6590   if (NULL != tunnel_get_by_local_id (c, tid))
6591   {
6592     GNUNET_break (0);
6593     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6594     return;
6595   }
6596
6597   while (NULL != tunnel_get_by_pi (myid, next_tid))
6598     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
6599   t = tunnel_new (myid, next_tid++, c, tid);
6600   if (NULL == t)
6601   {
6602     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Tunnel creation failed.\n");
6603     GNUNET_break (0);
6604     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6605     return;
6606   }
6607   next_tid = next_tid & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
6608   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED TUNNEL %s [%x] (%x)\n",
6609               GNUNET_i2s (&my_full_id), t->id.tid, t->local_tid);
6610   t->peers = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6611
6612   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel created\n");
6613   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6614   return;
6615 }
6616
6617
6618 /**
6619  * Handler for requests of deleting tunnels
6620  *
6621  * @param cls closure
6622  * @param client identification of the client
6623  * @param message the actual message
6624  */
6625 static void
6626 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
6627                              const struct GNUNET_MessageHeader *message)
6628 {
6629   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
6630   struct MeshClient *c;
6631   struct MeshTunnel *t;
6632   MESH_TunnelNumber tid;
6633
6634   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6635               "Got a DESTROY TUNNEL from client!\n");
6636
6637   /* Sanity check for client registration */
6638   if (NULL == (c = client_get (client)))
6639   {
6640     GNUNET_break (0);
6641     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6642     return;
6643   }
6644   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6645
6646   /* Message sanity check */
6647   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
6648   {
6649     GNUNET_break (0);
6650     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6651     return;
6652   }
6653
6654   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6655
6656   /* Retrieve tunnel */
6657   tid = ntohl (tunnel_msg->tunnel_id);
6658   t = tunnel_get_by_local_id(c, tid);
6659   if (NULL == t)
6660   {
6661     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
6662     GNUNET_break (0);
6663     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6664     return;
6665   }
6666   if (c != t->owner || tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
6667   {
6668     client_ignore_tunnel (c, t);
6669     tunnel_destroy_empty (t);
6670     GNUNET_SERVER_receive_done (client, GNUNET_OK);
6671     return;
6672   }
6673   send_client_tunnel_disconnect (t, c);
6674   client_delete_tunnel (c, t);
6675
6676   /* Don't try to ACK the client about the tunnel_destroy multicast packet */
6677   t->owner = NULL;
6678   tunnel_send_destroy (t, 0);
6679   t->destroy = GNUNET_YES;
6680   /* The tunnel will be destroyed when the last message is transmitted. */
6681   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6682   return;
6683 }
6684
6685
6686 /**
6687  * Handler for requests of seeting tunnel's speed.
6688  *
6689  * @param cls Closure (unused).
6690  * @param client Identification of the client.
6691  * @param message The actual message.
6692  */
6693 static void
6694 handle_local_tunnel_speed (void *cls, struct GNUNET_SERVER_Client *client,
6695                            const struct GNUNET_MessageHeader *message)
6696 {
6697   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
6698   struct MeshClient *c;
6699   struct MeshTunnel *t;
6700   MESH_TunnelNumber tid;
6701
6702   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6703               "Got a SPEED request from client!\n");
6704
6705   /* Sanity check for client registration */
6706   if (NULL == (c = client_get (client)))
6707   {
6708     GNUNET_break (0);
6709     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6710     return;
6711   }
6712
6713   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6714
6715   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6716
6717   /* Retrieve tunnel */
6718   tid = ntohl (tunnel_msg->tunnel_id);
6719   t = tunnel_get_by_local_id(c, tid);
6720   if (NULL == t)
6721   {
6722     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  tunnel %X not found\n", tid);
6723     GNUNET_break (0);
6724     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6725     return;
6726   }
6727
6728   switch (ntohs(message->type))
6729   {
6730       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MIN:
6731           t->speed_min = GNUNET_YES;
6732           break;
6733       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MAX:
6734           t->speed_min = GNUNET_NO;
6735           break;
6736       default:
6737           GNUNET_break (0);
6738   }
6739   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6740 }
6741
6742
6743 /**
6744  * Handler for requests of seeting tunnel's buffering policy.
6745  *
6746  * @param cls Closure (unused).
6747  * @param client Identification of the client.
6748  * @param message The actual message.
6749  */
6750 static void
6751 handle_local_tunnel_buffer (void *cls, struct GNUNET_SERVER_Client *client,
6752                             const struct GNUNET_MessageHeader *message)
6753 {
6754   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
6755   struct MeshClient *c;
6756   struct MeshTunnel *t;
6757   MESH_TunnelNumber tid;
6758
6759   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6760               "Got a BUFFER request from client!\n");
6761
6762   /* Sanity check for client registration */
6763   if (NULL == (c = client_get (client)))
6764   {
6765     GNUNET_break (0);
6766     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6767     return;
6768   }
6769   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6770
6771   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6772
6773   /* Retrieve tunnel */
6774   tid = ntohl (tunnel_msg->tunnel_id);
6775   t = tunnel_get_by_local_id(c, tid);
6776   if (NULL == t)
6777   {
6778     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
6779     GNUNET_break (0);
6780     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6781     return;
6782   }
6783
6784   switch (ntohs(message->type))
6785   {
6786       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER:
6787           t->nobuffer = GNUNET_NO;
6788           break;
6789       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER:
6790           t->nobuffer = GNUNET_YES;
6791           break;
6792       default:
6793           GNUNET_break (0);
6794   }
6795
6796   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6797 }
6798
6799
6800 /**
6801  * Handler for connection requests to new peers
6802  *
6803  * @param cls closure
6804  * @param client identification of the client
6805  * @param message the actual message (PeerControl)
6806  */
6807 static void
6808 handle_local_connect_add (void *cls, struct GNUNET_SERVER_Client *client,
6809                           const struct GNUNET_MessageHeader *message)
6810 {
6811   struct GNUNET_MESH_PeerControl *peer_msg;
6812   struct MeshPeerInfo *peer_info;
6813   struct MeshClient *c;
6814   struct MeshTunnel *t;
6815   MESH_TunnelNumber tid;
6816
6817   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got connection request\n");
6818   /* Sanity check for client registration */
6819   if (NULL == (c = client_get (client)))
6820   {
6821     GNUNET_break (0);
6822     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6823     return;
6824   }
6825   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6826
6827   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6828
6829   /* Sanity check for message size */
6830   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6831   {
6832     GNUNET_break (0);
6833     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6834     return;
6835   }
6836
6837   /* Tunnel exists? */
6838   tid = ntohl (peer_msg->tunnel_id);
6839   t = tunnel_get_by_local_id (c, tid);
6840   if (NULL == t)
6841   {
6842     GNUNET_break (0);
6843     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6844     return;
6845   }
6846
6847   /* Does client own tunnel? */
6848   if (t->owner->handle != client)
6849   {
6850     GNUNET_break (0);
6851     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6852     return;
6853   }
6854   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "     for %s\n",
6855               GNUNET_i2s (&peer_msg->peer));
6856   peer_info = peer_info_get (&peer_msg->peer);
6857
6858   tunnel_add_peer (t, peer_info);
6859   peer_info_connect (peer_info, t);
6860
6861   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6862   return;
6863 }
6864
6865
6866 /**
6867  * Handler for disconnection requests of peers in a tunnel
6868  *
6869  * @param cls closure
6870  * @param client identification of the client
6871  * @param message the actual message (PeerControl)
6872  */
6873 static void
6874 handle_local_connect_del (void *cls, struct GNUNET_SERVER_Client *client,
6875                           const struct GNUNET_MessageHeader *message)
6876 {
6877   struct GNUNET_MESH_PeerControl *peer_msg;
6878   struct MeshPeerInfo *peer_info;
6879   struct MeshClient *c;
6880   struct MeshTunnel *t;
6881   MESH_TunnelNumber tid;
6882
6883   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER DEL request\n");
6884   /* Sanity check for client registration */
6885   if (NULL == (c = client_get (client)))
6886   {
6887     GNUNET_break (0);
6888     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6889     return;
6890   }
6891   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6892
6893   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6894
6895   /* Sanity check for message size */
6896   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6897   {
6898     GNUNET_break (0);
6899     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6900     return;
6901   }
6902
6903   /* Tunnel exists? */
6904   tid = ntohl (peer_msg->tunnel_id);
6905   t = tunnel_get_by_local_id (c, tid);
6906   if (NULL == t)
6907   {
6908     GNUNET_break (0);
6909     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6910     return;
6911   }
6912   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
6913
6914   /* Does client own tunnel? */
6915   if (t->owner->handle != client)
6916   {
6917     GNUNET_break (0);
6918     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6919     return;
6920   }
6921
6922   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for peer %s\n",
6923               GNUNET_i2s (&peer_msg->peer));
6924   /* Is the peer in the tunnel? */
6925   peer_info =
6926       GNUNET_CONTAINER_multihashmap_get (t->peers, &peer_msg->peer.hashPubKey);
6927   if (NULL == peer_info)
6928   {
6929     GNUNET_break (0);
6930     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6931     return;
6932   }
6933
6934   /* Ok, delete peer from tunnel */
6935   GNUNET_CONTAINER_multihashmap_remove_all (t->peers,
6936                                             &peer_msg->peer.hashPubKey);
6937
6938   send_destroy_path (t, peer_info->id);
6939   tunnel_delete_peer (t, peer_info->id);
6940   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6941   return;
6942 }
6943
6944 /**
6945  * Handler for blacklist requests of peers in a tunnel
6946  *
6947  * @param cls closure
6948  * @param client identification of the client
6949  * @param message the actual message (PeerControl)
6950  * 
6951  * FIXME implement DHT block bloomfilter
6952  */
6953 static void
6954 handle_local_blacklist (void *cls, struct GNUNET_SERVER_Client *client,
6955                           const struct GNUNET_MessageHeader *message)
6956 {
6957   struct GNUNET_MESH_PeerControl *peer_msg;
6958   struct MeshClient *c;
6959   struct MeshTunnel *t;
6960   MESH_TunnelNumber tid;
6961
6962   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER BLACKLIST request\n");
6963   /* Sanity check for client registration */
6964   if (NULL == (c = client_get (client)))
6965   {
6966     GNUNET_break (0);
6967     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6968     return;
6969   }
6970   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6971
6972   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6973
6974   /* Sanity check for message size */
6975   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6976   {
6977     GNUNET_break (0);
6978     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6979     return;
6980   }
6981
6982   /* Tunnel exists? */
6983   tid = ntohl (peer_msg->tunnel_id);
6984   t = tunnel_get_by_local_id (c, tid);
6985   if (NULL == t)
6986   {
6987     GNUNET_break (0);
6988     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6989     return;
6990   }
6991   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
6992
6993   GNUNET_array_append(t->blacklisted, t->nblacklisted,
6994                       GNUNET_PEER_intern(&peer_msg->peer));
6995 }
6996
6997
6998 /**
6999  * Handler for unblacklist requests of peers in a tunnel
7000  *
7001  * @param cls closure
7002  * @param client identification of the client
7003  * @param message the actual message (PeerControl)
7004  */
7005 static void
7006 handle_local_unblacklist (void *cls, struct GNUNET_SERVER_Client *client,
7007                           const struct GNUNET_MessageHeader *message)
7008 {
7009   struct GNUNET_MESH_PeerControl *peer_msg;
7010   struct MeshClient *c;
7011   struct MeshTunnel *t;
7012   MESH_TunnelNumber tid;
7013   GNUNET_PEER_Id pid;
7014   unsigned int i;
7015
7016   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER UNBLACKLIST request\n");
7017   /* Sanity check for client registration */
7018   if (NULL == (c = client_get (client)))
7019   {
7020     GNUNET_break (0);
7021     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7022     return;
7023   }
7024   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7025
7026   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
7027
7028   /* Sanity check for message size */
7029   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
7030   {
7031     GNUNET_break (0);
7032     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7033     return;
7034   }
7035
7036   /* Tunnel exists? */
7037   tid = ntohl (peer_msg->tunnel_id);
7038   t = tunnel_get_by_local_id (c, tid);
7039   if (NULL == t)
7040   {
7041     GNUNET_break (0);
7042     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7043     return;
7044   }
7045   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
7046
7047   /* if peer is not known, complain */
7048   pid = GNUNET_PEER_search (&peer_msg->peer);
7049   if (0 == pid)
7050   {
7051     GNUNET_break (0);
7052     return;
7053   }
7054
7055   /* search and remove from list */
7056   for (i = 0; i < t->nblacklisted; i++)
7057   {
7058     if (t->blacklisted[i] == pid)
7059     {
7060       t->blacklisted[i] = t->blacklisted[t->nblacklisted - 1];
7061       GNUNET_array_grow (t->blacklisted, t->nblacklisted, t->nblacklisted - 1);
7062       return;
7063     }
7064   }
7065
7066   /* if peer hasn't been blacklisted, complain */
7067   GNUNET_break (0);
7068 }
7069
7070
7071 /**
7072  * Handler for connection requests to new peers by type
7073  *
7074  * @param cls closure
7075  * @param client identification of the client
7076  * @param message the actual message (ConnectPeerByType)
7077  */
7078 static void
7079 handle_local_connect_by_type (void *cls, struct GNUNET_SERVER_Client *client,
7080                               const struct GNUNET_MessageHeader *message)
7081 {
7082   struct GNUNET_MESH_ConnectPeerByType *connect_msg;
7083   struct MeshClient *c;
7084   struct MeshTunnel *t;
7085   struct GNUNET_HashCode hash;
7086   MESH_TunnelNumber tid;
7087
7088   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got connect by type request\n");
7089   /* Sanity check for client registration */
7090   if (NULL == (c = client_get (client)))
7091   {
7092     GNUNET_break (0);
7093     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7094     return;
7095   }
7096   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7097
7098   connect_msg = (struct GNUNET_MESH_ConnectPeerByType *) message;
7099
7100   /* Sanity check for message size */
7101   if (sizeof (struct GNUNET_MESH_ConnectPeerByType) !=
7102       ntohs (connect_msg->header.size))
7103   {
7104     GNUNET_break (0);
7105     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7106     return;
7107   }
7108
7109   /* Tunnel exists? */
7110   tid = ntohl (connect_msg->tunnel_id);
7111   t = tunnel_get_by_local_id (c, tid);
7112   if (NULL == t)
7113   {
7114     GNUNET_break (0);
7115     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7116     return;
7117   }
7118
7119   /* Does client own tunnel? */
7120   if (t->owner->handle != client)
7121   {
7122     GNUNET_break (0);
7123     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7124     return;
7125   }
7126
7127   /* Do WE have the service? */
7128   t->type = ntohl (connect_msg->type);
7129   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " type requested: %u\n", t->type);
7130   GNUNET_CRYPTO_hash (&t->type, sizeof (GNUNET_MESH_ApplicationType), &hash);
7131   if (GNUNET_CONTAINER_multihashmap_contains (applications, &hash) ==
7132       GNUNET_YES)
7133   {
7134     /* Yes! Fast forward, add ourselves to the tunnel and send the
7135      * good news to the client, and alert the destination client of
7136      * an incoming tunnel.
7137      *
7138      * FIXME send a path create to self, avoid code duplication
7139      */
7140     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " available locally\n");
7141     GNUNET_CONTAINER_multihashmap_put (t->peers, &my_full_id.hashPubKey,
7142                                        peer_info_get (&my_full_id),
7143                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
7144
7145     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " notifying client\n");
7146     send_client_peer_connected (t, myid);
7147     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Done\n");
7148     GNUNET_SERVER_receive_done (client, GNUNET_OK);
7149
7150     t->local_tid_dest = next_local_tid++;
7151     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
7152     GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
7153                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
7154
7155     return;
7156   }
7157   /* Ok, lets find a peer offering the service */
7158   if (NULL != t->dht_get_type)
7159   {
7160     GNUNET_DHT_get_stop (t->dht_get_type);
7161   }
7162   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " looking in DHT for %s\n",
7163               GNUNET_h2s (&hash));
7164   t->dht_get_type =
7165       GNUNET_DHT_get_start (dht_handle, 
7166                             GNUNET_BLOCK_TYPE_MESH_PEER_BY_TYPE,
7167                             &hash,
7168                             dht_replication_level,
7169                             GNUNET_DHT_RO_RECORD_ROUTE |
7170                             GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
7171                             NULL, 0,
7172                             &dht_get_type_handler, t);
7173
7174   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7175   return;
7176 }
7177
7178
7179 /**
7180  * Handler for connection requests to new peers by a string service description.
7181  *
7182  * @param cls closure
7183  * @param client identification of the client
7184  * @param message the actual message, which includes messages the client wants
7185  */
7186 static void
7187 handle_local_connect_by_string (void *cls, struct GNUNET_SERVER_Client *client,
7188                                 const struct GNUNET_MessageHeader *message)
7189 {
7190   struct GNUNET_MESH_ConnectPeerByString *msg;
7191   struct MeshRegexSearchInfo *info;
7192   struct MeshTunnel *t;
7193   struct MeshClient *c;
7194   MESH_TunnelNumber tid;
7195   const char *string;
7196   size_t size;
7197   size_t len;
7198
7199   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7200               "Connect by string started\n");
7201   msg = (struct GNUNET_MESH_ConnectPeerByString *) message;
7202   size = htons (message->size);
7203
7204   /* Sanity check for client registration */
7205   if (NULL == (c = client_get (client)))
7206   {
7207     GNUNET_break (0);
7208     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7209     return;
7210   }
7211   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7212
7213   /* Message size sanity check */
7214   if (sizeof(struct GNUNET_MESH_ConnectPeerByString) >= size)
7215   {
7216     GNUNET_break (0);
7217     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7218     return;
7219   }
7220
7221   /* Tunnel exists? */
7222   tid = ntohl (msg->tunnel_id);
7223   t = tunnel_get_by_local_id (c, tid);
7224   if (NULL == t)
7225   {
7226     GNUNET_break (0);
7227     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7228     return;
7229   }
7230
7231   /* Does client own tunnel? */
7232   if (t->owner->handle != client)
7233   {
7234     GNUNET_break (0);
7235     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7236     return;
7237   }
7238
7239   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7240               "  on tunnel %s [%u]\n",
7241               GNUNET_i2s(&my_full_id),
7242               t->id.tid);
7243
7244   /* Only one connect_by_string allowed at the same time! */
7245   /* FIXME: allow more, return handle at api level to cancel, document */
7246   if (NULL != t->regex_search)
7247   {
7248     GNUNET_break (0);
7249     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7250     return;
7251   }
7252
7253   /* Find string itself */
7254   len = size - sizeof(struct GNUNET_MESH_ConnectPeerByString);
7255   string = (const char *) &msg[1];
7256
7257   info = GNUNET_malloc (sizeof (struct MeshRegexSearchInfo));
7258   info->t = t;
7259   info->description = GNUNET_strndup (string, len);
7260   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   string: %s\n", info->description);
7261
7262   t->regex_search = info;
7263
7264   info->search_handle = GNUNET_REGEX_search (dht_handle,
7265                                              info->description,
7266                                              &regex_found_handler, info,
7267                                              stats);
7268
7269   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7270   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "connect by string processed\n");
7271 }
7272
7273
7274 /**
7275  * Handler for client traffic directed to one peer
7276  *
7277  * @param cls closure
7278  * @param client identification of the client
7279  * @param message the actual message
7280  */
7281 static void
7282 handle_local_unicast (void *cls, struct GNUNET_SERVER_Client *client,
7283                       const struct GNUNET_MessageHeader *message)
7284 {
7285   struct MeshClient *c;
7286   struct MeshTunnel *t;
7287   struct MeshPeerInfo *pi;
7288   struct GNUNET_MESH_Unicast *data_msg;
7289   MESH_TunnelNumber tid;
7290   size_t size;
7291
7292   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7293               "Got a unicast request from a client!\n");
7294
7295   /* Sanity check for client registration */
7296   if (NULL == (c = client_get (client)))
7297   {
7298     GNUNET_break (0);
7299     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7300     return;
7301   }
7302   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7303
7304   data_msg = (struct GNUNET_MESH_Unicast *) message;
7305
7306   /* Sanity check for message size */
7307   size = ntohs (message->size);
7308   if (sizeof (struct GNUNET_MESH_Unicast) +
7309       sizeof (struct GNUNET_MessageHeader) > size)
7310   {
7311     GNUNET_break (0);
7312     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7313     return;
7314   }
7315
7316   /* Tunnel exists? */
7317   tid = ntohl (data_msg->tid);
7318   t = tunnel_get_by_local_id (c, tid);
7319   if (NULL == t)
7320   {
7321     GNUNET_break (0);
7322     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7323     return;
7324   }
7325
7326   /*  Is it a local tunnel? Then, does client own the tunnel? */
7327   if (t->owner->handle != client)
7328   {
7329     GNUNET_break (0);
7330     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7331     return;
7332   }
7333
7334   pi = GNUNET_CONTAINER_multihashmap_get (t->peers,
7335                                           &data_msg->destination.hashPubKey);
7336   /* Is the selected peer in the tunnel? */
7337   if (NULL == pi)
7338   {
7339     GNUNET_break (0);
7340     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7341     return;
7342   }
7343
7344   /* PID should be as expected */
7345   if (ntohl (data_msg->pid) != t->fwd_pid + 1)
7346   {
7347     GNUNET_break (0);
7348     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7349               "Unicast PID, expected %u, got %u\n",
7350               t->fwd_pid + 1, ntohl (data_msg->pid));
7351     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7352     return;
7353   }
7354
7355   /* Ok, everything is correct, send the message
7356    * (pretend we got it from a mesh peer)
7357    */
7358   {
7359     /* Work around const limitation */
7360     char buf[ntohs (message->size)] GNUNET_ALIGN;
7361     struct GNUNET_MESH_Unicast *copy;
7362
7363     copy = (struct GNUNET_MESH_Unicast *) buf;
7364     memcpy (buf, data_msg, size);
7365     copy->oid = my_full_id;
7366     copy->tid = htonl (t->id.tid);
7367     copy->ttl = htonl (default_ttl);
7368     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7369                 "  calling generic handler...\n");
7370     handle_mesh_data_unicast (NULL, &my_full_id, &copy->header, NULL, 0);
7371   }
7372   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "receive done OK\n");
7373   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7374
7375   return;
7376 }
7377
7378
7379 /**
7380  * Handler for client traffic directed to the origin
7381  *
7382  * @param cls closure
7383  * @param client identification of the client
7384  * @param message the actual message
7385  */
7386 static void
7387 handle_local_to_origin (void *cls, struct GNUNET_SERVER_Client *client,
7388                         const struct GNUNET_MessageHeader *message)
7389 {
7390   struct GNUNET_MESH_ToOrigin *data_msg;
7391   struct MeshTunnelClientInfo *clinfo;
7392   struct MeshClient *c;
7393   struct MeshTunnel *t;
7394   MESH_TunnelNumber tid;
7395   size_t size;
7396
7397   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7398               "Got a ToOrigin request from a client!\n");
7399   /* Sanity check for client registration */
7400   if (NULL == (c = client_get (client)))
7401   {
7402     GNUNET_break (0);
7403     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7404     return;
7405   }
7406   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7407
7408   data_msg = (struct GNUNET_MESH_ToOrigin *) message;
7409
7410   /* Sanity check for message size */
7411   size = ntohs (message->size);
7412   if (sizeof (struct GNUNET_MESH_ToOrigin) +
7413       sizeof (struct GNUNET_MessageHeader) > size)
7414   {
7415     GNUNET_break (0);
7416     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7417     return;
7418   }
7419
7420   /* Tunnel exists? */
7421   tid = ntohl (data_msg->tid);
7422   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
7423   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
7424   {
7425     GNUNET_break (0);
7426     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7427     return;
7428   }
7429   t = tunnel_get_by_local_id (c, tid);
7430   if (NULL == t)
7431   {
7432     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
7433     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
7434     GNUNET_break (0);
7435     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7436     return;
7437   }
7438
7439   /*  It should be sent by someone who has this as incoming tunnel. */
7440   if (GNUNET_NO == client_knows_tunnel (c, t))
7441   {
7442     GNUNET_break (0);
7443     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7444     return;
7445   }
7446
7447   /* PID should be as expected */
7448   clinfo = tunnel_get_client_fc (t, c);
7449   if (ntohl (data_msg->pid) != clinfo->bck_pid + 1)
7450   {
7451     GNUNET_break (0);
7452     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7453                 "To Origin PID, expected %u, got %u\n",
7454                 clinfo->bck_pid + 1,
7455                 ntohl (data_msg->pid));
7456     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7457     return;
7458   }
7459   clinfo->bck_pid++;
7460
7461   /* Ok, everything is correct, send the message
7462    * (pretend we got it from a mesh peer)
7463    */
7464   {
7465     char buf[ntohs (message->size)] GNUNET_ALIGN;
7466     struct GNUNET_MESH_ToOrigin *copy;
7467
7468     /* Work around const limitation */
7469     copy = (struct GNUNET_MESH_ToOrigin *) buf;
7470     memcpy (buf, data_msg, size);
7471     GNUNET_PEER_resolve (t->id.oid, &copy->oid);
7472     copy->tid = htonl (t->id.tid);
7473     copy->ttl = htonl (default_ttl);
7474     copy->pid = htonl (t->bck_pid + 1);
7475
7476     copy->sender = my_full_id;
7477     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7478                 "  calling generic handler...\n");
7479     handle_mesh_data_to_orig (NULL, &my_full_id, &copy->header, NULL, 0);
7480   }
7481   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7482
7483   return;
7484 }
7485
7486
7487 /**
7488  * Handler for client traffic directed to all peers in a tunnel
7489  *
7490  * @param cls closure
7491  * @param client identification of the client
7492  * @param message the actual message
7493  */
7494 static void
7495 handle_local_multicast (void *cls, struct GNUNET_SERVER_Client *client,
7496                         const struct GNUNET_MessageHeader *message)
7497 {
7498   struct MeshClient *c;
7499   struct MeshTunnel *t;
7500   struct GNUNET_MESH_Multicast *data_msg;
7501   MESH_TunnelNumber tid;
7502
7503   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7504               "Got a multicast request from a client!\n");
7505
7506   /* Sanity check for client registration */
7507   if (NULL == (c = client_get (client)))
7508   {
7509     GNUNET_break (0);
7510     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7511     return;
7512   }
7513   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7514
7515   data_msg = (struct GNUNET_MESH_Multicast *) message;
7516
7517   /* Sanity check for message size */
7518   if (sizeof (struct GNUNET_MESH_Multicast) +
7519       sizeof (struct GNUNET_MessageHeader) > ntohs (data_msg->header.size))
7520   {
7521     GNUNET_break (0);
7522     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7523     return;
7524   }
7525
7526   /* Tunnel exists? */
7527   tid = ntohl (data_msg->tid);
7528   t = tunnel_get_by_local_id (c, tid);
7529   if (NULL == t)
7530   {
7531     GNUNET_break (0);
7532     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
7533     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
7534     GNUNET_break (0);
7535     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7536     return;
7537   }
7538
7539   /* Does client own tunnel? */
7540   if (t->owner->handle != client)
7541   {
7542     GNUNET_break (0);
7543     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7544     return;
7545   }
7546
7547   /* PID should be as expected */
7548   if (ntohl (data_msg->pid) != t->fwd_pid + 1)
7549   {
7550     GNUNET_break (0);
7551     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7552               "Multicast PID, expected %u, got %u\n",
7553               t->fwd_pid + 1, ntohl (data_msg->pid));
7554     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7555     return;
7556   }
7557
7558   {
7559     char buf[ntohs (message->size)] GNUNET_ALIGN;
7560     struct GNUNET_MESH_Multicast *copy;
7561
7562     copy = (struct GNUNET_MESH_Multicast *) buf;
7563     memcpy (buf, message, ntohs (message->size));
7564     copy->oid = my_full_id;
7565     copy->tid = htonl (t->id.tid);
7566     copy->ttl = htonl (default_ttl);
7567     GNUNET_assert (ntohl (copy->pid) == (t->fwd_pid + 1));
7568     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7569                 "  calling generic handler...\n");
7570     handle_mesh_data_multicast (client, &my_full_id, &copy->header, NULL, 0);
7571   }
7572
7573   GNUNET_SERVER_receive_done (t->owner->handle, GNUNET_OK);
7574   return;
7575 }
7576
7577
7578 /**
7579  * Handler for client's ACKs for payload traffic.
7580  *
7581  * @param cls Closure (unused).
7582  * @param client Identification of the client.
7583  * @param message The actual message.
7584  */
7585 static void
7586 handle_local_ack (void *cls, struct GNUNET_SERVER_Client *client,
7587                   const struct GNUNET_MessageHeader *message)
7588 {
7589   struct GNUNET_MESH_LocalAck *msg;
7590   struct MeshTunnel *t;
7591   struct MeshClient *c;
7592   MESH_TunnelNumber tid;
7593   uint32_t ack;
7594
7595   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a local ACK\n");
7596   /* Sanity check for client registration */
7597   if (NULL == (c = client_get (client)))
7598   {
7599     GNUNET_break (0);
7600     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7601     return;
7602   }
7603   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7604
7605   msg = (struct GNUNET_MESH_LocalAck *) message;
7606
7607   /* Tunnel exists? */
7608   tid = ntohl (msg->tunnel_id);
7609   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
7610   t = tunnel_get_by_local_id (c, tid);
7611   if (NULL == t)
7612   {
7613     GNUNET_break (0);
7614     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
7615     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
7616     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7617     return;
7618   }
7619
7620   ack = ntohl (msg->max_pid);
7621   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ack %u\n", ack);
7622
7623   /* Does client own tunnel? I.E: Is this an ACK for BCK traffic? */
7624   if (NULL != t->owner && t->owner->handle == client)
7625   {
7626     /* The client owns the tunnel, ACK is for data to_origin, send BCK ACK. */
7627     t->bck_ack = ack;
7628     tunnel_send_bck_ack(t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
7629   }
7630   else
7631   {
7632     /* The client doesn't own the tunnel, this ACK is for FWD traffic. */
7633     tunnel_set_client_fwd_ack (t, c, ack);
7634     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
7635   }
7636
7637   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7638
7639   return;
7640 }
7641
7642
7643 /**
7644  * Iterator over all peers to send a monitoring client info about a tunnel.
7645  *
7646  * @param cls Closure (message being built).
7647  * @param key Key (hashed tunnel ID, unused).
7648  * @param value Peer info.
7649  *
7650  * @return GNUNET_YES, to keep iterating.
7651  */
7652 static int
7653 monitor_peers_iterator (void *cls,
7654                         const struct GNUNET_HashCode * key,
7655                         void *value)
7656 {
7657   struct GNUNET_MESH_LocalMonitor *msg = cls;
7658   struct GNUNET_PeerIdentity *id;
7659   struct MeshPeerInfo *info = value;
7660
7661   id = (struct GNUNET_PeerIdentity *) &msg[1];
7662   GNUNET_PEER_resolve (info->id, &id[msg->npeers]);
7663   msg->npeers++;
7664
7665   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
7666               "*    sending info about peer %s [%u]\n",
7667               GNUNET_i2s (&id[msg->npeers - 1]), msg->npeers);
7668
7669   return GNUNET_YES;
7670 }
7671
7672
7673
7674 /**
7675  * Iterator over all tunnels to send a monitoring client info about each tunnel.
7676  *
7677  * @param cls Closure (client handle).
7678  * @param key Key (hashed tunnel ID, unused).
7679  * @param value Tunnel info.
7680  *
7681  * @return GNUNET_YES, to keep iterating.
7682  */
7683 static int
7684 monitor_all_tunnels_iterator (void *cls,
7685                               const struct GNUNET_HashCode * key,
7686                               void *value)
7687 {
7688   struct GNUNET_SERVER_Client *client = cls;
7689   struct MeshTunnel *t = value;
7690   struct GNUNET_MESH_LocalMonitor *msg;
7691   uint32_t npeers;
7692   
7693   npeers = GNUNET_CONTAINER_multihashmap_size (t->peers);
7694   msg = GNUNET_malloc (sizeof(struct GNUNET_MESH_LocalMonitor) +
7695   npeers * sizeof (struct GNUNET_PeerIdentity));
7696   GNUNET_PEER_resolve(t->id.oid, &msg->owner);
7697   msg->tunnel_id = htonl (t->id.tid);
7698   msg->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor) +
7699   npeers * sizeof (struct GNUNET_PeerIdentity));
7700   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS);
7701   msg->npeers = 0;
7702   (void) GNUNET_CONTAINER_multihashmap_iterate (t->peers,
7703                                                 monitor_peers_iterator,
7704                                                 msg);
7705   
7706   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
7707               "*  sending info about tunnel %s [%u] (%u peers)\n",
7708               GNUNET_i2s (&msg->owner), t->id.tid, npeers);
7709   
7710   if (msg->npeers != npeers)
7711   {
7712     GNUNET_break (0);
7713     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7714                 "Get tunnels fail: size %u - iter %u\n",
7715                 npeers, msg->npeers);
7716   }
7717   
7718     msg->npeers = htonl (npeers);
7719     GNUNET_SERVER_notification_context_unicast (nc, client,
7720                                                 &msg->header, GNUNET_NO);
7721     return GNUNET_YES;
7722 }
7723
7724
7725 /**
7726  * Handler for client's MONITOR request.
7727  *
7728  * @param cls Closure (unused).
7729  * @param client Identification of the client.
7730  * @param message The actual message.
7731  */
7732 static void
7733 handle_local_get_tunnels (void *cls, struct GNUNET_SERVER_Client *client,
7734                           const struct GNUNET_MessageHeader *message)
7735 {
7736   struct MeshClient *c;
7737
7738   /* Sanity check for client registration */
7739   if (NULL == (c = client_get (client)))
7740   {
7741     GNUNET_break (0);
7742     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7743     return;
7744   }
7745
7746   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
7747               "Received get tunnels request from client %u\n",
7748               c->id);
7749   GNUNET_CONTAINER_multihashmap_iterate (tunnels,
7750                                          monitor_all_tunnels_iterator,
7751                                          client);
7752   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
7753               "Get tunnels request from client %u completed\n",
7754               c->id);
7755   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7756 }
7757
7758
7759 /**
7760  * Data needed to build a Monitor_Tunnel message.
7761  */
7762 struct MeshMonitorTunnelContext
7763 {
7764   /**
7765    * Partial message, including peer count.
7766    */
7767   struct GNUNET_MESH_LocalMonitor *msg;
7768
7769   /**
7770    * Hashmap with positions: peer->position.
7771    */
7772   struct GNUNET_CONTAINER_MultiHashMap *lookup;
7773
7774   /**
7775    * Index of the parent of each peer in the message, realtive to the absolute
7776    * order in the array (can be in a previous message).
7777    */
7778   uint32_t parents[1024];
7779
7780   /**
7781    * Peers visited so far in the tree, aka position of the current peer.
7782    */
7783   unsigned int npeers;
7784
7785   /**
7786    * Client requesting the info.
7787    */
7788   struct MeshClient *c;
7789 };
7790
7791
7792 /**
7793  * Send a client a message about the structure of a tunnel.
7794  *
7795  * @param ctx Context of the tunnel iteration, with info regarding the state
7796  *            of the execution and the number of peers visited for this message.
7797  */
7798 static void
7799 send_client_tunnel_info (struct MeshMonitorTunnelContext *ctx)
7800 {
7801   struct GNUNET_MESH_LocalMonitor *resp = ctx->msg;
7802   struct GNUNET_PeerIdentity *pid;
7803   unsigned int *parent;
7804   size_t size;
7805
7806   size = sizeof (struct GNUNET_MESH_LocalMonitor);
7807   size += (sizeof (struct GNUNET_PeerIdentity) + sizeof (int)) * resp->npeers;
7808   resp->header.size = htons (size);
7809   pid = (struct GNUNET_PeerIdentity *) &resp[1];
7810   parent = (unsigned int *) &pid[resp->npeers];
7811   memcpy (parent, ctx->parents, sizeof(uint32_t) * resp->npeers);
7812   GNUNET_SERVER_notification_context_unicast (nc, ctx->c->handle,
7813                                               &resp->header, GNUNET_NO);
7814 }
7815
7816 /**
7817  * Iterator over a tunnel tree to build a message containing all peers
7818  * the in the tunnel, including relay nodes.
7819  *
7820  * @param cls Closure (pointer to pointer of message being built).
7821  * @param peer Short ID of a peer.
7822  * @param parent Short ID of the @c peer 's parent.
7823  */
7824 static void
7825 tunnel_tree_iterator (void *cls,
7826                       GNUNET_PEER_Id peer,
7827                       GNUNET_PEER_Id parent)
7828 {
7829   struct MeshMonitorTunnelContext *ctx = cls;
7830   struct GNUNET_MESH_LocalMonitor *msg;
7831   struct GNUNET_PeerIdentity *pid;
7832   struct GNUNET_PeerIdentity ppid;
7833
7834   msg = ctx->msg;
7835   pid = (struct GNUNET_PeerIdentity *) &msg[1];
7836   GNUNET_PEER_resolve (peer, &pid[msg->npeers]);
7837   GNUNET_CONTAINER_multihashmap_put (ctx->lookup,
7838                                      &pid[msg->npeers].hashPubKey,
7839                                      (void *) (long) ctx->npeers,
7840                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
7841   GNUNET_PEER_resolve (parent, &ppid);
7842   ctx->parents[msg->npeers] =
7843       htonl ((long) GNUNET_CONTAINER_multihashmap_get (ctx->lookup,
7844                                                        &ppid.hashPubKey));
7845
7846   ctx->npeers++;
7847   msg->npeers++;
7848
7849   if (sizeof (struct GNUNET_MESH_LocalMonitor) +
7850       (msg->npeers + 1) *
7851       (sizeof (struct GNUNET_PeerIdentity) + sizeof (uint32_t))
7852       > USHRT_MAX)
7853   {
7854     send_client_tunnel_info (ctx);
7855     msg->npeers = 0;
7856   }
7857 }
7858
7859
7860 /**
7861  * Handler for client's MONITOR_TUNNEL request.
7862  *
7863  * @param cls Closure (unused).
7864  * @param client Identification of the client.
7865  * @param message The actual message.
7866  */
7867 static void
7868 handle_local_show_tunnel (void *cls, struct GNUNET_SERVER_Client *client,
7869                           const struct GNUNET_MessageHeader *message)
7870 {
7871   const struct GNUNET_MESH_LocalMonitor *msg;
7872   struct GNUNET_MESH_LocalMonitor *resp;
7873   struct MeshMonitorTunnelContext ctx;
7874   struct MeshClient *c;
7875   struct MeshTunnel *t;
7876
7877   /* Sanity check for client registration */
7878   if (NULL == (c = client_get (client)))
7879   {
7880     GNUNET_break (0);
7881     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7882     return;
7883   }
7884
7885   msg = (struct GNUNET_MESH_LocalMonitor *) message;
7886   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
7887               "Received tunnel info request from client %u for tunnel %s[%X]\n",
7888               c->id,
7889               &msg->owner,
7890               ntohl (msg->tunnel_id));
7891   t = tunnel_get (&msg->owner, ntohl (msg->tunnel_id));
7892   if (NULL == t)
7893   {
7894     /* We don't know the tunnel */
7895     struct GNUNET_MESH_LocalMonitor warn;
7896
7897     warn = *msg;
7898     warn.npeers = htonl (UINT_MAX);
7899     GNUNET_SERVER_notification_context_unicast (nc, client,
7900                                                 &warn.header,
7901                                                 GNUNET_NO);
7902     GNUNET_SERVER_receive_done (client, GNUNET_OK);
7903     return;
7904   }
7905
7906   /* Initialize context */
7907   resp = GNUNET_malloc (USHRT_MAX); /* avoid realloc'ing on each step */
7908   *resp = *msg;
7909   resp->npeers = 0;
7910   ctx.msg = resp;
7911   ctx.lookup = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_YES);
7912   ctx.c = c;
7913
7914   /* Collect and send information */
7915   tree_iterate_all (t->tree, &tunnel_tree_iterator, &ctx);
7916   send_client_tunnel_info (&ctx);
7917
7918   /* Free context */
7919   GNUNET_CONTAINER_multihashmap_destroy (ctx.lookup);
7920   GNUNET_free (resp);
7921
7922   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
7923               "Monitor tunnel request from client %u completed\n",
7924               c->id);
7925   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7926 }
7927
7928
7929 /**
7930  * Functions to handle messages from clients
7931  */
7932 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
7933   {&handle_local_new_client, NULL,
7934    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
7935   {&handle_local_announce_regex, NULL,
7936    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ANNOUNCE_REGEX, 0},
7937   {&handle_local_tunnel_create, NULL,
7938    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
7939    sizeof (struct GNUNET_MESH_TunnelMessage)},
7940   {&handle_local_tunnel_destroy, NULL,
7941    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
7942    sizeof (struct GNUNET_MESH_TunnelMessage)},
7943   {&handle_local_tunnel_speed, NULL,
7944    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MIN,
7945    sizeof (struct GNUNET_MESH_TunnelMessage)},
7946   {&handle_local_tunnel_speed, NULL,
7947    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MAX,
7948    sizeof (struct GNUNET_MESH_TunnelMessage)},
7949   {&handle_local_tunnel_buffer, NULL,
7950    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER,
7951    sizeof (struct GNUNET_MESH_TunnelMessage)},
7952   {&handle_local_tunnel_buffer, NULL,
7953    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER,
7954    sizeof (struct GNUNET_MESH_TunnelMessage)},
7955   {&handle_local_connect_add, NULL,
7956    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD,
7957    sizeof (struct GNUNET_MESH_PeerControl)},
7958   {&handle_local_connect_del, NULL,
7959    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL,
7960    sizeof (struct GNUNET_MESH_PeerControl)},
7961   {&handle_local_blacklist, NULL,
7962    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_BLACKLIST,
7963    sizeof (struct GNUNET_MESH_PeerControl)},
7964   {&handle_local_unblacklist, NULL,
7965    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_UNBLACKLIST,
7966    sizeof (struct GNUNET_MESH_PeerControl)},
7967   {&handle_local_connect_by_type, NULL,
7968    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE,
7969    sizeof (struct GNUNET_MESH_ConnectPeerByType)},
7970   {&handle_local_connect_by_string, NULL,
7971    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_STRING, 0},
7972   {&handle_local_unicast, NULL,
7973    GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
7974   {&handle_local_to_origin, NULL,
7975    GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
7976   {&handle_local_multicast, NULL,
7977    GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
7978   {&handle_local_ack, NULL,
7979    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK,
7980    sizeof (struct GNUNET_MESH_LocalAck)},
7981   {&handle_local_get_tunnels, NULL,
7982    GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS,
7983    sizeof (struct GNUNET_MessageHeader)},
7984   {&handle_local_show_tunnel, NULL,
7985    GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNEL,
7986      sizeof (struct GNUNET_MESH_LocalMonitor)},
7987   {NULL, NULL, 0, 0}
7988 };
7989
7990
7991 /**
7992  * To be called on core init/fail.
7993  *
7994  * @param cls service closure
7995  * @param server handle to the server for this service
7996  * @param identity the public identity of this peer
7997  */
7998 static void
7999 core_init (void *cls, struct GNUNET_CORE_Handle *server,
8000            const struct GNUNET_PeerIdentity *identity)
8001 {
8002   static int i = 0;
8003   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
8004   core_handle = server;
8005   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)) ||
8006       NULL == server)
8007   {
8008     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
8009     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8010                 " core id %s\n",
8011                 GNUNET_i2s (identity));
8012     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8013                 " my id %s\n",
8014                 GNUNET_i2s (&my_full_id));
8015     GNUNET_SCHEDULER_shutdown (); // Try gracefully
8016     if (10 < i++)
8017       GNUNET_abort(); // Try harder
8018   }
8019   return;
8020 }
8021
8022
8023 /**
8024  * Method called whenever a given peer connects.
8025  *
8026  * @param cls closure
8027  * @param peer peer identity this notification is about
8028  * @param atsi performance data for the connection
8029  * @param atsi_count number of records in 'atsi'
8030  */
8031 static void
8032 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
8033               const struct GNUNET_ATS_Information *atsi,
8034               unsigned int atsi_count)
8035 {
8036   struct MeshPeerInfo *peer_info;
8037   struct MeshPeerPath *path;
8038
8039   DEBUG_CONN ("Peer connected\n");
8040   DEBUG_CONN ("     %s\n", GNUNET_i2s (&my_full_id));
8041   peer_info = peer_info_get (peer);
8042   if (myid == peer_info->id)
8043   {
8044     DEBUG_CONN ("     (self)\n");
8045     return;
8046   }
8047   else
8048   {
8049     DEBUG_CONN ("     %s\n", GNUNET_i2s (peer));
8050   }
8051   path = path_new (2);
8052   path->peers[0] = myid;
8053   path->peers[1] = peer_info->id;
8054   GNUNET_PEER_change_rc (myid, 1);
8055   GNUNET_PEER_change_rc (peer_info->id, 1);
8056   peer_info_add_path (peer_info, path, GNUNET_YES);
8057   GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
8058   return;
8059 }
8060
8061
8062 /**
8063  * Method called whenever a peer disconnects.
8064  *
8065  * @param cls closure
8066  * @param peer peer identity this notification is about
8067  */
8068 static void
8069 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
8070 {
8071   struct MeshPeerInfo *pi;
8072   struct MeshPeerQueue *q;
8073   struct MeshPeerQueue *n;
8074
8075   DEBUG_CONN ("Peer disconnected\n");
8076   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
8077   if (NULL == pi)
8078   {
8079     GNUNET_break (0);
8080     return;
8081   }
8082   q = pi->queue_head;
8083   while (NULL != q)
8084   {
8085       n = q->next;
8086       /* TODO try to reroute this traffic instead */
8087       queue_destroy(q, GNUNET_YES);
8088       q = n;
8089   }
8090   if (NULL != pi->core_transmit)
8091   {
8092     GNUNET_CORE_notify_transmit_ready_cancel(pi->core_transmit);
8093     pi->core_transmit = NULL;
8094   }
8095   peer_info_remove_path (pi, pi->id, myid);
8096   if (myid == pi->id)
8097   {
8098     DEBUG_CONN ("     (self)\n");
8099   }
8100   GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
8101   return;
8102 }
8103
8104
8105 /******************************************************************************/
8106 /************************      MAIN FUNCTIONS      ****************************/
8107 /******************************************************************************/
8108
8109 /**
8110  * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
8111  *
8112  * @param cls closure
8113  * @param key current key code
8114  * @param value value in the hash map
8115  * @return GNUNET_YES if we should continue to iterate,
8116  *         GNUNET_NO if not.
8117  */
8118 static int
8119 shutdown_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
8120 {
8121   struct MeshTunnel *t = value;
8122
8123   tunnel_destroy (t);
8124   return GNUNET_YES;
8125 }
8126
8127 /**
8128  * Iterator over peer hash map entries to destroy the tunnel during shutdown.
8129  *
8130  * @param cls closure
8131  * @param key current key code
8132  * @param value value in the hash map
8133  * @return GNUNET_YES if we should continue to iterate,
8134  *         GNUNET_NO if not.
8135  */
8136 static int
8137 shutdown_peer (void *cls, const struct GNUNET_HashCode * key, void *value)
8138 {
8139   struct MeshPeerInfo *p = value;
8140   struct MeshPeerQueue *q;
8141   struct MeshPeerQueue *n;
8142
8143   q = p->queue_head;
8144   while (NULL != q)
8145   {
8146       n = q->next;
8147       if (q->peer == p)
8148       {
8149         queue_destroy(q, GNUNET_YES);
8150       }
8151       q = n;
8152   }
8153   peer_info_destroy (p);
8154   return GNUNET_YES;
8155 }
8156
8157
8158 /**
8159  * Task run during shutdown.
8160  *
8161  * @param cls unused
8162  * @param tc unused
8163  */
8164 static void
8165 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
8166 {
8167   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
8168
8169   if (core_handle != NULL)
8170   {
8171     GNUNET_CORE_disconnect (core_handle);
8172     core_handle = NULL;
8173   }
8174   if (NULL != keygen)
8175   {
8176     GNUNET_CRYPTO_ecc_key_create_stop (keygen);
8177     keygen = NULL;
8178   }
8179   GNUNET_CONTAINER_multihashmap_iterate (tunnels, &shutdown_tunnel, NULL);
8180   GNUNET_CONTAINER_multihashmap_iterate (peers, &shutdown_peer, NULL);
8181   if (dht_handle != NULL)
8182   {
8183     GNUNET_DHT_disconnect (dht_handle);
8184     dht_handle = NULL;
8185   }
8186   if (nc != NULL)
8187   {
8188     GNUNET_SERVER_notification_context_destroy (nc);
8189     nc = NULL;
8190   }
8191   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
8192   {
8193     GNUNET_SCHEDULER_cancel (announce_id_task);
8194     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
8195   }
8196   if (GNUNET_SCHEDULER_NO_TASK != announce_applications_task)
8197   {
8198     GNUNET_SCHEDULER_cancel (announce_applications_task);
8199     announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
8200   }
8201   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
8202 }
8203
8204
8205 /**
8206  * Callback for hostkey read/generation.
8207  *
8208  * @param cls Closure (Configuration handle).
8209  * @param pk The ECC private key.
8210  * @param emsg Error message, if any.
8211  */
8212 static void
8213 key_generation_cb (void *cls,
8214                    struct GNUNET_CRYPTO_EccPrivateKey *pk,
8215                    const char *emsg)
8216 {
8217   const struct GNUNET_CONFIGURATION_Handle *c = cls;
8218   struct MeshPeerInfo *peer;
8219   struct MeshPeerPath *p;
8220
8221   keygen = NULL;  
8222   if (NULL == pk)
8223   {
8224     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8225                 _("Mesh service could not access hostkey: %s. Exiting.\n"),
8226                 emsg);
8227     GNUNET_SCHEDULER_shutdown ();
8228     return;
8229   }
8230   my_private_key = pk;
8231   GNUNET_CRYPTO_ecc_key_get_public (my_private_key, &my_public_key);
8232   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
8233                       &my_full_id.hashPubKey);
8234   myid = GNUNET_PEER_intern (&my_full_id);
8235   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
8236               "Mesh for peer [%s] starting\n",
8237               GNUNET_i2s(&my_full_id));
8238
8239   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
8240                                      NULL,      /* Closure passed to MESH functions */
8241                                      &core_init,        /* Call core_init once connected */
8242                                      &core_connect,     /* Handle connects */
8243                                      &core_disconnect,  /* remove peers on disconnects */
8244                                      NULL,      /* Don't notify about all incoming messages */
8245                                      GNUNET_NO, /* For header only in notification */
8246                                      NULL,      /* Don't notify about all outbound messages */
8247                                      GNUNET_NO, /* For header-only out notification */
8248                                      core_handlers);    /* Register these handlers */
8249   
8250   if (core_handle == NULL)
8251   {
8252     GNUNET_break (0);
8253     GNUNET_SCHEDULER_shutdown ();
8254     return;
8255   }
8256
8257   next_tid = 0;
8258   next_local_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
8259
8260
8261   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
8262   nc = GNUNET_SERVER_notification_context_create (server_handle, 1);
8263   GNUNET_SERVER_disconnect_notify (server_handle,
8264                                    &handle_local_client_disconnect, NULL);
8265
8266
8267   clients = NULL;
8268   clients_tail = NULL;
8269   next_client_id = 0;
8270
8271   announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
8272   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
8273
8274   /* Create a peer_info for the local peer */
8275   peer = peer_info_get (&my_full_id);
8276   p = path_new (1);
8277   p->peers[0] = myid;
8278   GNUNET_PEER_change_rc (myid, 1);
8279   peer_info_add_path (peer, p, GNUNET_YES);
8280   GNUNET_SERVER_resume (server_handle);
8281   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Mesh service running\n");
8282 }
8283
8284
8285 /**
8286  * Process mesh requests.
8287  *
8288  * @param cls closure
8289  * @param server the initialized server
8290  * @param c configuration to use
8291  */
8292 static void
8293 run (void *cls, struct GNUNET_SERVER_Handle *server,
8294      const struct GNUNET_CONFIGURATION_Handle *c)
8295 {
8296   char *keyfile;
8297
8298   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
8299   server_handle = server;
8300
8301   if (GNUNET_OK !=
8302       GNUNET_CONFIGURATION_get_value_filename (c, "PEER", "PRIVATE_KEY",
8303                                                &keyfile))
8304   {
8305     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8306                 _
8307                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8308                 "mesh", "peer/privatekey");
8309     GNUNET_SCHEDULER_shutdown ();
8310     return;
8311   }
8312
8313   if (GNUNET_OK !=
8314       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_PATH_TIME",
8315                                            &refresh_path_time))
8316   {
8317     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8318                 _
8319                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8320                 "mesh", "refresh path time");
8321     GNUNET_SCHEDULER_shutdown ();
8322     return;
8323   }
8324
8325   if (GNUNET_OK !=
8326       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "APP_ANNOUNCE_TIME",
8327                                            &app_announce_time))
8328   {
8329     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8330                 _
8331                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8332                 "mesh", "app announce time");
8333     GNUNET_SCHEDULER_shutdown ();
8334     return;
8335   }
8336   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
8337               "APP_ANNOUNCE_TIME %llu ms\n", 
8338               app_announce_time.rel_value);
8339   if (GNUNET_OK !=
8340       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "ID_ANNOUNCE_TIME",
8341                                            &id_announce_time))
8342   {
8343     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8344                 _
8345                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8346                 "mesh", "id announce time");
8347     GNUNET_SCHEDULER_shutdown ();
8348     return;
8349   }
8350
8351   if (GNUNET_OK !=
8352       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "CONNECT_TIMEOUT",
8353                                            &connect_timeout))
8354   {
8355     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8356                 _
8357                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8358                 "mesh", "connect timeout");
8359     GNUNET_SCHEDULER_shutdown ();
8360     return;
8361   }
8362
8363   if (GNUNET_OK !=
8364       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
8365                                              &max_msgs_queue))
8366   {
8367     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8368                 _
8369                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8370                 "mesh", "max msgs queue");
8371     GNUNET_SCHEDULER_shutdown ();
8372     return;
8373   }
8374
8375   if (GNUNET_OK !=
8376       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_TUNNELS",
8377                                              &max_tunnels))
8378   {
8379     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8380                 _
8381                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8382                 "mesh", "max tunnels");
8383     GNUNET_SCHEDULER_shutdown ();
8384     return;
8385   }
8386
8387   if (GNUNET_OK !=
8388       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
8389                                              &default_ttl))
8390   {
8391     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
8392                 _
8393                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
8394                 "mesh", "default ttl", 64);
8395     default_ttl = 64;
8396   }
8397
8398   if (GNUNET_OK !=
8399       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_PEERS",
8400                                              &max_peers))
8401   {
8402     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
8403                 _("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
8404                 "mesh", "max peers", 1000);
8405     max_peers = 1000;
8406   }
8407
8408   if (GNUNET_OK !=
8409       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DHT_REPLICATION_LEVEL",
8410                                              &dht_replication_level))
8411   {
8412     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
8413                 _
8414                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
8415                 "mesh", "dht replication level", 3);
8416     dht_replication_level = 3;
8417   }
8418
8419   tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
8420   incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
8421   peers = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
8422   applications = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
8423   types = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
8424
8425   dht_handle = GNUNET_DHT_connect (c, 64);
8426   if (NULL == dht_handle)
8427   {
8428     GNUNET_break (0);
8429   }
8430   stats = GNUNET_STATISTICS_create ("mesh", c);
8431
8432   GNUNET_SERVER_suspend (server_handle);
8433   /* Scheduled the task to clean up when shutdown is called */
8434   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
8435                                 NULL);
8436   keygen = GNUNET_CRYPTO_ecc_key_create_start (keyfile,
8437                                                &key_generation_cb,
8438                                                (void *) c);
8439   GNUNET_free (keyfile);
8440 }
8441
8442
8443 /**
8444  * The main function for the mesh service.
8445  *
8446  * @param argc number of arguments from the command line
8447  * @param argv command line arguments
8448  * @return 0 ok, 1 on error
8449  */
8450 int
8451 main (int argc, char *const *argv)
8452 {
8453   int ret;
8454   int r;
8455
8456   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
8457   r = GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
8458                           NULL);
8459   ret = (GNUNET_OK == r) ? 0 : 1;
8460   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");
8461
8462   INTERVAL_SHOW;
8463
8464   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
8465               "Mesh for peer [%s] FWD ACKs %u, BCK ACKs %u\n",
8466               GNUNET_i2s(&my_full_id), debug_fwd_ack, debug_bck_ack);
8467
8468   return ret;
8469 }