- debug
[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   DEBUG_DHT ("Putting APP key: %s\n", GNUNET_h2s (key));
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 = 
2030         GNUNET_realloc (peer->tunnels, 
2031                         peer->ntunnels * sizeof(struct MeshTunnel *));
2032       return GNUNET_YES;
2033     }
2034   }
2035   return GNUNET_YES;
2036 }
2037
2038
2039 /**
2040   * Core callback to write a pre-constructed data packet to core buffer
2041   *
2042   * @param cls Closure (MeshTransmissionDescriptor with data in "data" member).
2043   * @param size Number of bytes available in buf.
2044   * @param buf Where the to write the message.
2045   *
2046   * @return number of bytes written to buf
2047   */
2048 static size_t
2049 send_core_data_raw (void *cls, size_t size, void *buf)
2050 {
2051   struct MeshTransmissionDescriptor *info = cls;
2052   struct GNUNET_MessageHeader *msg;
2053   size_t total_size;
2054
2055   GNUNET_assert (NULL != info);
2056   GNUNET_assert (NULL != info->mesh_data);
2057   msg = (struct GNUNET_MessageHeader *) info->mesh_data->data;
2058   total_size = ntohs (msg->size);
2059
2060   if (total_size > size)
2061   {
2062     GNUNET_break (0);
2063     return 0;
2064   }
2065   memcpy (buf, msg, total_size);
2066   data_descriptor_decrement_rc (info->mesh_data);
2067   GNUNET_free (info);
2068   return total_size;
2069 }
2070
2071
2072 /**
2073  * Sends an already built non-multicast message to a peer,
2074  * properly registrating all used resources.
2075  *
2076  * @param message Message to send. Function makes a copy of it.
2077  * @param peer Short ID of the neighbor whom to send the message.
2078  * @param t Tunnel on which this message is transmitted.
2079  */
2080 static void
2081 send_prebuilt_message (const struct GNUNET_MessageHeader *message,
2082                        const struct GNUNET_PeerIdentity *peer,
2083                        struct MeshTunnel *t)
2084 {
2085   struct MeshTransmissionDescriptor *info;
2086   struct MeshPeerInfo *neighbor;
2087   struct MeshPeerPath *p;
2088   size_t size;
2089   uint16_t type;
2090
2091 //   GNUNET_TRANSPORT_try_connect(); FIXME use?
2092
2093   size = ntohs (message->size);
2094   info = GNUNET_malloc (sizeof (struct MeshTransmissionDescriptor));
2095   info->mesh_data = GNUNET_malloc (sizeof (struct MeshData));
2096   info->mesh_data->data = GNUNET_malloc (size);
2097   memcpy (info->mesh_data->data, message, size);
2098   type = ntohs(message->type);
2099   switch (type)
2100   {
2101     struct GNUNET_MESH_Unicast *m;
2102     struct GNUNET_MESH_ToOrigin *to;
2103
2104     case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
2105       m = (struct GNUNET_MESH_Unicast *) info->mesh_data->data;
2106       m->ttl = htonl (ntohl (m->ttl) - 1);
2107       break;
2108     case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
2109       to = (struct GNUNET_MESH_ToOrigin *) info->mesh_data->data;
2110       t->bck_pid++;
2111       to->pid = htonl(t->bck_pid);
2112   }
2113   info->mesh_data->data_len = size;
2114   info->mesh_data->reference_counter = 1;
2115   info->mesh_data->total_out = 1;
2116   neighbor = peer_info_get (peer);
2117   for (p = neighbor->path_head; NULL != p; p = p->next)
2118   {
2119     if (2 >= p->length)
2120     {
2121       break;
2122     }
2123   }
2124   if (NULL == p)
2125   {
2126 #if MESH_DEBUG
2127     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2128                 "  %s IS NOT DIRECTLY CONNECTED\n",
2129                 GNUNET_i2s(peer));
2130     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2131                 "  PATHS TO %s:\n",
2132                 GNUNET_i2s(peer));
2133     for (p = neighbor->path_head; NULL != p; p = p->next)
2134     {
2135       struct GNUNET_PeerIdentity debug_id;
2136       unsigned int i;
2137
2138       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2139                   "    path with %u hops through:\n",
2140                   p->length);
2141       for (i = 0; i < p->length; i++)
2142       {
2143         GNUNET_PEER_resolve(p->peers[i], &debug_id);
2144         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2145                     "      hop %u: %s\n",
2146                     i, GNUNET_i2s(&debug_id));
2147       }
2148     }
2149 #endif
2150     GNUNET_break (0); // FIXME sometimes fails (testing disconnect?)
2151     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2152                     " no direct connection to %s\n",
2153                     GNUNET_i2s (peer));
2154     GNUNET_free (info->mesh_data->data);
2155     GNUNET_free (info->mesh_data);
2156     GNUNET_free (info);
2157     return;
2158   }
2159   info->peer = neighbor;
2160   if (GNUNET_MESSAGE_TYPE_MESH_PATH_ACK == type)
2161     type = 0;
2162   queue_add (info,
2163              type,
2164              size,
2165              neighbor,
2166              t);
2167 }
2168
2169
2170 /**
2171  * Sends a CREATE PATH message for a path to a peer, properly registrating
2172  * all used resources.
2173  *
2174  * @param peer PeerInfo of the final peer for whom this path is being created.
2175  * @param p Path itself.
2176  * @param t Tunnel for which the path is created.
2177  */
2178 static void
2179 send_create_path (struct MeshPeerInfo *peer, struct MeshPeerPath *p,
2180                   struct MeshTunnel *t)
2181 {
2182   struct GNUNET_PeerIdentity id;
2183   struct MeshPathInfo *path_info;
2184   struct MeshPeerInfo *neighbor;
2185
2186   unsigned int i;
2187
2188   if (NULL == p)
2189   {
2190     p = tree_get_path_to_peer (t->tree, peer->id);
2191     if (NULL == p)
2192     {
2193       GNUNET_break (0);
2194       return;
2195     }
2196   }
2197   for (i = 0; i < p->length; i++)
2198   {
2199     if (p->peers[i] == myid)
2200       break;
2201   }
2202   if (i >= p->length - 1)
2203   {
2204     path_destroy (p);
2205     GNUNET_break (0);
2206     return;
2207   }
2208   GNUNET_PEER_resolve (p->peers[i + 1], &id);
2209
2210   path_info = GNUNET_malloc (sizeof (struct MeshPathInfo));
2211   path_info->path = p;
2212   path_info->t = t;
2213   neighbor = peer_info_get (&id);
2214   path_info->peer = neighbor;
2215   queue_add (path_info,
2216              GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE,
2217              sizeof (struct GNUNET_MESH_ManipulatePath) +
2218                 (p->length * sizeof (struct GNUNET_PeerIdentity)),
2219              neighbor,
2220              t);
2221 }
2222
2223
2224 /**
2225  * Sends a DESTROY PATH message to free resources for a path in a tunnel
2226  *
2227  * @param t Tunnel whose path to destroy.
2228  * @param destination Short ID of the peer to whom the path to destroy.
2229  */
2230 static void
2231 send_destroy_path (struct MeshTunnel *t, GNUNET_PEER_Id destination)
2232 {
2233   struct MeshPeerPath *p;
2234   size_t size;
2235
2236   p = tree_get_path_to_peer (t->tree, destination);
2237   if (NULL == p)
2238   {
2239     GNUNET_break (0);
2240     return;
2241   }
2242   size = sizeof (struct GNUNET_MESH_ManipulatePath);
2243   size += p->length * sizeof (struct GNUNET_PeerIdentity);
2244   {
2245     struct GNUNET_MESH_ManipulatePath *msg;
2246     struct GNUNET_PeerIdentity *pi;
2247     char cbuf[size];
2248     unsigned int i;
2249
2250     msg = (struct GNUNET_MESH_ManipulatePath *) cbuf;
2251     msg->header.size = htons (size);
2252     msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY);
2253     msg->tid = htonl (t->id.tid);
2254     pi = (struct GNUNET_PeerIdentity *) &msg[1];
2255     for (i = 0; i < p->length; i++)
2256     {
2257       GNUNET_PEER_resolve (p->peers[i], &pi[i]);
2258     }
2259     send_prebuilt_message (&msg->header, tree_get_first_hop (t->tree, destination), t);
2260   }
2261   path_destroy (p);
2262 }
2263
2264
2265 /**
2266  * Sends a PATH ACK message in reponse to a received PATH_CREATE directed to us.
2267  *
2268  * @param t Tunnel which to confirm.
2269  */
2270 static void
2271 send_path_ack (struct MeshTunnel *t) 
2272 {
2273   struct MeshTransmissionDescriptor *info;
2274   struct GNUNET_PeerIdentity id;
2275   GNUNET_PEER_Id peer;
2276
2277   peer = tree_get_predecessor (t->tree);
2278   GNUNET_PEER_resolve (peer, &id);
2279   info = GNUNET_malloc (sizeof (struct MeshTransmissionDescriptor));
2280   info->origin = &t->id;
2281   info->peer = GNUNET_CONTAINER_multihashmap_get (peers, &id.hashPubKey);
2282   GNUNET_assert (NULL != info->peer);
2283
2284   queue_add (info,
2285              GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
2286              sizeof (struct GNUNET_MESH_PathACK),
2287              info->peer,
2288              t);
2289 }
2290
2291
2292 /**
2293  * Try to establish a new connection to this peer.
2294  * Use the best path for the given tunnel.
2295  * If the peer doesn't have any path to it yet, try to get one.
2296  * If the peer already has some path, send a CREATE PATH towards it.
2297  *
2298  * @param peer PeerInfo of the peer.
2299  * @param t Tunnel for which to create the path, if possible.
2300  */
2301 static void
2302 peer_info_connect (struct MeshPeerInfo *peer, struct MeshTunnel *t)
2303 {
2304   struct MeshPeerPath *p;
2305   struct MeshPathInfo *path_info;
2306
2307   if (NULL != peer->path_head)
2308   {
2309     p = tree_get_path_to_peer (t->tree, peer->id);
2310     if (NULL == p)
2311     {
2312       GNUNET_break (0);
2313       return;
2314     }
2315
2316     // FIXME always send create path to self
2317     if (p->length > 1)
2318     {
2319       send_create_path (peer, p, t);
2320     }
2321     else
2322     {
2323       struct GNUNET_HashCode hash;
2324
2325       path_destroy (p);
2326       send_client_peer_connected (t, myid);
2327       t->local_tid_dest = next_local_tid++;
2328       GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber),
2329                           &hash);
2330       if (GNUNET_OK !=
2331           GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
2332                                              GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2333       {
2334         GNUNET_break (0);
2335         return;
2336       }
2337     }
2338   }
2339   else if (NULL == peer->dhtget)
2340   {
2341     struct GNUNET_PeerIdentity id;
2342
2343     GNUNET_PEER_resolve (peer->id, &id);
2344     path_info = GNUNET_malloc (sizeof (struct MeshPathInfo));
2345     path_info->peer = peer;
2346     path_info->t = t;
2347     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2348                 "  Starting DHT GET for peer %s\n", GNUNET_i2s (&id));
2349     peer->dhtgetcls = path_info;
2350     peer->dhtget = GNUNET_DHT_get_start (dht_handle,    /* handle */
2351                                          GNUNET_BLOCK_TYPE_MESH_PEER, /* type */
2352                                          &id.hashPubKey,     /* key to search */
2353                                          dht_replication_level, /* replication level */
2354                                          GNUNET_DHT_RO_RECORD_ROUTE |
2355                                          GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
2356                                          NULL,       /* xquery */ // FIXME BLOOMFILTER
2357                                          0,     /* xquery bits */ // FIXME BLOOMFILTER SIZE
2358                                          &dht_get_id_handler, path_info);
2359   }
2360   /* Otherwise, there is no path but the DHT get is already started. */
2361 }
2362
2363
2364 /**
2365  * Task to delay the connection of a peer
2366  *
2367  * @param cls Closure (path info with tunnel and peer to connect).
2368  *            Will be free'd on exection.
2369  * @param tc TaskContext
2370  */
2371 static void
2372 peer_info_connect_task (void *cls,
2373                         const struct GNUNET_SCHEDULER_TaskContext *tc)
2374 {
2375   struct MeshPathInfo *path_info = cls;
2376
2377   path_info->peer->connect_task = GNUNET_SCHEDULER_NO_TASK;
2378
2379   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2380   {
2381     GNUNET_free (cls);
2382     return;
2383   }
2384   peer_info_connect (path_info->peer, path_info->t);
2385   GNUNET_free (cls);
2386 }
2387
2388
2389 /**
2390  * Destroy the peer_info and free any allocated resources linked to it
2391  *
2392  * @param pi The peer_info to destroy.
2393  *
2394  * @return GNUNET_OK on success
2395  */
2396 static int
2397 peer_info_destroy (struct MeshPeerInfo *pi)
2398 {
2399   struct GNUNET_PeerIdentity id;
2400   struct MeshPeerPath *p;
2401   struct MeshPeerPath *nextp;
2402
2403   GNUNET_PEER_resolve (pi->id, &id);
2404   GNUNET_PEER_change_rc (pi->id, -1);
2405
2406   if (GNUNET_YES !=
2407       GNUNET_CONTAINER_multihashmap_remove (peers, &id.hashPubKey, pi))
2408   {
2409     GNUNET_break (0);
2410     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2411                 "removing peer %s, not in hashmap\n", GNUNET_i2s (&id));
2412   }
2413   if (NULL != pi->dhtget)
2414   {
2415     GNUNET_DHT_get_stop (pi->dhtget);
2416     GNUNET_free (pi->dhtgetcls);
2417   }
2418   p = pi->path_head;
2419   while (NULL != p)
2420   {
2421     nextp = p->next;
2422     GNUNET_CONTAINER_DLL_remove (pi->path_head, pi->path_tail, p);
2423     path_destroy (p);
2424     p = nextp;
2425   }
2426   if (GNUNET_SCHEDULER_NO_TASK != pi->connect_task)
2427   {
2428     GNUNET_free (GNUNET_SCHEDULER_cancel (pi->connect_task));
2429   }
2430   GNUNET_free (pi);
2431   return GNUNET_OK;
2432 }
2433
2434
2435 /**
2436  * Remove all paths that rely on a direct connection between p1 and p2
2437  * from the peer itself and notify all tunnels about it.
2438  *
2439  * @param peer PeerInfo of affected peer.
2440  * @param p1 GNUNET_PEER_Id of one peer.
2441  * @param p2 GNUNET_PEER_Id of another peer that was connected to the first and
2442  *           no longer is.
2443  *
2444  * TODO: optimize (see below)
2445  */
2446 static void
2447 peer_info_remove_path (struct MeshPeerInfo *peer, GNUNET_PEER_Id p1,
2448                        GNUNET_PEER_Id p2)
2449 {
2450   struct MeshPeerPath *p;
2451   struct MeshPeerPath *aux;
2452   struct MeshPeerInfo *peer_d;
2453   GNUNET_PEER_Id d;
2454   unsigned int destroyed;
2455   unsigned int best;
2456   unsigned int cost;
2457   unsigned int i;
2458
2459   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "peer_info_remove_path\n");
2460   destroyed = 0;
2461   p = peer->path_head;
2462   while (NULL != p)
2463   {
2464     aux = p->next;
2465     for (i = 0; i < (p->length - 1); i++)
2466     {
2467       if ((p->peers[i] == p1 && p->peers[i + 1] == p2) ||
2468           (p->peers[i] == p2 && p->peers[i + 1] == p1))
2469       {
2470         GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, p);
2471         path_destroy (p);
2472         destroyed++;
2473         break;
2474       }
2475     }
2476     p = aux;
2477   }
2478   if (0 == destroyed)
2479     return;
2480
2481   for (i = 0; i < peer->ntunnels; i++)
2482   {
2483     d = tunnel_notify_connection_broken (peer->tunnels[i], p1, p2);
2484     if (0 == d)
2485       continue;
2486     /* TODO
2487      * Problem: one or more peers have been deleted from the tunnel tree.
2488      * We don't know who they are to try to add them again.
2489      * We need to try to find a new path for each of the disconnected peers.
2490      * Some of them might already have a path to reach them that does not
2491      * involve p1 and p2. Adding all anew might render in a better tree than
2492      * the trivial immediate fix.
2493      *
2494      * Trivial immiediate fix: try to reconnect to the disconnected node. All
2495      * its children will be reachable trough him.
2496      */
2497     peer_d = peer_info_get_short (d);
2498     best = UINT_MAX;
2499     aux = NULL;
2500     for (p = peer_d->path_head; NULL != p; p = p->next)
2501     {
2502       if ((cost = tree_get_path_cost (peer->tunnels[i]->tree, p)) < best)
2503       {
2504         best = cost;
2505         aux = p;
2506       }
2507     }
2508     if (NULL != aux)
2509     {
2510       /* No callback, as peer will be already disconnected and a connection
2511        * scheduled by tunnel_notify_connection_broken.
2512        */
2513       tree_add_path (peer->tunnels[i]->tree, aux, NULL, NULL);
2514     }
2515     else
2516     {
2517       peer_info_connect (peer_d, peer->tunnels[i]);
2518     }
2519   }
2520   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "peer_info_remove_path END\n");
2521 }
2522
2523
2524 /**
2525  * Add the path to the peer and update the path used to reach it in case this
2526  * is the shortest.
2527  *
2528  * @param peer_info Destination peer to add the path to.
2529  * @param path New path to add. Last peer must be the peer in arg 1.
2530  *             Path will be either used of freed if already known.
2531  * @param trusted Do we trust that this path is real?
2532  */
2533 void
2534 peer_info_add_path (struct MeshPeerInfo *peer_info, struct MeshPeerPath *path,
2535                     int trusted)
2536 {
2537   struct MeshPeerPath *aux;
2538   unsigned int l;
2539   unsigned int l2;
2540
2541   if ((NULL == peer_info) || (NULL == path))
2542   {
2543     GNUNET_break (0);
2544     path_destroy (path);
2545     return;
2546   }
2547   if (path->peers[path->length - 1] != peer_info->id)
2548   {
2549     GNUNET_break (0);
2550     path_destroy (path);
2551     return;
2552   }
2553   if (path->length <= 2 && GNUNET_NO == trusted)
2554   {
2555     /* Only allow CORE to tell us about direct paths */
2556     path_destroy (path);
2557     return;
2558   }
2559   GNUNET_assert (peer_info->id == path->peers[path->length - 1]);
2560   for (l = 1; l < path->length; l++)
2561   {
2562     if (path->peers[l] == myid)
2563     {
2564       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shortening path by %u\n", l);
2565       for (l2 = 0; l2 < path->length - l; l2++)
2566       {
2567         path->peers[l2] = path->peers[l + l2];
2568       }
2569       path->length -= l;
2570       l = 1;
2571       path->peers =
2572           GNUNET_realloc (path->peers, path->length * sizeof (GNUNET_PEER_Id));
2573     }
2574   }
2575 #if MESH_DEBUG
2576   {
2577     struct GNUNET_PeerIdentity id;
2578
2579     GNUNET_PEER_resolve (peer_info->id, &id);
2580     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "adding path [%u] to peer %s\n",
2581                 path->length, GNUNET_i2s (&id));
2582   }
2583 #endif
2584   l = path_get_length (path);
2585   if (0 == l)
2586   {
2587     GNUNET_free (path);
2588     return;
2589   }
2590
2591   GNUNET_assert (peer_info->id == path->peers[path->length - 1]);
2592   for (aux = peer_info->path_head; aux != NULL; aux = aux->next)
2593   {
2594     l2 = path_get_length (aux);
2595     if (l2 > l)
2596     {
2597       GNUNET_CONTAINER_DLL_insert_before (peer_info->path_head,
2598                                           peer_info->path_tail, aux, path);
2599       return;
2600     }
2601     else
2602     {
2603       if (l2 == l && memcmp (path->peers, aux->peers, l) == 0)
2604       {
2605         path_destroy (path);
2606         return;
2607       }
2608     }
2609   }
2610   GNUNET_CONTAINER_DLL_insert_tail (peer_info->path_head, peer_info->path_tail,
2611                                     path);
2612   return;
2613 }
2614
2615
2616 /**
2617  * Add the path to the origin peer and update the path used to reach it in case
2618  * this is the shortest.
2619  * The path is given in peer_info -> destination, therefore we turn the path
2620  * upside down first.
2621  *
2622  * @param peer_info Peer to add the path to, being the origin of the path.
2623  * @param path New path to add after being inversed.
2624  * @param trusted Do we trust that this path is real?
2625  */
2626 static void
2627 peer_info_add_path_to_origin (struct MeshPeerInfo *peer_info,
2628                               struct MeshPeerPath *path, int trusted)
2629 {
2630   path_invert (path);
2631   peer_info_add_path (peer_info, path, trusted);
2632 }
2633
2634
2635 /**
2636  * Function called if the connection to the peer has been stalled for a while,
2637  * possibly due to a missed ACK. Poll the peer about its ACK status.
2638  *
2639  * @param cls Closure (cinfo).
2640  * @param tc TaskContext.
2641  */
2642 static void
2643 tunnel_poll (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2644 {
2645   struct MeshTunnelChildInfo *cinfo = cls;
2646   struct GNUNET_MESH_Poll msg;
2647   struct GNUNET_PeerIdentity id;
2648   struct MeshTunnel *t;
2649
2650   cinfo->fc_poll = GNUNET_SCHEDULER_NO_TASK;
2651   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2652   {
2653     return;
2654   }
2655
2656   t = cinfo->t;
2657   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_POLL);
2658   msg.header.size = htons (sizeof (msg));
2659   msg.tid = htonl (t->id.tid);
2660   GNUNET_PEER_resolve (t->id.oid, &msg.oid);
2661   msg.last_ack = htonl (cinfo->fwd_ack);
2662
2663   GNUNET_PEER_resolve (cinfo->id, &id);
2664   send_prebuilt_message (&msg.header, &id, cinfo->t);
2665   cinfo->fc_poll_time = GNUNET_TIME_relative_min (
2666     MESH_MAX_POLL_TIME,
2667     GNUNET_TIME_relative_multiply (cinfo->fc_poll_time, 2));
2668   cinfo->fc_poll = GNUNET_SCHEDULER_add_delayed (cinfo->fc_poll_time,
2669                                                  &tunnel_poll, cinfo);
2670 }
2671
2672
2673 /**
2674  * Build a PeerPath from the paths returned from the DHT, reversing the paths
2675  * to obtain a local peer -> destination path and interning the peer ids.
2676  *
2677  * @return Newly allocated and created path
2678  */
2679 static struct MeshPeerPath *
2680 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
2681                      unsigned int get_path_length,
2682                      const struct GNUNET_PeerIdentity *put_path,
2683                      unsigned int put_path_length)
2684 {
2685   struct MeshPeerPath *p;
2686   GNUNET_PEER_Id id;
2687   int i;
2688
2689   p = path_new (1);
2690   p->peers[0] = myid;
2691   GNUNET_PEER_change_rc (myid, 1);
2692   i = get_path_length;
2693   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   GET has %d hops.\n", i);
2694   for (i--; i >= 0; i--)
2695   {
2696     id = GNUNET_PEER_intern (&get_path[i]);
2697     if (p->length > 0 && id == p->peers[p->length - 1])
2698     {
2699       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Optimizing 1 hop out.\n");
2700       GNUNET_PEER_change_rc (id, -1);
2701     }
2702     else
2703     {
2704       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Adding from GET: %s.\n",
2705                   GNUNET_i2s (&get_path[i]));
2706       p->length++;
2707       p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
2708       p->peers[p->length - 1] = id;
2709     }
2710   }
2711   i = put_path_length;
2712   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   PUT has %d hops.\n", i);
2713   for (i--; i >= 0; i--)
2714   {
2715     id = GNUNET_PEER_intern (&put_path[i]);
2716     if (id == myid)
2717     {
2718       /* PUT path went through us, so discard the path up until now and start
2719        * from here to get a much shorter (and loop-free) path.
2720        */
2721       path_destroy (p);
2722       p = path_new (0);
2723     }
2724     if (p->length > 0 && id == p->peers[p->length - 1])
2725     {
2726       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Optimizing 1 hop out.\n");
2727       GNUNET_PEER_change_rc (id, -1);
2728     }
2729     else
2730     {
2731       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Adding from PUT: %s.\n",
2732                   GNUNET_i2s (&put_path[i]));
2733       p->length++;
2734       p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
2735       p->peers[p->length - 1] = id;
2736     }
2737   }
2738 #if MESH_DEBUG
2739   if (get_path_length > 0)
2740     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (first of GET: %s)\n",
2741                 GNUNET_i2s (&get_path[0]));
2742   if (put_path_length > 0)
2743     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (first of PUT: %s)\n",
2744                 GNUNET_i2s (&put_path[0]));
2745   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   In total: %d hops\n",
2746               p->length);
2747   for (i = 0; i < p->length; i++)
2748   {
2749     struct GNUNET_PeerIdentity peer_id;
2750
2751     GNUNET_PEER_resolve (p->peers[i], &peer_id);
2752     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "       %u: %s\n", p->peers[i],
2753                 GNUNET_i2s (&peer_id));
2754   }
2755 #endif
2756   return p;
2757 }
2758
2759
2760 /**
2761  * Adds a path to the peer_infos of all the peers in the path
2762  *
2763  * @param p Path to process.
2764  * @param confirmed Whether we know if the path works or not.
2765  */
2766 static void
2767 path_add_to_peers (struct MeshPeerPath *p, int confirmed)
2768 {
2769   unsigned int i;
2770
2771   /* TODO: invert and add */
2772   for (i = 0; i < p->length && p->peers[i] != myid; i++) /* skip'em */ ;
2773   for (i++; i < p->length; i++)
2774   {
2775     struct MeshPeerInfo *aux;
2776     struct MeshPeerPath *copy;
2777
2778     aux = peer_info_get_short (p->peers[i]);
2779     copy = path_duplicate (p);
2780     copy->length = i + 1;
2781     peer_info_add_path (aux, copy, GNUNET_NO);
2782   }
2783 }
2784
2785
2786 /**
2787  * Send keepalive packets for a peer
2788  *
2789  * @param cls Closure (tunnel for which to send the keepalive).
2790  * @param tc Notification context.
2791  *
2792  * TODO: implement explicit multicast keepalive?
2793  */
2794 static void
2795 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
2796
2797
2798 /**
2799  * Search for a tunnel among the incoming tunnels
2800  *
2801  * @param tid the local id of the tunnel
2802  *
2803  * @return tunnel handler, NULL if doesn't exist
2804  */
2805 static struct MeshTunnel *
2806 tunnel_get_incoming (MESH_TunnelNumber tid)
2807 {
2808   struct GNUNET_HashCode hash;
2809
2810   GNUNET_assert (tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV);
2811   GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
2812   return GNUNET_CONTAINER_multihashmap_get (incoming_tunnels, &hash);
2813 }
2814
2815
2816 /**
2817  * Search for a tunnel among the tunnels for a client
2818  *
2819  * @param c the client whose tunnels to search in
2820  * @param tid the local id of the tunnel
2821  *
2822  * @return tunnel handler, NULL if doesn't exist
2823  */
2824 static struct MeshTunnel *
2825 tunnel_get_by_local_id (struct MeshClient *c, MESH_TunnelNumber tid)
2826 {
2827   if (tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
2828   {
2829     return tunnel_get_incoming (tid);
2830   }
2831   else
2832   {
2833     struct GNUNET_HashCode hash;
2834
2835     GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
2836     return GNUNET_CONTAINER_multihashmap_get (c->own_tunnels, &hash);
2837   }
2838 }
2839
2840
2841 /**
2842  * Search for a tunnel by global ID using PEER_ID
2843  *
2844  * @param pi owner of the tunnel
2845  * @param tid global tunnel number
2846  *
2847  * @return tunnel handler, NULL if doesn't exist
2848  */
2849 static struct MeshTunnel *
2850 tunnel_get_by_pi (GNUNET_PEER_Id pi, MESH_TunnelNumber tid)
2851 {
2852   struct MESH_TunnelID id;
2853   struct GNUNET_HashCode hash;
2854
2855   id.oid = pi;
2856   id.tid = tid;
2857
2858   GNUNET_CRYPTO_hash (&id, sizeof (struct MESH_TunnelID), &hash);
2859   return GNUNET_CONTAINER_multihashmap_get (tunnels, &hash);
2860 }
2861
2862
2863 /**
2864  * Search for a tunnel by global ID using full PeerIdentities
2865  *
2866  * @param oid owner of the tunnel
2867  * @param tid global tunnel number
2868  *
2869  * @return tunnel handler, NULL if doesn't exist
2870  */
2871 static struct MeshTunnel *
2872 tunnel_get (const struct GNUNET_PeerIdentity *oid, MESH_TunnelNumber tid)
2873 {
2874   return tunnel_get_by_pi (GNUNET_PEER_search (oid), tid);
2875 }
2876
2877
2878 /**
2879  * Delete an active client from the tunnel.
2880  * 
2881  * @param t Tunnel.
2882  * @param c Client.
2883  */
2884 static void
2885 tunnel_delete_active_client (struct MeshTunnel *t, const struct MeshClient *c)
2886 {
2887   unsigned int i;
2888
2889   for (i = 0; i < t->nclients; i++)
2890   {
2891     if (t->clients[i] == c)
2892     {
2893       t->clients[i] = t->clients[t->nclients - 1];
2894       t->clients_fc[i] = t->clients_fc[t->nclients - 1];
2895       GNUNET_array_grow (t->clients, t->nclients, t->nclients - 1);
2896       t->nclients++;
2897       GNUNET_array_grow (t->clients_fc, t->nclients, t->nclients - 1);
2898       break;
2899     }
2900   }
2901 }
2902
2903
2904 /**
2905  * Delete an ignored client from the tunnel.
2906  * 
2907  * @param t Tunnel.
2908  * @param c Client.
2909  */
2910 static void
2911 tunnel_delete_ignored_client (struct MeshTunnel *t, const struct MeshClient *c)
2912 {
2913   unsigned int i;
2914
2915   for (i = 0; i < t->nignore; i++)
2916   {
2917     if (t->ignore[i] == c)
2918     {
2919       t->ignore[i] = t->ignore[t->nignore - 1];
2920       GNUNET_array_grow (t->ignore, t->nignore, t->nignore - 1);
2921       break;
2922     }
2923   }
2924 }
2925
2926
2927 /**
2928  * Delete a client from the tunnel. It should be only done on
2929  * client disconnection, otherwise use client_ignore_tunnel.
2930  * 
2931  * @param t Tunnel.
2932  * @param c Client.
2933  */
2934 static void
2935 tunnel_delete_client (struct MeshTunnel *t, const struct MeshClient *c)
2936 {
2937   tunnel_delete_ignored_client (t, c);
2938   tunnel_delete_active_client (t, c);
2939 }
2940
2941
2942 /**
2943  * @brief Iterator to destroy MeshTunnelChildInfo of tunnel children.
2944  * 
2945  * Destroys queue elements of all waiting transmissions and frees all memory
2946  * used by the struct and its elements.
2947  *
2948  * @param cls Closure (tunnel info).
2949  * @param key Hash of GNUNET_PEER_Id (unused).
2950  * @param value MeshTunnelChildInfo of the child.
2951  *
2952  * @return always GNUNET_YES, to keep iterating
2953  */
2954 static int
2955 tunnel_destroy_child (void *cls,
2956                       const struct GNUNET_HashCode * key,
2957                       void *value)
2958 {
2959   struct MeshTunnelChildInfo *cinfo = value;
2960   struct MeshTunnel *t = cls;
2961   struct MeshPeerQueue *q;
2962   unsigned int c;
2963   unsigned int i;
2964
2965   for (c = 0; c < cinfo->send_buffer_n; c++)
2966   {
2967     i = (cinfo->send_buffer_start + c) % t->fwd_queue_max;
2968     q = cinfo->send_buffer[i];
2969     cinfo->send_buffer[i] = NULL;
2970     if (NULL != q)
2971       queue_destroy (q, GNUNET_YES);
2972     else
2973       GNUNET_break (0);
2974     GNUNET_log (GNUNET_ERROR_TYPE_INFO, "%u %u\n", c, cinfo->send_buffer_n);
2975   }
2976   GNUNET_free_non_null (cinfo->send_buffer);
2977   if (GNUNET_SCHEDULER_NO_TASK != cinfo->fc_poll)
2978   {
2979     GNUNET_SCHEDULER_cancel (cinfo->fc_poll);
2980     cinfo->fc_poll = GNUNET_SCHEDULER_NO_TASK;
2981   }
2982   GNUNET_free (cinfo);
2983   return GNUNET_YES;
2984 }
2985
2986
2987 /**
2988  * Callback used to notify a client owner of a tunnel that a peer has
2989  * disconnected, most likely because of a path change.
2990  *
2991  * @param cls Closure (tunnel this notification is about).
2992  * @param peer_id Short ID of disconnected peer.
2993  */
2994 void
2995 tunnel_notify_client_peer_disconnected (void *cls, GNUNET_PEER_Id peer_id)
2996 {
2997   struct MeshTunnel *t = cls;
2998   struct MeshPeerInfo *peer;
2999   struct MeshPathInfo *path_info;
3000
3001   client_notify_peer_disconnected (t->owner, t, peer_id);
3002
3003   peer = peer_info_get_short (peer_id);
3004   path_info = GNUNET_malloc (sizeof (struct MeshPathInfo));
3005   path_info->peer = peer;
3006   path_info->t = t;
3007   peer->connect_task = GNUNET_SCHEDULER_add_now (&peer_info_connect_task,
3008                                                  path_info);
3009 }
3010
3011
3012 /**
3013  * Add a peer to a tunnel, accomodating paths accordingly and initializing all
3014  * needed rescources.
3015  * If peer already exists, reevaluate shortest path and change if different.
3016  *
3017  * @param t Tunnel we want to add a new peer to
3018  * @param peer PeerInfo of the peer being added
3019  *
3020  */
3021 static void
3022 tunnel_add_peer (struct MeshTunnel *t, struct MeshPeerInfo *peer)
3023 {
3024   struct GNUNET_PeerIdentity id;
3025   struct MeshPeerPath *best_p;
3026   struct MeshPeerPath *p;
3027   unsigned int best_cost;
3028   unsigned int cost;
3029
3030   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "tunnel_add_peer\n");
3031   GNUNET_PEER_resolve (peer->id, &id);
3032   if (GNUNET_NO ==
3033       GNUNET_CONTAINER_multihashmap_contains (t->peers, &id.hashPubKey))
3034   {
3035     GNUNET_array_append (peer->tunnels, peer->ntunnels, t);
3036     GNUNET_assert (GNUNET_OK ==
3037                    GNUNET_CONTAINER_multihashmap_put (t->peers, &id.hashPubKey,
3038                                                       peer,
3039                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
3040   }
3041
3042   if (NULL != (p = peer->path_head))
3043   {
3044     best_p = p;
3045     best_cost = tree_get_path_cost (t->tree, p);
3046     while (NULL != p)
3047     {
3048       if ((cost = tree_get_path_cost (t->tree, p)) < best_cost)
3049       {
3050         best_cost = cost;
3051         best_p = p;
3052       }
3053       p = p->next;
3054     }
3055     tree_add_path (t->tree, best_p, &tunnel_notify_client_peer_disconnected, t);
3056     if (GNUNET_SCHEDULER_NO_TASK == t->path_refresh_task)
3057       t->path_refresh_task =
3058           GNUNET_SCHEDULER_add_delayed (refresh_path_time, &path_refresh, t);
3059   }
3060   else
3061   {
3062     /* Start a DHT get */
3063     peer_info_connect (peer, t);
3064   }
3065   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "tunnel_add_peer END\n");
3066 }
3067
3068 /**
3069  * Add a path to a tunnel which we don't own, just to remember the next hop.
3070  * If destination node was already in the tunnel, the first hop information
3071  * will be replaced with the new path.
3072  *
3073  * @param t Tunnel we want to add a new peer to
3074  * @param p Path to add
3075  * @param own_pos Position of local node in path.
3076  *
3077  */
3078 static void
3079 tunnel_add_path (struct MeshTunnel *t, struct MeshPeerPath *p,
3080                  unsigned int own_pos)
3081 {
3082   struct GNUNET_PeerIdentity id;
3083
3084   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "tunnel_add_path\n");
3085   GNUNET_assert (0 != own_pos);
3086   tree_add_path (t->tree, p, NULL, NULL);
3087   if (own_pos < p->length - 1)
3088   {
3089     GNUNET_PEER_resolve (p->peers[own_pos + 1], &id);
3090     tree_update_first_hops (t->tree, myid, &id);
3091   }
3092   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "tunnel_add_path END\n");
3093 }
3094
3095 /**
3096  * Add a client to a tunnel, initializing all needed data structures.
3097  * 
3098  * @param t Tunnel to which add the client.
3099  * @param c Client which to add to the tunnel.
3100  */
3101 static void
3102 tunnel_add_client (struct MeshTunnel *t, struct MeshClient *c)
3103 {
3104   struct MeshTunnelClientInfo clinfo;
3105
3106   GNUNET_array_append (t->clients, t->nclients, c);
3107   clinfo.fwd_ack = t->fwd_pid + 1;
3108   clinfo.bck_ack = t->nobuffer ? 1 : INITIAL_WINDOW_SIZE - 1;
3109   clinfo.fwd_pid = t->fwd_pid;
3110   clinfo.bck_pid = (uint32_t) -1; // Expected next: 0
3111   t->nclients--;
3112   GNUNET_array_append (t->clients_fc, t->nclients, clinfo);
3113 }
3114
3115
3116 /**
3117  * Notifies a tunnel that a connection has broken that affects at least
3118  * some of its peers. Sends a notification towards the root of the tree.
3119  * In case the peer is the owner of the tree, notifies the client that owns
3120  * the tunnel and tries to reconnect.
3121  *
3122  * @param t Tunnel affected.
3123  * @param p1 Peer that got disconnected from p2.
3124  * @param p2 Peer that got disconnected from p1.
3125  *
3126  * @return Short ID of the peer disconnected (either p1 or p2).
3127  *         0 if the tunnel remained unaffected.
3128  */
3129 static GNUNET_PEER_Id
3130 tunnel_notify_connection_broken (struct MeshTunnel *t, GNUNET_PEER_Id p1,
3131                                  GNUNET_PEER_Id p2)
3132 {
3133   GNUNET_PEER_Id pid;
3134
3135   pid =
3136       tree_notify_connection_broken (t->tree, p1, p2,
3137                                      &tunnel_notify_client_peer_disconnected,
3138                                      t);
3139   if (myid != p1 && myid != p2)
3140   {
3141     return pid;
3142   }
3143   if (pid != myid)
3144   {
3145     if (tree_get_predecessor (t->tree) != 0)
3146     {
3147       /* We are the peer still connected, notify owner of the disconnection. */
3148       struct GNUNET_MESH_PathBroken msg;
3149       struct GNUNET_PeerIdentity neighbor;
3150
3151       msg.header.size = htons (sizeof (msg));
3152       msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN);
3153       GNUNET_PEER_resolve (t->id.oid, &msg.oid);
3154       msg.tid = htonl (t->id.tid);
3155       msg.peer1 = my_full_id;
3156       GNUNET_PEER_resolve (pid, &msg.peer2);
3157       GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &neighbor);
3158       send_prebuilt_message (&msg.header, &neighbor, t);
3159     }
3160   }
3161   return pid;
3162 }
3163
3164
3165 /**
3166  * Send a multicast packet to a neighbor.
3167  *
3168  * @param cls Closure (Info about the multicast packet)
3169  * @param neighbor_id Short ID of the neighbor to send the packet to.
3170  */
3171 static void
3172 tunnel_send_multicast_iterator (void *cls, GNUNET_PEER_Id neighbor_id)
3173 {
3174   struct MeshData *mdata = cls;
3175   struct MeshTransmissionDescriptor *info;
3176   struct GNUNET_PeerIdentity neighbor;
3177   struct GNUNET_MessageHeader *msg;
3178
3179   info = GNUNET_malloc (sizeof (struct MeshTransmissionDescriptor));
3180
3181   info->mesh_data = mdata;
3182   (mdata->reference_counter) ++;
3183   info->destination = neighbor_id;
3184   GNUNET_PEER_resolve (neighbor_id, &neighbor);
3185   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   sending to %s...\n",
3186               GNUNET_i2s (&neighbor));
3187   info->peer = peer_info_get (&neighbor);
3188   GNUNET_assert (NULL != info->peer);
3189   msg = (struct GNUNET_MessageHeader *) mdata->data;
3190   queue_add(info,
3191             ntohs (msg->type),
3192             info->mesh_data->data_len,
3193             info->peer,
3194             mdata->t);
3195 }
3196
3197
3198 /**
3199  * Queue a message in a tunnel in multicast, sending a copy to each child node
3200  * down the local one in the tunnel tree.
3201  *
3202  * @param t Tunnel in which to send the data.
3203  * @param msg Message to be sent.
3204  */
3205 static void
3206 tunnel_send_multicast (struct MeshTunnel *t,
3207                        const struct GNUNET_MessageHeader *msg)
3208 {
3209   struct MeshData *mdata;
3210
3211   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3212               " sending a multicast packet...\n");
3213
3214   mdata = GNUNET_malloc (sizeof (struct MeshData));
3215   mdata->data_len = ntohs (msg->size);
3216   mdata->t = t;
3217   mdata->data = GNUNET_malloc (mdata->data_len);
3218   memcpy (mdata->data, msg, mdata->data_len);
3219   if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_MESH_MULTICAST)
3220   {
3221     struct GNUNET_MESH_Multicast *mcast;
3222
3223     mcast = (struct GNUNET_MESH_Multicast *) mdata->data;
3224     if (t->fwd_queue_n >= t->fwd_queue_max)
3225     {
3226       GNUNET_break (0);
3227       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  queue full!\n");
3228       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3229                   "  message from %s!\n",
3230                   GNUNET_i2s(&mcast->oid));
3231       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3232                   "  message at %s!\n",
3233                   GNUNET_i2s(&my_full_id));
3234       GNUNET_free (mdata->data);
3235       GNUNET_free (mdata);
3236       return;
3237     }
3238     t->fwd_queue_n++;
3239     mcast->ttl = htonl (ntohl (mcast->ttl) - 1);
3240     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  data packet, ttl: %u\n",
3241                 ntohl (mcast->ttl));
3242   }
3243   else
3244   {
3245     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  not a data packet, no ttl\n");
3246   }
3247
3248   tree_iterate_children (t->tree, &tunnel_send_multicast_iterator, mdata);
3249   if (mdata->reference_counter == 0)
3250   {
3251     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3252               "  no one to send data to\n");
3253     GNUNET_free (mdata->data);
3254     GNUNET_free (mdata);
3255     if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_MESH_MULTICAST)
3256       t->fwd_queue_n--;
3257   }
3258   else
3259   {
3260     mdata->total_out = mdata->reference_counter;
3261   }
3262   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3263               " sending a multicast packet done\n");
3264   return;
3265 }
3266
3267
3268 /**
3269  * Increase the SKIP value of all peers that
3270  * have not received a unicast message.
3271  *
3272  * @param cls Closure (ID of the peer that HAS received the message).
3273  * @param key ID of the neighbor.
3274  * @param value Information about the neighbor.
3275  *
3276  * @return GNUNET_YES to keep iterating.
3277  */
3278 static int
3279 tunnel_add_skip (void *cls,
3280                  const struct GNUNET_HashCode * key,
3281                  void *value)
3282 {
3283   struct GNUNET_PeerIdentity *neighbor = cls;
3284   struct MeshTunnelChildInfo *cinfo = value;
3285
3286   /* TODO compare only pointers? key == neighbor? */
3287   if (0 == memcmp (&neighbor->hashPubKey, key, sizeof (struct GNUNET_HashCode)))
3288   {
3289     return GNUNET_YES;
3290   }
3291   cinfo->skip++;
3292   return GNUNET_YES;
3293 }
3294
3295
3296 /**
3297  * @brief Get neighbor's Flow Control information.
3298  *
3299  * Retrieves the MeshTunnelChildInfo containing Flow Control data about a direct
3300  * descendant of the local node in a certain tunnel.
3301  * If the info is not yet there (recently created path), creates the data struct
3302  * and inserts it into the tunnel info, initialized to the current tunnel ACK
3303  * values.
3304  *
3305  * @param t Tunnel related.
3306  * @param peer Neighbor whose Flow Control info is needed.
3307  *
3308  * @return Neighbor's Flow Control info.
3309  */
3310 static struct MeshTunnelChildInfo *
3311 tunnel_get_neighbor_fc (struct MeshTunnel *t,
3312                         const struct GNUNET_PeerIdentity *peer)
3313 {
3314   struct MeshTunnelChildInfo *cinfo;
3315
3316   if (NULL == t->children_fc)
3317     return NULL;
3318
3319   cinfo = GNUNET_CONTAINER_multihashmap_get (t->children_fc,
3320                                              &peer->hashPubKey);
3321   if (NULL == cinfo)
3322   {
3323     uint32_t delta;
3324
3325     cinfo = GNUNET_malloc (sizeof (struct MeshTunnelChildInfo));
3326     cinfo->id = GNUNET_PEER_intern (peer);
3327     cinfo->skip = t->fwd_pid;
3328     cinfo->t = t;
3329
3330     delta = t->nobuffer ? 1 : INITIAL_WINDOW_SIZE;
3331     cinfo->fwd_ack = t->fwd_pid + delta;
3332     cinfo->bck_ack = delta;
3333     cinfo->bck_pid = -1;
3334
3335     cinfo->fc_poll = GNUNET_SCHEDULER_NO_TASK;
3336     cinfo->fc_poll_time = GNUNET_TIME_UNIT_SECONDS;
3337
3338     cinfo->send_buffer =
3339         GNUNET_malloc (sizeof(struct MeshPeerQueue *) * t->fwd_queue_max);
3340
3341     GNUNET_assert (GNUNET_OK ==
3342       GNUNET_CONTAINER_multihashmap_put (t->children_fc,
3343                                          &peer->hashPubKey,
3344                                          cinfo,
3345                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
3346   }
3347   return cinfo;
3348 }
3349
3350
3351 /**
3352  * Get the Flow Control info of a client.
3353  * 
3354  * @param t Tunnel on which to look.
3355  * @param c Client whose ACK to get.
3356  * 
3357  * @return ACK value.
3358  */
3359 static struct MeshTunnelClientInfo *
3360 tunnel_get_client_fc (struct MeshTunnel *t,
3361                       struct MeshClient *c)
3362 {
3363   unsigned int i;
3364
3365   for (i = 0; i < t->nclients; i++)
3366   {
3367     if (t->clients[i] != c)
3368       continue;
3369     return &t->clients_fc[i];
3370   }
3371   GNUNET_assert (0);
3372   return NULL; // avoid compiler / coverity complaints
3373 }
3374
3375
3376 /**
3377  * Iterator to get the appropiate ACK value from all children nodes.
3378  *
3379  * @param cls Closue (tunnel).
3380  * @param id Id of the child node.
3381  */
3382 static void
3383 tunnel_get_child_fwd_ack (void *cls,
3384                           GNUNET_PEER_Id id)
3385 {
3386   struct GNUNET_PeerIdentity peer_id;
3387   struct MeshTunnelChildInfo *cinfo;
3388   struct MeshTunnelChildIteratorContext *ctx = cls;
3389   struct MeshTunnel *t = ctx->t;
3390   uint32_t ack;
3391
3392   GNUNET_PEER_resolve (id, &peer_id);
3393   cinfo = tunnel_get_neighbor_fc (t, &peer_id);
3394   ack = cinfo->fwd_ack;
3395
3396   ctx->nchildren++;
3397   if (GNUNET_NO == ctx->init)
3398   {
3399     ctx->max_child_ack = ack;
3400     ctx->init = GNUNET_YES;
3401   }
3402
3403   if (GNUNET_YES == t->speed_min)
3404   {
3405     ctx->max_child_ack = ctx->max_child_ack > ack ? ack : ctx->max_child_ack;
3406   }
3407   else
3408   {
3409     ctx->max_child_ack = ctx->max_child_ack > ack ? ctx->max_child_ack : ack;
3410   }
3411
3412 }
3413
3414
3415 /**
3416  * Get the maximum PID allowed to transmit to any
3417  * tunnel child of the local peer, depending on the tunnel
3418  * buffering/speed settings.
3419  *
3420  * @param t Tunnel.
3421  *
3422  * @return Maximum PID allowed (uint32 MAX), -1LL if node has no children.
3423  */
3424 static int64_t
3425 tunnel_get_children_fwd_ack (struct MeshTunnel *t)
3426 {
3427   struct MeshTunnelChildIteratorContext ctx;
3428   ctx.t = t;
3429   ctx.max_child_ack = 0;
3430   ctx.nchildren = 0;
3431   ctx.init = GNUNET_NO;
3432   tree_iterate_children (t->tree, tunnel_get_child_fwd_ack, &ctx);
3433
3434   if (0 == ctx.nchildren)
3435   {
3436     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3437             "  tunnel has no children, no FWD ACK\n");
3438     return -1LL;
3439   }
3440
3441   if (GNUNET_YES == t->nobuffer && GMC_is_pid_bigger(ctx.max_child_ack, t->fwd_pid))
3442     ctx.max_child_ack = t->fwd_pid + 1; // Might overflow, it's ok.
3443
3444   return (int64_t) ctx.max_child_ack;
3445 }
3446
3447
3448 /**
3449  * Set the FWD ACK value of a client in a particular tunnel.
3450  * 
3451  * @param t Tunnel affected.
3452  * @param c Client whose ACK to set.
3453  * @param ack ACK value.
3454  */
3455 static void
3456 tunnel_set_client_fwd_ack (struct MeshTunnel *t,
3457                            struct MeshClient *c, 
3458                            uint32_t ack)
3459 {
3460   unsigned int i;
3461
3462   for (i = 0; i < t->nclients; i++)
3463   {
3464     if (t->clients[i] != c)
3465       continue;
3466     t->clients_fc[i].fwd_ack = ack;
3467     return;
3468   }
3469   GNUNET_break (0);
3470 }
3471
3472
3473 /**
3474  * Get the highest ACK value of all clients in a particular tunnel,
3475  * according to the buffering/speed settings.
3476  * 
3477  * @param t Tunnel on which to look.
3478  * 
3479  * @return Corresponding ACK value (max uint32_t).
3480  *         If no clients are suscribed, -1LL.
3481  */
3482 static int64_t
3483 tunnel_get_clients_fwd_ack (struct MeshTunnel *t)
3484 {
3485   unsigned int i;
3486   int64_t ack;
3487
3488   if (0 == t->nclients)
3489   {
3490     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3491                 "  tunnel has no clients, no FWD ACK\n");
3492     return -1LL;
3493   }
3494
3495   for (ack = -1LL, i = 0; i < t->nclients; i++)
3496   {
3497     if (-1LL == ack ||
3498         (GNUNET_YES == t->speed_min &&
3499          GNUNET_YES == GMC_is_pid_bigger (ack, t->clients_fc[i].fwd_ack)) ||
3500         (GNUNET_NO == t->speed_min &&
3501          GNUNET_YES == GMC_is_pid_bigger (t->clients_fc[i].fwd_ack, ack)))
3502     {
3503       ack = t->clients_fc[i].fwd_ack;
3504     }
3505   }
3506
3507   if (GNUNET_YES == t->nobuffer && GMC_is_pid_bigger(ack, t->fwd_pid))
3508     ack = (uint32_t) t->fwd_pid + 1; // Might overflow, it's ok.
3509
3510   return (uint32_t) ack;
3511 }
3512
3513
3514 /**
3515  * Get the current fwd ack value for a tunnel, taking in account the tunnel
3516  * mode and the status of all children nodes.
3517  *
3518  * @param t Tunnel.
3519  *
3520  * @return Maximum PID allowed.
3521  */
3522 static uint32_t
3523 tunnel_get_fwd_ack (struct MeshTunnel *t)
3524 {
3525   uint32_t ack;
3526   uint32_t count;
3527   uint32_t buffer_free;
3528   int64_t child_ack;
3529   int64_t client_ack;
3530
3531   count = t->fwd_pid - t->skip;
3532   buffer_free = t->fwd_queue_max - t->fwd_queue_n;
3533   child_ack = tunnel_get_children_fwd_ack (t);
3534   client_ack = tunnel_get_clients_fwd_ack (t);
3535   if (GNUNET_YES == t->nobuffer)
3536   {
3537     ack = count;
3538     if (-1LL == child_ack)
3539       child_ack = client_ack;
3540     if (-1LL == child_ack)
3541     {
3542       GNUNET_break (0);
3543       client_ack = child_ack = ack;
3544     }
3545   }
3546   else
3547   {
3548     ack = count + buffer_free; // Overflow? OK!
3549   }
3550   if (-1LL == child_ack)
3551   {
3552     // Node has no children, child_ack AND core buffer are irrelevant.
3553     if (-1LL == client_ack) // No children AND no clients? Not good!
3554     {
3555       GNUNET_STATISTICS_update (stats, "# mesh acks with no target",
3556                                 1, GNUNET_NO);
3557
3558     }
3559     return (uint32_t) client_ack;
3560   }
3561   if (-1LL == client_ack)
3562   {
3563     client_ack = ack;
3564   }
3565   if (GNUNET_YES == t->speed_min)
3566   {
3567     ack = GMC_min_pid ((uint32_t) child_ack, ack);
3568     ack = GMC_min_pid ((uint32_t) client_ack, ack);
3569   }
3570   else
3571   {
3572     ack = GMC_max_pid ((uint32_t) child_ack, ack);
3573     ack = GMC_max_pid ((uint32_t) client_ack, ack);
3574   }
3575   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3576               "c %u, bf %u, ch %lld, cl %lld, ACK: %u\n",
3577               count, buffer_free, child_ack, client_ack, ack);
3578   return ack;
3579 }
3580
3581
3582 /**
3583  * Build a local ACK message and send it to a local client.
3584  * 
3585  * @param t Tunnel on which to send the ACK.
3586  * @param c Client to whom send the ACK.
3587  * @param ack Value of the ACK.
3588  */
3589 static void
3590 send_local_ack (struct MeshTunnel *t, struct MeshClient *c, uint32_t ack)
3591 {
3592   struct GNUNET_MESH_LocalAck msg;
3593
3594   msg.header.size = htons (sizeof (msg));
3595   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
3596   msg.tunnel_id = htonl (t->owner == c ? t->local_tid : t->local_tid_dest);
3597   msg.max_pid = htonl (ack); 
3598   GNUNET_SERVER_notification_context_unicast(nc,
3599                                               c->handle,
3600                                               &msg.header,
3601                                               GNUNET_NO);
3602 }
3603
3604 /**
3605  * Build an ACK message and queue it to send to the given peer.
3606  * 
3607  * @param t Tunnel on which to send the ACK.
3608  * @param peer Peer to whom send the ACK.
3609  * @param ack Value of the ACK.
3610  */
3611 static void
3612 send_ack (struct MeshTunnel *t, struct GNUNET_PeerIdentity *peer,  uint32_t ack)
3613 {
3614   struct GNUNET_MESH_ACK msg;
3615
3616   GNUNET_PEER_resolve (t->id.oid, &msg.oid);
3617   msg.header.size = htons (sizeof (msg));
3618   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_ACK);
3619   msg.pid = htonl (ack);
3620   msg.tid = htonl (t->id.tid);
3621
3622   send_prebuilt_message (&msg.header, peer, t);
3623 }
3624
3625
3626 /**
3627  * Notify a the owner of a tunnel about how many more
3628  * payload packages will we accept on a given tunnel.
3629  *
3630  * @param t Tunnel on which to send the ACK.
3631  */
3632 static void
3633 tunnel_send_client_fwd_ack (struct MeshTunnel *t)
3634 {
3635   uint32_t ack;
3636
3637   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3638               "Sending client FWD ACK on tunnel %X\n",
3639               t->local_tid);
3640
3641   ack = tunnel_get_fwd_ack (t);
3642
3643   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ack %u\n", ack);
3644   if (t->last_fwd_ack == ack)
3645   {
3646     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " same as last, not sending!\n");
3647     return;
3648   }
3649
3650   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " sending!\n");
3651   t->last_fwd_ack = ack;
3652   send_local_ack (t, t->owner, ack);
3653 }
3654
3655
3656 /**
3657  * Send an ACK informing the predecessor about the available buffer space.
3658  * In case there is no predecessor, inform the owning client.
3659  * If buffering is off, send only on behalf of children or self if endpoint.
3660  * If buffering is on, send when sent to children and buffer space is free.
3661  * Note that although the name is fwd_ack, the FWD mean forward *traffic*,
3662  * the ACK itself goes "back" (towards root).
3663  * 
3664  * @param t Tunnel on which to send the ACK.
3665  * @param type Type of message that triggered the ACK transmission.
3666  */
3667 static void
3668 tunnel_send_fwd_ack (struct MeshTunnel *t, uint16_t type)
3669 {
3670   struct GNUNET_PeerIdentity id;
3671   uint32_t ack;
3672
3673   if (NULL != t->owner)
3674   {
3675     tunnel_send_client_fwd_ack (t);
3676     return;
3677   }
3678   /* Is it after unicast / multicast retransmission? */
3679   switch (type)
3680   {
3681     case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
3682     case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
3683       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3684                   "ACK due to FWD DATA retransmission\n");
3685       if (GNUNET_YES == t->nobuffer)
3686       {
3687         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, nobuffer\n");
3688         return;
3689       }
3690       break;
3691     case GNUNET_MESSAGE_TYPE_MESH_ACK:
3692     case GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK:
3693       break;
3694     case GNUNET_MESSAGE_TYPE_MESH_POLL:
3695       t->force_ack = GNUNET_YES;
3696       break;
3697     default:
3698       GNUNET_break (0);
3699   }
3700
3701   /* Check if we need to transmit the ACK */
3702   if (t->fwd_queue_max > t->fwd_queue_n * 4 &&
3703       GMC_is_pid_bigger(t->last_fwd_ack, t->fwd_pid) &&
3704       GNUNET_NO == t->force_ack)
3705   {
3706     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, buffer free\n");
3707     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3708                 "  t->qmax: %u, t->qn: %u\n",
3709                 t->fwd_queue_max, t->fwd_queue_n);
3710     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3711                 "  t->pid: %u, t->ack: %u\n",
3712                 t->fwd_pid, t->last_fwd_ack);
3713     return;
3714   }
3715
3716   /* Ok, ACK might be necessary, what PID to ACK? */
3717   ack = tunnel_get_fwd_ack (t);
3718
3719   /* If speed_min and not all children have ack'd, dont send yet */
3720   if (ack == t->last_fwd_ack && GNUNET_NO == t->force_ack)
3721   {
3722     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending FWD ACK, not ready\n");
3723     return;
3724   }
3725
3726   t->last_fwd_ack = ack;
3727   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
3728   send_ack (t, &id, ack);
3729   debug_fwd_ack++;
3730   t->force_ack = GNUNET_NO;
3731 }
3732
3733
3734 /**
3735  * Iterator to send a child node a BCK ACK to allow him to send more
3736  * to_origin data.
3737  *
3738  * @param cls Closure (tunnel).
3739  * @param id Id of the child node.
3740  */
3741 static void
3742 tunnel_send_child_bck_ack (void *cls,
3743                            GNUNET_PEER_Id id)
3744 {
3745   struct MeshTunnel *t = cls;
3746   struct MeshTunnelChildInfo *cinfo;
3747   struct GNUNET_PeerIdentity peer;
3748   uint32_t ack;
3749
3750   GNUNET_PEER_resolve (id, &peer);
3751   cinfo = tunnel_get_neighbor_fc (t, &peer);
3752   ack = cinfo->bck_pid + t->bck_queue_max - t->bck_queue_n;
3753
3754   if (cinfo->bck_ack == ack && GNUNET_NO == t->force_ack)
3755   {
3756     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3757                 "    Not sending ACK, not needed\n");
3758     return;
3759   }
3760   cinfo->bck_ack = ack;
3761
3762   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3763               "    Sending BCK ACK %u (last sent: %u)\n",
3764               ack, cinfo->bck_ack);
3765   send_ack (t, &peer, ack);
3766 }
3767
3768
3769 /**
3770  * @brief Send BCK ACKs to clients to allow them more to_origin traffic
3771  * 
3772  * Iterates over all clients and sends BCK ACKs to the ones that need it.
3773  *
3774  * FIXME fc: what happens if we have 2 clients but q_size is 1?
3775  *           - implement a size 1 buffer in each client_fc AND children_fc
3776  *           to hold at least 1 message per "child".
3777  *             problem: violates no buffer policy
3778  *           - ack 0 and make "children" poll for transmission slots
3779  *             problem: big overhead, extra latency even in low traffic
3780  *                      settings
3781  * 
3782  * @param t Tunnel on which to send the BCK ACKs.
3783  */
3784 static void
3785 tunnel_send_clients_bck_ack (struct MeshTunnel *t)
3786 {
3787   unsigned int i;
3788   unsigned int tunnel_delta;
3789
3790   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Sending BCK ACK to clients\n");
3791
3792   tunnel_delta = t->bck_queue_max - t->bck_queue_n;
3793   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   tunnel delta: %u\n", tunnel_delta);
3794
3795   /* Find client whom to allow to send to origin (with lowest buffer space) */
3796   for (i = 0; i < t->nclients; i++)
3797   {
3798     struct MeshTunnelClientInfo *clinfo;
3799     unsigned int delta;
3800
3801     clinfo = &t->clients_fc[i];
3802     delta = clinfo->bck_ack - clinfo->bck_pid;
3803     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    client %u delta: %u\n",
3804          t->clients[i]->id, delta);
3805
3806     if ((GNUNET_NO == t->nobuffer && tunnel_delta > delta) ||
3807         (GNUNET_YES == t->nobuffer && 0 == delta))
3808     {
3809       uint32_t ack;
3810
3811       ack = clinfo->bck_pid;
3812       ack += t->nobuffer ? 1 : tunnel_delta;
3813       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3814                   "    sending ack to client %u: %u\n",
3815                   t->clients[i]->id, ack);
3816       send_local_ack (t, t->clients[i], ack);
3817       clinfo->bck_ack = ack;
3818     }
3819     else
3820     {
3821       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3822                   "    not sending ack to client %u (td %u, d %u)\n",
3823                   t->clients[i]->id, tunnel_delta, delta);
3824     }
3825   }
3826 }
3827
3828
3829 /**
3830  * Send an ACK informing the children nodes and destination clients about
3831  * the available buffer space.
3832  * If buffering is off, send only on behalf of root (can be self).
3833  * If buffering is on, send when sent to predecessor and buffer space is free.
3834  * Note that although the name is bck_ack, the BCK mean backwards *traffic*,
3835  * the ACK itself goes "forward" (towards children/clients).
3836  * 
3837  * @param t Tunnel on which to send the ACK.
3838  * @param type Type of message that triggered the ACK transmission.
3839  */
3840 static void
3841 tunnel_send_bck_ack (struct MeshTunnel *t, uint16_t type)
3842 {
3843   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3844               "Sending BCK ACK on tunnel %u [%u] due to %s\n",
3845               t->id.oid, t->id.tid, GNUNET_MESH_DEBUG_M2S(type));
3846   /* Is it after data to_origin retransmission? */
3847   switch (type)
3848   {
3849     case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
3850       if (GNUNET_YES == t->nobuffer)
3851       {
3852         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3853                     "    Not sending ACK, nobuffer\n");
3854         return;
3855       }
3856       break;
3857     case GNUNET_MESSAGE_TYPE_MESH_ACK:
3858     case GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK:
3859       break;
3860     case GNUNET_MESSAGE_TYPE_MESH_POLL:
3861       t->force_ack = GNUNET_YES;
3862       break;
3863     default:
3864       GNUNET_break (0);
3865   }
3866
3867   tunnel_send_clients_bck_ack (t);
3868   tree_iterate_children (t->tree, &tunnel_send_child_bck_ack, t);
3869   t->force_ack = GNUNET_NO;
3870 }
3871
3872
3873 /**
3874  * @brief Re-initiate traffic to this peer if necessary.
3875  *
3876  * Check if there is traffic queued towards this peer
3877  * and the core transmit handle is NULL (traffic was stalled).
3878  * If so, call core tmt rdy.
3879  *
3880  * @param cls Closure (unused)
3881  * @param peer_id Short ID of peer to which initiate traffic.
3882  */
3883 static void
3884 peer_unlock_queue(void *cls, GNUNET_PEER_Id peer_id)
3885 {
3886   struct MeshPeerInfo *peer;
3887   struct GNUNET_PeerIdentity id;
3888   struct MeshPeerQueue *q;
3889   size_t size;
3890
3891   peer = peer_info_get_short(peer_id);
3892   if (NULL != peer->core_transmit)
3893     return;
3894
3895   q = queue_get_next(peer);
3896   if (NULL == q)
3897   {
3898     /* Might br multicast traffic already sent to this particular peer but
3899      * not to other children in this tunnel.
3900      * This way t->queue_n would be > 0 but the queue of this particular peer
3901      * would be empty.
3902      */
3903     return;
3904   }
3905   size = q->size;
3906   GNUNET_PEER_resolve (peer->id, &id);
3907   peer->core_transmit =
3908         GNUNET_CORE_notify_transmit_ready(core_handle,
3909                                           0,
3910                                           0,
3911                                           GNUNET_TIME_UNIT_FOREVER_REL,
3912                                           &id,
3913                                           size,
3914                                           &queue_send,
3915                                           peer);
3916         return;
3917 }
3918
3919
3920 /**
3921  * @brief Allow transmission of FWD traffic on this tunnel
3922  *
3923  * Check if there is traffic queued towards any children
3924  * and the core transmit handle is NULL, and if so, call core tmt rdy.
3925  *
3926  * @param t Tunnel on which to unlock FWD traffic.
3927  */
3928 static void
3929 tunnel_unlock_fwd_queues (struct MeshTunnel *t)
3930 {
3931   if (0 == t->fwd_queue_n)
3932     return;
3933
3934   tree_iterate_children (t->tree, &peer_unlock_queue, NULL);
3935 }
3936
3937
3938 /**
3939  * @brief Allow transmission of BCK traffic on this tunnel
3940  *
3941  * Check if there is traffic queued towards the root of the tree
3942  * and the core transmit handle is NULL, and if so, call core tmt rdy.
3943  *
3944  * @param t Tunnel on which to unlock BCK traffic.
3945  */
3946 static void
3947 tunnel_unlock_bck_queue (struct MeshTunnel *t)
3948 {
3949   if (0 == t->bck_queue_n)
3950     return;
3951
3952   peer_unlock_queue(NULL, tree_get_predecessor(t->tree));
3953 }
3954
3955
3956 /**
3957  * Send a message to all peers in this tunnel that the tunnel is no longer
3958  * valid.
3959  *
3960  * @param t The tunnel whose peers to notify.
3961  * @param parent ID of the parent, in case the tree is already destroyed.
3962  */
3963 static void
3964 tunnel_send_destroy (struct MeshTunnel *t, GNUNET_PEER_Id parent)
3965 {
3966   struct GNUNET_MESH_TunnelDestroy msg;
3967   struct GNUNET_PeerIdentity id;
3968
3969   msg.header.size = htons (sizeof (msg));
3970   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY);
3971   GNUNET_PEER_resolve (t->id.oid, &msg.oid);
3972   msg.tid = htonl (t->id.tid);
3973   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3974               "  sending tunnel destroy for tunnel: %s [%X]\n",
3975               GNUNET_i2s (&msg.oid), t->id.tid);
3976   if (tree_count_children(t->tree) > 0)
3977   {
3978     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  sending multicast to children\n");
3979     tunnel_send_multicast (t, &msg.header);
3980   }
3981   if (0 == parent)
3982     parent = tree_get_predecessor (t->tree);
3983   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  parent: %u\n", parent);
3984   if (0 == parent)
3985     return;
3986
3987   GNUNET_PEER_resolve (parent, &id);
3988   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3989               "  sending back to %s\n",
3990               GNUNET_i2s (&id));
3991   send_prebuilt_message (&msg.header, &id, t);
3992 }
3993
3994
3995 /**
3996  * Cancel all transmissions towards a neighbor that belong to a certain tunnel.
3997  *
3998  * @param cls Closure (Tunnel which to cancel).
3999  * @param neighbor_id Short ID of the neighbor to whom cancel the transmissions.
4000  */
4001 static void
4002 tunnel_cancel_queues (void *cls, GNUNET_PEER_Id neighbor_id)
4003 {
4004   struct MeshTunnel *t = cls;
4005   struct MeshPeerInfo *peer_info;
4006   struct MeshPeerQueue *pq;
4007   struct MeshPeerQueue *next;
4008
4009   peer_info = peer_info_get_short (neighbor_id);
4010   for (pq = peer_info->queue_head; NULL != pq; pq = next)
4011   {
4012     next = pq->next;
4013     if (pq->tunnel == t)
4014     {
4015       if (GNUNET_MESSAGE_TYPE_MESH_MULTICAST == pq->type ||
4016           GNUNET_MESSAGE_TYPE_MESH_UNICAST == pq->type ||
4017           GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == pq->type)
4018       {
4019         // Should have been removed on destroy children
4020         GNUNET_break (0);
4021       }
4022       queue_destroy (pq, GNUNET_YES);
4023     }
4024   }
4025   if (NULL == peer_info->queue_head && NULL != peer_info->core_transmit)
4026   {
4027     GNUNET_CORE_notify_transmit_ready_cancel(peer_info->core_transmit);
4028     peer_info->core_transmit = NULL;
4029   }
4030 }
4031
4032 /**
4033  * Destroy the tunnel and free any allocated resources linked to it.
4034  *
4035  * @param t the tunnel to destroy
4036  *
4037  * @return GNUNET_OK on success
4038  */
4039 static int
4040 tunnel_destroy (struct MeshTunnel *t)
4041 {
4042   struct MeshClient *c;
4043   struct GNUNET_HashCode hash;
4044   unsigned int i;
4045   int r;
4046
4047   if (NULL == t)
4048     return GNUNET_OK;
4049
4050   r = GNUNET_OK;
4051   c = t->owner;
4052 #if MESH_DEBUG
4053   {
4054     struct GNUNET_PeerIdentity id;
4055
4056     GNUNET_PEER_resolve (t->id.oid, &id);
4057     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s [%x]\n",
4058                 GNUNET_i2s (&id), t->id.tid);
4059     if (NULL != c)
4060       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
4061   }
4062 #endif
4063
4064   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
4065   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &hash, t))
4066   {
4067     GNUNET_break (0);
4068     r = GNUNET_SYSERR;
4069   }
4070
4071   if (NULL != c)
4072   {
4073     GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
4074     if (GNUNET_YES !=
4075         GNUNET_CONTAINER_multihashmap_remove (c->own_tunnels, &hash, t))
4076     {
4077       GNUNET_break (0);
4078       r = GNUNET_SYSERR;
4079     }
4080   }
4081
4082   GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
4083   for (i = 0; i < t->nclients; i++)
4084   {
4085     c = t->clients[i];
4086     if (GNUNET_YES !=
4087           GNUNET_CONTAINER_multihashmap_remove (c->incoming_tunnels, &hash, t))
4088     {
4089       GNUNET_break (0);
4090       r = GNUNET_SYSERR;
4091     }
4092   }
4093   for (i = 0; i < t->nignore; i++)
4094   {
4095     c = t->ignore[i];
4096     if (GNUNET_YES !=
4097           GNUNET_CONTAINER_multihashmap_remove (c->ignore_tunnels, &hash, t))
4098     {
4099       GNUNET_break (0);
4100       r = GNUNET_SYSERR;
4101     }
4102   }
4103
4104   (void) GNUNET_CONTAINER_multihashmap_remove (incoming_tunnels, &hash, t);
4105   GNUNET_free_non_null (t->clients);
4106   GNUNET_free_non_null (t->ignore);
4107   GNUNET_free_non_null (t->clients_fc);
4108
4109   if (NULL != t->peers)
4110   {
4111     GNUNET_CONTAINER_multihashmap_iterate (t->peers, &peer_info_delete_tunnel,
4112                                            t);
4113     GNUNET_CONTAINER_multihashmap_destroy (t->peers);
4114   }
4115
4116   GNUNET_CONTAINER_multihashmap_iterate (t->children_fc,
4117                                          &tunnel_destroy_child,
4118                                          t);
4119   GNUNET_CONTAINER_multihashmap_destroy (t->children_fc);
4120   t->children_fc = NULL;
4121
4122   tree_iterate_children (t->tree, &tunnel_cancel_queues, t);
4123   tree_destroy (t->tree);
4124
4125   if (NULL != t->regex_search)
4126     GNUNET_REGEX_search_cancel (t->regex_search->search_handle);
4127   if (NULL != t->dht_get_type)
4128     GNUNET_DHT_get_stop (t->dht_get_type);
4129   if (GNUNET_SCHEDULER_NO_TASK != t->timeout_task)
4130     GNUNET_SCHEDULER_cancel (t->timeout_task);
4131   if (GNUNET_SCHEDULER_NO_TASK != t->path_refresh_task)
4132     GNUNET_SCHEDULER_cancel (t->path_refresh_task);
4133
4134   n_tunnels--;
4135   GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
4136   GNUNET_free (t);
4137   return r;
4138 }
4139
4140 #define TUNNEL_DESTROY_EMPTY_TIME GNUNET_TIME_UNIT_MILLISECONDS
4141
4142 /**
4143  * Tunnel is empty: destroy it.
4144  * 
4145  * @param cls Closure (Tunnel).
4146  * @param tc TaskContext. 
4147  */
4148 static void
4149 tunnel_destroy_empty_delayed (void *cls,
4150                               const struct GNUNET_SCHEDULER_TaskContext *tc)
4151 {
4152   struct MeshTunnel *t = cls;
4153
4154   t->delayed_destroy = GNUNET_SCHEDULER_NO_TASK;
4155   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4156     return;
4157
4158   if (0 != t->nclients ||
4159       0 != tree_count_children (t->tree))
4160     return;
4161
4162   #if MESH_DEBUG
4163   {
4164     struct GNUNET_PeerIdentity id;
4165
4166     GNUNET_PEER_resolve (t->id.oid, &id);
4167     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4168                 "executing destruction of empty tunnel %s [%X]\n",
4169                 GNUNET_i2s (&id), t->id.tid);
4170   }
4171   #endif
4172
4173   tunnel_send_destroy (t, 0);
4174   if (0 == t->pending_messages)
4175     tunnel_destroy (t);
4176   else
4177     t->destroy = GNUNET_YES;
4178 }
4179
4180
4181 /**
4182  * Schedule tunnel destruction if is empty and no new traffic comes in a time.
4183  * 
4184  * @param t Tunnel to destroy if empty.
4185  */
4186 static void
4187 tunnel_destroy_empty (struct MeshTunnel *t)
4188 {
4189   if (GNUNET_SCHEDULER_NO_TASK != t->delayed_destroy || 
4190       0 != t->nclients ||
4191       0 != tree_count_children (t->tree))
4192   {
4193     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4194                 "%u %u %u\n",
4195                 t->delayed_destroy, t->nclients, tree_count_children(t->tree));
4196     return;
4197   }
4198
4199   #if MESH_DEBUG
4200   {
4201     struct GNUNET_PeerIdentity id;
4202
4203     GNUNET_PEER_resolve (t->id.oid, &id);
4204     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4205                 "scheduling destruction of empty tunnel %s [%X]\n",
4206                 GNUNET_i2s (&id), t->id.tid);
4207   }
4208   #endif
4209
4210   t->delayed_destroy =
4211       GNUNET_SCHEDULER_add_delayed (TUNNEL_DESTROY_EMPTY_TIME,
4212                                     &tunnel_destroy_empty_delayed,
4213                                     t);
4214 }
4215
4216
4217 /**
4218  * Create a new tunnel
4219  * 
4220  * @param owner Who is the owner of the tunnel (short ID).
4221  * @param tid Tunnel Number of the tunnel.
4222  * @param client Clients that owns the tunnel, NULL for foreign tunnels.
4223  * @param local Tunnel Number for the tunnel, for the client point of view.
4224  * 
4225  * @return A new initialized tunnel. NULL on error.
4226  */
4227 static struct MeshTunnel *
4228 tunnel_new (GNUNET_PEER_Id owner,
4229             MESH_TunnelNumber tid,
4230             struct MeshClient *client,
4231             MESH_TunnelNumber local)
4232 {
4233   struct MeshTunnel *t;
4234   struct GNUNET_HashCode hash;
4235
4236   if (n_tunnels >= max_tunnels && NULL == client)
4237     return NULL;
4238
4239   t = GNUNET_malloc (sizeof (struct MeshTunnel));
4240   t->id.oid = owner;
4241   t->id.tid = tid;
4242   t->fwd_queue_max = (max_msgs_queue / max_tunnels) + 1;
4243   t->bck_queue_max = t->fwd_queue_max;
4244   t->tree = tree_new (owner);
4245   t->owner = client;
4246   t->fwd_pid = (uint32_t) -1; // Next (expected) = 0
4247   t->bck_pid = (uint32_t) -1; // Next (expected) = 0
4248   t->bck_ack = INITIAL_WINDOW_SIZE - 1;
4249   t->last_fwd_ack = INITIAL_WINDOW_SIZE - 1;
4250   t->local_tid = local;
4251   t->children_fc = GNUNET_CONTAINER_multihashmap_create (8, GNUNET_NO);
4252   n_tunnels++;
4253   GNUNET_STATISTICS_update (stats, "# tunnels", 1, GNUNET_NO);
4254
4255   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
4256   if (GNUNET_OK !=
4257       GNUNET_CONTAINER_multihashmap_put (tunnels, &hash, t,
4258                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
4259   {
4260     GNUNET_break (0);
4261     tunnel_destroy (t);
4262     if (NULL != client)
4263     {
4264       GNUNET_break (0);
4265       GNUNET_SERVER_receive_done (client->handle, GNUNET_SYSERR);
4266     }
4267     return NULL;
4268   }
4269
4270   if (NULL != client)
4271   {
4272     GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
4273     if (GNUNET_OK !=
4274         GNUNET_CONTAINER_multihashmap_put (client->own_tunnels, &hash, t,
4275                                           GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
4276     {
4277       tunnel_destroy (t);
4278       GNUNET_break (0);
4279       GNUNET_SERVER_receive_done (client->handle, GNUNET_SYSERR);
4280       return NULL;
4281     }
4282   }
4283
4284   return t;
4285 }
4286
4287 /**
4288  * Callback when removing children from a tunnel tree. Notify owner.
4289  *
4290  * @param cls Closure (tunnel).
4291  * @param peer_id Short ID of the peer deleted.
4292  */
4293 void
4294 tunnel_child_removed (void *cls, GNUNET_PEER_Id peer_id)
4295 {
4296   struct MeshTunnel *t = cls;
4297
4298   client_notify_peer_disconnected (t->owner, t, peer_id);
4299 }
4300
4301 /**
4302  * Removes an explicit path from a tunnel, freeing all intermediate nodes
4303  * that are no longer needed, as well as nodes of no longer reachable peers.
4304  * The tunnel itself is also destoyed if results in a remote empty tunnel.
4305  *
4306  * @param t Tunnel from which to remove the path.
4307  * @param peer Short id of the peer which should be removed.
4308  */
4309 static void
4310 tunnel_delete_peer (struct MeshTunnel *t, GNUNET_PEER_Id peer)
4311 {
4312   int r;
4313
4314   r = tree_del_peer (t->tree, peer, &tunnel_child_removed, t);
4315   if (GNUNET_NO == r)
4316   {
4317     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4318                 "Tunnel %u [%u] has no more nodes\n",
4319                 t->id.oid, t->id.tid);
4320   }
4321 }
4322
4323
4324 /**
4325  * tunnel_destroy_iterator: iterator for deleting each tunnel that belongs to a
4326  * client when the client disconnects. If the client is not the owner, the
4327  * owner will get notified if no more clients are in the tunnel and the client
4328  * get removed from the tunnel's list.
4329  *
4330  * @param cls closure (client that is disconnecting)
4331  * @param key the hash of the local tunnel id (used to access the hashmap)
4332  * @param value the value stored at the key (tunnel to destroy)
4333  *
4334  * @return GNUNET_OK, keep iterating.
4335  */
4336 static int
4337 tunnel_destroy_iterator (void *cls,
4338                          const struct GNUNET_HashCode * key,
4339                          void *value)
4340 {
4341   struct MeshTunnel *t = value;
4342   struct MeshClient *c = cls;
4343
4344   send_client_tunnel_disconnect (t, c);
4345   if (c != t->owner)
4346   {
4347     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Client %u is destination.\n", c->id);
4348     tunnel_delete_client (t, c);
4349     client_delete_tunnel (c, t);
4350     tunnel_destroy_empty (t);
4351     return GNUNET_OK;
4352   }
4353   tunnel_send_destroy (t, 0);
4354   t->owner = NULL;
4355   t->destroy = GNUNET_YES;
4356
4357   return GNUNET_OK;
4358 }
4359
4360
4361 /**
4362  * Timeout function, destroys tunnel if called
4363  *
4364  * @param cls Closure (tunnel to destroy).
4365  * @param tc TaskContext
4366  */
4367 static void
4368 tunnel_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4369 {
4370   struct MeshTunnel *t = cls;
4371   struct GNUNET_PeerIdentity id;
4372
4373   t->timeout_task = GNUNET_SCHEDULER_NO_TASK;
4374   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4375     return;
4376   GNUNET_PEER_resolve(t->id.oid, &id);
4377   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4378               "Tunnel %s [%X] timed out. Destroying.\n",
4379               GNUNET_i2s(&id), t->id.tid);
4380   send_clients_tunnel_destroy (t);
4381   tunnel_destroy (t);
4382 }
4383
4384 /**
4385  * Resets the tunnel timeout. Starts it if no timeout was running.
4386  *
4387  * @param t Tunnel whose timeout to reset.
4388  *
4389  * TODO use heap to improve efficiency of scheduler.
4390  */
4391 static void
4392 tunnel_reset_timeout (struct MeshTunnel *t)
4393 {
4394   if (GNUNET_SCHEDULER_NO_TASK != t->timeout_task)
4395     GNUNET_SCHEDULER_cancel (t->timeout_task);
4396   t->timeout_task =
4397       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
4398                                     (refresh_path_time, 4), &tunnel_timeout, t);
4399 }
4400
4401
4402 /******************************************************************************/
4403 /****************      MESH NETWORK HANDLER HELPERS     ***********************/
4404 /******************************************************************************/
4405
4406 /**
4407  * Function to send a create path packet to a peer.
4408  *
4409  * @param cls closure
4410  * @param size number of bytes available in buf
4411  * @param buf where the callee should write the message
4412  * @return number of bytes written to buf
4413  */
4414 static size_t
4415 send_core_path_create (void *cls, size_t size, void *buf)
4416 {
4417   struct MeshPathInfo *info = cls;
4418   struct GNUNET_MESH_ManipulatePath *msg;
4419   struct GNUNET_PeerIdentity *peer_ptr;
4420   struct MeshTunnel *t = info->t;
4421   struct MeshPeerPath *p = info->path;
4422   size_t size_needed;
4423   uint32_t opt;
4424   int i;
4425
4426   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATE PATH sending...\n");
4427   size_needed =
4428       sizeof (struct GNUNET_MESH_ManipulatePath) +
4429       p->length * sizeof (struct GNUNET_PeerIdentity);
4430
4431   if (size < size_needed || NULL == buf)
4432   {
4433     GNUNET_break (0);
4434     return 0;
4435   }
4436   msg = (struct GNUNET_MESH_ManipulatePath *) buf;
4437   msg->header.size = htons (size_needed);
4438   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE);
4439   msg->tid = ntohl (t->id.tid);
4440
4441   opt = 0;
4442   if (GNUNET_YES == t->speed_min)
4443     opt |= MESH_TUNNEL_OPT_SPEED_MIN;
4444   if (GNUNET_YES == t->nobuffer)
4445     opt |= MESH_TUNNEL_OPT_NOBUFFER;
4446   msg->opt = htonl(opt);
4447   msg->reserved = 0;
4448
4449   peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
4450   for (i = 0; i < p->length; i++)
4451   {
4452     GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
4453   }
4454
4455   path_destroy (p);
4456   GNUNET_free (info);
4457
4458   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4459               "CREATE PATH (%u bytes long) sent!\n", size_needed);
4460   return size_needed;
4461 }
4462
4463
4464 /**
4465  * Fill the core buffer 
4466  *
4467  * @param cls closure (data itself)
4468  * @param size number of bytes available in buf
4469  * @param buf where the callee should write the message
4470  *
4471  * @return number of bytes written to buf
4472  */
4473 static size_t
4474 send_core_data_multicast (void *cls, size_t size, void *buf)
4475 {
4476   struct MeshTransmissionDescriptor *info = cls;
4477   size_t total_size;
4478
4479   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Multicast callback.\n");
4480   GNUNET_assert (NULL != info);
4481   GNUNET_assert (NULL != info->peer);
4482   total_size = info->mesh_data->data_len;
4483   GNUNET_assert (total_size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
4484
4485   if (total_size > size)
4486   {
4487     GNUNET_break (0);
4488     return 0;
4489   }
4490   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " copying data...\n");
4491   memcpy (buf, info->mesh_data->data, total_size);
4492 #if MESH_DEBUG
4493   {
4494     struct GNUNET_MESH_Multicast *mc;
4495     struct GNUNET_MessageHeader *mh;
4496
4497     mh = buf;
4498     if (ntohs (mh->type) == GNUNET_MESSAGE_TYPE_MESH_MULTICAST)
4499     {
4500       mc = (struct GNUNET_MESH_Multicast *) mh;
4501       mh = (struct GNUNET_MessageHeader *) &mc[1];
4502       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4503                   " multicast, payload type %s\n",
4504                   GNUNET_MESH_DEBUG_M2S (ntohs (mh->type)));
4505       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4506                   " multicast, payload size %u\n", ntohs (mh->size));
4507     }
4508     else
4509     {
4510       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " type %s\n",
4511                   GNUNET_MESH_DEBUG_M2S (ntohs (mh->type)));
4512     }
4513   }
4514 #endif
4515   data_descriptor_decrement_rc (info->mesh_data);
4516   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "freeing info...\n");
4517   GNUNET_free (info);
4518   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "return %u\n", total_size);
4519   return total_size;
4520 }
4521
4522
4523 /**
4524  * Creates a path ack message in buf and frees all unused resources.
4525  *
4526  * @param cls closure (MeshTransmissionDescriptor)
4527  * @param size number of bytes available in buf
4528  * @param buf where the callee should write the message
4529  * @return number of bytes written to buf
4530  */
4531 static size_t
4532 send_core_path_ack (void *cls, size_t size, void *buf)
4533 {
4534   struct MeshTransmissionDescriptor *info = cls;
4535   struct GNUNET_MESH_PathACK *msg = buf;
4536
4537   GNUNET_assert (NULL != info);
4538   if (sizeof (struct GNUNET_MESH_PathACK) > size)
4539   {
4540     GNUNET_break (0);
4541     return 0;
4542   }
4543   msg->header.size = htons (sizeof (struct GNUNET_MESH_PathACK));
4544   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_ACK);
4545   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
4546   msg->tid = htonl (info->origin->tid);
4547   msg->peer_id = my_full_id;
4548
4549   GNUNET_free (info);
4550   /* TODO add signature */
4551
4552   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "PATH ACK sent!\n");
4553   return sizeof (struct GNUNET_MESH_PathACK);
4554 }
4555
4556
4557 /**
4558  * Free a transmission that was already queued with all resources
4559  * associated to the request.
4560  *
4561  * @param queue Queue handler to cancel.
4562  * @param clear_cls Is it necessary to free associated cls?
4563  */
4564 static void
4565 queue_destroy (struct MeshPeerQueue *queue, int clear_cls)
4566 {
4567   struct MeshTransmissionDescriptor *dd;
4568   struct MeshPathInfo *path_info;
4569   struct MeshTunnelChildInfo *cinfo;
4570   struct GNUNET_PeerIdentity id;
4571   unsigned int i;
4572   unsigned int max;
4573
4574   if (GNUNET_YES == clear_cls)
4575   {
4576     switch (queue->type)
4577     {
4578       case GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY:
4579         GNUNET_log (GNUNET_ERROR_TYPE_INFO, "   cancelling TUNNEL_DESTROY\n");
4580         GNUNET_break (GNUNET_YES == queue->tunnel->destroy);
4581         /* fall through */
4582       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4583       case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
4584       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4585       case GNUNET_MESSAGE_TYPE_MESH_ACK:
4586       case GNUNET_MESSAGE_TYPE_MESH_POLL:
4587       case GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE:
4588         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4589                     "   prebuilt message\n");
4590         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4591                     "   type %s\n",
4592                     GNUNET_MESH_DEBUG_M2S(queue->type));
4593         dd = queue->cls;
4594         data_descriptor_decrement_rc (dd->mesh_data);
4595         break;
4596       case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
4597         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   type create path\n");
4598         path_info = queue->cls;
4599         path_destroy (path_info->path);
4600         break;
4601       default:
4602         GNUNET_break (0);
4603         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4604                     "   type %s unknown!\n",
4605                     GNUNET_MESH_DEBUG_M2S(queue->type));
4606     }
4607     GNUNET_free_non_null (queue->cls);
4608   }
4609   GNUNET_CONTAINER_DLL_remove (queue->peer->queue_head,
4610                                queue->peer->queue_tail,
4611                                queue);
4612
4613   /* Delete from child_fc in the appropiate tunnel */
4614   max = queue->tunnel->fwd_queue_max;
4615   GNUNET_PEER_resolve (queue->peer->id, &id);
4616   cinfo = tunnel_get_neighbor_fc (queue->tunnel, &id);
4617   if (NULL != cinfo)
4618   {
4619     for (i = 0; i < cinfo->send_buffer_n; i++)
4620     {
4621       unsigned int i2;
4622       i2 = (cinfo->send_buffer_start + i) % max;
4623       if (cinfo->send_buffer[i2] == queue)
4624       {
4625         /* Found corresponding entry in the send_buffer. Move all others back. */
4626         unsigned int j;
4627         unsigned int j2;
4628         unsigned int j3;
4629
4630         for (j = i, j2 = 0, j3 = 0; j < cinfo->send_buffer_n - 1; j++)
4631         {
4632           j2 = (cinfo->send_buffer_start + j) % max;
4633           j3 = (cinfo->send_buffer_start + j + 1) % max;
4634           cinfo->send_buffer[j2] = cinfo->send_buffer[j3];
4635         }
4636
4637         cinfo->send_buffer[j3] = NULL;
4638         cinfo->send_buffer_n--;
4639       }
4640     }
4641   }
4642
4643   GNUNET_free (queue);
4644 }
4645
4646
4647 /**
4648  * @brief Get the next transmittable message from the queue.
4649  *
4650  * This will be the head, except in the case of being a data packet
4651  * not allowed by the destination peer.
4652  *
4653  * @param peer Destination peer.
4654  *
4655  * @return The next viable MeshPeerQueue element to send to that peer.
4656  *         NULL when there are no transmittable messages.
4657  */
4658 struct MeshPeerQueue *
4659 queue_get_next (const struct MeshPeerInfo *peer)
4660 {
4661   struct MeshPeerQueue *q;
4662   struct MeshTunnel *t;
4663   struct MeshTransmissionDescriptor *info;
4664   struct MeshTunnelChildInfo *cinfo;
4665   struct GNUNET_MESH_Unicast *ucast;
4666   struct GNUNET_MESH_ToOrigin *to_orig;
4667   struct GNUNET_MESH_Multicast *mcast;
4668   struct GNUNET_PeerIdentity id;
4669   uint32_t pid;
4670   uint32_t ack;
4671
4672   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   selecting message\n");
4673   for (q = peer->queue_head; NULL != q; q = q->next)
4674   {
4675     t = q->tunnel;
4676     info = q->cls;
4677     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4678                 "*********     %s\n",
4679                 GNUNET_MESH_DEBUG_M2S(q->type));
4680     switch (q->type)
4681     {
4682       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4683         ucast = (struct GNUNET_MESH_Unicast *) info->mesh_data->data;
4684         pid = ntohl (ucast->pid);
4685         GNUNET_PEER_resolve (info->peer->id, &id);
4686         cinfo = tunnel_get_neighbor_fc(t, &id);
4687         ack = cinfo->fwd_ack;
4688         break;
4689       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4690         to_orig = (struct GNUNET_MESH_ToOrigin *) info->mesh_data->data;
4691         pid = ntohl (to_orig->pid);
4692         ack = t->bck_ack;
4693         break;
4694       case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
4695         mcast = (struct GNUNET_MESH_Multicast *) info->mesh_data->data;
4696         if (GNUNET_MESSAGE_TYPE_MESH_MULTICAST != ntohs(mcast->header.type)) 
4697         {
4698           // Not a multicast payload: multicast control traffic (destroy, etc)
4699           return q;
4700         }
4701         pid = ntohl (mcast->pid);
4702         GNUNET_PEER_resolve (info->peer->id, &id);
4703         cinfo = tunnel_get_neighbor_fc(t, &id);
4704         ack = cinfo->fwd_ack;
4705         break;
4706       default:
4707         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4708                     "*********   OK!\n");
4709         return q;
4710     }
4711         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4712                     "*********     ACK: %u, PID: %u\n",
4713                     ack, pid);
4714     if (GNUNET_NO == GMC_is_pid_bigger(pid, ack))
4715     {
4716       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4717                   "*********   OK!\n");
4718       return q;
4719     }
4720     else
4721     {
4722       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4723                   "*********     NEXT!\n");
4724     }
4725   }
4726   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4727                 "*********   nothing found\n");
4728   return NULL;
4729 }
4730
4731
4732 /**
4733   * Core callback to write a queued packet to core buffer
4734   *
4735   * @param cls Closure (peer info).
4736   * @param size Number of bytes available in buf.
4737   * @param buf Where the to write the message.
4738   *
4739   * @return number of bytes written to buf
4740   */
4741 static size_t
4742 queue_send (void *cls, size_t size, void *buf)
4743 {
4744     struct MeshPeerInfo *peer = cls;
4745     struct GNUNET_MessageHeader *msg;
4746     struct MeshPeerQueue *queue;
4747     struct MeshTunnel *t;
4748     struct MeshTunnelChildInfo *cinfo;
4749     struct GNUNET_PeerIdentity dst_id;
4750     size_t data_size;
4751
4752     peer->core_transmit = NULL;
4753     cinfo = NULL;
4754
4755     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "********* Queue send\n");
4756     queue = queue_get_next (peer);
4757
4758     /* Queue has no internal mesh traffic nor sendable payload */
4759     if (NULL == queue)
4760     {
4761       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   not ready, return\n");
4762       if (NULL == peer->queue_head)
4763         GNUNET_break (0); // Should've been canceled
4764       return 0;
4765     }
4766     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   not empty\n");
4767
4768     GNUNET_PEER_resolve (peer->id, &dst_id);
4769     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4770                 "*********   towards %s\n",
4771                 GNUNET_i2s(&dst_id));
4772     /* Check if buffer size is enough for the message */
4773     if (queue->size > size)
4774     {
4775         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4776                     "*********   not enough room, reissue\n");
4777         peer->core_transmit =
4778             GNUNET_CORE_notify_transmit_ready (core_handle,
4779                                                0,
4780                                                0,
4781                                                GNUNET_TIME_UNIT_FOREVER_REL,
4782                                                &dst_id,
4783                                                queue->size,
4784                                                &queue_send,
4785                                                peer);
4786         return 0;
4787     }
4788     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   size ok\n");
4789
4790     t = queue->tunnel;
4791     GNUNET_assert (0 < t->pending_messages);
4792     t->pending_messages--;
4793     if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == queue->type)
4794     {
4795       t->fwd_queue_n--;
4796       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4797                   "*********   unicast: t->q (%u/%u)\n",
4798                   t->fwd_queue_n, t->fwd_queue_max);
4799     }
4800     else if (GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == queue->type)
4801     {
4802       t->bck_queue_n--;
4803       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   to origin\n");
4804     }
4805
4806     /* Fill buf */
4807     switch (queue->type)
4808     {
4809       case 0:
4810       case GNUNET_MESSAGE_TYPE_MESH_ACK:
4811       case GNUNET_MESSAGE_TYPE_MESH_POLL:
4812       case GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN:
4813       case GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY:
4814       case GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY:
4815         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4816                     "*********   raw: %s\n",
4817                     GNUNET_MESH_DEBUG_M2S (queue->type));
4818         /* Fall through */
4819       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4820       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4821         data_size = send_core_data_raw (queue->cls, size, buf);
4822         msg = (struct GNUNET_MessageHeader *) buf;
4823         switch (ntohs (msg->type)) // Type of preconstructed message
4824         {
4825           case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4826             tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_UNICAST);
4827             break;
4828           case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4829             tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
4830             break;
4831           default:
4832               break;
4833         }
4834         break;
4835       case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
4836         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   multicast\n");
4837         {
4838           struct MeshTransmissionDescriptor *info = queue->cls;
4839
4840           if ((1 == info->mesh_data->reference_counter
4841               && GNUNET_YES == t->speed_min)
4842               ||
4843               (info->mesh_data->total_out == info->mesh_data->reference_counter
4844               && GNUNET_NO == t->speed_min))
4845           {
4846             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4847                         "*********   considered sent\n");
4848             t->fwd_queue_n--;
4849           }
4850           else
4851           {
4852             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4853                         "*********   NOT considered sent yet\n");
4854             t->pending_messages++;
4855           }
4856         }
4857         data_size = send_core_data_multicast(queue->cls, size, buf);
4858         tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
4859         break;
4860       case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
4861         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path create\n");
4862         data_size = send_core_path_create (queue->cls, size, buf);
4863         break;
4864       case GNUNET_MESSAGE_TYPE_MESH_PATH_ACK:
4865         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path ack\n");
4866         data_size = send_core_path_ack (queue->cls, size, buf);
4867         break;
4868       case GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE:
4869         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path keepalive\n");
4870         data_size = send_core_data_multicast (queue->cls, size, buf);
4871         break;
4872       default:
4873         GNUNET_break (0);
4874         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4875                     "*********   type unknown: %u\n",
4876                     queue->type);
4877         data_size = 0;
4878     }
4879     switch (queue->type)
4880     {
4881       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4882       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4883       case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
4884         cinfo = tunnel_get_neighbor_fc (t, &dst_id);
4885         if (cinfo->send_buffer[cinfo->send_buffer_start] != queue)
4886         {
4887           GNUNET_break (0);
4888           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4889                       "at pos %u (%p) != %p\n",
4890                       cinfo->send_buffer_start,
4891                       cinfo->send_buffer[cinfo->send_buffer_start],
4892                       queue);
4893         }
4894         if (cinfo->send_buffer_n > 0)
4895         {
4896           cinfo->send_buffer[cinfo->send_buffer_start] = NULL;
4897           cinfo->send_buffer_n--;
4898           cinfo->send_buffer_start++;
4899           cinfo->send_buffer_start %= t->fwd_queue_max;
4900         }
4901         else
4902         {
4903           GNUNET_break (0);
4904         }
4905         break;
4906       default:
4907         break;
4908     }
4909
4910     /* Free queue, but cls was freed by send_core_* */
4911     queue_destroy (queue, GNUNET_NO);
4912
4913     if (GNUNET_YES == t->destroy && 0 == t->pending_messages)
4914     {
4915       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********  destroying tunnel!\n");
4916       tunnel_destroy (t);
4917     }
4918
4919     /* If more data in queue, send next */
4920     queue = queue_get_next(peer);
4921     if (NULL != queue)
4922     {
4923         struct GNUNET_PeerIdentity id;
4924
4925         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   more data!\n");
4926         GNUNET_PEER_resolve (peer->id, &id);
4927         peer->core_transmit =
4928             GNUNET_CORE_notify_transmit_ready(core_handle,
4929                                               0,
4930                                               0,
4931                                               GNUNET_TIME_UNIT_FOREVER_REL,
4932                                               &id,
4933                                               queue->size,
4934                                               &queue_send,
4935                                               peer);
4936     }
4937     else
4938     {
4939       if (NULL != peer->queue_head)
4940       {
4941         GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4942                     "*********   %s stalled\n",
4943                     GNUNET_i2s(&my_full_id));
4944         if (NULL == cinfo)
4945           cinfo = tunnel_get_neighbor_fc (t, &dst_id);
4946         // FIXME unify bck/fwd structures, bck does not have cinfo right now
4947         if (NULL != cinfo && GNUNET_SCHEDULER_NO_TASK == cinfo->fc_poll)
4948         {
4949           cinfo->fc_poll = GNUNET_SCHEDULER_add_delayed (cinfo->fc_poll_time,
4950                                                          &tunnel_poll, cinfo);
4951         }
4952       }
4953     }
4954     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   return %d\n", data_size);
4955     return data_size;
4956 }
4957
4958
4959 /**
4960  * @brief Queue and pass message to core when possible.
4961  * 
4962  * If type is payload (UNICAST, TO_ORIGIN, MULTICAST) checks for queue status
4963  * and accounts for it. In case the queue is full, the message is dropped and
4964  * a break issued.
4965  * 
4966  * Otherwise, message is treated as internal and allowed to go regardless of 
4967  * queue status.
4968  *
4969  * @param cls Closure (@c type dependant). It will be used by queue_send to
4970  *            build the message to be sent if not already prebuilt.
4971  * @param type Type of the message, 0 for a raw message.
4972  * @param size Size of the message.
4973  * @param dst Neighbor to send message to.
4974  * @param t Tunnel this message belongs to.
4975  */
4976 static void
4977 queue_add (void *cls, uint16_t type, size_t size,
4978            struct MeshPeerInfo *dst, struct MeshTunnel *t)
4979 {
4980   struct MeshPeerQueue *queue;
4981   struct MeshTunnelChildInfo *cinfo;
4982   struct GNUNET_PeerIdentity id;
4983   unsigned int *max;
4984   unsigned int *n;
4985   unsigned int i;
4986
4987   n = NULL;
4988   if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == type ||
4989       GNUNET_MESSAGE_TYPE_MESH_MULTICAST == type)
4990   {
4991     n = &t->fwd_queue_n;
4992     max = &t->fwd_queue_max;
4993   }
4994   else if (GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == type)
4995   {
4996     n = &t->bck_queue_n;
4997     max = &t->bck_queue_max;
4998   }
4999   if (NULL != n)
5000   {
5001     if (*n >= *max)
5002     {
5003       GNUNET_break(0);
5004       GNUNET_STATISTICS_update(stats,
5005                                "# messages dropped (buffer full)",
5006                                1, GNUNET_NO);
5007       return; // Drop message
5008     }
5009     (*n)++;
5010   }
5011   queue = GNUNET_malloc (sizeof (struct MeshPeerQueue));
5012   queue->cls = cls;
5013   queue->type = type;
5014   queue->size = size;
5015   queue->peer = dst;
5016   queue->tunnel = t;
5017   GNUNET_CONTAINER_DLL_insert_tail (dst->queue_head, dst->queue_tail, queue);
5018   GNUNET_PEER_resolve (dst->id, &id);
5019   if (NULL == dst->core_transmit)
5020   {
5021       dst->core_transmit =
5022           GNUNET_CORE_notify_transmit_ready (core_handle,
5023                                              0,
5024                                              0,
5025                                              GNUNET_TIME_UNIT_FOREVER_REL,
5026                                              &id,
5027                                              size,
5028                                              &queue_send,
5029                                              dst);
5030   }
5031   t->pending_messages++;
5032   if (NULL == n) // Is this internal mesh traffic?
5033     return;
5034
5035   // It's payload, keep track of buffer per peer.
5036   cinfo = tunnel_get_neighbor_fc(t, &id);
5037   i = (cinfo->send_buffer_start + cinfo->send_buffer_n) % t->fwd_queue_max;
5038   if (NULL != cinfo->send_buffer[i])
5039   {
5040     GNUNET_break (cinfo->send_buffer_n == t->fwd_queue_max); // aka i == start
5041     queue_destroy (cinfo->send_buffer[cinfo->send_buffer_start], GNUNET_YES);
5042     cinfo->send_buffer_start++;
5043     cinfo->send_buffer_start %= t->fwd_queue_max;
5044   }
5045   else
5046   {
5047     cinfo->send_buffer_n++;
5048   }
5049   cinfo->send_buffer[i] = queue;
5050   if (cinfo->send_buffer_n > t->fwd_queue_max)
5051   {
5052     GNUNET_break (0);
5053     cinfo->send_buffer_n = t->fwd_queue_max;
5054   }
5055 }
5056
5057
5058 /******************************************************************************/
5059 /********************      MESH NETWORK HANDLERS     **************************/
5060 /******************************************************************************/
5061
5062
5063 /**
5064  * Core handler for path creation
5065  *
5066  * @param cls closure
5067  * @param message message
5068  * @param peer peer identity this notification is about
5069  * @param atsi performance data
5070  * @param atsi_count number of records in 'atsi'
5071  *
5072  * @return GNUNET_OK to keep the connection open,
5073  *         GNUNET_SYSERR to close it (signal serious error)
5074  */
5075 static int
5076 handle_mesh_path_create (void *cls, const struct GNUNET_PeerIdentity *peer,
5077                          const struct GNUNET_MessageHeader *message,
5078                          const struct GNUNET_ATS_Information *atsi,
5079                          unsigned int atsi_count)
5080 {
5081   unsigned int own_pos;
5082   uint16_t size;
5083   uint16_t i;
5084   MESH_TunnelNumber tid;
5085   struct GNUNET_MESH_ManipulatePath *msg;
5086   struct GNUNET_PeerIdentity *pi;
5087   struct GNUNET_HashCode hash;
5088   struct MeshPeerPath *path;
5089   struct MeshPeerInfo *dest_peer_info;
5090   struct MeshPeerInfo *orig_peer_info;
5091   struct MeshTunnel *t;
5092
5093   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5094               "Received a path create msg [%s]\n",
5095               GNUNET_i2s (&my_full_id));
5096   size = ntohs (message->size);
5097   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
5098   {
5099     GNUNET_break_op (0);
5100     return GNUNET_OK;
5101   }
5102
5103   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
5104   if (size % sizeof (struct GNUNET_PeerIdentity))
5105   {
5106     GNUNET_break_op (0);
5107     return GNUNET_OK;
5108   }
5109   size /= sizeof (struct GNUNET_PeerIdentity);
5110   if (size < 2)
5111   {
5112     GNUNET_break_op (0);
5113     return GNUNET_OK;
5114   }
5115   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
5116   msg = (struct GNUNET_MESH_ManipulatePath *) message;
5117
5118   tid = ntohl (msg->tid);
5119   pi = (struct GNUNET_PeerIdentity *) &msg[1];
5120   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5121               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi), tid);
5122   t = tunnel_get (pi, tid);
5123   if (NULL == t) // FIXME only for INCOMING tunnels?
5124   {
5125     uint32_t opt;
5126
5127     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating tunnel\n");
5128     t = tunnel_new (GNUNET_PEER_intern (pi), tid, NULL, 0);
5129     if (NULL == t)
5130     {
5131       // FIXME notify failure
5132       return GNUNET_OK;
5133     }
5134     opt = ntohl (msg->opt);
5135     t->speed_min = (0 != (opt & MESH_TUNNEL_OPT_SPEED_MIN)) ?
5136                    GNUNET_YES : GNUNET_NO;
5137     if (0 != (opt & MESH_TUNNEL_OPT_NOBUFFER))
5138     {
5139       t->nobuffer = GNUNET_YES;
5140       t->last_fwd_ack = t->fwd_pid + 1;
5141     }
5142     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5143                 "  speed_min: %d, nobuffer:%d\n",
5144                 t->speed_min, t->nobuffer);
5145
5146     if (GNUNET_YES == t->nobuffer)
5147     {
5148       t->bck_queue_max = 1;
5149       t->fwd_queue_max = 1;
5150     }
5151
5152     // FIXME only assign a local tid if a local client is interested (on demand)
5153     while (NULL != tunnel_get_incoming (next_local_tid))
5154       next_local_tid = (next_local_tid + 1) | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
5155     t->local_tid_dest = next_local_tid++;
5156     next_local_tid = next_local_tid | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
5157     // FIXME end
5158
5159     tunnel_reset_timeout (t);
5160     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
5161     if (GNUNET_OK !=
5162         GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
5163                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
5164     {
5165       tunnel_destroy (t);
5166       GNUNET_break (0);
5167       return GNUNET_OK;
5168     }
5169   }
5170   dest_peer_info =
5171       GNUNET_CONTAINER_multihashmap_get (peers, &pi[size - 1].hashPubKey);
5172   if (NULL == dest_peer_info)
5173   {
5174     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5175                 "  Creating PeerInfo for destination.\n");
5176     dest_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
5177     dest_peer_info->id = GNUNET_PEER_intern (&pi[size - 1]);
5178     GNUNET_CONTAINER_multihashmap_put (peers, &pi[size - 1].hashPubKey,
5179                                        dest_peer_info,
5180                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
5181   }
5182   orig_peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &pi->hashPubKey);
5183   if (NULL == orig_peer_info)
5184   {
5185     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5186                 "  Creating PeerInfo for origin.\n");
5187     orig_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
5188     orig_peer_info->id = GNUNET_PEER_intern (pi);
5189     GNUNET_CONTAINER_multihashmap_put (peers, &pi->hashPubKey, orig_peer_info,
5190                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
5191   }
5192   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
5193   path = path_new (size);
5194   own_pos = 0;
5195   for (i = 0; i < size; i++)
5196   {
5197     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
5198                 GNUNET_i2s (&pi[i]));
5199     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
5200     if (path->peers[i] == myid)
5201       own_pos = i;
5202   }
5203   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
5204   if (own_pos == 0)
5205   {
5206     /* cannot be self, must be 'not found' */
5207     /* create path: self not found in path through self */
5208     GNUNET_break_op (0);
5209     path_destroy (path);
5210     tunnel_destroy (t);
5211     return GNUNET_OK;
5212   }
5213   path_add_to_peers (path, GNUNET_NO);
5214   tunnel_add_path (t, path, own_pos);
5215   if (own_pos == size - 1)
5216   {
5217     /* It is for us! Send ack. */
5218     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
5219     peer_info_add_path_to_origin (orig_peer_info, path, GNUNET_NO);
5220     if (NULL == t->peers)
5221     {
5222       /* New tunnel! Notify clients on first payload message. */
5223       t->peers = GNUNET_CONTAINER_multihashmap_create (4, GNUNET_NO);
5224     }
5225     GNUNET_break (GNUNET_SYSERR !=
5226                   GNUNET_CONTAINER_multihashmap_put (t->peers,
5227                                                      &my_full_id.hashPubKey,
5228                                                      peer_info_get
5229                                                      (&my_full_id),
5230                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE));
5231     send_path_ack (t);
5232   }
5233   else
5234   {
5235     struct MeshPeerPath *path2;
5236
5237     /* It's for somebody else! Retransmit. */
5238     path2 = path_duplicate (path);
5239     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Retransmitting.\n");
5240     peer_info_add_path (dest_peer_info, path2, GNUNET_NO);
5241     path2 = path_duplicate (path);
5242     peer_info_add_path_to_origin (orig_peer_info, path2, GNUNET_NO);
5243     send_create_path (dest_peer_info, path, t);
5244   }
5245   return GNUNET_OK;
5246 }
5247
5248
5249 /**
5250  * Core handler for path destruction
5251  *
5252  * @param cls closure
5253  * @param message message
5254  * @param peer peer identity this notification is about
5255  * @param atsi performance data
5256  * @param atsi_count number of records in 'atsi'
5257  *
5258  * @return GNUNET_OK to keep the connection open,
5259  *         GNUNET_SYSERR to close it (signal serious error)
5260  */
5261 static int
5262 handle_mesh_path_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
5263                           const struct GNUNET_MessageHeader *message,
5264                           const struct GNUNET_ATS_Information *atsi,
5265                           unsigned int atsi_count)
5266 {
5267   struct GNUNET_MESH_ManipulatePath *msg;
5268   struct GNUNET_PeerIdentity *pi;
5269   struct MeshPeerPath *path;
5270   struct MeshTunnel *t;
5271   unsigned int own_pos;
5272   unsigned int i;
5273   size_t size;
5274
5275   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5276               "Received a PATH DESTROY msg from %s\n", GNUNET_i2s (peer));
5277   size = ntohs (message->size);
5278   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
5279   {
5280     GNUNET_break_op (0);
5281     return GNUNET_OK;
5282   }
5283
5284   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
5285   if (size % sizeof (struct GNUNET_PeerIdentity))
5286   {
5287     GNUNET_break_op (0);
5288     return GNUNET_OK;
5289   }
5290   size /= sizeof (struct GNUNET_PeerIdentity);
5291   if (size < 2)
5292   {
5293     GNUNET_break_op (0);
5294     return GNUNET_OK;
5295   }
5296   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
5297
5298   msg = (struct GNUNET_MESH_ManipulatePath *) message;
5299   pi = (struct GNUNET_PeerIdentity *) &msg[1];
5300   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5301               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi),
5302               msg->tid);
5303   t = tunnel_get (pi, ntohl (msg->tid));
5304   if (NULL == t)
5305   {
5306     /* TODO notify back: we don't know this tunnel */
5307     GNUNET_break_op (0);
5308     return GNUNET_OK;
5309   }
5310   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
5311   path = path_new (size);
5312   own_pos = 0;
5313   for (i = 0; i < size; i++)
5314   {
5315     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
5316                 GNUNET_i2s (&pi[i]));
5317     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
5318     if (path->peers[i] == myid)
5319       own_pos = i;
5320   }
5321   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
5322   if (own_pos < path->length - 1)
5323     send_prebuilt_message (message, &pi[own_pos + 1], t);
5324   else
5325     send_client_tunnel_disconnect(t, NULL);
5326
5327   tunnel_delete_peer (t, path->peers[path->length - 1]);
5328   path_destroy (path);
5329   return GNUNET_OK;
5330 }
5331
5332
5333 /**
5334  * Core handler for notifications of broken paths
5335  *
5336  * @param cls closure
5337  * @param message message
5338  * @param peer peer identity this notification is about
5339  * @param atsi performance data
5340  * @param atsi_count number of records in 'atsi'
5341  *
5342  * @return GNUNET_OK to keep the connection open,
5343  *         GNUNET_SYSERR to close it (signal serious error)
5344  */
5345 static int
5346 handle_mesh_path_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
5347                          const struct GNUNET_MessageHeader *message,
5348                          const struct GNUNET_ATS_Information *atsi,
5349                          unsigned int atsi_count)
5350 {
5351   struct GNUNET_MESH_PathBroken *msg;
5352   struct MeshTunnel *t;
5353
5354   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5355               "Received a PATH BROKEN msg from %s\n", GNUNET_i2s (peer));
5356   msg = (struct GNUNET_MESH_PathBroken *) message;
5357   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
5358               GNUNET_i2s (&msg->peer1));
5359   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
5360               GNUNET_i2s (&msg->peer2));
5361   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5362   if (NULL == t)
5363   {
5364     GNUNET_break_op (0);
5365     return GNUNET_OK;
5366   }
5367   tunnel_notify_connection_broken (t, GNUNET_PEER_search (&msg->peer1),
5368                                    GNUNET_PEER_search (&msg->peer2));
5369   return GNUNET_OK;
5370
5371 }
5372
5373
5374 /**
5375  * Core handler for tunnel destruction
5376  *
5377  * @param cls closure
5378  * @param message message
5379  * @param peer peer identity this notification is about
5380  * @param atsi performance data
5381  * @param atsi_count number of records in 'atsi'
5382  *
5383  * @return GNUNET_OK to keep the connection open,
5384  *         GNUNET_SYSERR to close it (signal serious error)
5385  */
5386 static int
5387 handle_mesh_tunnel_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
5388                             const struct GNUNET_MessageHeader *message,
5389                             const struct GNUNET_ATS_Information *atsi,
5390                             unsigned int atsi_count)
5391 {
5392   struct GNUNET_MESH_TunnelDestroy *msg;
5393   struct MeshTunnel *t;
5394   GNUNET_PEER_Id parent;
5395   GNUNET_PEER_Id pid;
5396
5397   msg = (struct GNUNET_MESH_TunnelDestroy *) message;
5398   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5399               "Got a TUNNEL DESTROY packet from %s\n",
5400               GNUNET_i2s (peer));
5401   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5402               "  for tunnel %s [%u]\n",
5403               GNUNET_i2s (&msg->oid), ntohl (msg->tid));
5404   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5405   /* Check signature */
5406   if (NULL == t)
5407   {
5408     /* Probably already got the message from another path,
5409      * destroyed the tunnel and retransmitted to children.
5410      * Safe to ignore.
5411      */
5412     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel",
5413                               1, GNUNET_NO);
5414     return GNUNET_OK;
5415   }
5416   parent = tree_get_predecessor (t->tree);
5417   pid = GNUNET_PEER_search (peer);
5418   if (pid != parent)
5419   {
5420     unsigned int nc;
5421
5422     tree_del_peer (t->tree, pid, &tunnel_child_removed, t);
5423     nc = tree_count_children (t->tree);
5424     if (nc > 0 || NULL != t->owner || t->nclients > 0)
5425     {
5426       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5427                   "still in use: %u cl, %u ch\n",
5428                   t->nclients, nc);
5429       return GNUNET_OK;
5430     }
5431   }
5432   if (t->local_tid_dest >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
5433   {
5434     /* Tunnel was incoming, notify clients */
5435     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "INCOMING TUNNEL %X %X\n",
5436                 t->local_tid, t->local_tid_dest);
5437     send_clients_tunnel_destroy (t);
5438   }
5439   tunnel_send_destroy (t, parent);
5440   t->destroy = GNUNET_YES;
5441   // TODO: add timeout to destroy the tunnel anyway
5442   return GNUNET_OK;
5443 }
5444
5445
5446 /**
5447  * Core handler for mesh network traffic going from the origin to a peer
5448  *
5449  * @param cls closure
5450  * @param peer peer identity this notification is about
5451  * @param message message
5452  * @param atsi performance data
5453  * @param atsi_count number of records in 'atsi'
5454  * @return GNUNET_OK to keep the connection open,
5455  *         GNUNET_SYSERR to close it (signal serious error)
5456  */
5457 static int
5458 handle_mesh_data_unicast (void *cls, const struct GNUNET_PeerIdentity *peer,
5459                           const struct GNUNET_MessageHeader *message,
5460                           const struct GNUNET_ATS_Information *atsi,
5461                           unsigned int atsi_count)
5462 {
5463   struct GNUNET_MESH_Unicast *msg;
5464   struct GNUNET_PeerIdentity *neighbor;
5465   struct MeshTunnelChildInfo *cinfo;
5466   struct MeshTunnel *t;
5467   GNUNET_PEER_Id dest_id;
5468   uint32_t pid;
5469   uint32_t ttl;
5470   size_t size;
5471
5472   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a unicast packet from %s\n",
5473               GNUNET_i2s (peer));
5474   /* Check size */
5475   size = ntohs (message->size);
5476   if (size <
5477       sizeof (struct GNUNET_MESH_Unicast) +
5478       sizeof (struct GNUNET_MessageHeader))
5479   {
5480     GNUNET_break (0);
5481     return GNUNET_OK;
5482   }
5483   msg = (struct GNUNET_MESH_Unicast *) message;
5484   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %s\n",
5485               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
5486   /* Check tunnel */
5487   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5488   if (NULL == t)
5489   {
5490     /* TODO notify back: we don't know this tunnel */
5491     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
5492     GNUNET_break_op (0);
5493     return GNUNET_OK;
5494   }
5495   pid = ntohl (msg->pid);
5496   if (t->fwd_pid == pid)
5497   {
5498     GNUNET_STATISTICS_update (stats, "# duplicate PID drops", 1, GNUNET_NO);
5499     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5500                 " Already seen pid %u, DROPPING!\n", pid);
5501     return GNUNET_OK;
5502   }
5503   else
5504   {
5505     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5506                 " pid %u not seen yet, forwarding\n", pid);
5507   }
5508
5509   t->skip += (pid - t->fwd_pid) - 1;
5510   t->fwd_pid = pid;
5511
5512   if (GMC_is_pid_bigger (pid, t->last_fwd_ack))
5513   {
5514     GNUNET_STATISTICS_update (stats, "# unsolicited unicast", 1, GNUNET_NO);
5515     GNUNET_break_op (0);
5516     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5517                 "Received PID %u, ACK %u\n",
5518                 pid, t->last_fwd_ack);
5519     return GNUNET_OK;
5520   }
5521
5522   tunnel_reset_timeout (t);
5523   dest_id = GNUNET_PEER_search (&msg->destination);
5524   if (dest_id == myid)
5525   {
5526     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5527                 "  it's for us! sending to clients...\n");
5528     GNUNET_STATISTICS_update (stats, "# unicast received", 1, GNUNET_NO);
5529     send_subscribed_clients (message, &msg[1].header, t);
5530     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_UNICAST);
5531     return GNUNET_OK;
5532   }
5533   ttl = ntohl (msg->ttl);
5534   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ttl);
5535   if (ttl == 0)
5536   {
5537     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
5538     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
5539     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5540     return GNUNET_OK;
5541   }
5542   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5543               "  not for us, retransmitting...\n");
5544
5545   neighbor = tree_get_first_hop (t->tree, dest_id);
5546   cinfo = tunnel_get_neighbor_fc (t, neighbor);
5547   cinfo->fwd_pid = pid;
5548   GNUNET_CONTAINER_multihashmap_iterate (t->children_fc,
5549                                          &tunnel_add_skip,
5550                                          &neighbor);
5551   if (GNUNET_YES == t->nobuffer &&
5552       GNUNET_YES == GMC_is_pid_bigger (pid, cinfo->fwd_ack))
5553   {
5554     GNUNET_STATISTICS_update (stats, "# unsolicited unicast", 1, GNUNET_NO);
5555     GNUNET_log (GNUNET_ERROR_TYPE_INFO, "  %u > %u\n", pid, cinfo->fwd_ack);
5556     GNUNET_break_op (0);
5557     return GNUNET_OK;
5558   }
5559   send_prebuilt_message (message, neighbor, t);
5560   GNUNET_STATISTICS_update (stats, "# unicast forwarded", 1, GNUNET_NO);
5561   return GNUNET_OK;
5562 }
5563
5564
5565 /**
5566  * Core handler for mesh network traffic going from the origin to all peers
5567  *
5568  * @param cls closure
5569  * @param message message
5570  * @param peer peer identity this notification is about
5571  * @param atsi performance data
5572  * @param atsi_count number of records in 'atsi'
5573  * @return GNUNET_OK to keep the connection open,
5574  *         GNUNET_SYSERR to close it (signal serious error)
5575  *
5576  * TODO: Check who we got this from, to validate route.
5577  */
5578 static int
5579 handle_mesh_data_multicast (void *cls, const struct GNUNET_PeerIdentity *peer,
5580                             const struct GNUNET_MessageHeader *message,
5581                             const struct GNUNET_ATS_Information *atsi,
5582                             unsigned int atsi_count)
5583 {
5584   struct GNUNET_MESH_Multicast *msg;
5585   struct MeshTunnel *t;
5586   size_t size;
5587   uint32_t pid;
5588
5589   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a multicast packet from %s\n",
5590               GNUNET_i2s (peer));
5591   size = ntohs (message->size);
5592   if (sizeof (struct GNUNET_MESH_Multicast) +
5593       sizeof (struct GNUNET_MessageHeader) > size)
5594   {
5595     GNUNET_break_op (0);
5596     return GNUNET_OK;
5597   }
5598   msg = (struct GNUNET_MESH_Multicast *) message;
5599   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5600
5601   if (NULL == t)
5602   {
5603     /* TODO notify that we dont know that tunnel */
5604     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
5605     GNUNET_break_op (0);
5606     return GNUNET_OK;
5607   }
5608   pid = ntohl (msg->pid);
5609   if (t->fwd_pid == pid)
5610   {
5611     /* already seen this packet, drop */
5612     GNUNET_STATISTICS_update (stats, "# duplicate PID drops", 1, GNUNET_NO);
5613     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5614                 " Already seen pid %u, DROPPING!\n", pid);
5615     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5616     return GNUNET_OK;
5617   }
5618   else
5619   {
5620     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5621                 " pid %u not seen yet, forwarding\n", pid);
5622   }
5623   t->skip += (pid - t->fwd_pid) - 1;
5624   t->fwd_pid = pid;
5625   tunnel_reset_timeout (t);
5626
5627   /* Transmit to locally interested clients */
5628   if (NULL != t->peers &&
5629       GNUNET_CONTAINER_multihashmap_contains (t->peers, &my_full_id.hashPubKey))
5630   {
5631     GNUNET_STATISTICS_update (stats, "# multicast received", 1, GNUNET_NO);
5632     send_subscribed_clients (message, &msg[1].header, t);
5633     tunnel_send_fwd_ack(t, GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
5634   }
5635   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ntohl (msg->ttl));
5636   if (ntohl (msg->ttl) == 0)
5637   {
5638     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
5639     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
5640     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5641     return GNUNET_OK;
5642   }
5643   GNUNET_STATISTICS_update (stats, "# multicast forwarded", 1, GNUNET_NO);
5644   tunnel_send_multicast (t, message);
5645   return GNUNET_OK;
5646 }
5647
5648
5649 /**
5650  * Core handler for mesh network traffic toward the owner of a tunnel
5651  *
5652  * @param cls closure
5653  * @param message message
5654  * @param peer peer identity this notification is about
5655  * @param atsi performance data
5656  * @param atsi_count number of records in 'atsi'
5657  *
5658  * @return GNUNET_OK to keep the connection open,
5659  *         GNUNET_SYSERR to close it (signal serious error)
5660  */
5661 static int
5662 handle_mesh_data_to_orig (void *cls, const struct GNUNET_PeerIdentity *peer,
5663                           const struct GNUNET_MessageHeader *message,
5664                           const struct GNUNET_ATS_Information *atsi,
5665                           unsigned int atsi_count)
5666 {
5667   struct GNUNET_MESH_ToOrigin *msg;
5668   struct GNUNET_PeerIdentity id;
5669   struct MeshPeerInfo *peer_info;
5670   struct MeshTunnel *t;
5671   struct MeshTunnelChildInfo *cinfo;
5672   GNUNET_PEER_Id predecessor;
5673   size_t size;
5674   uint32_t pid;
5675
5676   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a ToOrigin packet from %s\n",
5677               GNUNET_i2s (peer));
5678   size = ntohs (message->size);
5679   if (size < sizeof (struct GNUNET_MESH_ToOrigin) +     /* Payload must be */
5680       sizeof (struct GNUNET_MessageHeader))     /* at least a header */
5681   {
5682     GNUNET_break_op (0);
5683     return GNUNET_OK;
5684   }
5685   msg = (struct GNUNET_MESH_ToOrigin *) message;
5686   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %s\n",
5687               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
5688   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5689   pid = ntohl (msg->pid);
5690
5691   if (NULL == t)
5692   {
5693     /* TODO notify that we dont know this tunnel (whom)? */
5694     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
5695     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5696                 "Received to_origin with PID %u on unknown tunnel %s [%u]\n",
5697                 pid, GNUNET_i2s (&msg->oid), ntohl (msg->tid));
5698     return GNUNET_OK;
5699   }
5700
5701   cinfo = tunnel_get_neighbor_fc(t, peer);
5702   if (NULL == cinfo)
5703   {
5704     GNUNET_break (0);
5705     return GNUNET_OK;
5706   }
5707
5708   if (cinfo->bck_pid == pid)
5709   {
5710     /* already seen this packet, drop */
5711     GNUNET_STATISTICS_update (stats, "# duplicate PID drops BCK", 1, GNUNET_NO);
5712     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5713                 " Already seen pid %u, DROPPING!\n", pid);
5714     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5715     return GNUNET_OK;
5716   }
5717
5718   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5719               " pid %u not seen yet, forwarding\n", pid);
5720   cinfo->bck_pid = pid;
5721
5722   if (NULL != t->owner)
5723   {
5724     char cbuf[size];
5725     struct GNUNET_MESH_ToOrigin *copy;
5726
5727     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5728                 "  it's for us! sending to clients...\n");
5729     /* TODO signature verification */
5730     memcpy (cbuf, message, size);
5731     copy = (struct GNUNET_MESH_ToOrigin *) cbuf;
5732     copy->tid = htonl (t->local_tid);
5733     t->bck_pid++;
5734     copy->pid = htonl (t->bck_pid);
5735     GNUNET_STATISTICS_update (stats, "# to origin received", 1, GNUNET_NO);
5736     GNUNET_SERVER_notification_context_unicast (nc, t->owner->handle,
5737                                                 &copy->header, GNUNET_NO);
5738     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
5739     return GNUNET_OK;
5740   }
5741   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5742               "  not for us, retransmitting...\n");
5743
5744   peer_info = peer_info_get (&msg->oid);
5745   if (NULL == peer_info)
5746   {
5747     /* unknown origin of tunnel */
5748     GNUNET_break (0);
5749     return GNUNET_OK;
5750   }
5751   predecessor = tree_get_predecessor (t->tree);
5752   if (0 == predecessor)
5753   {
5754     if (GNUNET_YES == t->destroy)
5755     {
5756       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5757                   "to orig received on a dying tunnel %s [%X]\n",
5758                   GNUNET_i2s (&msg->oid), ntohl(msg->tid));
5759       return GNUNET_OK;
5760     }
5761     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
5762                 "unknown to origin at %s\n",
5763                 GNUNET_i2s (&my_full_id));
5764     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
5765                 "from peer %s\n",
5766                 GNUNET_i2s (peer));
5767     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
5768                 "for tunnel %s [%X]\n",
5769                 GNUNET_i2s (&msg->oid), ntohl(msg->tid));
5770     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
5771                 "current tree:\n");
5772     tree_debug (t->tree);
5773     return GNUNET_OK;
5774   }
5775   GNUNET_PEER_resolve (predecessor, &id);
5776   send_prebuilt_message (message, &id, t);
5777   GNUNET_STATISTICS_update (stats, "# to origin forwarded", 1, GNUNET_NO);
5778
5779   return GNUNET_OK;
5780 }
5781
5782
5783 /**
5784  * Core handler for mesh network traffic point-to-point acks.
5785  *
5786  * @param cls closure
5787  * @param message message
5788  * @param peer peer identity this notification is about
5789  * @param atsi performance data
5790  * @param atsi_count number of records in 'atsi'
5791  *
5792  * @return GNUNET_OK to keep the connection open,
5793  *         GNUNET_SYSERR to close it (signal serious error)
5794  */
5795 static int
5796 handle_mesh_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5797                  const struct GNUNET_MessageHeader *message,
5798                  const struct GNUNET_ATS_Information *atsi,
5799                  unsigned int atsi_count)
5800 {
5801   struct GNUNET_MESH_ACK *msg;
5802   struct MeshTunnel *t;
5803   uint32_t ack;
5804
5805   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK packet from %s!\n",
5806               GNUNET_i2s (peer));
5807   msg = (struct GNUNET_MESH_ACK *) message;
5808
5809   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5810
5811   if (NULL == t)
5812   {
5813     /* TODO notify that we dont know this tunnel (whom)? */
5814     GNUNET_STATISTICS_update (stats, "# ack on unknown tunnel", 1, GNUNET_NO);
5815     return GNUNET_OK;
5816   }
5817   ack = ntohl (msg->pid);
5818   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ACK %u\n", ack);
5819
5820   /* Is this a forward or backward ACK? */
5821   if (tree_get_predecessor(t->tree) != GNUNET_PEER_search(peer))
5822   {
5823     struct MeshTunnelChildInfo *cinfo;
5824
5825     debug_bck_ack++;
5826     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
5827     cinfo = tunnel_get_neighbor_fc (t, peer);
5828     cinfo->fwd_ack = ack;
5829     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5830     tunnel_unlock_fwd_queues (t);
5831     if (GNUNET_SCHEDULER_NO_TASK != cinfo->fc_poll)
5832     {
5833       GNUNET_SCHEDULER_cancel (cinfo->fc_poll);
5834       cinfo->fc_poll = GNUNET_SCHEDULER_NO_TASK;
5835       cinfo->fc_poll_time = GNUNET_TIME_UNIT_SECONDS;
5836     }
5837   }
5838   else
5839   {
5840     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
5841     t->bck_ack = ack;
5842     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5843     tunnel_unlock_bck_queue (t);
5844   }
5845   return GNUNET_OK;
5846 }
5847
5848
5849 /**
5850  * Core handler for mesh network traffic point-to-point ack polls.
5851  *
5852  * @param cls closure
5853  * @param message message
5854  * @param peer peer identity this notification is about
5855  * @param atsi performance data
5856  * @param atsi_count number of records in 'atsi'
5857  *
5858  * @return GNUNET_OK to keep the connection open,
5859  *         GNUNET_SYSERR to close it (signal serious error)
5860  */
5861 static int
5862 handle_mesh_poll (void *cls, const struct GNUNET_PeerIdentity *peer,
5863                   const struct GNUNET_MessageHeader *message,
5864                   const struct GNUNET_ATS_Information *atsi,
5865                   unsigned int atsi_count)
5866 {
5867   struct GNUNET_MESH_Poll *msg;
5868   struct MeshTunnel *t;
5869
5870   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an POLL packet from %s!\n",
5871               GNUNET_i2s (peer));
5872
5873   msg = (struct GNUNET_MESH_Poll *) message;
5874
5875   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5876
5877   if (NULL == t)
5878   {
5879     /* TODO notify that we dont know this tunnel (whom)? */
5880     GNUNET_STATISTICS_update (stats, "# poll on unknown tunnel", 1, GNUNET_NO);
5881     GNUNET_break_op (0);
5882     return GNUNET_OK;
5883   }
5884
5885   /* Is this a forward or backward ACK? */
5886   if (tree_get_predecessor(t->tree) != GNUNET_PEER_search(peer))
5887   {
5888     struct MeshTunnelChildInfo *cinfo;
5889
5890     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  from FWD\n");
5891     cinfo = tunnel_get_neighbor_fc (t, peer);
5892     cinfo->bck_ack = cinfo->fwd_pid; // mark as ready to send
5893     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_POLL);
5894   }
5895   else
5896   {
5897     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  from BCK\n");
5898     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_POLL);
5899   }
5900
5901   return GNUNET_OK;
5902 }
5903
5904 /**
5905  * Core handler for path ACKs
5906  *
5907  * @param cls closure
5908  * @param message message
5909  * @param peer peer identity this notification is about
5910  * @param atsi performance data
5911  * @param atsi_count number of records in 'atsi'
5912  *
5913  * @return GNUNET_OK to keep the connection open,
5914  *         GNUNET_SYSERR to close it (signal serious error)
5915  */
5916 static int
5917 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5918                       const struct GNUNET_MessageHeader *message,
5919                       const struct GNUNET_ATS_Information *atsi,
5920                       unsigned int atsi_count)
5921 {
5922   struct GNUNET_MESH_PathACK *msg;
5923   struct GNUNET_PeerIdentity id;
5924   struct MeshPeerInfo *peer_info;
5925   struct MeshPeerPath *p;
5926   struct MeshTunnel *t;
5927
5928   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a path ACK msg [%s]\n",
5929               GNUNET_i2s (&my_full_id));
5930   msg = (struct GNUNET_MESH_PathACK *) message;
5931   t = tunnel_get (&msg->oid, ntohl(msg->tid));
5932   if (NULL == t)
5933   {
5934     /* TODO notify that we don't know the tunnel */
5935     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel", 1, GNUNET_NO);
5936     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  don't know the tunnel %s [%X]!\n",
5937                 GNUNET_i2s (&msg->oid), ntohl(msg->tid));
5938     return GNUNET_OK;
5939   }
5940   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %s [%X]\n",
5941               GNUNET_i2s (&msg->oid), ntohl(msg->tid));
5942
5943   peer_info = peer_info_get (&msg->peer_id);
5944   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by peer %s\n",
5945               GNUNET_i2s (&msg->peer_id));
5946   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  via peer %s\n",
5947               GNUNET_i2s (peer));
5948
5949   if (NULL != t->regex_search && t->regex_search->peer == peer_info->id)
5950   {
5951     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5952                 "connect_by_string completed, stopping search\n");
5953     regex_cancel_search (t->regex_search);
5954     t->regex_search = NULL;
5955   }
5956
5957   /* Add paths to peers? */
5958   p = tree_get_path_to_peer (t->tree, peer_info->id);
5959   if (NULL != p)
5960   {
5961     path_add_to_peers (p, GNUNET_YES);
5962     path_destroy (p);
5963   }
5964   else
5965   {
5966     GNUNET_break (0);
5967   }
5968
5969   /* Message for us? */
5970   if (0 == memcmp (&msg->oid, &my_full_id, sizeof (struct GNUNET_PeerIdentity)))
5971   {
5972     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
5973     if (NULL == t->owner)
5974     {
5975       GNUNET_break_op (0);
5976       return GNUNET_OK;
5977     }
5978     if (NULL != t->dht_get_type)
5979     {
5980       GNUNET_DHT_get_stop (t->dht_get_type);
5981       t->dht_get_type = NULL;
5982     }
5983     if (tree_get_status (t->tree, peer_info->id) != MESH_PEER_READY)
5984     {
5985       tree_set_status (t->tree, peer_info->id, MESH_PEER_READY);
5986       send_client_peer_connected (t, peer_info->id);
5987     }
5988     if (NULL != peer_info->dhtget)
5989     {
5990       GNUNET_DHT_get_stop (peer_info->dhtget);
5991       peer_info->dhtget = NULL;
5992     }
5993     return GNUNET_OK;
5994   }
5995
5996   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5997               "  not for us, retransmitting...\n");
5998   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
5999   peer_info = peer_info_get (&msg->oid);
6000   send_prebuilt_message (message, &id, t);
6001   return GNUNET_OK;
6002 }
6003
6004
6005 /**
6006  * Core handler for mesh keepalives.
6007  *
6008  * @param cls closure
6009  * @param message message
6010  * @param peer peer identity this notification is about
6011  * @param atsi performance data
6012  * @param atsi_count number of records in 'atsi'
6013  * @return GNUNET_OK to keep the connection open,
6014  *         GNUNET_SYSERR to close it (signal serious error)
6015  *
6016  * TODO: Check who we got this from, to validate route.
6017  */
6018 static int
6019 handle_mesh_keepalive (void *cls, const struct GNUNET_PeerIdentity *peer,
6020                        const struct GNUNET_MessageHeader *message,
6021                        const struct GNUNET_ATS_Information *atsi,
6022                        unsigned int atsi_count)
6023 {
6024   struct GNUNET_MESH_TunnelKeepAlive *msg;
6025   struct MeshTunnel *t;
6026
6027   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a keepalive packet from %s\n",
6028               GNUNET_i2s (peer));
6029
6030   msg = (struct GNUNET_MESH_TunnelKeepAlive *) message;
6031   t = tunnel_get (&msg->oid, ntohl (msg->tid));
6032
6033   if (NULL == t)
6034   {
6035     /* TODO notify that we dont know that tunnel */
6036     GNUNET_STATISTICS_update (stats, "# keepalive on unknown tunnel", 1,
6037                               GNUNET_NO);
6038     return GNUNET_OK;
6039   }
6040
6041   tunnel_reset_timeout (t);
6042
6043   GNUNET_STATISTICS_update (stats, "# keepalives forwarded", 1, GNUNET_NO);
6044   tunnel_send_multicast (t, message);
6045   return GNUNET_OK;
6046   }
6047
6048
6049
6050 /**
6051  * Functions to handle messages from core
6052  */
6053 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
6054   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
6055   {&handle_mesh_path_destroy, GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY, 0},
6056   {&handle_mesh_path_broken, GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN,
6057    sizeof (struct GNUNET_MESH_PathBroken)},
6058   {&handle_mesh_tunnel_destroy, GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY,
6059    sizeof (struct GNUNET_MESH_TunnelDestroy)},
6060   {&handle_mesh_data_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
6061   {&handle_mesh_data_multicast, GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
6062   {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE,
6063     sizeof (struct GNUNET_MESH_TunnelKeepAlive)},
6064   {&handle_mesh_data_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
6065   {&handle_mesh_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
6066     sizeof (struct GNUNET_MESH_ACK)},
6067   {&handle_mesh_poll, GNUNET_MESSAGE_TYPE_MESH_POLL,
6068     sizeof (struct GNUNET_MESH_Poll)},
6069   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
6070    sizeof (struct GNUNET_MESH_PathACK)},
6071   {NULL, 0, 0}
6072 };
6073
6074
6075
6076 /******************************************************************************/
6077 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
6078 /******************************************************************************/
6079
6080 /**
6081  * deregister_app: iterator for removing each application registered by a client
6082  *
6083  * @param cls closure
6084  * @param key the hash of the application id (used to access the hashmap)
6085  * @param value the value stored at the key (client)
6086  *
6087  * @return GNUNET_OK on success
6088  */
6089 static int
6090 deregister_app (void *cls, const struct GNUNET_HashCode * key, void *value)
6091 {
6092   struct MeshClient *c = cls;
6093
6094   GNUNET_break (GNUNET_YES ==
6095                 GNUNET_CONTAINER_multihashmap_remove (applications, key, c));
6096   return GNUNET_OK;
6097 }
6098
6099 #if LATER
6100 /**
6101  * notify_client_connection_failure: notify a client that the connection to the
6102  * requested remote peer is not possible (for instance, no route found)
6103  * Function called when the socket is ready to queue more data. "buf" will be
6104  * NULL and "size" zero if the socket was closed for writing in the meantime.
6105  *
6106  * @param cls closure
6107  * @param size number of bytes available in buf
6108  * @param buf where the callee should write the message
6109  * @return number of bytes written to buf
6110  */
6111 static size_t
6112 notify_client_connection_failure (void *cls, size_t size, void *buf)
6113 {
6114   int size_needed;
6115   struct MeshPeerInfo *peer_info;
6116   struct GNUNET_MESH_PeerControl *msg;
6117   struct GNUNET_PeerIdentity id;
6118
6119   if (0 == size && NULL == buf)
6120   {
6121     // TODO retry? cancel?
6122     return 0;
6123   }
6124
6125   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
6126   peer_info = (struct MeshPeerInfo *) cls;
6127   msg = (struct GNUNET_MESH_PeerControl *) buf;
6128   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
6129   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
6130 //     msg->tunnel_id = htonl(peer_info->t->tid);
6131   GNUNET_PEER_resolve (peer_info->id, &id);
6132   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
6133
6134   return size_needed;
6135 }
6136 #endif
6137
6138
6139 /**
6140  * Send keepalive packets for a peer
6141  *
6142  * @param cls Closure (tunnel for which to send the keepalive).
6143  * @param tc Notification context.
6144  */
6145 static void
6146 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
6147 {
6148   struct MeshTunnel *t = cls;
6149   struct GNUNET_MESH_TunnelKeepAlive *msg;
6150   size_t size = sizeof (struct GNUNET_MESH_TunnelKeepAlive);
6151   char cbuf[size];
6152
6153   t->path_refresh_task = GNUNET_SCHEDULER_NO_TASK;
6154   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
6155   {
6156     return;
6157   }
6158
6159   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6160               "sending keepalive for tunnel %d\n", t->id.tid);
6161
6162   msg = (struct GNUNET_MESH_TunnelKeepAlive *) cbuf;
6163   msg->header.size = htons (size);
6164   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE);
6165   msg->oid = my_full_id;
6166   msg->tid = htonl (t->id.tid);
6167   tunnel_send_multicast (t, &msg->header);
6168
6169   t->path_refresh_task =
6170       GNUNET_SCHEDULER_add_delayed (refresh_path_time, &path_refresh, t);
6171   tunnel_reset_timeout(t);
6172 }
6173
6174
6175 /**
6176  * Function to process paths received for a new peer addition. The recorded
6177  * paths form the initial tunnel, which can be optimized later.
6178  * Called on each result obtained for the DHT search.
6179  *
6180  * @param cls closure
6181  * @param exp when will this value expire
6182  * @param key key of the result
6183  * @param get_path path of the get request
6184  * @param get_path_length lenght of get_path
6185  * @param put_path path of the put request
6186  * @param put_path_length length of the put_path
6187  * @param type type of the result
6188  * @param size number of bytes in data
6189  * @param data pointer to the result data
6190  *
6191  * TODO: re-issue the request after certain time? cancel after X results?
6192  */
6193 static void
6194 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
6195                     const struct GNUNET_HashCode * key,
6196                     const struct GNUNET_PeerIdentity *get_path,
6197                     unsigned int get_path_length,
6198                     const struct GNUNET_PeerIdentity *put_path,
6199                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
6200                     size_t size, const void *data)
6201 {
6202   struct MeshPathInfo *path_info = cls;
6203   struct MeshPeerPath *p;
6204   struct GNUNET_PeerIdentity pi;
6205   int i;
6206
6207   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
6208   GNUNET_PEER_resolve (path_info->peer->id, &pi);
6209   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", GNUNET_i2s (&pi));
6210
6211   p = path_build_from_dht (get_path, get_path_length,
6212                            put_path, put_path_length);
6213   path_add_to_peers (p, GNUNET_NO);
6214   path_destroy (p);
6215   for (i = 0; i < path_info->peer->ntunnels; i++)
6216   {
6217     tunnel_add_peer (path_info->peer->tunnels[i], path_info->peer);
6218     peer_info_connect (path_info->peer, path_info->t);
6219   }
6220
6221   return;
6222 }
6223
6224
6225 /**
6226  * Function to process paths received for a new peer addition. The recorded
6227  * paths form the initial tunnel, which can be optimized later.
6228  * Called on each result obtained for the DHT search.
6229  *
6230  * @param cls closure
6231  * @param exp when will this value expire
6232  * @param key key of the result
6233  * @param get_path path of the get request
6234  * @param get_path_length lenght of get_path
6235  * @param put_path path of the put request
6236  * @param put_path_length length of the put_path
6237  * @param type type of the result
6238  * @param size number of bytes in data
6239  * @param data pointer to the result data
6240  */
6241 static void
6242 dht_get_type_handler (void *cls, struct GNUNET_TIME_Absolute exp,
6243                       const struct GNUNET_HashCode * key,
6244                       const struct GNUNET_PeerIdentity *get_path,
6245                       unsigned int get_path_length,
6246                       const struct GNUNET_PeerIdentity *put_path,
6247                       unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
6248                       size_t size, const void *data)
6249 {
6250   const struct PBlock *pb = data;
6251   const struct GNUNET_PeerIdentity *pi = &pb->id;
6252   struct MeshTunnel *t = cls;
6253   struct MeshPeerInfo *peer_info;
6254   struct MeshPeerPath *p;
6255
6256   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got type DHT result!\n");
6257   if (size != sizeof (struct PBlock))
6258   {
6259     GNUNET_break_op (0);
6260     return;
6261   }
6262   if (ntohl(pb->type) != t->type)
6263   {
6264     GNUNET_break_op (0);
6265     return;
6266   }
6267   GNUNET_assert (NULL != t->owner);
6268   peer_info = peer_info_get (pi);
6269   (void) GNUNET_CONTAINER_multihashmap_put (t->peers, &pi->hashPubKey,
6270                                             peer_info,
6271                                             GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
6272
6273   p = path_build_from_dht (get_path, get_path_length, put_path,
6274                            put_path_length);
6275   path_add_to_peers (p, GNUNET_NO);
6276   path_destroy(p);
6277   tunnel_add_peer (t, peer_info);
6278   peer_info_connect (peer_info, t);
6279 }
6280
6281
6282 /******************************************************************************/
6283 /*********************       MESH LOCAL HANDLES      **************************/
6284 /******************************************************************************/
6285
6286
6287 /**
6288  * Handler for client disconnection
6289  *
6290  * @param cls closure
6291  * @param client identification of the client; NULL
6292  *        for the last call when the server is destroyed
6293  */
6294 static void
6295 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
6296 {
6297   struct MeshClient *c;
6298   struct MeshClient *next;
6299   unsigned int i;
6300
6301   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected\n");
6302   if (client == NULL)
6303   {
6304     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (SERVER DOWN)\n");
6305     return;
6306   }
6307
6308   c = clients;
6309   while (NULL != c)
6310   {
6311     if (c->handle != client)
6312     {
6313       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ... searching\n");
6314       c = c->next;
6315       continue;
6316     }
6317     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u)\n",
6318                 c->id);
6319     GNUNET_SERVER_client_drop (c->handle);
6320     c->shutting_down = GNUNET_YES;
6321     GNUNET_assert (NULL != c->own_tunnels);
6322     GNUNET_assert (NULL != c->incoming_tunnels);
6323     GNUNET_CONTAINER_multihashmap_iterate (c->own_tunnels,
6324                                            &tunnel_destroy_iterator, c);
6325     GNUNET_CONTAINER_multihashmap_iterate (c->incoming_tunnels,
6326                                            &tunnel_destroy_iterator, c);
6327     GNUNET_CONTAINER_multihashmap_iterate (c->ignore_tunnels,
6328                                            &tunnel_destroy_iterator, c);
6329     GNUNET_CONTAINER_multihashmap_destroy (c->own_tunnels);
6330     GNUNET_CONTAINER_multihashmap_destroy (c->incoming_tunnels);
6331     GNUNET_CONTAINER_multihashmap_destroy (c->ignore_tunnels);
6332
6333     /* deregister clients applications */
6334     if (NULL != c->apps)
6335     {
6336       GNUNET_CONTAINER_multihashmap_iterate (c->apps, &deregister_app, c);
6337       GNUNET_CONTAINER_multihashmap_destroy (c->apps);
6338     }
6339     if (0 == GNUNET_CONTAINER_multihashmap_size (applications) &&
6340         GNUNET_SCHEDULER_NO_TASK != announce_applications_task)
6341     {
6342       GNUNET_SCHEDULER_cancel (announce_applications_task);
6343       announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
6344     }
6345     if (NULL != c->types)
6346       GNUNET_CONTAINER_multihashmap_destroy (c->types);
6347     for (i = 0; i < c->n_regex; i++)
6348     {
6349       GNUNET_free (c->regexes[i].regex);
6350       if (NULL != c->regexes[i].h)
6351         GNUNET_REGEX_announce_cancel (c->regexes[i].h);
6352     }
6353     GNUNET_free_non_null (c->regexes);
6354     if (GNUNET_SCHEDULER_NO_TASK != c->regex_announce_task)
6355       GNUNET_SCHEDULER_cancel (c->regex_announce_task);
6356     next = c->next;
6357     GNUNET_CONTAINER_DLL_remove (clients, clients_tail, c);
6358     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT FREE at %p\n", c);
6359     GNUNET_free (c);
6360     GNUNET_STATISTICS_update (stats, "# clients", -1, GNUNET_NO);
6361     c = next;
6362   }
6363   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   done!\n");
6364   return;
6365 }
6366
6367
6368 /**
6369  * Handler for new clients
6370  *
6371  * @param cls closure
6372  * @param client identification of the client
6373  * @param message the actual message, which includes messages the client wants
6374  */
6375 static void
6376 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
6377                          const struct GNUNET_MessageHeader *message)
6378 {
6379   struct GNUNET_MESH_ClientConnect *cc_msg;
6380   struct MeshClient *c;
6381   GNUNET_MESH_ApplicationType *a;
6382   unsigned int size;
6383   uint16_t ntypes;
6384   uint16_t *t;
6385   uint16_t napps;
6386   uint16_t i;
6387
6388   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected\n");
6389   /* Check data sanity */
6390   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
6391   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
6392   ntypes = ntohs (cc_msg->types);
6393   napps = ntohs (cc_msg->applications);
6394   if (size !=
6395       ntypes * sizeof (uint16_t) + napps * sizeof (GNUNET_MESH_ApplicationType))
6396   {
6397     GNUNET_break (0);
6398     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6399     return;
6400   }
6401
6402   /* Create new client structure */
6403   c = GNUNET_malloc (sizeof (struct MeshClient));
6404   c->id = next_client_id++;
6405   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT NEW %u\n", c->id);
6406   c->handle = client;
6407   GNUNET_SERVER_client_keep (client);
6408   a = (GNUNET_MESH_ApplicationType *) &cc_msg[1];
6409   if (napps > 0)
6410   {
6411     GNUNET_MESH_ApplicationType at;
6412     struct GNUNET_HashCode hc;
6413
6414     c->apps = GNUNET_CONTAINER_multihashmap_create (napps, GNUNET_NO);
6415     for (i = 0; i < napps; i++)
6416     {
6417       at = ntohl (a[i]);
6418       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  app type: %u\n", at);
6419       GNUNET_CRYPTO_hash (&at, sizeof (at), &hc);
6420       /* store in clients hashmap */
6421       GNUNET_CONTAINER_multihashmap_put (c->apps, &hc, (void *) (long) at,
6422                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6423       /* store in global hashmap, for announcements */
6424       GNUNET_CONTAINER_multihashmap_put (applications, &hc, c,
6425                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6426     }
6427     if (GNUNET_SCHEDULER_NO_TASK == announce_applications_task)
6428       announce_applications_task =
6429           GNUNET_SCHEDULER_add_now (&announce_applications, NULL);
6430
6431   }
6432   if (ntypes > 0)
6433   {
6434     uint16_t u16;
6435     struct GNUNET_HashCode hc;
6436
6437     t = (uint16_t *) & a[napps];
6438     c->types = GNUNET_CONTAINER_multihashmap_create (ntypes, GNUNET_NO);
6439     for (i = 0; i < ntypes; i++)
6440     {
6441       u16 = ntohs (t[i]);
6442       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  msg type: %u\n", u16);
6443       GNUNET_CRYPTO_hash (&u16, sizeof (u16), &hc);
6444
6445       /* store in clients hashmap */
6446       GNUNET_CONTAINER_multihashmap_put (c->types, &hc, c,
6447                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6448       /* store in global hashmap */
6449       GNUNET_CONTAINER_multihashmap_put (types, &hc, c,
6450                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6451     }
6452   }
6453   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6454               " client has %u+%u subscriptions\n", napps, ntypes);
6455
6456   GNUNET_CONTAINER_DLL_insert (clients, clients_tail, c);
6457   c->own_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6458   c->incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6459   c->ignore_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6460   GNUNET_SERVER_notification_context_add (nc, client);
6461   GNUNET_STATISTICS_update (stats, "# clients", 1, GNUNET_NO);
6462
6463   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6464   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
6465 }
6466
6467
6468 /**
6469  * Handler for clients announcing available services by a regular expression.
6470  *
6471  * @param cls closure
6472  * @param client identification of the client
6473  * @param message the actual message, which includes messages the client wants
6474  */
6475 static void
6476 handle_local_announce_regex (void *cls, struct GNUNET_SERVER_Client *client,
6477                              const struct GNUNET_MessageHeader *message)
6478 {
6479   const struct GNUNET_MESH_RegexAnnounce *msg;
6480   struct MeshRegexDescriptor rd;
6481   struct MeshClient *c;
6482   char *regex;
6483   size_t len;
6484   size_t offset;
6485
6486   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "announce regex started\n");
6487
6488   /* Sanity check for client registration */
6489   if (NULL == (c = client_get (client)))
6490   {
6491     GNUNET_break (0);
6492     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6493     return;
6494   }
6495   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6496
6497   msg = (const struct GNUNET_MESH_RegexAnnounce *) message;
6498
6499   len = ntohs (message->size) - sizeof(struct GNUNET_MESH_RegexAnnounce);
6500   if (NULL != c->partial_regex)
6501   {
6502     regex = c->partial_regex;
6503     offset = strlen (c->partial_regex);
6504     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6505                 "  continuation, already have %u bytes\n",
6506                 offset);
6507   }
6508   else
6509   {
6510     regex = NULL;
6511     offset = 0;
6512   }
6513
6514   regex = GNUNET_realloc (regex, offset + len + 1);
6515   memcpy (&regex[offset], &msg[1], len);
6516   regex[offset + len] = '\0';
6517   if (0 == ntohs (msg->last))
6518   {
6519     c->partial_regex = regex;
6520     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6521                 "  not ended, stored %u bytes for later\n",
6522                 len);
6523     GNUNET_SERVER_receive_done (client, GNUNET_OK);
6524     return;
6525   }
6526   rd.regex = regex;
6527   rd.compression = ntohs (msg->compression_characters);
6528   rd.h = NULL;
6529   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  length %u\n", len);
6530   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regex %s\n", regex);
6531   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  compr %u\n", ntohs (rd.compression));
6532   GNUNET_array_append (c->regexes, c->n_regex, rd);
6533   c->partial_regex = NULL;
6534   if (GNUNET_SCHEDULER_NO_TASK == c->regex_announce_task)
6535   {
6536     c->regex_announce_task = GNUNET_SCHEDULER_add_now (&regex_announce, c);
6537   }
6538   else
6539   {
6540     regex_put (&rd);
6541   }
6542   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6543   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "announce regex processed\n");
6544 }
6545
6546
6547 /**
6548  * Handler for requests of new tunnels
6549  *
6550  * @param cls closure
6551  * @param client identification of the client
6552  * @param message the actual message
6553  */
6554 static void
6555 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
6556                             const struct GNUNET_MessageHeader *message)
6557 {
6558   struct GNUNET_MESH_TunnelMessage *t_msg;
6559   struct MeshTunnel *t;
6560   struct MeshClient *c;
6561   MESH_TunnelNumber tid;
6562
6563   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel requested\n");
6564
6565   /* Sanity check for client registration */
6566   if (NULL == (c = client_get (client)))
6567   {
6568     GNUNET_break (0);
6569     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6570     return;
6571   }
6572   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6573
6574   /* Message sanity check */
6575   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
6576   {
6577     GNUNET_break (0);
6578     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6579     return;
6580   }
6581
6582   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6583   /* Sanity check for tunnel numbering */
6584   tid = ntohl (t_msg->tunnel_id);
6585   if (0 == (tid & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
6586   {
6587     GNUNET_break (0);
6588     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6589     return;
6590   }
6591   /* Sanity check for duplicate tunnel IDs */
6592   if (NULL != tunnel_get_by_local_id (c, tid))
6593   {
6594     GNUNET_break (0);
6595     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6596     return;
6597   }
6598
6599   while (NULL != tunnel_get_by_pi (myid, next_tid))
6600     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
6601   t = tunnel_new (myid, next_tid++, c, tid);
6602   if (NULL == t)
6603   {
6604     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Tunnel creation failed.\n");
6605     GNUNET_break (0);
6606     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6607     return;
6608   }
6609   next_tid = next_tid & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
6610   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED TUNNEL %s [%x] (%x)\n",
6611               GNUNET_i2s (&my_full_id), t->id.tid, t->local_tid);
6612   t->peers = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6613
6614   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel created\n");
6615   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6616   return;
6617 }
6618
6619
6620 /**
6621  * Handler for requests of deleting tunnels
6622  *
6623  * @param cls closure
6624  * @param client identification of the client
6625  * @param message the actual message
6626  */
6627 static void
6628 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
6629                              const struct GNUNET_MessageHeader *message)
6630 {
6631   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
6632   struct MeshClient *c;
6633   struct MeshTunnel *t;
6634   MESH_TunnelNumber tid;
6635
6636   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6637               "Got a DESTROY TUNNEL from client!\n");
6638
6639   /* Sanity check for client registration */
6640   if (NULL == (c = client_get (client)))
6641   {
6642     GNUNET_break (0);
6643     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6644     return;
6645   }
6646   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6647
6648   /* Message sanity check */
6649   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
6650   {
6651     GNUNET_break (0);
6652     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6653     return;
6654   }
6655
6656   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6657
6658   /* Retrieve tunnel */
6659   tid = ntohl (tunnel_msg->tunnel_id);
6660   t = tunnel_get_by_local_id(c, tid);
6661   if (NULL == t)
6662   {
6663     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
6664     GNUNET_break (0);
6665     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6666     return;
6667   }
6668   if (c != t->owner || tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
6669   {
6670     client_ignore_tunnel (c, t);
6671     tunnel_destroy_empty (t);
6672     GNUNET_SERVER_receive_done (client, GNUNET_OK);
6673     return;
6674   }
6675   send_client_tunnel_disconnect (t, c);
6676   client_delete_tunnel (c, t);
6677
6678   /* Don't try to ACK the client about the tunnel_destroy multicast packet */
6679   t->owner = NULL;
6680   tunnel_send_destroy (t, 0);
6681   t->destroy = GNUNET_YES;
6682   /* The tunnel will be destroyed when the last message is transmitted. */
6683   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6684   return;
6685 }
6686
6687
6688 /**
6689  * Handler for requests of seeting tunnel's speed.
6690  *
6691  * @param cls Closure (unused).
6692  * @param client Identification of the client.
6693  * @param message The actual message.
6694  */
6695 static void
6696 handle_local_tunnel_speed (void *cls, struct GNUNET_SERVER_Client *client,
6697                            const struct GNUNET_MessageHeader *message)
6698 {
6699   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
6700   struct MeshClient *c;
6701   struct MeshTunnel *t;
6702   MESH_TunnelNumber tid;
6703
6704   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6705               "Got a SPEED request from client!\n");
6706
6707   /* Sanity check for client registration */
6708   if (NULL == (c = client_get (client)))
6709   {
6710     GNUNET_break (0);
6711     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6712     return;
6713   }
6714
6715   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6716
6717   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6718
6719   /* Retrieve tunnel */
6720   tid = ntohl (tunnel_msg->tunnel_id);
6721   t = tunnel_get_by_local_id(c, tid);
6722   if (NULL == t)
6723   {
6724     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  tunnel %X not found\n", tid);
6725     GNUNET_break (0);
6726     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6727     return;
6728   }
6729
6730   switch (ntohs(message->type))
6731   {
6732       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MIN:
6733           t->speed_min = GNUNET_YES;
6734           break;
6735       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MAX:
6736           t->speed_min = GNUNET_NO;
6737           break;
6738       default:
6739           GNUNET_break (0);
6740   }
6741   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6742 }
6743
6744
6745 /**
6746  * Handler for requests of seeting tunnel's buffering policy.
6747  *
6748  * @param cls Closure (unused).
6749  * @param client Identification of the client.
6750  * @param message The actual message.
6751  */
6752 static void
6753 handle_local_tunnel_buffer (void *cls, struct GNUNET_SERVER_Client *client,
6754                             const struct GNUNET_MessageHeader *message)
6755 {
6756   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
6757   struct MeshClient *c;
6758   struct MeshTunnel *t;
6759   MESH_TunnelNumber tid;
6760
6761   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6762               "Got a BUFFER request from client!\n");
6763
6764   /* Sanity check for client registration */
6765   if (NULL == (c = client_get (client)))
6766   {
6767     GNUNET_break (0);
6768     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6769     return;
6770   }
6771   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6772
6773   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6774
6775   /* Retrieve tunnel */
6776   tid = ntohl (tunnel_msg->tunnel_id);
6777   t = tunnel_get_by_local_id(c, tid);
6778   if (NULL == t)
6779   {
6780     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
6781     GNUNET_break (0);
6782     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6783     return;
6784   }
6785
6786   switch (ntohs(message->type))
6787   {
6788       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER:
6789           t->nobuffer = GNUNET_NO;
6790           break;
6791       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER:
6792           t->nobuffer = GNUNET_YES;
6793           break;
6794       default:
6795           GNUNET_break (0);
6796   }
6797
6798   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6799 }
6800
6801
6802 /**
6803  * Handler for connection requests to new peers
6804  *
6805  * @param cls closure
6806  * @param client identification of the client
6807  * @param message the actual message (PeerControl)
6808  */
6809 static void
6810 handle_local_connect_add (void *cls, struct GNUNET_SERVER_Client *client,
6811                           const struct GNUNET_MessageHeader *message)
6812 {
6813   struct GNUNET_MESH_PeerControl *peer_msg;
6814   struct MeshPeerInfo *peer_info;
6815   struct MeshClient *c;
6816   struct MeshTunnel *t;
6817   MESH_TunnelNumber tid;
6818
6819   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got connection request\n");
6820   /* Sanity check for client registration */
6821   if (NULL == (c = client_get (client)))
6822   {
6823     GNUNET_break (0);
6824     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6825     return;
6826   }
6827   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6828
6829   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6830
6831   /* Sanity check for message size */
6832   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6833   {
6834     GNUNET_break (0);
6835     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6836     return;
6837   }
6838
6839   /* Tunnel exists? */
6840   tid = ntohl (peer_msg->tunnel_id);
6841   t = tunnel_get_by_local_id (c, tid);
6842   if (NULL == t)
6843   {
6844     GNUNET_break (0);
6845     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6846     return;
6847   }
6848
6849   /* Does client own tunnel? */
6850   if (t->owner->handle != client)
6851   {
6852     GNUNET_break (0);
6853     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6854     return;
6855   }
6856   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "     for %s\n",
6857               GNUNET_i2s (&peer_msg->peer));
6858   peer_info = peer_info_get (&peer_msg->peer);
6859
6860   tunnel_add_peer (t, peer_info);
6861   peer_info_connect (peer_info, t);
6862
6863   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6864   return;
6865 }
6866
6867
6868 /**
6869  * Handler for disconnection requests of peers in a tunnel
6870  *
6871  * @param cls closure
6872  * @param client identification of the client
6873  * @param message the actual message (PeerControl)
6874  */
6875 static void
6876 handle_local_connect_del (void *cls, struct GNUNET_SERVER_Client *client,
6877                           const struct GNUNET_MessageHeader *message)
6878 {
6879   struct GNUNET_MESH_PeerControl *peer_msg;
6880   struct MeshPeerInfo *peer_info;
6881   struct MeshClient *c;
6882   struct MeshTunnel *t;
6883   MESH_TunnelNumber tid;
6884
6885   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER DEL request\n");
6886   /* Sanity check for client registration */
6887   if (NULL == (c = client_get (client)))
6888   {
6889     GNUNET_break (0);
6890     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6891     return;
6892   }
6893   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6894
6895   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6896
6897   /* Sanity check for message size */
6898   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6899   {
6900     GNUNET_break (0);
6901     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6902     return;
6903   }
6904
6905   /* Tunnel exists? */
6906   tid = ntohl (peer_msg->tunnel_id);
6907   t = tunnel_get_by_local_id (c, tid);
6908   if (NULL == t)
6909   {
6910     GNUNET_break (0);
6911     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6912     return;
6913   }
6914   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
6915
6916   /* Does client own tunnel? */
6917   if (t->owner->handle != client)
6918   {
6919     GNUNET_break (0);
6920     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6921     return;
6922   }
6923
6924   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for peer %s\n",
6925               GNUNET_i2s (&peer_msg->peer));
6926   /* Is the peer in the tunnel? */
6927   peer_info =
6928       GNUNET_CONTAINER_multihashmap_get (t->peers, &peer_msg->peer.hashPubKey);
6929   if (NULL == peer_info)
6930   {
6931     GNUNET_break (0);
6932     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6933     return;
6934   }
6935
6936   /* Ok, delete peer from tunnel */
6937   GNUNET_CONTAINER_multihashmap_remove_all (t->peers,
6938                                             &peer_msg->peer.hashPubKey);
6939
6940   send_destroy_path (t, peer_info->id);
6941   tunnel_delete_peer (t, peer_info->id);
6942   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6943   return;
6944 }
6945
6946 /**
6947  * Handler for blacklist requests of peers in a tunnel
6948  *
6949  * @param cls closure
6950  * @param client identification of the client
6951  * @param message the actual message (PeerControl)
6952  * 
6953  * FIXME implement DHT block bloomfilter
6954  */
6955 static void
6956 handle_local_blacklist (void *cls, struct GNUNET_SERVER_Client *client,
6957                           const struct GNUNET_MessageHeader *message)
6958 {
6959   struct GNUNET_MESH_PeerControl *peer_msg;
6960   struct MeshClient *c;
6961   struct MeshTunnel *t;
6962   MESH_TunnelNumber tid;
6963
6964   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER BLACKLIST request\n");
6965   /* Sanity check for client registration */
6966   if (NULL == (c = client_get (client)))
6967   {
6968     GNUNET_break (0);
6969     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6970     return;
6971   }
6972   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6973
6974   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6975
6976   /* Sanity check for message size */
6977   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6978   {
6979     GNUNET_break (0);
6980     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6981     return;
6982   }
6983
6984   /* Tunnel exists? */
6985   tid = ntohl (peer_msg->tunnel_id);
6986   t = tunnel_get_by_local_id (c, tid);
6987   if (NULL == t)
6988   {
6989     GNUNET_break (0);
6990     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6991     return;
6992   }
6993   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
6994
6995   GNUNET_array_append(t->blacklisted, t->nblacklisted,
6996                       GNUNET_PEER_intern(&peer_msg->peer));
6997 }
6998
6999
7000 /**
7001  * Handler for unblacklist requests of peers in a tunnel
7002  *
7003  * @param cls closure
7004  * @param client identification of the client
7005  * @param message the actual message (PeerControl)
7006  */
7007 static void
7008 handle_local_unblacklist (void *cls, struct GNUNET_SERVER_Client *client,
7009                           const struct GNUNET_MessageHeader *message)
7010 {
7011   struct GNUNET_MESH_PeerControl *peer_msg;
7012   struct MeshClient *c;
7013   struct MeshTunnel *t;
7014   MESH_TunnelNumber tid;
7015   GNUNET_PEER_Id pid;
7016   unsigned int i;
7017
7018   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER UNBLACKLIST request\n");
7019   /* Sanity check for client registration */
7020   if (NULL == (c = client_get (client)))
7021   {
7022     GNUNET_break (0);
7023     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7024     return;
7025   }
7026   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7027
7028   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
7029
7030   /* Sanity check for message size */
7031   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
7032   {
7033     GNUNET_break (0);
7034     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7035     return;
7036   }
7037
7038   /* Tunnel exists? */
7039   tid = ntohl (peer_msg->tunnel_id);
7040   t = tunnel_get_by_local_id (c, tid);
7041   if (NULL == t)
7042   {
7043     GNUNET_break (0);
7044     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7045     return;
7046   }
7047   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
7048
7049   /* if peer is not known, complain */
7050   pid = GNUNET_PEER_search (&peer_msg->peer);
7051   if (0 == pid)
7052   {
7053     GNUNET_break (0);
7054     return;
7055   }
7056
7057   /* search and remove from list */
7058   for (i = 0; i < t->nblacklisted; i++)
7059   {
7060     if (t->blacklisted[i] == pid)
7061     {
7062       t->blacklisted[i] = t->blacklisted[t->nblacklisted - 1];
7063       GNUNET_array_grow (t->blacklisted, t->nblacklisted, t->nblacklisted - 1);
7064       return;
7065     }
7066   }
7067
7068   /* if peer hasn't been blacklisted, complain */
7069   GNUNET_break (0);
7070 }
7071
7072
7073 /**
7074  * Handler for connection requests to new peers by type
7075  *
7076  * @param cls closure
7077  * @param client identification of the client
7078  * @param message the actual message (ConnectPeerByType)
7079  */
7080 static void
7081 handle_local_connect_by_type (void *cls, struct GNUNET_SERVER_Client *client,
7082                               const struct GNUNET_MessageHeader *message)
7083 {
7084   struct GNUNET_MESH_ConnectPeerByType *connect_msg;
7085   struct MeshClient *c;
7086   struct MeshTunnel *t;
7087   struct GNUNET_HashCode hash;
7088   MESH_TunnelNumber tid;
7089
7090   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got connect by type request\n");
7091   /* Sanity check for client registration */
7092   if (NULL == (c = client_get (client)))
7093   {
7094     GNUNET_break (0);
7095     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7096     return;
7097   }
7098   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7099
7100   connect_msg = (struct GNUNET_MESH_ConnectPeerByType *) message;
7101
7102   /* Sanity check for message size */
7103   if (sizeof (struct GNUNET_MESH_ConnectPeerByType) !=
7104       ntohs (connect_msg->header.size))
7105   {
7106     GNUNET_break (0);
7107     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7108     return;
7109   }
7110
7111   /* Tunnel exists? */
7112   tid = ntohl (connect_msg->tunnel_id);
7113   t = tunnel_get_by_local_id (c, tid);
7114   if (NULL == t)
7115   {
7116     GNUNET_break (0);
7117     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7118     return;
7119   }
7120
7121   /* Does client own tunnel? */
7122   if (t->owner->handle != client)
7123   {
7124     GNUNET_break (0);
7125     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7126     return;
7127   }
7128
7129   /* Do WE have the service? */
7130   t->type = ntohl (connect_msg->type);
7131   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " type requested: %u\n", t->type);
7132   GNUNET_CRYPTO_hash (&t->type, sizeof (GNUNET_MESH_ApplicationType), &hash);
7133   if (GNUNET_CONTAINER_multihashmap_contains (applications, &hash) ==
7134       GNUNET_YES)
7135   {
7136     /* Yes! Fast forward, add ourselves to the tunnel and send the
7137      * good news to the client, and alert the destination client of
7138      * an incoming tunnel.
7139      *
7140      * FIXME send a path create to self, avoid code duplication
7141      */
7142     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " available locally\n");
7143     GNUNET_CONTAINER_multihashmap_put (t->peers, &my_full_id.hashPubKey,
7144                                        peer_info_get (&my_full_id),
7145                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
7146
7147     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " notifying client\n");
7148     send_client_peer_connected (t, myid);
7149     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Done\n");
7150     GNUNET_SERVER_receive_done (client, GNUNET_OK);
7151
7152     t->local_tid_dest = next_local_tid++;
7153     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
7154     GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
7155                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
7156
7157     return;
7158   }
7159   /* Ok, lets find a peer offering the service */
7160   if (NULL != t->dht_get_type)
7161   {
7162     GNUNET_DHT_get_stop (t->dht_get_type);
7163   }
7164   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " looking in DHT for %s\n",
7165               GNUNET_h2s (&hash));
7166   t->dht_get_type =
7167       GNUNET_DHT_get_start (dht_handle, 
7168                             GNUNET_BLOCK_TYPE_MESH_PEER_BY_TYPE,
7169                             &hash,
7170                             dht_replication_level,
7171                             GNUNET_DHT_RO_RECORD_ROUTE |
7172                             GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
7173                             NULL, 0,
7174                             &dht_get_type_handler, t);
7175
7176   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7177   return;
7178 }
7179
7180
7181 /**
7182  * Handler for connection requests to new peers by a string service description.
7183  *
7184  * @param cls closure
7185  * @param client identification of the client
7186  * @param message the actual message, which includes messages the client wants
7187  */
7188 static void
7189 handle_local_connect_by_string (void *cls, struct GNUNET_SERVER_Client *client,
7190                                 const struct GNUNET_MessageHeader *message)
7191 {
7192   struct GNUNET_MESH_ConnectPeerByString *msg;
7193   struct MeshRegexSearchInfo *info;
7194   struct MeshTunnel *t;
7195   struct MeshClient *c;
7196   MESH_TunnelNumber tid;
7197   const char *string;
7198   size_t size;
7199   size_t len;
7200
7201   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7202               "Connect by string started\n");
7203   msg = (struct GNUNET_MESH_ConnectPeerByString *) message;
7204   size = htons (message->size);
7205
7206   /* Sanity check for client registration */
7207   if (NULL == (c = client_get (client)))
7208   {
7209     GNUNET_break (0);
7210     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7211     return;
7212   }
7213   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7214
7215   /* Message size sanity check */
7216   if (sizeof(struct GNUNET_MESH_ConnectPeerByString) >= size)
7217   {
7218     GNUNET_break (0);
7219     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7220     return;
7221   }
7222
7223   /* Tunnel exists? */
7224   tid = ntohl (msg->tunnel_id);
7225   t = tunnel_get_by_local_id (c, tid);
7226   if (NULL == t)
7227   {
7228     GNUNET_break (0);
7229     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7230     return;
7231   }
7232
7233   /* Does client own tunnel? */
7234   if (t->owner->handle != client)
7235   {
7236     GNUNET_break (0);
7237     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7238     return;
7239   }
7240
7241   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7242               "  on tunnel %s [%u]\n",
7243               GNUNET_i2s(&my_full_id),
7244               t->id.tid);
7245
7246   /* Only one connect_by_string allowed at the same time! */
7247   /* FIXME: allow more, return handle at api level to cancel, document */
7248   if (NULL != t->regex_search)
7249   {
7250     GNUNET_break (0);
7251     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7252     return;
7253   }
7254
7255   /* Find string itself */
7256   len = size - sizeof(struct GNUNET_MESH_ConnectPeerByString);
7257   string = (const char *) &msg[1];
7258
7259   info = GNUNET_malloc (sizeof (struct MeshRegexSearchInfo));
7260   info->t = t;
7261   info->description = GNUNET_strndup (string, len);
7262   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   string: %s\n", info->description);
7263
7264   t->regex_search = info;
7265
7266   info->search_handle = GNUNET_REGEX_search (dht_handle,
7267                                              info->description,
7268                                              &regex_found_handler, info,
7269                                              stats);
7270
7271   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7272   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "connect by string processed\n");
7273 }
7274
7275
7276 /**
7277  * Handler for client traffic directed to one peer
7278  *
7279  * @param cls closure
7280  * @param client identification of the client
7281  * @param message the actual message
7282  */
7283 static void
7284 handle_local_unicast (void *cls, struct GNUNET_SERVER_Client *client,
7285                       const struct GNUNET_MessageHeader *message)
7286 {
7287   struct MeshClient *c;
7288   struct MeshTunnel *t;
7289   struct MeshPeerInfo *pi;
7290   struct GNUNET_MESH_Unicast *data_msg;
7291   MESH_TunnelNumber tid;
7292   size_t size;
7293
7294   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7295               "Got a unicast request from a client!\n");
7296
7297   /* Sanity check for client registration */
7298   if (NULL == (c = client_get (client)))
7299   {
7300     GNUNET_break (0);
7301     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7302     return;
7303   }
7304   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7305
7306   data_msg = (struct GNUNET_MESH_Unicast *) message;
7307
7308   /* Sanity check for message size */
7309   size = ntohs (message->size);
7310   if (sizeof (struct GNUNET_MESH_Unicast) +
7311       sizeof (struct GNUNET_MessageHeader) > size)
7312   {
7313     GNUNET_break (0);
7314     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7315     return;
7316   }
7317
7318   /* Tunnel exists? */
7319   tid = ntohl (data_msg->tid);
7320   t = tunnel_get_by_local_id (c, tid);
7321   if (NULL == t)
7322   {
7323     GNUNET_break (0);
7324     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7325     return;
7326   }
7327
7328   /*  Is it a local tunnel? Then, does client own the tunnel? */
7329   if (t->owner->handle != client)
7330   {
7331     GNUNET_break (0);
7332     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7333     return;
7334   }
7335
7336   pi = GNUNET_CONTAINER_multihashmap_get (t->peers,
7337                                           &data_msg->destination.hashPubKey);
7338   /* Is the selected peer in the tunnel? */
7339   if (NULL == pi)
7340   {
7341     GNUNET_break (0);
7342     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7343     return;
7344   }
7345
7346   /* PID should be as expected */
7347   if (ntohl (data_msg->pid) != t->fwd_pid + 1)
7348   {
7349     GNUNET_break (0);
7350     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7351               "Unicast PID, expected %u, got %u\n",
7352               t->fwd_pid + 1, ntohl (data_msg->pid));
7353     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7354     return;
7355   }
7356
7357   /* Ok, everything is correct, send the message
7358    * (pretend we got it from a mesh peer)
7359    */
7360   {
7361     /* Work around const limitation */
7362     char buf[ntohs (message->size)] GNUNET_ALIGN;
7363     struct GNUNET_MESH_Unicast *copy;
7364
7365     copy = (struct GNUNET_MESH_Unicast *) buf;
7366     memcpy (buf, data_msg, size);
7367     copy->oid = my_full_id;
7368     copy->tid = htonl (t->id.tid);
7369     copy->ttl = htonl (default_ttl);
7370     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7371                 "  calling generic handler...\n");
7372     handle_mesh_data_unicast (NULL, &my_full_id, &copy->header, NULL, 0);
7373   }
7374   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "receive done OK\n");
7375   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7376
7377   return;
7378 }
7379
7380
7381 /**
7382  * Handler for client traffic directed to the origin
7383  *
7384  * @param cls closure
7385  * @param client identification of the client
7386  * @param message the actual message
7387  */
7388 static void
7389 handle_local_to_origin (void *cls, struct GNUNET_SERVER_Client *client,
7390                         const struct GNUNET_MessageHeader *message)
7391 {
7392   struct GNUNET_MESH_ToOrigin *data_msg;
7393   struct MeshTunnelClientInfo *clinfo;
7394   struct MeshClient *c;
7395   struct MeshTunnel *t;
7396   MESH_TunnelNumber tid;
7397   size_t size;
7398
7399   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7400               "Got a ToOrigin request from a client!\n");
7401   /* Sanity check for client registration */
7402   if (NULL == (c = client_get (client)))
7403   {
7404     GNUNET_break (0);
7405     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7406     return;
7407   }
7408   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7409
7410   data_msg = (struct GNUNET_MESH_ToOrigin *) message;
7411
7412   /* Sanity check for message size */
7413   size = ntohs (message->size);
7414   if (sizeof (struct GNUNET_MESH_ToOrigin) +
7415       sizeof (struct GNUNET_MessageHeader) > size)
7416   {
7417     GNUNET_break (0);
7418     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7419     return;
7420   }
7421
7422   /* Tunnel exists? */
7423   tid = ntohl (data_msg->tid);
7424   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
7425   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
7426   {
7427     GNUNET_break (0);
7428     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7429     return;
7430   }
7431   t = tunnel_get_by_local_id (c, tid);
7432   if (NULL == t)
7433   {
7434     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
7435     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
7436     GNUNET_break (0);
7437     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7438     return;
7439   }
7440
7441   /*  It should be sent by someone who has this as incoming tunnel. */
7442   if (GNUNET_NO == client_knows_tunnel (c, t))
7443   {
7444     GNUNET_break (0);
7445     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7446     return;
7447   }
7448
7449   /* PID should be as expected */
7450   clinfo = tunnel_get_client_fc (t, c);
7451   if (ntohl (data_msg->pid) != clinfo->bck_pid + 1)
7452   {
7453     GNUNET_break (0);
7454     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7455                 "To Origin PID, expected %u, got %u\n",
7456                 clinfo->bck_pid + 1,
7457                 ntohl (data_msg->pid));
7458     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7459     return;
7460   }
7461   clinfo->bck_pid++;
7462
7463   /* Ok, everything is correct, send the message
7464    * (pretend we got it from a mesh peer)
7465    */
7466   {
7467     char buf[ntohs (message->size)] GNUNET_ALIGN;
7468     struct GNUNET_MESH_ToOrigin *copy;
7469
7470     /* Work around const limitation */
7471     copy = (struct GNUNET_MESH_ToOrigin *) buf;
7472     memcpy (buf, data_msg, size);
7473     GNUNET_PEER_resolve (t->id.oid, &copy->oid);
7474     copy->tid = htonl (t->id.tid);
7475     copy->ttl = htonl (default_ttl);
7476     copy->pid = htonl (t->bck_pid + 1);
7477
7478     copy->sender = my_full_id;
7479     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7480                 "  calling generic handler...\n");
7481     handle_mesh_data_to_orig (NULL, &my_full_id, &copy->header, NULL, 0);
7482   }
7483   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7484
7485   return;
7486 }
7487
7488
7489 /**
7490  * Handler for client traffic directed to all peers in a tunnel
7491  *
7492  * @param cls closure
7493  * @param client identification of the client
7494  * @param message the actual message
7495  */
7496 static void
7497 handle_local_multicast (void *cls, struct GNUNET_SERVER_Client *client,
7498                         const struct GNUNET_MessageHeader *message)
7499 {
7500   struct MeshClient *c;
7501   struct MeshTunnel *t;
7502   struct GNUNET_MESH_Multicast *data_msg;
7503   MESH_TunnelNumber tid;
7504
7505   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7506               "Got a multicast request from a client!\n");
7507
7508   /* Sanity check for client registration */
7509   if (NULL == (c = client_get (client)))
7510   {
7511     GNUNET_break (0);
7512     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7513     return;
7514   }
7515   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7516
7517   data_msg = (struct GNUNET_MESH_Multicast *) message;
7518
7519   /* Sanity check for message size */
7520   if (sizeof (struct GNUNET_MESH_Multicast) +
7521       sizeof (struct GNUNET_MessageHeader) > ntohs (data_msg->header.size))
7522   {
7523     GNUNET_break (0);
7524     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7525     return;
7526   }
7527
7528   /* Tunnel exists? */
7529   tid = ntohl (data_msg->tid);
7530   t = tunnel_get_by_local_id (c, tid);
7531   if (NULL == t)
7532   {
7533     GNUNET_break (0);
7534     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
7535     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
7536     GNUNET_break (0);
7537     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7538     return;
7539   }
7540
7541   /* Does client own tunnel? */
7542   if (t->owner->handle != client)
7543   {
7544     GNUNET_break (0);
7545     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7546     return;
7547   }
7548
7549   /* PID should be as expected */
7550   if (ntohl (data_msg->pid) != t->fwd_pid + 1)
7551   {
7552     GNUNET_break (0);
7553     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7554               "Multicast PID, expected %u, got %u\n",
7555               t->fwd_pid + 1, ntohl (data_msg->pid));
7556     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7557     return;
7558   }
7559
7560   {
7561     char buf[ntohs (message->size)] GNUNET_ALIGN;
7562     struct GNUNET_MESH_Multicast *copy;
7563
7564     copy = (struct GNUNET_MESH_Multicast *) buf;
7565     memcpy (buf, message, ntohs (message->size));
7566     copy->oid = my_full_id;
7567     copy->tid = htonl (t->id.tid);
7568     copy->ttl = htonl (default_ttl);
7569     GNUNET_assert (ntohl (copy->pid) == (t->fwd_pid + 1));
7570     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7571                 "  calling generic handler...\n");
7572     handle_mesh_data_multicast (client, &my_full_id, &copy->header, NULL, 0);
7573   }
7574
7575   GNUNET_SERVER_receive_done (t->owner->handle, GNUNET_OK);
7576   return;
7577 }
7578
7579
7580 /**
7581  * Handler for client's ACKs for payload traffic.
7582  *
7583  * @param cls Closure (unused).
7584  * @param client Identification of the client.
7585  * @param message The actual message.
7586  */
7587 static void
7588 handle_local_ack (void *cls, struct GNUNET_SERVER_Client *client,
7589                   const struct GNUNET_MessageHeader *message)
7590 {
7591   struct GNUNET_MESH_LocalAck *msg;
7592   struct MeshTunnel *t;
7593   struct MeshClient *c;
7594   MESH_TunnelNumber tid;
7595   uint32_t ack;
7596
7597   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a local ACK\n");
7598   /* Sanity check for client registration */
7599   if (NULL == (c = client_get (client)))
7600   {
7601     GNUNET_break (0);
7602     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7603     return;
7604   }
7605   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7606
7607   msg = (struct GNUNET_MESH_LocalAck *) message;
7608
7609   /* Tunnel exists? */
7610   tid = ntohl (msg->tunnel_id);
7611   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
7612   t = tunnel_get_by_local_id (c, tid);
7613   if (NULL == t)
7614   {
7615     GNUNET_break (0);
7616     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
7617     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
7618     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7619     return;
7620   }
7621
7622   ack = ntohl (msg->max_pid);
7623   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ack %u\n", ack);
7624
7625   /* Does client own tunnel? I.E: Is this an ACK for BCK traffic? */
7626   if (NULL != t->owner && t->owner->handle == client)
7627   {
7628     /* The client owns the tunnel, ACK is for data to_origin, send BCK ACK. */
7629     t->bck_ack = ack;
7630     tunnel_send_bck_ack(t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
7631   }
7632   else
7633   {
7634     /* The client doesn't own the tunnel, this ACK is for FWD traffic. */
7635     tunnel_set_client_fwd_ack (t, c, ack);
7636     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
7637   }
7638
7639   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7640
7641   return;
7642 }
7643
7644
7645 /**
7646  * Iterator over all peers to send a monitoring client info about a tunnel.
7647  *
7648  * @param cls Closure (message being built).
7649  * @param key Key (hashed tunnel ID, unused).
7650  * @param value Peer info.
7651  *
7652  * @return GNUNET_YES, to keep iterating.
7653  */
7654 static int
7655 monitor_peers_iterator (void *cls,
7656                         const struct GNUNET_HashCode * key,
7657                         void *value)
7658 {
7659   struct GNUNET_MESH_LocalMonitor *msg = cls;
7660   struct GNUNET_PeerIdentity *id;
7661   struct MeshPeerInfo *info = value;
7662
7663   id = (struct GNUNET_PeerIdentity *) &msg[1];
7664   GNUNET_PEER_resolve (info->id, &id[msg->npeers]);
7665   msg->npeers++;
7666
7667   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
7668               "*    sending info about peer %s [%u]\n",
7669               GNUNET_i2s (&id[msg->npeers - 1]), msg->npeers);
7670
7671   return GNUNET_YES;
7672 }
7673
7674
7675
7676 /**
7677  * Iterator over all tunnels to send a monitoring client info about each tunnel.
7678  *
7679  * @param cls Closure (client handle).
7680  * @param key Key (hashed tunnel ID, unused).
7681  * @param value Tunnel info.
7682  *
7683  * @return GNUNET_YES, to keep iterating.
7684  */
7685 static int
7686 monitor_all_tunnels_iterator (void *cls,
7687                               const struct GNUNET_HashCode * key,
7688                               void *value)
7689 {
7690   struct GNUNET_SERVER_Client *client = cls;
7691   struct MeshTunnel *t = value;
7692   struct GNUNET_MESH_LocalMonitor *msg;
7693   uint32_t npeers;
7694   
7695   npeers = GNUNET_CONTAINER_multihashmap_size (t->peers);
7696   msg = GNUNET_malloc (sizeof(struct GNUNET_MESH_LocalMonitor) +
7697   npeers * sizeof (struct GNUNET_PeerIdentity));
7698   GNUNET_PEER_resolve(t->id.oid, &msg->owner);
7699   msg->tunnel_id = htonl (t->id.tid);
7700   msg->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor) +
7701   npeers * sizeof (struct GNUNET_PeerIdentity));
7702   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS);
7703   msg->npeers = 0;
7704   (void) GNUNET_CONTAINER_multihashmap_iterate (t->peers,
7705                                                 monitor_peers_iterator,
7706                                                 msg);
7707   
7708   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
7709               "*  sending info about tunnel %s [%u] (%u peers)\n",
7710               GNUNET_i2s (&msg->owner), t->id.tid, npeers);
7711   
7712   if (msg->npeers != npeers)
7713   {
7714     GNUNET_break (0);
7715     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7716                 "Get tunnels fail: size %u - iter %u\n",
7717                 npeers, msg->npeers);
7718   }
7719   
7720     msg->npeers = htonl (npeers);
7721     GNUNET_SERVER_notification_context_unicast (nc, client,
7722                                                 &msg->header, GNUNET_NO);
7723     return GNUNET_YES;
7724 }
7725
7726
7727 /**
7728  * Handler for client's MONITOR request.
7729  *
7730  * @param cls Closure (unused).
7731  * @param client Identification of the client.
7732  * @param message The actual message.
7733  */
7734 static void
7735 handle_local_get_tunnels (void *cls, struct GNUNET_SERVER_Client *client,
7736                           const struct GNUNET_MessageHeader *message)
7737 {
7738   struct MeshClient *c;
7739
7740   /* Sanity check for client registration */
7741   if (NULL == (c = client_get (client)))
7742   {
7743     GNUNET_break (0);
7744     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7745     return;
7746   }
7747
7748   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
7749               "Received get tunnels request from client %u\n",
7750               c->id);
7751   GNUNET_CONTAINER_multihashmap_iterate (tunnels,
7752                                          monitor_all_tunnels_iterator,
7753                                          client);
7754   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
7755               "Get tunnels request from client %u completed\n",
7756               c->id);
7757   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7758 }
7759
7760
7761 /**
7762  * Data needed to build a Monitor_Tunnel message.
7763  */
7764 struct MeshMonitorTunnelContext
7765 {
7766   /**
7767    * Partial message, including peer count.
7768    */
7769   struct GNUNET_MESH_LocalMonitor *msg;
7770
7771   /**
7772    * Hashmap with positions: peer->position.
7773    */
7774   struct GNUNET_CONTAINER_MultiHashMap *lookup;
7775
7776   /**
7777    * Index of the parent of each peer in the message, realtive to the absolute
7778    * order in the array (can be in a previous message).
7779    */
7780   uint32_t parents[1024];
7781
7782   /**
7783    * Peers visited so far in the tree, aka position of the current peer.
7784    */
7785   unsigned int npeers;
7786
7787   /**
7788    * Client requesting the info.
7789    */
7790   struct MeshClient *c;
7791 };
7792
7793
7794 /**
7795  * Send a client a message about the structure of a tunnel.
7796  *
7797  * @param ctx Context of the tunnel iteration, with info regarding the state
7798  *            of the execution and the number of peers visited for this message.
7799  */
7800 static void
7801 send_client_tunnel_info (struct MeshMonitorTunnelContext *ctx)
7802 {
7803   struct GNUNET_MESH_LocalMonitor *resp = ctx->msg;
7804   struct GNUNET_PeerIdentity *pid;
7805   unsigned int *parent;
7806   size_t size;
7807
7808   size = sizeof (struct GNUNET_MESH_LocalMonitor);
7809   size += (sizeof (struct GNUNET_PeerIdentity) + sizeof (int)) * resp->npeers;
7810   resp->header.size = htons (size);
7811   pid = (struct GNUNET_PeerIdentity *) &resp[1];
7812   parent = (unsigned int *) &pid[resp->npeers];
7813   memcpy (parent, ctx->parents, sizeof(uint32_t) * resp->npeers);
7814   GNUNET_SERVER_notification_context_unicast (nc, ctx->c->handle,
7815                                               &resp->header, GNUNET_NO);
7816 }
7817
7818 /**
7819  * Iterator over a tunnel tree to build a message containing all peers
7820  * the in the tunnel, including relay nodes.
7821  *
7822  * @param cls Closure (pointer to pointer of message being built).
7823  * @param peer Short ID of a peer.
7824  * @param parent Short ID of the @c peer 's parent.
7825  */
7826 static void
7827 tunnel_tree_iterator (void *cls,
7828                       GNUNET_PEER_Id peer,
7829                       GNUNET_PEER_Id parent)
7830 {
7831   struct MeshMonitorTunnelContext *ctx = cls;
7832   struct GNUNET_MESH_LocalMonitor *msg;
7833   struct GNUNET_PeerIdentity *pid;
7834   struct GNUNET_PeerIdentity ppid;
7835
7836   msg = ctx->msg;
7837   pid = (struct GNUNET_PeerIdentity *) &msg[1];
7838   GNUNET_PEER_resolve (peer, &pid[msg->npeers]);
7839   GNUNET_CONTAINER_multihashmap_put (ctx->lookup,
7840                                      &pid[msg->npeers].hashPubKey,
7841                                      (void *) (long) ctx->npeers,
7842                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
7843   GNUNET_PEER_resolve (parent, &ppid);
7844   ctx->parents[msg->npeers] =
7845       htonl ((long) GNUNET_CONTAINER_multihashmap_get (ctx->lookup,
7846                                                        &ppid.hashPubKey));
7847
7848   ctx->npeers++;
7849   msg->npeers++;
7850
7851   if (sizeof (struct GNUNET_MESH_LocalMonitor) +
7852       (msg->npeers + 1) *
7853       (sizeof (struct GNUNET_PeerIdentity) + sizeof (uint32_t))
7854       > USHRT_MAX)
7855   {
7856     send_client_tunnel_info (ctx);
7857     msg->npeers = 0;
7858   }
7859 }
7860
7861
7862 /**
7863  * Handler for client's MONITOR_TUNNEL request.
7864  *
7865  * @param cls Closure (unused).
7866  * @param client Identification of the client.
7867  * @param message The actual message.
7868  */
7869 static void
7870 handle_local_show_tunnel (void *cls, struct GNUNET_SERVER_Client *client,
7871                           const struct GNUNET_MessageHeader *message)
7872 {
7873   const struct GNUNET_MESH_LocalMonitor *msg;
7874   struct GNUNET_MESH_LocalMonitor *resp;
7875   struct MeshMonitorTunnelContext ctx;
7876   struct MeshClient *c;
7877   struct MeshTunnel *t;
7878
7879   /* Sanity check for client registration */
7880   if (NULL == (c = client_get (client)))
7881   {
7882     GNUNET_break (0);
7883     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7884     return;
7885   }
7886
7887   msg = (struct GNUNET_MESH_LocalMonitor *) message;
7888   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
7889               "Received tunnel info request from client %u for tunnel %s[%X]\n",
7890               c->id,
7891               &msg->owner,
7892               ntohl (msg->tunnel_id));
7893   t = tunnel_get (&msg->owner, ntohl (msg->tunnel_id));
7894   if (NULL == t)
7895   {
7896     /* We don't know the tunnel */
7897     struct GNUNET_MESH_LocalMonitor warn;
7898
7899     warn = *msg;
7900     warn.npeers = htonl (UINT_MAX);
7901     GNUNET_SERVER_notification_context_unicast (nc, client,
7902                                                 &warn.header,
7903                                                 GNUNET_NO);
7904     GNUNET_SERVER_receive_done (client, GNUNET_OK);
7905     return;
7906   }
7907
7908   /* Initialize context */
7909   resp = GNUNET_malloc (USHRT_MAX); /* avoid realloc'ing on each step */
7910   *resp = *msg;
7911   resp->npeers = 0;
7912   ctx.msg = resp;
7913   ctx.lookup = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_YES);
7914   ctx.c = c;
7915
7916   /* Collect and send information */
7917   tree_iterate_all (t->tree, &tunnel_tree_iterator, &ctx);
7918   send_client_tunnel_info (&ctx);
7919
7920   /* Free context */
7921   GNUNET_CONTAINER_multihashmap_destroy (ctx.lookup);
7922   GNUNET_free (resp);
7923
7924   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
7925               "Monitor tunnel request from client %u completed\n",
7926               c->id);
7927   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7928 }
7929
7930
7931 /**
7932  * Functions to handle messages from clients
7933  */
7934 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
7935   {&handle_local_new_client, NULL,
7936    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
7937   {&handle_local_announce_regex, NULL,
7938    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ANNOUNCE_REGEX, 0},
7939   {&handle_local_tunnel_create, NULL,
7940    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
7941    sizeof (struct GNUNET_MESH_TunnelMessage)},
7942   {&handle_local_tunnel_destroy, NULL,
7943    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
7944    sizeof (struct GNUNET_MESH_TunnelMessage)},
7945   {&handle_local_tunnel_speed, NULL,
7946    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MIN,
7947    sizeof (struct GNUNET_MESH_TunnelMessage)},
7948   {&handle_local_tunnel_speed, NULL,
7949    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MAX,
7950    sizeof (struct GNUNET_MESH_TunnelMessage)},
7951   {&handle_local_tunnel_buffer, NULL,
7952    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER,
7953    sizeof (struct GNUNET_MESH_TunnelMessage)},
7954   {&handle_local_tunnel_buffer, NULL,
7955    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER,
7956    sizeof (struct GNUNET_MESH_TunnelMessage)},
7957   {&handle_local_connect_add, NULL,
7958    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD,
7959    sizeof (struct GNUNET_MESH_PeerControl)},
7960   {&handle_local_connect_del, NULL,
7961    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL,
7962    sizeof (struct GNUNET_MESH_PeerControl)},
7963   {&handle_local_blacklist, NULL,
7964    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_BLACKLIST,
7965    sizeof (struct GNUNET_MESH_PeerControl)},
7966   {&handle_local_unblacklist, NULL,
7967    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_UNBLACKLIST,
7968    sizeof (struct GNUNET_MESH_PeerControl)},
7969   {&handle_local_connect_by_type, NULL,
7970    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE,
7971    sizeof (struct GNUNET_MESH_ConnectPeerByType)},
7972   {&handle_local_connect_by_string, NULL,
7973    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_STRING, 0},
7974   {&handle_local_unicast, NULL,
7975    GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
7976   {&handle_local_to_origin, NULL,
7977    GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
7978   {&handle_local_multicast, NULL,
7979    GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
7980   {&handle_local_ack, NULL,
7981    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK,
7982    sizeof (struct GNUNET_MESH_LocalAck)},
7983   {&handle_local_get_tunnels, NULL,
7984    GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS,
7985    sizeof (struct GNUNET_MessageHeader)},
7986   {&handle_local_show_tunnel, NULL,
7987    GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNEL,
7988      sizeof (struct GNUNET_MESH_LocalMonitor)},
7989   {NULL, NULL, 0, 0}
7990 };
7991
7992
7993 /**
7994  * To be called on core init/fail.
7995  *
7996  * @param cls service closure
7997  * @param server handle to the server for this service
7998  * @param identity the public identity of this peer
7999  */
8000 static void
8001 core_init (void *cls, struct GNUNET_CORE_Handle *server,
8002            const struct GNUNET_PeerIdentity *identity)
8003 {
8004   static int i = 0;
8005   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
8006   core_handle = server;
8007   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)) ||
8008       NULL == server)
8009   {
8010     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
8011     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8012                 " core id %s\n",
8013                 GNUNET_i2s (identity));
8014     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8015                 " my id %s\n",
8016                 GNUNET_i2s (&my_full_id));
8017     GNUNET_SCHEDULER_shutdown (); // Try gracefully
8018     if (10 < i++)
8019       GNUNET_abort(); // Try harder
8020   }
8021   return;
8022 }
8023
8024
8025 /**
8026  * Method called whenever a given peer connects.
8027  *
8028  * @param cls closure
8029  * @param peer peer identity this notification is about
8030  * @param atsi performance data for the connection
8031  * @param atsi_count number of records in 'atsi'
8032  */
8033 static void
8034 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
8035               const struct GNUNET_ATS_Information *atsi,
8036               unsigned int atsi_count)
8037 {
8038   struct MeshPeerInfo *peer_info;
8039   struct MeshPeerPath *path;
8040
8041   DEBUG_CONN ("Peer connected\n");
8042   DEBUG_CONN ("     %s\n", GNUNET_i2s (&my_full_id));
8043   peer_info = peer_info_get (peer);
8044   if (myid == peer_info->id)
8045   {
8046     DEBUG_CONN ("     (self)\n");
8047     return;
8048   }
8049   else
8050   {
8051     DEBUG_CONN ("     %s\n", GNUNET_i2s (peer));
8052   }
8053   path = path_new (2);
8054   path->peers[0] = myid;
8055   path->peers[1] = peer_info->id;
8056   GNUNET_PEER_change_rc (myid, 1);
8057   GNUNET_PEER_change_rc (peer_info->id, 1);
8058   peer_info_add_path (peer_info, path, GNUNET_YES);
8059   GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
8060   return;
8061 }
8062
8063
8064 /**
8065  * Method called whenever a peer disconnects.
8066  *
8067  * @param cls closure
8068  * @param peer peer identity this notification is about
8069  */
8070 static void
8071 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
8072 {
8073   struct MeshPeerInfo *pi;
8074   struct MeshPeerQueue *q;
8075   struct MeshPeerQueue *n;
8076
8077   DEBUG_CONN ("Peer disconnected\n");
8078   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
8079   if (NULL == pi)
8080   {
8081     GNUNET_break (0);
8082     return;
8083   }
8084   q = pi->queue_head;
8085   while (NULL != q)
8086   {
8087       n = q->next;
8088       /* TODO try to reroute this traffic instead */
8089       queue_destroy(q, GNUNET_YES);
8090       q = n;
8091   }
8092   if (NULL != pi->core_transmit)
8093   {
8094     GNUNET_CORE_notify_transmit_ready_cancel(pi->core_transmit);
8095     pi->core_transmit = NULL;
8096   }
8097   peer_info_remove_path (pi, pi->id, myid);
8098   if (myid == pi->id)
8099   {
8100     DEBUG_CONN ("     (self)\n");
8101   }
8102   GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
8103   return;
8104 }
8105
8106
8107 /******************************************************************************/
8108 /************************      MAIN FUNCTIONS      ****************************/
8109 /******************************************************************************/
8110
8111 /**
8112  * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
8113  *
8114  * @param cls closure
8115  * @param key current key code
8116  * @param value value in the hash map
8117  * @return GNUNET_YES if we should continue to iterate,
8118  *         GNUNET_NO if not.
8119  */
8120 static int
8121 shutdown_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
8122 {
8123   struct MeshTunnel *t = value;
8124
8125   tunnel_destroy (t);
8126   return GNUNET_YES;
8127 }
8128
8129 /**
8130  * Iterator over peer hash map entries to destroy the tunnel during shutdown.
8131  *
8132  * @param cls closure
8133  * @param key current key code
8134  * @param value value in the hash map
8135  * @return GNUNET_YES if we should continue to iterate,
8136  *         GNUNET_NO if not.
8137  */
8138 static int
8139 shutdown_peer (void *cls, const struct GNUNET_HashCode * key, void *value)
8140 {
8141   struct MeshPeerInfo *p = value;
8142   struct MeshPeerQueue *q;
8143   struct MeshPeerQueue *n;
8144
8145   q = p->queue_head;
8146   while (NULL != q)
8147   {
8148       n = q->next;
8149       if (q->peer == p)
8150       {
8151         queue_destroy(q, GNUNET_YES);
8152       }
8153       q = n;
8154   }
8155   peer_info_destroy (p);
8156   return GNUNET_YES;
8157 }
8158
8159
8160 /**
8161  * Task run during shutdown.
8162  *
8163  * @param cls unused
8164  * @param tc unused
8165  */
8166 static void
8167 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
8168 {
8169   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
8170
8171   if (core_handle != NULL)
8172   {
8173     GNUNET_CORE_disconnect (core_handle);
8174     core_handle = NULL;
8175   }
8176   if (NULL != keygen)
8177   {
8178     GNUNET_CRYPTO_ecc_key_create_stop (keygen);
8179     keygen = NULL;
8180   }
8181   GNUNET_CONTAINER_multihashmap_iterate (tunnels, &shutdown_tunnel, NULL);
8182   GNUNET_CONTAINER_multihashmap_iterate (peers, &shutdown_peer, NULL);
8183   if (dht_handle != NULL)
8184   {
8185     GNUNET_DHT_disconnect (dht_handle);
8186     dht_handle = NULL;
8187   }
8188   if (nc != NULL)
8189   {
8190     GNUNET_SERVER_notification_context_destroy (nc);
8191     nc = NULL;
8192   }
8193   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
8194   {
8195     GNUNET_SCHEDULER_cancel (announce_id_task);
8196     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
8197   }
8198   if (GNUNET_SCHEDULER_NO_TASK != announce_applications_task)
8199   {
8200     GNUNET_SCHEDULER_cancel (announce_applications_task);
8201     announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
8202   }
8203   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
8204 }
8205
8206
8207 /**
8208  * Callback for hostkey read/generation.
8209  *
8210  * @param cls Closure (Configuration handle).
8211  * @param pk The ECC private key.
8212  * @param emsg Error message, if any.
8213  */
8214 static void
8215 key_generation_cb (void *cls,
8216                    struct GNUNET_CRYPTO_EccPrivateKey *pk,
8217                    const char *emsg)
8218 {
8219   const struct GNUNET_CONFIGURATION_Handle *c = cls;
8220   struct MeshPeerInfo *peer;
8221   struct MeshPeerPath *p;
8222
8223   keygen = NULL;  
8224   if (NULL == pk)
8225   {
8226     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8227                 _("Mesh service could not access hostkey: %s. Exiting.\n"),
8228                 emsg);
8229     GNUNET_SCHEDULER_shutdown ();
8230     return;
8231   }
8232   my_private_key = pk;
8233   GNUNET_CRYPTO_ecc_key_get_public (my_private_key, &my_public_key);
8234   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
8235                       &my_full_id.hashPubKey);
8236   myid = GNUNET_PEER_intern (&my_full_id);
8237   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
8238               "Mesh for peer [%s] starting\n",
8239               GNUNET_i2s(&my_full_id));
8240
8241   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
8242                                      NULL,      /* Closure passed to MESH functions */
8243                                      &core_init,        /* Call core_init once connected */
8244                                      &core_connect,     /* Handle connects */
8245                                      &core_disconnect,  /* remove peers on disconnects */
8246                                      NULL,      /* Don't notify about all incoming messages */
8247                                      GNUNET_NO, /* For header only in notification */
8248                                      NULL,      /* Don't notify about all outbound messages */
8249                                      GNUNET_NO, /* For header-only out notification */
8250                                      core_handlers);    /* Register these handlers */
8251   
8252   if (core_handle == NULL)
8253   {
8254     GNUNET_break (0);
8255     GNUNET_SCHEDULER_shutdown ();
8256     return;
8257   }
8258
8259   next_tid = 0;
8260   next_local_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
8261
8262
8263   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
8264   nc = GNUNET_SERVER_notification_context_create (server_handle, 1);
8265   GNUNET_SERVER_disconnect_notify (server_handle,
8266                                    &handle_local_client_disconnect, NULL);
8267
8268
8269   clients = NULL;
8270   clients_tail = NULL;
8271   next_client_id = 0;
8272
8273   announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
8274   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
8275
8276   /* Create a peer_info for the local peer */
8277   peer = peer_info_get (&my_full_id);
8278   p = path_new (1);
8279   p->peers[0] = myid;
8280   GNUNET_PEER_change_rc (myid, 1);
8281   peer_info_add_path (peer, p, GNUNET_YES);
8282   GNUNET_SERVER_resume (server_handle);
8283   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Mesh service running\n");
8284 }
8285
8286
8287 /**
8288  * Process mesh requests.
8289  *
8290  * @param cls closure
8291  * @param server the initialized server
8292  * @param c configuration to use
8293  */
8294 static void
8295 run (void *cls, struct GNUNET_SERVER_Handle *server,
8296      const struct GNUNET_CONFIGURATION_Handle *c)
8297 {
8298   char *keyfile;
8299
8300   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
8301   server_handle = server;
8302
8303   if (GNUNET_OK !=
8304       GNUNET_CONFIGURATION_get_value_filename (c, "PEER", "PRIVATE_KEY",
8305                                                &keyfile))
8306   {
8307     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8308                 _
8309                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8310                 "mesh", "peer/privatekey");
8311     GNUNET_SCHEDULER_shutdown ();
8312     return;
8313   }
8314
8315   if (GNUNET_OK !=
8316       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_PATH_TIME",
8317                                            &refresh_path_time))
8318   {
8319     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8320                 _
8321                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8322                 "mesh", "refresh path time");
8323     GNUNET_SCHEDULER_shutdown ();
8324     return;
8325   }
8326
8327   if (GNUNET_OK !=
8328       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "APP_ANNOUNCE_TIME",
8329                                            &app_announce_time))
8330   {
8331     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8332                 _
8333                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8334                 "mesh", "app announce time");
8335     GNUNET_SCHEDULER_shutdown ();
8336     return;
8337   }
8338   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
8339               "APP_ANNOUNCE_TIME %llu ms\n", 
8340               app_announce_time.rel_value);
8341   if (GNUNET_OK !=
8342       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "ID_ANNOUNCE_TIME",
8343                                            &id_announce_time))
8344   {
8345     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8346                 _
8347                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8348                 "mesh", "id announce time");
8349     GNUNET_SCHEDULER_shutdown ();
8350     return;
8351   }
8352
8353   if (GNUNET_OK !=
8354       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "CONNECT_TIMEOUT",
8355                                            &connect_timeout))
8356   {
8357     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8358                 _
8359                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8360                 "mesh", "connect timeout");
8361     GNUNET_SCHEDULER_shutdown ();
8362     return;
8363   }
8364
8365   if (GNUNET_OK !=
8366       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
8367                                              &max_msgs_queue))
8368   {
8369     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8370                 _
8371                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8372                 "mesh", "max msgs queue");
8373     GNUNET_SCHEDULER_shutdown ();
8374     return;
8375   }
8376
8377   if (GNUNET_OK !=
8378       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_TUNNELS",
8379                                              &max_tunnels))
8380   {
8381     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8382                 _
8383                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8384                 "mesh", "max tunnels");
8385     GNUNET_SCHEDULER_shutdown ();
8386     return;
8387   }
8388
8389   if (GNUNET_OK !=
8390       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
8391                                              &default_ttl))
8392   {
8393     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
8394                 _
8395                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
8396                 "mesh", "default ttl", 64);
8397     default_ttl = 64;
8398   }
8399
8400   if (GNUNET_OK !=
8401       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_PEERS",
8402                                              &max_peers))
8403   {
8404     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
8405                 _("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
8406                 "mesh", "max peers", 1000);
8407     max_peers = 1000;
8408   }
8409
8410   if (GNUNET_OK !=
8411       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DHT_REPLICATION_LEVEL",
8412                                              &dht_replication_level))
8413   {
8414     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
8415                 _
8416                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
8417                 "mesh", "dht replication level", 3);
8418     dht_replication_level = 3;
8419   }
8420
8421   tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
8422   incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
8423   peers = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
8424   applications = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
8425   types = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
8426
8427   dht_handle = GNUNET_DHT_connect (c, 64);
8428   if (NULL == dht_handle)
8429   {
8430     GNUNET_break (0);
8431   }
8432   stats = GNUNET_STATISTICS_create ("mesh", c);
8433
8434   GNUNET_SERVER_suspend (server_handle);
8435   /* Scheduled the task to clean up when shutdown is called */
8436   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
8437                                 NULL);
8438   keygen = GNUNET_CRYPTO_ecc_key_create_start (keyfile,
8439                                                &key_generation_cb,
8440                                                (void *) c);
8441   GNUNET_free (keyfile);
8442 }
8443
8444
8445 /**
8446  * The main function for the mesh service.
8447  *
8448  * @param argc number of arguments from the command line
8449  * @param argv command line arguments
8450  * @return 0 ok, 1 on error
8451  */
8452 int
8453 main (int argc, char *const *argv)
8454 {
8455   int ret;
8456   int r;
8457
8458   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
8459   r = GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
8460                           NULL);
8461   ret = (GNUNET_OK == r) ? 0 : 1;
8462   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");
8463
8464   INTERVAL_SHOW;
8465
8466   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
8467               "Mesh for peer [%s] FWD ACKs %u, BCK ACKs %u\n",
8468               GNUNET_i2s(&my_full_id), debug_fwd_ack, debug_bck_ack);
8469
8470   return ret;
8471 }