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