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