Move regex DHT integration from mesh to regex
[oweals/gnunet.git] / src / mesh / gnunet-service-mesh-new.c
1 /*
2      This file is part of GNUnet.
3      (C) 2001-2012 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file mesh/gnunet-service-mesh.c
23  * @brief GNUnet MESH service
24  * @author Bartlomiej Polot
25  *
26  * STRUCTURE:
27  * - DATA STRUCTURES
28  * - GLOBAL VARIABLES
29  * - GENERAL HELPERS
30  * - PERIODIC FUNCTIONS
31  * - MESH NETWORK HANDLER HELPERS
32  * - MESH NETWORK HANDLES
33  * - MESH LOCAL HANDLER HELPERS
34  * - MESH LOCAL HANDLES
35  * - MAIN FUNCTIONS (main & run)
36  *
37  * TODO:
38  * - error reporting (CREATE/CHANGE/ADD/DEL?) -- new message!
39  * - partial disconnect reporting -- same as error reporting?
40  * - add ping message
41  * - relay corking down to core
42  * - set ttl relative to tree depth
43  * - Add data ACK count in path ACK
44  * - Make common GNUNET_MESH_Data header for unicast, to_orig, multicast
45  * TODO END
46  */
47
48 #include "platform.h"
49 #include "mesh.h"
50 #include "mesh_protocol.h"
51 #include "mesh_tunnel_tree.h"
52 #include "block_mesh.h"
53 #include "gnunet_dht_service.h"
54 #include "gnunet_statistics_service.h"
55 #include "gnunet_regex_lib.h"
56
57 #define MESH_BLOOM_SIZE         128
58
59 #define MESH_DEBUG_DHT          GNUNET_NO
60 #define MESH_DEBUG_CONNECTION   GNUNET_NO
61 #define MESH_DEBUG_TIMING       __LINUX__ && GNUNET_NO
62
63 #define MESH_MAX_POLL_TIME      GNUNET_TIME_relative_multiply (\
64                                   GNUNET_TIME_UNIT_MINUTES,\
65                                   10)
66
67 #if MESH_DEBUG_CONNECTION
68 #define DEBUG_CONN(...) GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
69 #else
70 #define DEBUG_CONN(...)
71 #endif
72
73 #if MESH_DEBUG_DHT
74 #define DEBUG_DHT(...) GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
75 #else
76 #define DEBUG_DHT(...)
77 #endif
78
79 #if MESH_DEBUG_TIMING
80 #include <time.h>
81 double __sum;
82 uint64_t __count;
83 struct timespec __mesh_start;
84 struct timespec __mesh_end;
85 #define INTERVAL_START clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &(__mesh_start))
86 #define INTERVAL_END \
87 do {\
88   clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &(__mesh_end));\
89   double __diff = __mesh_end.tv_nsec - __mesh_start.tv_nsec;\
90   if (__diff < 0) __diff += 1000000000;\
91   __sum += __diff;\
92   __count++;\
93 } while (0)
94 #define INTERVAL_SHOW \
95 if (0 < __count)\
96   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "AVG process time: %f ns\n", __sum/__count)
97 #else
98 #define INTERVAL_START
99 #define INTERVAL_END
100 #define INTERVAL_SHOW
101 #endif
102
103 /******************************************************************************/
104 /************************      DATA STRUCTURES     ****************************/
105 /******************************************************************************/
106
107 /** FWD declaration */
108 struct MeshPeerInfo;
109 struct MeshClient;
110
111
112 /**
113  * Struct representing a piece of data being sent to other peers
114  */
115 struct MeshData
116 {
117   /** Tunnel it belongs to. */
118   struct MeshTunnel *t;
119
120   /** How many remaining neighbors still hav't got it. */
121   unsigned int reference_counter;
122
123   /** How many remaining neighbors we need to send this to. */
124   unsigned int total_out;
125
126   /** Size of the data. */
127   size_t data_len;
128
129   /** Data itself */
130   void *data;
131 };
132
133
134 /**
135  * Struct containing info about a queued transmission to this peer
136  */
137 struct MeshPeerQueue
138 {
139     /**
140       * DLL next
141       */
142   struct MeshPeerQueue *next;
143
144     /**
145       * DLL previous
146       */
147   struct MeshPeerQueue *prev;
148
149     /**
150      * Peer this transmission is directed to.
151      */
152   struct MeshPeerInfo *peer;
153
154     /**
155      * Tunnel this message belongs to.
156      */
157   struct MeshTunnel *tunnel;
158
159     /**
160      * Pointer to info stucture used as cls.
161      */
162   void *cls;
163
164     /**
165      * Type of message
166      */
167   uint16_t type;
168
169     /**
170      * Size of the message
171      */
172   size_t size;
173 };
174
175
176 /**
177  * Struct to store regex information announced by clients.
178  */
179 struct MeshRegexDescriptor
180 {
181     /**
182      * Regular expression itself.
183      */
184   char *regex;
185
186     /**
187      * How many characters per edge can we squeeze?
188      */
189   uint16_t compression;
190
191     /**
192      * Handle to announce the regex.
193      */
194   struct GNUNET_REGEX_announce_handle *h;
195 };
196
197
198 /**
199  * Struct to keep information of searches of services described by a regex
200  * using a user-provided string service description.
201  */
202 struct MeshRegexSearchInfo
203 {
204     /**
205      * Which tunnel is this for
206      */
207   struct MeshTunnel *t;
208
209     /**
210      * User provided description of the searched service.
211      */
212   char *description;
213
214     /**
215      * Regex search handle.
216      */
217   struct GNUNET_REGEX_search_handle *search_handle;
218
219     /**
220      * Peer that is connecting via connect_by_string. When connected, free ctx.
221      */
222   GNUNET_PEER_Id peer;
223
224     /**
225      * Other peers that are found but not yet being connected to.
226      */
227   GNUNET_PEER_Id *peers;
228
229     /**
230      * Number of elements in peers.
231      */
232   unsigned int n_peers;
233
234     /**
235      * Next peer to try to connect to.
236      */
237   unsigned int i_peer;
238
239     /**
240      * Timeout for a connect attempt.
241      * When reached, try to connect to a different peer, if any. If not,
242      * try the same peer again.
243      */
244   GNUNET_SCHEDULER_TaskIdentifier timeout;
245
246 };
247
248
249 /**
250  * Struct containing all info possibly needed to build a package when called
251  * back by core.
252  */
253 struct MeshTransmissionDescriptor
254 {
255     /** ID of the tunnel this packet travels in */
256   struct MESH_TunnelID *origin;
257
258     /** Who was this message being sent to */
259   struct MeshPeerInfo *peer;
260
261     /** Ultimate destination of the packet */
262   GNUNET_PEER_Id destination;
263
264     /** Data descriptor */
265   struct MeshData* mesh_data;
266 };
267
268
269 /**
270  * Struct containing all information regarding a given peer
271  */
272 struct MeshPeerInfo
273 {
274     /**
275      * ID of the peer
276      */
277   GNUNET_PEER_Id id;
278
279     /**
280      * Last time we heard from this peer
281      */
282   struct GNUNET_TIME_Absolute last_contact;
283
284     /**
285      * Task handler for delayed connect task;
286      */
287   GNUNET_SCHEDULER_TaskIdentifier connect_task;
288
289     /**
290      * Number of attempts to reconnect so far
291      */
292   int n_reconnect_attempts;
293
294     /**
295      * Paths to reach the peer, ordered by ascending hop count
296      */
297   struct MeshPeerPath *path_head;
298
299     /**
300      * Paths to reach the peer, ordered by ascending hop count
301      */
302   struct MeshPeerPath *path_tail;
303
304     /**
305      * Handle to stop the DHT search for a path to this peer
306      */
307   struct GNUNET_DHT_GetHandle *dhtget;
308
309     /**
310      * Closure given to the DHT GET
311      */
312   struct MeshPathInfo *dhtgetcls;
313
314     /**
315      * Array of tunnels this peer participates in
316      * (most probably a small amount, therefore not a hashmap)
317      * When the path to the peer changes, notify these tunnels to let them
318      * re-adjust their path trees.
319      */
320   struct MeshTunnel **tunnels;
321
322     /**
323      * Number of tunnels this peers participates in
324      */
325   unsigned int ntunnels;
326
327    /**
328     * Transmission queue to core DLL head
329     */
330   struct MeshPeerQueue *queue_head;
331
332    /**
333     * Transmission queue to core DLL tail
334     */
335    struct MeshPeerQueue *queue_tail;
336
337    /**
338     * How many messages are in the queue to this peer.
339     */
340    unsigned int queue_n;
341
342    /**
343     * Handle to for queued transmissions
344     */
345   struct GNUNET_CORE_TransmitHandle *core_transmit;
346 };
347
348
349 /**
350  * Globally unique tunnel identification (owner + number)
351  * DO NOT USE OVER THE NETWORK
352  */
353 struct MESH_TunnelID
354 {
355     /**
356      * Node that owns the tunnel
357      */
358   GNUNET_PEER_Id oid;
359
360     /**
361      * Tunnel number to differentiate all the tunnels owned by the node oid
362      * ( tid < GNUNET_MESH_LOCAL_TUNNEL_ID_CLI )
363      */
364   MESH_TunnelNumber tid;
365 };
366
367
368 /**
369  * Struct containing all information regarding a tunnel
370  * For an intermediate node the improtant info used will be:
371  * - id        Tunnel unique identification
372  * - paths[0]  To know where to send it next
373  * - metainfo: ready, speeds, accounting
374  */
375 struct MeshTunnel
376 {
377     /**
378      * Tunnel ID
379      */
380   struct MESH_TunnelID id;
381
382     /**
383      * Local tunnel number ( >= GNUNET_MESH_LOCAL_TUNNEL_ID_CLI or 0 )
384      */
385   MESH_TunnelNumber local_tid;
386
387     /**
388      * Local tunnel number for local destination clients (incoming number)
389      * ( >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV or 0). All clients share the same
390      * number.
391      */
392   MESH_TunnelNumber local_tid_dest;
393
394     /**
395      * Is the speed on the tunnel limited to the slowest peer?
396      */
397   int speed_min;
398
399     /**
400      * Is the tunnel bufferless (minimum latency)?
401      */
402   int nobuffer;
403
404     /**
405      * Packet ID of the last fwd packet seen (sent/retransmitted/received).
406      */
407   uint32_t fwd_pid;
408
409     /**
410      * Packet ID of the last bck packet sent (unique counter per hop).
411      */
412   uint32_t bck_pid;
413
414     /**
415      * SKIP value for this tunnel.
416      */
417   uint32_t skip;
418
419     /**
420      * Force sending ACK? Flag to allow duplicate ACK on POLL.
421      */
422   int force_ack;
423
424     /**
425      * MeshTunnelChildInfo of all children, indexed by GNUNET_PEER_Id.
426      * Contains the Flow Control info: FWD ACK value received,
427      * last BCK ACK sent, PID and SKIP values.
428      */
429   struct GNUNET_CONTAINER_MultiHashMap *children_fc;
430
431     /**
432      * Last ACK sent towards the origin (for traffic towards leaf node).
433      */
434   uint32_t last_fwd_ack;
435
436   /**
437    * BCK ACK value received from the hop towards the owner of the tunnel,
438    * (previous node / owner): up to what message PID can we sent back to him.
439    */
440   uint32_t bck_ack;
441
442     /**
443      * How many messages are in the forward queue (towards leaves).
444      */
445   unsigned int fwd_queue_n;
446
447     /**
448      * How many messages do we accept in the forward queue.
449      */
450   unsigned int fwd_queue_max;
451
452     /**
453      * How many messages are in the backward queue (towards origin).
454      */
455   unsigned int bck_queue_n;
456
457     /**
458      * How many messages do we accept in the backward queue.
459     */
460    unsigned int bck_queue_max;
461
462     /**
463      * Task to poll peer in case of a stall.
464      */
465    GNUNET_SCHEDULER_TaskIdentifier fc_poll_bck;
466
467     /**
468      * Last time the tunnel was used
469      */
470   struct GNUNET_TIME_Absolute timestamp;
471
472     /**
473      * Peers in the tunnel, indexed by PeerIdentity -> (MeshPeerInfo)
474      * containing peers added by id or by type, not intermediate peers.
475      */
476   struct GNUNET_CONTAINER_MultiHashMap *peers;
477
478     /**
479      * Number of peers that are connected and potentially ready to receive data
480      */
481   unsigned int peers_ready;
482
483     /**
484      * Number of peers that have been added to the tunnel
485      */
486   unsigned int peers_total;
487
488     /**
489      * Client owner of the tunnel, if any
490      */
491   struct MeshClient *owner;
492
493     /**
494      * Clients that have been informed about and want to stay in the tunnel.
495      */
496   struct MeshClient **clients;
497
498     /**
499      * Flow control info for each client.
500      */
501   struct MeshTunnelClientInfo *clients_fc;
502
503   /**
504      * Number of elements in clients/clients_fc
505      */
506   unsigned int nclients;
507
508     /**
509      * Clients that have been informed but requested to leave the tunnel.
510      */
511   struct MeshClient **ignore;
512
513     /**
514      * Number of elements in clients
515      */
516   unsigned int nignore;
517
518     /**
519      * Blacklisted peers
520      */
521   GNUNET_PEER_Id *blacklisted;
522
523     /**
524      * Number of elements in blacklisted
525      */
526   unsigned int nblacklisted;
527
528   /**
529    * Bloomfilter (for peer identities) to stop circular routes
530    */
531   char bloomfilter[MESH_BLOOM_SIZE];
532
533   /**
534    * Tunnel paths
535    */
536   struct MeshTunnelTree *tree;
537
538   /**
539    * Application type we are looking for in this tunnel
540    */
541   GNUNET_MESH_ApplicationType type;
542
543     /**
544      * Used to search peers offering a service
545      */
546   struct GNUNET_DHT_GetHandle *dht_get_type;
547
548     /**
549      * Handle for the regex search for a connect_by_string
550      */
551   struct MeshRegexSearchInfo *regex_search;
552
553     /**
554      * Task to keep the used paths alive
555      */
556   GNUNET_SCHEDULER_TaskIdentifier path_refresh_task;
557
558     /**
559      * Task to destroy the tunnel after timeout
560      *
561      * FIXME: merge the two? a tunnel will have either
562      * a path refresh OR a timeout, never both!
563      */
564   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
565
566     /**
567      * Flag to signal the destruction of the tunnel.
568      * If this is set GNUNET_YES the tunnel will be destroyed
569      * when the queue is empty.
570      */
571   int destroy;
572
573     /**
574      * Total messages pending for this tunnels, payload or not.
575      */
576   unsigned int pending_messages;
577
578   /**
579    * If the tunnel is empty, destoy it.
580    */
581   GNUNET_SCHEDULER_TaskIdentifier delayed_destroy;
582 };
583
584
585 /**
586  * Info about a child node in a tunnel, needed to perform flow control.
587  */
588 struct MeshTunnelChildInfo
589 {
590     /**
591      * ID of the child node.
592      */
593   GNUNET_PEER_Id id;
594
595     /**
596      * SKIP value.
597      */
598   uint32_t skip;
599
600     /**
601      * Last sent PID.
602      */
603   uint32_t fwd_pid;
604
605     /**
606      * Last received PID.
607      */
608   uint32_t bck_pid;
609
610     /**
611      * Maximum PID allowed (FWD ACK received).
612      */
613   uint32_t fwd_ack;
614
615     /**
616      * Last ACK sent to that child (BCK ACK).
617      */
618   uint32_t bck_ack;
619
620     /**
621      * Circular buffer pointing to MeshPeerQueue elements for all
622      * payload traffic going to this child.
623      * Size determined by the tunnel queue size (@c t->fwd_queue_max).
624      */
625   struct MeshPeerQueue **send_buffer;
626
627     /**
628      * Index of the oldest element in the send_buffer.
629      */
630   unsigned int send_buffer_start;
631
632     /**
633      * How many elements are already in the buffer.
634      */
635   unsigned int send_buffer_n;
636
637     /**
638      * Tunnel this info is about
639      */
640   struct MeshTunnel *t;
641
642     /**
643      * Task to poll peer in case of a stall.
644      */
645   GNUNET_SCHEDULER_TaskIdentifier fc_poll;
646
647      /**
648       * Time to use for next polling call.
649       */
650    struct GNUNET_TIME_Relative fc_poll_time;
651 };
652
653
654 /**
655  * Info about a leaf client of a tunnel, needed to perform flow control.
656  */
657 struct MeshTunnelClientInfo
658 {
659   /**
660    * PID of the last packet sent to the client (FWD).
661    */
662   uint32_t fwd_pid;
663
664   /**
665    * PID of the last packet received from the client (BCK).
666    */
667   uint32_t bck_pid;
668
669   /**
670    * Maximum PID allowed (FWD ACK received).
671    */
672   uint32_t fwd_ack;
673   
674   /**
675    * Last ACK sent to that child (BCK ACK).
676    */
677   uint32_t bck_ack;
678 };
679
680
681
682 /**
683  * Info collected during iteration of child nodes in order to get the ACK value
684  * for a tunnel.
685  */
686 struct MeshTunnelChildIteratorContext
687 {
688     /**
689      * Tunnel whose info is being collected.
690      */
691   struct MeshTunnel *t;
692
693     /**
694      * Is this context initialized? Is the value in max_child_ack valid?
695      */
696   int init;
697
698     /**
699      * Maximum child ACK so far.
700      */
701   uint32_t max_child_ack;
702
703     /**
704      * Number of children nodes
705      */
706   unsigned int nchildren;
707 };
708
709
710 /**
711  * Info needed to work with tunnel paths and peers
712  */
713 struct MeshPathInfo
714 {
715   /**
716    * Tunnel
717    */
718   struct MeshTunnel *t;
719
720   /**
721    * Neighbouring peer to whom we send the packet to
722    */
723   struct MeshPeerInfo *peer;
724
725   /**
726    * Path itself
727    */
728   struct MeshPeerPath *path;
729 };
730
731
732 /**
733  * Struct containing information about a client of the service
734  */
735 struct MeshClient
736 {
737     /**
738      * Linked list next
739      */
740   struct MeshClient *next;
741
742     /**
743      * Linked list prev
744      */
745   struct MeshClient *prev;
746
747     /**
748      * Tunnels that belong to this client, indexed by local id
749      */
750   struct GNUNET_CONTAINER_MultiHashMap *own_tunnels;
751
752    /**
753      * Tunnels this client has accepted, indexed by incoming local id
754      */
755   struct GNUNET_CONTAINER_MultiHashMap *incoming_tunnels;
756
757    /**
758      * Tunnels this client has rejected, indexed by incoming local id
759      */
760   struct GNUNET_CONTAINER_MultiHashMap *ignore_tunnels;
761     /**
762      * Handle to communicate with the client
763      */
764   struct GNUNET_SERVER_Client *handle;
765
766     /**
767      * Applications that this client has claimed to provide
768      */
769   struct GNUNET_CONTAINER_MultiHashMap *apps;
770
771     /**
772      * Messages that this client has declared interest in
773      */
774   struct GNUNET_CONTAINER_MultiHashMap *types;
775
776     /**
777      * Whether the client is active or shutting down (don't send confirmations
778      * to a client that is shutting down.
779      */
780   int shutting_down;
781
782     /**
783      * ID of the client, mainly for debug messages
784      */
785   unsigned int id;
786   
787     /**
788      * Regular expressions describing the services offered by this client.
789      */
790   struct MeshRegexDescriptor *regexes; // FIXME regex add timeout? API to remove a regex?
791
792     /**
793      * Number of regular expressions in regexes.
794      */
795   unsigned int n_regex;
796
797     /**
798      * Task to refresh all regular expresions in the DHT.
799      */
800   GNUNET_SCHEDULER_TaskIdentifier regex_announce_task;
801
802     /**
803      * Tmp store for partially retrieved regex.
804      */
805   char *partial_regex;
806
807 };
808
809
810 /******************************************************************************/
811 /************************      DEBUG FUNCTIONS     ****************************/
812 /******************************************************************************/
813
814 #if MESH_DEBUG
815 /**
816  * GNUNET_SCHEDULER_Task for printing a message after some operation is done
817  * @param cls string to print
818  * @param success  GNUNET_OK if the PUT was transmitted,
819  *                GNUNET_NO on timeout,
820  *                GNUNET_SYSERR on disconnect from service
821  *                after the PUT message was transmitted
822  *                (so we don't know if it was received or not)
823  */
824
825 #if 0
826 static void
827 mesh_debug (void *cls, int success)
828 {
829   char *s = cls;
830
831   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s (%d)\n", s, success);
832 }
833 #endif
834
835 unsigned int debug_fwd_ack;
836 unsigned int debug_bck_ack;
837
838 #endif
839
840 /******************************************************************************/
841 /***********************      GLOBAL VARIABLES     ****************************/
842 /******************************************************************************/
843
844 /************************** Configuration parameters **************************/
845
846 /**
847  * How often to send tunnel keepalives. Tunnels timeout after 4 missed.
848  */
849 static struct GNUNET_TIME_Relative refresh_path_time;
850
851 /**
852  * How often to PUT local application numbers in the DHT.
853  */
854 static struct GNUNET_TIME_Relative app_announce_time;
855
856 /**
857  * How often to PUT own ID in the DHT.
858  */
859 static struct GNUNET_TIME_Relative id_announce_time;
860
861 /**
862  * Maximum time allowed to connect to a peer found by string.
863  */
864 static struct GNUNET_TIME_Relative connect_timeout;
865
866 /**
867  * Default TTL for payload packets.
868  */
869 static unsigned long long default_ttl;
870
871 /**
872  * DHT replication level, see DHT API: GNUNET_DHT_get_start, GNUNET_DHT_put.
873  */
874 static unsigned long long dht_replication_level;
875
876 /**
877  * How many tunnels are we willing to maintain.
878  * Local tunnels are always allowed, even if there are more tunnels than max.
879  */
880 static unsigned long long max_tunnels;
881
882 /**
883  * How many messages *in total* are we willing to queue, divided by number of 
884  * tunnels to get tunnel queue size.
885  */
886 static unsigned long long max_msgs_queue;
887
888 /**
889  * How many peers do we want to remember?
890  */
891 static unsigned long long max_peers;
892
893
894 /*************************** Static global variables **************************/
895
896 /**
897  * Hostkey generation context
898  */
899 static struct GNUNET_CRYPTO_RsaKeyGenerationContext *keygen;
900
901 /**
902  * DLL with all the clients, head.
903  */
904 static struct MeshClient *clients;
905
906 /**
907  * DLL with all the clients, tail.
908  */
909 static struct MeshClient *clients_tail;
910
911 /**
912  * Tunnels known, indexed by MESH_TunnelID (MeshTunnel).
913  */
914 static struct GNUNET_CONTAINER_MultiHashMap *tunnels;
915
916 /**
917  * Number of tunnels known.
918  */
919 static unsigned long long n_tunnels;
920
921 /**
922  * Tunnels incoming, indexed by MESH_TunnelNumber
923  * (which is greater than GNUNET_MESH_LOCAL_TUNNEL_ID_SERV).
924  */
925 static struct GNUNET_CONTAINER_MultiHashMap *incoming_tunnels;
926
927 /**
928  * Peers known, indexed by PeerIdentity (MeshPeerInfo).
929  */
930 static struct GNUNET_CONTAINER_MultiHashMap *peers;
931
932 /*
933  * Handle to communicate with transport
934  */
935 // static struct GNUNET_TRANSPORT_Handle *transport_handle;
936
937 /**
938  * Handle to communicate with core.
939  */
940 static struct GNUNET_CORE_Handle *core_handle;
941
942 /**
943  * Handle to use DHT.
944  */
945 static struct GNUNET_DHT_Handle *dht_handle;
946
947 /**
948  * Handle to server.
949  */
950 static struct GNUNET_SERVER_Handle *server_handle;
951
952 /**
953  * Handle to the statistics service.
954  */
955 static struct GNUNET_STATISTICS_Handle *stats;
956
957 /**
958  * Notification context, to send messages to local clients.
959  */
960 static struct GNUNET_SERVER_NotificationContext *nc;
961
962 /**
963  * Local peer own ID (memory efficient handle).
964  */
965 static GNUNET_PEER_Id myid;
966
967 /**
968  * Local peer own ID (full value).
969  */
970 static struct GNUNET_PeerIdentity my_full_id;
971
972 /**
973  * Own private key.
974  */
975 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
976
977 /**
978  * Own public key.
979  */
980 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
981
982 /**
983  * Tunnel ID for the next created tunnel (global tunnel number).
984  */
985 static MESH_TunnelNumber next_tid;
986
987 /**
988  * Tunnel ID for the next incoming tunnel (local tunnel number).
989  */
990 static MESH_TunnelNumber next_local_tid;
991
992 /**
993  * All application types provided by this peer.
994  */
995 static struct GNUNET_CONTAINER_MultiHashMap *applications;
996
997 /**
998  * All message types clients of this peer are interested in.
999  */
1000 static struct GNUNET_CONTAINER_MultiHashMap *types;
1001
1002 /**
1003  * Task to periodically announce provided applications.
1004  */
1005 GNUNET_SCHEDULER_TaskIdentifier announce_applications_task;
1006
1007 /**
1008  * Task to periodically announce itself in the network.
1009  */
1010 GNUNET_SCHEDULER_TaskIdentifier announce_id_task;
1011
1012 /**
1013  * Next ID to assign to a client.
1014  */
1015 unsigned int next_client_id;
1016
1017
1018 /******************************************************************************/
1019 /***********************         DECLARATIONS        **************************/
1020 /******************************************************************************/
1021
1022 /**
1023  * Function to process paths received for a new peer addition. The recorded
1024  * paths form the initial tunnel, which can be optimized later.
1025  * Called on each result obtained for the DHT search.
1026  *
1027  * @param cls closure
1028  * @param exp when will this value expire
1029  * @param key key of the result
1030  * @param type type of the result
1031  * @param size number of bytes in data
1032  * @param data pointer to the result data
1033  */
1034 static void
1035 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
1036                     const struct GNUNET_HashCode * key,
1037                     const struct GNUNET_PeerIdentity *get_path,
1038                     unsigned int get_path_length,
1039                     const struct GNUNET_PeerIdentity *put_path,
1040                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
1041                     size_t size, const void *data);
1042
1043
1044 /**
1045  * Retrieve the MeshPeerInfo stucture associated with the peer, create one
1046  * and insert it in the appropiate structures if the peer is not known yet.
1047  *
1048  * @param peer Full identity of the peer.
1049  *
1050  * @return Existing or newly created peer info.
1051  */
1052 static struct MeshPeerInfo *
1053 peer_info_get (const struct GNUNET_PeerIdentity *peer);
1054
1055
1056 /**
1057  * Retrieve the MeshPeerInfo stucture associated with the peer, create one
1058  * and insert it in the appropiate structures if the peer is not known yet.
1059  *
1060  * @param peer Short identity of the peer.
1061  *
1062  * @return Existing or newly created peer info.
1063  */
1064 static struct MeshPeerInfo *
1065 peer_info_get_short (const GNUNET_PEER_Id peer);
1066
1067
1068 /**
1069  * Try to establish a new connection to this peer.
1070  * Use the best path for the given tunnel.
1071  * If the peer doesn't have any path to it yet, try to get one.
1072  * If the peer already has some path, send a CREATE PATH towards it.
1073  *
1074  * @param peer PeerInfo of the peer.
1075  * @param t Tunnel for which to create the path, if possible.
1076  */
1077 static void
1078 peer_info_connect (struct MeshPeerInfo *peer, struct MeshTunnel *t);
1079
1080
1081 /**
1082  * Build a PeerPath from the paths returned from the DHT, reversing the paths
1083  * to obtain a local peer -> destination path and interning the peer ids.
1084  *
1085  * @return Newly allocated and created path
1086  */
1087 static struct MeshPeerPath *
1088 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
1089                      unsigned int get_path_length,
1090                      const struct GNUNET_PeerIdentity *put_path,
1091                      unsigned int put_path_length);
1092
1093
1094 /**
1095  * Adds a path to the peer_infos of all the peers in the path
1096  *
1097  * @param p Path to process.
1098  * @param confirmed Whether we know if the path works or not.
1099  */
1100 static void
1101 path_add_to_peers (struct MeshPeerPath *p, int confirmed);
1102
1103
1104 /**
1105  * Add a peer to a tunnel, accomodating paths accordingly and initializing all
1106  * needed rescources.
1107  * If peer already exists, reevaluate shortest path and change if different.
1108  *
1109  * @param t Tunnel we want to add a new peer to
1110  * @param peer PeerInfo of the peer being added
1111  *
1112  */
1113 static void
1114 tunnel_add_peer (struct MeshTunnel *t, struct MeshPeerInfo *peer);
1115
1116
1117 /**
1118  * Removes an explicit path from a tunnel, freeing all intermediate nodes
1119  * that are no longer needed, as well as nodes of no longer reachable peers.
1120  * The tunnel itself is also destoyed if results in a remote empty tunnel.
1121  *
1122  * @param t Tunnel from which to remove the path.
1123  * @param peer Short id of the peer which should be removed.
1124  */
1125 static void
1126 tunnel_delete_peer (struct MeshTunnel *t, GNUNET_PEER_Id peer);
1127
1128
1129 /**
1130  * Search for a tunnel by global ID using full PeerIdentities.
1131  *
1132  * @param oid owner of the tunnel.
1133  * @param tid global tunnel number.
1134  *
1135  * @return tunnel handler, NULL if doesn't exist.
1136  */
1137 static struct MeshTunnel *
1138 tunnel_get (const struct GNUNET_PeerIdentity *oid, MESH_TunnelNumber tid);
1139
1140
1141 /**
1142  * Delete an active client from the tunnel.
1143  *
1144  * @param t Tunnel.
1145  * @param c Client.
1146  */
1147 static void
1148 tunnel_delete_active_client (struct MeshTunnel *t, const struct MeshClient *c);
1149
1150 /**
1151  * Notify a tunnel that a connection has broken that affects at least
1152  * some of its peers.
1153  *
1154  * @param t Tunnel affected.
1155  * @param p1 Peer that got disconnected from p2.
1156  * @param p2 Peer that got disconnected from p1.
1157  *
1158  * @return Short ID of the peer disconnected (either p1 or p2).
1159  *         0 if the tunnel remained unaffected.
1160  */
1161 static GNUNET_PEER_Id
1162 tunnel_notify_connection_broken (struct MeshTunnel *t, GNUNET_PEER_Id p1,
1163                                  GNUNET_PEER_Id p2);
1164
1165
1166 /**
1167  * Get the current ack value for a tunnel, for data going from root to leaves,
1168  * taking in account the tunnel mode and the status of all children and clients.
1169  *
1170  * @param t Tunnel.
1171  *
1172  * @return Maximum PID allowed.
1173  */
1174 static uint32_t
1175 tunnel_get_fwd_ack (struct MeshTunnel *t);
1176
1177
1178 /**
1179  * Add a client to a tunnel, initializing all needed data structures.
1180  * 
1181  * @param t Tunnel to which add the client.
1182  * @param c Client which to add to the tunnel.
1183  */
1184 static void
1185 tunnel_add_client (struct MeshTunnel *t, struct MeshClient *c);
1186
1187
1188 /**
1189  * @brief Queue and pass message to core when possible.
1190  * 
1191  * If type is payload (UNICAST, TO_ORIGIN, MULTICAST) checks for queue status
1192  * and accounts for it. In case the queue is full, the message is dropped and
1193  * a break issued.
1194  * 
1195  * Otherwise, message is treated as internal and allowed to go regardless of 
1196  * queue status.
1197  *
1198  * @param cls Closure (@c type dependant). It will be used by queue_send to
1199  *            build the message to be sent if not already prebuilt.
1200  * @param type Type of the message, 0 for a raw message.
1201  * @param size Size of the message.
1202  * @param dst Neighbor to send message to.
1203  * @param t Tunnel this message belongs to.
1204  */
1205 static void
1206 queue_add (void *cls, uint16_t type, size_t size,
1207            struct MeshPeerInfo *dst, struct MeshTunnel *t);
1208
1209
1210 /**
1211  * Free a transmission that was already queued with all resources
1212  * associated to the request.
1213  *
1214  * @param queue Queue handler to cancel.
1215  * @param clear_cls Is it necessary to free associated cls?
1216  */
1217 static void
1218 queue_destroy (struct MeshPeerQueue *queue, int clear_cls);
1219
1220
1221 /**
1222  * @brief Get the next transmittable message from the queue.
1223  *
1224  * This will be the head, except in the case of being a data packet
1225  * not allowed by the destination peer.
1226  *
1227  * @param peer Destination peer.
1228  *
1229  * @return The next viable MeshPeerQueue element to send to that peer.
1230  *         NULL when there are no transmittable messages.
1231  */
1232 struct MeshPeerQueue *
1233 queue_get_next (const struct MeshPeerInfo *peer);
1234
1235
1236 /**
1237  * Core callback to write a queued packet to core buffer
1238  *
1239  * @param cls Closure (peer info).
1240  * @param size Number of bytes available in buf.
1241  * @param buf Where the to write the message.
1242  *
1243  * @return number of bytes written to buf
1244  */
1245 static size_t
1246 queue_send (void *cls, size_t size, void *buf);
1247
1248 /******************************************************************************/
1249 /************************    REGEX INTEGRATION     ****************************/
1250 /******************************************************************************/
1251
1252 /**
1253  * Cancel a mesh regex search and free resources.
1254  */
1255 static void
1256 regex_cancel_search (struct MeshRegexSearchInfo *regex_search)
1257 {
1258   GNUNET_REGEX_search_cancel (regex_search->search_handle);
1259   if (0 < regex_search->n_peers)
1260     GNUNET_free (regex_search->peers);
1261   if (GNUNET_SCHEDULER_NO_TASK != regex_search->timeout)
1262   {
1263     GNUNET_SCHEDULER_cancel(regex_search->timeout);
1264   }
1265   GNUNET_free (regex_search);
1266 }
1267
1268
1269 /**
1270  * Function called if the connect attempt to a peer found via
1271  * connect_by_string times out. Try to connect to another peer, if any.
1272  * Otherwise try to reconnect to the same peer.
1273  *
1274  * @param cls Closure (info about regex search).
1275  * @param tc TaskContext.
1276  */
1277 static void
1278 regex_connect_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1279 {
1280   struct MeshRegexSearchInfo *info = cls;
1281   struct MeshPeerInfo *peer_info;
1282   GNUNET_PEER_Id id;
1283   GNUNET_PEER_Id old;
1284
1285   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Regex connect timeout\n");
1286   info->timeout = GNUNET_SCHEDULER_NO_TASK;
1287   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1288   {
1289     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " due to shutdown\n");
1290     return;
1291   }
1292
1293   old = info->peer;
1294   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  timed out: %u\n", old);
1295
1296   if (0 < info->n_peers)
1297   {
1298     // Select next peer, put current in that spot.
1299     id = info->peers[info->i_peer];
1300     info->peers[info->i_peer] = info->peer;
1301     info->i_peer = (info->i_peer + 1) % info->n_peers;
1302   }
1303   else
1304   {
1305     // Try to connect to same peer again.
1306     id = info->peer;
1307   }
1308   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  trying: %u\n", id);
1309
1310   peer_info = peer_info_get_short(id);
1311   tunnel_add_peer (info->t, peer_info);
1312   if (old != id)
1313     tunnel_delete_peer (info->t, old);
1314   peer_info_connect (peer_info, info->t);
1315   info->timeout = GNUNET_SCHEDULER_add_delayed (connect_timeout,
1316                                                 &regex_connect_timeout,
1317                                                 info);
1318   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Regex connect timeout END\n");
1319 }
1320
1321
1322 /**
1323  * Function to process DHT string to regex matching.
1324  * Called on each result obtained for the DHT search.
1325  *
1326  * @param cls Closure provided in GNUNET_REGEX_search.
1327  * @param id Peer providing a regex that matches the string.
1328  * @param get_path Path of the get request.
1329  * @param get_path_length Lenght of get_path.
1330  * @param put_path Path of the put request.
1331  * @param put_path_length Length of the put_path.
1332  */
1333 static void
1334 regex_found_handler (void *cls,
1335                      const struct GNUNET_PeerIdentity *id,
1336                      const struct GNUNET_PeerIdentity *get_path,
1337                      unsigned int get_path_length,
1338                      const struct GNUNET_PeerIdentity *put_path,
1339                      unsigned int put_path_length)
1340 {
1341   struct MeshRegexSearchInfo *info = cls;
1342   struct MeshPeerPath *p;
1343   struct MeshPeerInfo *peer_info;
1344
1345   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got regex results from DHT!\n");
1346   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", info->description);
1347
1348   peer_info = peer_info_get (id);
1349   p = path_build_from_dht (get_path, get_path_length,
1350                            put_path, put_path_length);
1351   path_add_to_peers (p, GNUNET_NO);
1352   path_destroy(p);
1353
1354   tunnel_add_peer (info->t, peer_info);
1355   peer_info_connect (peer_info, info->t);
1356   if (0 == info->peer)
1357   {
1358     info->peer = peer_info->id;
1359   }
1360   else
1361   {
1362     GNUNET_array_append (info->peers, info->n_peers, peer_info->id);
1363   }
1364
1365   if (GNUNET_SCHEDULER_NO_TASK != info->timeout)
1366     return;
1367
1368   info->timeout = GNUNET_SCHEDULER_add_delayed (connect_timeout,
1369                                                 &regex_connect_timeout,
1370                                                 info);
1371
1372   return;
1373 }
1374
1375
1376 /**
1377  * Store the regular expression describing a local service into the DHT.
1378  *
1379  * @param regex The regular expresion.
1380  */
1381 static void
1382 regex_put (struct MeshRegexDescriptor *regex)
1383 {
1384   DEBUG_DHT ("  regex_put (%s) start\n", regex->regex);
1385   if (NULL == regex->h)
1386   {
1387     DEBUG_DHT ("  first put, creating DFA\n");
1388     regex->h = GNUNET_REGEX_announce (dht_handle,
1389                                       &my_full_id,
1390                                       regex->regex,
1391                                       regex->compression,
1392                                       stats);
1393   }
1394   else
1395   {
1396     DEBUG_DHT ("  not first put, using cached data\n");
1397     GNUNET_REGEX_reannounce (regex->h);
1398   }
1399   DEBUG_DHT ("  regex_put (%s) end\n", regex->regex);
1400 }
1401
1402
1403 /**
1404  * Periodically announce what applications are provided by local clients
1405  * (by regex)
1406  *
1407  * @param cls closure
1408  * @param tc task context
1409  */
1410 static void
1411 regex_announce (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1412 {
1413   struct MeshClient *c = cls;
1414   unsigned int i;
1415
1416   c->regex_announce_task = GNUNET_SCHEDULER_NO_TASK;
1417   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1418     return;
1419   DEBUG_DHT ("Starting PUT for regex\n");
1420   for (i = 0; i < c->n_regex; i++)
1421     regex_put (&c->regexes[i]);
1422   c->regex_announce_task = GNUNET_SCHEDULER_add_delayed (app_announce_time,
1423                                                          &regex_announce,
1424                                                          cls);
1425   DEBUG_DHT ("Finished PUT for regex\n");
1426 }
1427
1428
1429 /******************************************************************************/
1430 /************************    PERIODIC FUNCTIONS    ****************************/
1431 /******************************************************************************/
1432
1433 /**
1434  * Announce iterator over for each application provided by the peer
1435  *
1436  * @param cls closure
1437  * @param key current key code
1438  * @param value value in the hash map
1439  * @return GNUNET_YES if we should continue to
1440  *         iterate,
1441  *         GNUNET_NO if not.
1442  */
1443 static int
1444 announce_application (void *cls, const struct GNUNET_HashCode * key, void *value)
1445 {
1446   struct PBlock block;
1447   struct MeshClient *c;
1448
1449   block.id = my_full_id;
1450   c =  GNUNET_CONTAINER_multihashmap_get (applications, key);
1451   GNUNET_assert(NULL != c);
1452   block.type = (long) GNUNET_CONTAINER_multihashmap_get (c->apps, key);
1453   if (0 == block.type)
1454   {
1455     GNUNET_break(0);
1456     return GNUNET_YES;
1457   }
1458   block.type = htonl (block.type);
1459
1460   GNUNET_break (NULL != 
1461                 GNUNET_DHT_put (dht_handle, key,
1462                                 dht_replication_level,
1463                                 GNUNET_DHT_RO_RECORD_ROUTE |
1464                                 GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
1465                                 GNUNET_BLOCK_TYPE_MESH_PEER_BY_TYPE,
1466                                 sizeof (block),
1467                                 (const char *) &block,
1468                                 GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_HOURS), /* FIXME: this should be an option */
1469                                 app_announce_time, NULL, NULL));
1470   return GNUNET_OK;
1471 }
1472
1473
1474 /**
1475  * Periodically announce what applications are provided by local clients
1476  * (by type)
1477  *
1478  * @param cls closure
1479  * @param tc task context
1480  */
1481 static void
1482 announce_applications (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1483 {
1484   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1485   {
1486     announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
1487     return;
1488   }
1489  
1490   DEBUG_DHT ("Starting PUT for apps\n");
1491
1492   GNUNET_CONTAINER_multihashmap_iterate (applications, &announce_application,
1493                                          NULL);
1494   announce_applications_task =
1495       GNUNET_SCHEDULER_add_delayed (app_announce_time, &announce_applications,
1496                                     cls);
1497   DEBUG_DHT ("Finished PUT for apps\n");
1498 }
1499
1500
1501 /**
1502  * Periodically announce self id in the DHT
1503  *
1504  * @param cls closure
1505  * @param tc task context
1506  */
1507 static void
1508 announce_id (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1509 {
1510   struct PBlock block;
1511
1512   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1513   {
1514     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
1515     return;
1516   }
1517   /* TODO
1518    * - Set data expiration in function of X
1519    * - Adapt X to churn
1520    */
1521   DEBUG_DHT ("DHT_put for ID %s started.\n", GNUNET_i2s (&my_full_id));
1522
1523   block.id = my_full_id;
1524   block.type = htonl (0);
1525   GNUNET_DHT_put (dht_handle,   /* DHT handle */
1526                   &my_full_id.hashPubKey,       /* Key to use */
1527                   dht_replication_level,     /* Replication level */
1528                   GNUNET_DHT_RO_RECORD_ROUTE | GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,    /* DHT options */
1529                   GNUNET_BLOCK_TYPE_MESH_PEER,       /* Block type */
1530                   sizeof (block),  /* Size of the data */
1531                   (const char *) &block, /* Data itself */
1532                   GNUNET_TIME_UNIT_FOREVER_ABS,  /* Data expiration */
1533                   GNUNET_TIME_UNIT_FOREVER_REL, /* Retry time */
1534                   NULL,         /* Continuation */
1535                   NULL);        /* Continuation closure */
1536   announce_id_task =
1537       GNUNET_SCHEDULER_add_delayed (id_announce_time, &announce_id, cls);
1538 }
1539
1540
1541 /******************************************************************************/
1542 /******************      GENERAL HELPER FUNCTIONS      ************************/
1543 /******************************************************************************/
1544
1545 /**
1546  * Decrements the reference counter and frees all resources if needed
1547  *
1548  * @param mesh_data Data Descriptor used in a multicast message.
1549  *                  Freed no longer needed (last message).
1550  */
1551 static void
1552 data_descriptor_decrement_rc (struct MeshData *mesh_data)
1553 {
1554   if (0 == --(mesh_data->reference_counter))
1555   {
1556     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Last copy!\n");
1557     GNUNET_free (mesh_data->data);
1558     GNUNET_free (mesh_data);
1559   }
1560 }
1561
1562
1563 /**
1564  * Check if client has registered with the service and has not disconnected
1565  *
1566  * @param client the client to check
1567  *
1568  * @return non-NULL if client exists in the global DLL
1569  */
1570 static struct MeshClient *
1571 client_get (struct GNUNET_SERVER_Client *client)
1572 {
1573   struct MeshClient *c;
1574
1575   c = clients;
1576   while (NULL != c)
1577   {
1578     if (c->handle == client)
1579       return c;
1580     c = c->next;
1581   }
1582   return NULL;
1583 }
1584
1585
1586 /**
1587  * Checks if a given client has subscribed to certain message type
1588  *
1589  * @param message_type Type of message to check
1590  * @param c Client to check
1591  *
1592  * @return GNUNET_YES or GNUNET_NO, depending on subscription status
1593  * 
1594  * FIXME: use of crypto_hash slows it down
1595  *  The hash function alone takes 8-10us out of the ~55us for the whole
1596  * process of retransmitting the message from one local client to another.
1597  * Find faster implementation!
1598  */
1599 static int
1600 client_is_subscribed (uint16_t message_type, struct MeshClient *c)
1601 {
1602   struct GNUNET_HashCode hc;
1603
1604   if (NULL == c->types)
1605     return GNUNET_NO;
1606
1607   GNUNET_CRYPTO_hash (&message_type, sizeof (uint16_t), &hc);
1608   return GNUNET_CONTAINER_multihashmap_contains (c->types, &hc);
1609 }
1610
1611
1612 /**
1613  * Check whether client wants traffic from a tunnel.
1614  *
1615  * @param c Client to check.
1616  * @param t Tunnel to be found.
1617  *
1618  * @return GNUNET_YES if client knows tunnel.
1619  * 
1620  * TODO look in client hashmap
1621  */
1622 static int
1623 client_wants_tunnel (struct MeshClient *c, struct MeshTunnel *t)
1624 {
1625   unsigned int i;
1626
1627   for (i = 0; i < t->nclients; i++)
1628     if (t->clients[i] == c)
1629       return GNUNET_YES;
1630   return GNUNET_NO;
1631 }
1632
1633
1634 /**
1635  * Check whether client has been informed about a tunnel.
1636  *
1637  * @param c Client to check.
1638  * @param t Tunnel to be found.
1639  *
1640  * @return GNUNET_YES if client knows tunnel.
1641  * 
1642  * TODO look in client hashmap
1643  */
1644 static int
1645 client_knows_tunnel (struct MeshClient *c, struct MeshTunnel *t)
1646 {
1647   unsigned int i;
1648
1649   for (i = 0; i < t->nignore; i++)
1650     if (t->ignore[i] == c)
1651       return GNUNET_YES;
1652   return client_wants_tunnel(c, t);
1653 }
1654
1655
1656 /**
1657  * Marks a client as uninterested in traffic from the tunnel, updating both
1658  * client and tunnel to reflect this.
1659  *
1660  * @param c Client that doesn't want traffic anymore.
1661  * @param t Tunnel which should be ignored.
1662  *
1663  * FIXME when to delete an incoming tunnel?
1664  */
1665 static void
1666 client_ignore_tunnel (struct MeshClient *c, struct MeshTunnel *t)
1667 {
1668   struct GNUNET_HashCode hash;
1669
1670   GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
1671   GNUNET_break (GNUNET_YES ==
1672                 GNUNET_CONTAINER_multihashmap_remove (c->incoming_tunnels,
1673                                                       &hash, t));
1674   GNUNET_break (GNUNET_YES ==
1675                 GNUNET_CONTAINER_multihashmap_put (c->ignore_tunnels, &hash, t,
1676                                                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
1677   tunnel_delete_active_client (t, c);
1678   GNUNET_array_append (t->ignore, t->nignore, c);
1679 }
1680
1681
1682 /**
1683  * Deletes a tunnel from a client (either owner or destination). To be used on
1684  * tunnel destroy, otherwise, use client_ignore_tunnel.
1685  *
1686  * @param c Client whose tunnel to delete.
1687  * @param t Tunnel which should be deleted.
1688  */
1689 static void
1690 client_delete_tunnel (struct MeshClient *c, struct MeshTunnel *t)
1691 {
1692   struct GNUNET_HashCode hash;
1693
1694   if (c == t->owner)
1695   {
1696     GNUNET_CRYPTO_hash(&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
1697     GNUNET_assert (GNUNET_YES ==
1698                    GNUNET_CONTAINER_multihashmap_remove (c->own_tunnels,
1699                                                          &hash,
1700                                                          t));
1701   }
1702   else
1703   {
1704     GNUNET_CRYPTO_hash(&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
1705     // FIXME XOR?
1706     GNUNET_assert (GNUNET_YES ==
1707                    GNUNET_CONTAINER_multihashmap_remove (c->incoming_tunnels,
1708                                                          &hash,
1709                                                          t) ||
1710                    GNUNET_YES ==
1711                    GNUNET_CONTAINER_multihashmap_remove (c->ignore_tunnels,
1712                                                          &hash,
1713                                                          t));
1714   }
1715 }
1716
1717
1718 /**
1719  * Notify the owner of a tunnel that a peer has disconnected.
1720  * 
1721  * @param c Client (owner of tunnel).
1722  * @param t Tunnel this message is about.
1723  * @param peer_id Short ID of the disconnected peer.
1724  */
1725 void
1726 client_notify_peer_disconnected (struct MeshClient *c,
1727                                  struct MeshTunnel *t,
1728                                  GNUNET_PEER_Id peer_id)
1729 {
1730   struct GNUNET_MESH_PeerControl msg;
1731
1732   if (NULL == t->owner || NULL == nc)
1733     return;
1734
1735   msg.header.size = htons (sizeof (msg));
1736   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL);
1737   msg.tunnel_id = htonl (t->local_tid);
1738   GNUNET_PEER_resolve (peer_id, &msg.peer);
1739   GNUNET_SERVER_notification_context_unicast (nc, t->owner->handle,
1740                                               &msg.header, GNUNET_NO);
1741 }
1742
1743
1744 /**
1745  * Send the message to all clients that have subscribed to its type
1746  *
1747  * @param msg Pointer to the message itself
1748  * @param payload Pointer to the payload of the message.
1749  * @param t The tunnel to whose clients this message goes.
1750  * 
1751  * @return number of clients this message was sent to
1752  */
1753 static unsigned int
1754 send_subscribed_clients (const struct GNUNET_MessageHeader *msg,
1755                          const struct GNUNET_MessageHeader *payload,
1756                          struct MeshTunnel *t)
1757 {
1758   struct MeshClient *c;
1759   MESH_TunnelNumber *tid;
1760   unsigned int count;
1761   uint16_t type;
1762   char cbuf[htons (msg->size)];
1763
1764   type = ntohs (payload->type);
1765   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending to clients...\n");
1766   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "message of type %s\n",
1767               GNUNET_MESH_DEBUG_M2S (type));
1768
1769   memcpy (cbuf, msg, sizeof (cbuf));
1770   switch (htons (msg->type))
1771   {
1772     struct GNUNET_MESH_Unicast *uc;
1773     struct GNUNET_MESH_Multicast *mc;
1774     struct GNUNET_MESH_ToOrigin *to;
1775
1776     case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
1777       uc = (struct GNUNET_MESH_Unicast *) cbuf;
1778       tid = &uc->tid;
1779       break;
1780     case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
1781       mc = (struct GNUNET_MESH_Multicast *) cbuf;
1782       tid = &mc->tid;
1783       break;
1784     case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
1785       to = (struct GNUNET_MESH_ToOrigin *) cbuf;
1786       tid = &to->tid;
1787       break;
1788     default:
1789       GNUNET_break (0);
1790       return 0;
1791   }
1792
1793   for (count = 0, c = clients; c != NULL; c = c->next)
1794   {
1795     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   client %u\n", c->id);
1796     if (client_is_subscribed (type, c))
1797     {
1798       if (htons (msg->type) == GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN)
1799       {
1800         if (c != t->owner)
1801           continue;
1802         *tid = htonl (t->local_tid);
1803       }
1804       else
1805       {
1806         if (GNUNET_NO == client_knows_tunnel (c, t))
1807         {
1808           /* This client doesn't know the tunnel */
1809           struct GNUNET_MESH_TunnelNotification tmsg;
1810           struct GNUNET_HashCode hash;
1811
1812           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "     sending tunnel create\n");
1813           tmsg.header.size = htons (sizeof (tmsg));
1814           tmsg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
1815           GNUNET_PEER_resolve (t->id.oid, &tmsg.peer);
1816           tmsg.tunnel_id = htonl (t->local_tid_dest);
1817           tmsg.opt = 0;
1818           if (GNUNET_YES == t->speed_min)
1819             tmsg.opt |= MESH_TUNNEL_OPT_SPEED_MIN;
1820           if (GNUNET_YES == t->nobuffer)
1821             tmsg.opt |= MESH_TUNNEL_OPT_NOBUFFER;
1822           GNUNET_SERVER_notification_context_unicast (nc, c->handle,
1823                                                       &tmsg.header, GNUNET_NO);
1824           tunnel_add_client (t, c);
1825           GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber),
1826                               &hash);
1827           GNUNET_break (GNUNET_OK == GNUNET_CONTAINER_multihashmap_put (
1828                                        c->incoming_tunnels, &hash, t,
1829                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
1830         }
1831         *tid = htonl (t->local_tid_dest);
1832       }
1833
1834       /* Check if the client wants to get traffic from the tunnel */
1835       if (GNUNET_NO == client_wants_tunnel(c, t))
1836         continue;
1837       count++;
1838       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "     sending\n");
1839       GNUNET_SERVER_notification_context_unicast (nc, c->handle,
1840                                                   (struct GNUNET_MessageHeader
1841                                                    *) cbuf, GNUNET_NO);
1842     }
1843   }
1844
1845   return count;
1846 }
1847
1848
1849 /**
1850  * Notify the client that owns the tunnel that a peer has connected to it
1851  * (the requested path to it has been confirmed).
1852  *
1853  * @param t Tunnel whose owner to notify
1854  * @param id Short id of the peer that has connected
1855  */
1856 static void
1857 send_client_peer_connected (const struct MeshTunnel *t, const GNUNET_PEER_Id id)
1858 {
1859   struct GNUNET_MESH_PeerControl pc;
1860
1861   if (NULL == t->owner || GNUNET_YES == t->destroy)
1862     return;
1863
1864   pc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD);
1865   pc.header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
1866   pc.tunnel_id = htonl (t->local_tid);
1867   GNUNET_PEER_resolve (id, &pc.peer);
1868   GNUNET_SERVER_notification_context_unicast (nc, t->owner->handle, &pc.header,
1869                                               GNUNET_NO);
1870 }
1871
1872
1873 /**
1874  * Notify all clients (not depending on registration status) that the incoming
1875  * tunnel is no longer valid.
1876  *
1877  * @param t Tunnel that was destroyed.
1878  */
1879 static void
1880 send_clients_tunnel_destroy (struct MeshTunnel *t)
1881 {
1882   struct GNUNET_MESH_TunnelMessage msg;
1883
1884   msg.header.size = htons (sizeof (msg));
1885   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
1886   msg.tunnel_id = htonl (t->local_tid_dest);
1887   GNUNET_SERVER_notification_context_broadcast (nc, &msg.header, GNUNET_NO);
1888 }
1889
1890
1891 /**
1892  * Notify clients of tunnel disconnections, if needed.
1893  * In case the origin disconnects, the destination clients get a tunnel destroy
1894  * notification. If the last destination disconnects (only one remaining client
1895  * in tunnel), the origin gets a (local ID) peer disconnected.
1896  * Note that the function must be called BEFORE removing the client from
1897  * the tunnel.
1898  *
1899  * @param t Tunnel that was destroyed.
1900  * @param c Client that disconnected.
1901  */
1902 static void
1903 send_client_tunnel_disconnect (struct MeshTunnel *t, struct MeshClient *c)
1904 {
1905   unsigned int i;
1906
1907   if (c == t->owner)
1908   {
1909     struct GNUNET_MESH_TunnelMessage msg;
1910
1911     msg.header.size = htons (sizeof (msg));
1912     msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
1913     msg.tunnel_id = htonl (t->local_tid_dest);
1914     for (i = 0; i < t->nclients; i++)
1915       GNUNET_SERVER_notification_context_unicast (nc, t->clients[i]->handle,
1916                                                   &msg.header, GNUNET_NO);
1917   }
1918   // FIXME when to disconnect an incoming tunnel?
1919   else if (1 == t->nclients && NULL != t->owner)
1920   {
1921     struct GNUNET_MESH_PeerControl msg;
1922
1923     msg.header.size = htons (sizeof (msg));
1924     msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL);
1925     msg.tunnel_id = htonl (t->local_tid);
1926     msg.peer = my_full_id;
1927     GNUNET_SERVER_notification_context_unicast (nc, t->owner->handle,
1928                                                 &msg.header, GNUNET_NO);
1929   }
1930 }
1931
1932
1933 /**
1934  * Iterator over all the peers to remove the oldest not-used entry.
1935  *
1936  * @param cls Closure (unsued).
1937  * @param key ID of the peer.
1938  * @param value Peer_Info of the peer.
1939  *
1940  * FIXME implement
1941  */
1942 static int
1943 peer_info_timeout (void *cls,
1944                    const struct GNUNET_HashCode *key,
1945                    void *value)
1946 {
1947   return GNUNET_YES;
1948 }
1949
1950 /**
1951  * Retrieve the MeshPeerInfo stucture associated with the peer, create one
1952  * and insert it in the appropiate structures if the peer is not known yet.
1953  *
1954  * @param peer Full identity of the peer.
1955  *
1956  * @return Existing or newly created peer info.
1957  */
1958 static struct MeshPeerInfo *
1959 peer_info_get (const struct GNUNET_PeerIdentity *peer)
1960 {
1961   struct MeshPeerInfo *peer_info;
1962
1963   peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
1964   if (NULL == peer_info)
1965   {
1966     peer_info =
1967         (struct MeshPeerInfo *) GNUNET_malloc (sizeof (struct MeshPeerInfo));
1968     if (GNUNET_CONTAINER_multihashmap_size (peers) > max_peers)
1969     {
1970       GNUNET_CONTAINER_multihashmap_iterate (peers,
1971                                              &peer_info_timeout,
1972                                              NULL);
1973     }
1974     GNUNET_CONTAINER_multihashmap_put (peers, &peer->hashPubKey, peer_info,
1975                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1976     peer_info->id = GNUNET_PEER_intern (peer);
1977   }
1978   peer_info->last_contact = GNUNET_TIME_absolute_get();
1979
1980   return peer_info;
1981 }
1982
1983
1984 /**
1985  * Retrieve the MeshPeerInfo stucture associated with the peer, create one
1986  * and insert it in the appropiate structures if the peer is not known yet.
1987  *
1988  * @param peer Short identity of the peer.
1989  *
1990  * @return Existing or newly created peer info.
1991  */
1992 static struct MeshPeerInfo *
1993 peer_info_get_short (const GNUNET_PEER_Id peer)
1994 {
1995   struct GNUNET_PeerIdentity id;
1996
1997   GNUNET_PEER_resolve (peer, &id);
1998   return peer_info_get (&id);
1999 }
2000
2001
2002 /**
2003  * Iterator to remove the tunnel from the list of tunnels a peer participates
2004  * in.
2005  *
2006  * @param cls Closure (tunnel info)
2007  * @param key GNUNET_PeerIdentity of the peer (unused)
2008  * @param value PeerInfo of the peer
2009  *
2010  * @return always GNUNET_YES, to keep iterating
2011  */
2012 static int
2013 peer_info_delete_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
2014 {
2015   struct MeshTunnel *t = cls;
2016   struct MeshPeerInfo *peer = value;
2017   unsigned int i;
2018
2019   for (i = 0; i < peer->ntunnels; i++)
2020   {
2021     if (0 ==
2022         memcmp (&peer->tunnels[i]->id, &t->id, sizeof (struct MESH_TunnelID)))
2023     {
2024       peer->ntunnels--;
2025       peer->tunnels[i] = peer->tunnels[peer->ntunnels];
2026       peer->tunnels = GNUNET_realloc (peer->tunnels, peer->ntunnels);
2027       return GNUNET_YES;
2028     }
2029   }
2030   return GNUNET_YES;
2031 }
2032
2033
2034 /**
2035   * Core callback to write a pre-constructed data packet to core buffer
2036   *
2037   * @param cls Closure (MeshTransmissionDescriptor with data in "data" member).
2038   * @param size Number of bytes available in buf.
2039   * @param buf Where the to write the message.
2040   *
2041   * @return number of bytes written to buf
2042   */
2043 static size_t
2044 send_core_data_raw (void *cls, size_t size, void *buf)
2045 {
2046   struct MeshTransmissionDescriptor *info = cls;
2047   struct GNUNET_MessageHeader *msg;
2048   size_t total_size;
2049
2050   GNUNET_assert (NULL != info);
2051   GNUNET_assert (NULL != info->mesh_data);
2052   msg = (struct GNUNET_MessageHeader *) info->mesh_data->data;
2053   total_size = ntohs (msg->size);
2054
2055   if (total_size > size)
2056   {
2057     GNUNET_break (0);
2058     return 0;
2059   }
2060   memcpy (buf, msg, total_size);
2061   data_descriptor_decrement_rc (info->mesh_data);
2062   GNUNET_free (info);
2063   return total_size;
2064 }
2065
2066
2067 /**
2068  * Sends an already built non-multicast message to a peer,
2069  * properly registrating all used resources.
2070  *
2071  * @param message Message to send. Function makes a copy of it.
2072  * @param peer Short ID of the neighbor whom to send the message.
2073  * @param t Tunnel on which this message is transmitted.
2074  */
2075 static void
2076 send_prebuilt_message (const struct GNUNET_MessageHeader *message,
2077                        const struct GNUNET_PeerIdentity *peer,
2078                        struct MeshTunnel *t)
2079 {
2080   struct MeshTransmissionDescriptor *info;
2081   struct MeshPeerInfo *neighbor;
2082   struct MeshPeerPath *p;
2083   size_t size;
2084   uint16_t type;
2085
2086 //   GNUNET_TRANSPORT_try_connect(); FIXME use?
2087
2088   size = ntohs (message->size);
2089   info = GNUNET_malloc (sizeof (struct MeshTransmissionDescriptor));
2090   info->mesh_data = GNUNET_malloc (sizeof (struct MeshData));
2091   info->mesh_data->data = GNUNET_malloc (size);
2092   memcpy (info->mesh_data->data, message, size);
2093   type = ntohs(message->type);
2094   switch (type)
2095   {
2096     struct GNUNET_MESH_Unicast *m;
2097     struct GNUNET_MESH_ToOrigin *to;
2098
2099     case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
2100       m = (struct GNUNET_MESH_Unicast *) info->mesh_data->data;
2101       m->ttl = htonl (ntohl (m->ttl) - 1);
2102       break;
2103     case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
2104       to = (struct GNUNET_MESH_ToOrigin *) info->mesh_data->data;
2105       t->bck_pid++;
2106       to->pid = htonl(t->bck_pid);
2107   }
2108   info->mesh_data->data_len = size;
2109   info->mesh_data->reference_counter = 1;
2110   info->mesh_data->total_out = 1;
2111   neighbor = peer_info_get (peer);
2112   for (p = neighbor->path_head; NULL != p; p = p->next)
2113   {
2114     if (2 >= p->length)
2115     {
2116       break;
2117     }
2118   }
2119   if (NULL == p)
2120   {
2121 #if MESH_DEBUG
2122     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2123                 "  %s IS NOT DIRECTLY CONNECTED\n",
2124                 GNUNET_i2s(peer));
2125     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2126                 "  PATHS TO %s:\n",
2127                 GNUNET_i2s(peer));
2128     for (p = neighbor->path_head; NULL != p; p = p->next)
2129     {
2130       struct GNUNET_PeerIdentity debug_id;
2131       unsigned int i;
2132
2133       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2134                   "    path with %u hops through:\n",
2135                   p->length);
2136       for (i = 0; i < p->length; i++)
2137       {
2138         GNUNET_PEER_resolve(p->peers[i], &debug_id);
2139         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2140                     "      hop %u: %s\n",
2141                     i, GNUNET_i2s(&debug_id));
2142       }
2143     }
2144 #endif
2145     GNUNET_break (0); // FIXME sometimes fails (testing disconnect?)
2146     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2147                     " no direct connection to %s\n",
2148                     GNUNET_i2s (peer));
2149     GNUNET_free (info->mesh_data->data);
2150     GNUNET_free (info->mesh_data);
2151     GNUNET_free (info);
2152     return;
2153   }
2154   info->peer = neighbor;
2155   if (GNUNET_MESSAGE_TYPE_MESH_PATH_ACK == type)
2156     type = 0;
2157   queue_add (info,
2158              type,
2159              size,
2160              neighbor,
2161              t);
2162 }
2163
2164
2165 /**
2166  * Sends a CREATE PATH message for a path to a peer, properly registrating
2167  * all used resources.
2168  *
2169  * @param peer PeerInfo of the final peer for whom this path is being created.
2170  * @param p Path itself.
2171  * @param t Tunnel for which the path is created.
2172  */
2173 static void
2174 send_create_path (struct MeshPeerInfo *peer, struct MeshPeerPath *p,
2175                   struct MeshTunnel *t)
2176 {
2177   struct GNUNET_PeerIdentity id;
2178   struct MeshPathInfo *path_info;
2179   struct MeshPeerInfo *neighbor;
2180
2181   unsigned int i;
2182
2183   if (NULL == p)
2184   {
2185     p = tree_get_path_to_peer (t->tree, peer->id);
2186     if (NULL == p)
2187     {
2188       GNUNET_break (0);
2189       return;
2190     }
2191   }
2192   for (i = 0; i < p->length; i++)
2193   {
2194     if (p->peers[i] == myid)
2195       break;
2196   }
2197   if (i >= p->length - 1)
2198   {
2199     path_destroy (p);
2200     GNUNET_break (0);
2201     return;
2202   }
2203   GNUNET_PEER_resolve (p->peers[i + 1], &id);
2204
2205   path_info = GNUNET_malloc (sizeof (struct MeshPathInfo));
2206   path_info->path = p;
2207   path_info->t = t;
2208   neighbor = peer_info_get (&id);
2209   path_info->peer = neighbor;
2210   queue_add (path_info,
2211              GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE,
2212              sizeof (struct GNUNET_MESH_ManipulatePath) +
2213                 (p->length * sizeof (struct GNUNET_PeerIdentity)),
2214              neighbor,
2215              t);
2216 }
2217
2218
2219 /**
2220  * Sends a DESTROY PATH message to free resources for a path in a tunnel
2221  *
2222  * @param t Tunnel whose path to destroy.
2223  * @param destination Short ID of the peer to whom the path to destroy.
2224  */
2225 static void
2226 send_destroy_path (struct MeshTunnel *t, GNUNET_PEER_Id destination)
2227 {
2228   struct MeshPeerPath *p;
2229   size_t size;
2230
2231   p = tree_get_path_to_peer (t->tree, destination);
2232   if (NULL == p)
2233   {
2234     GNUNET_break (0);
2235     return;
2236   }
2237   size = sizeof (struct GNUNET_MESH_ManipulatePath);
2238   size += p->length * sizeof (struct GNUNET_PeerIdentity);
2239   {
2240     struct GNUNET_MESH_ManipulatePath *msg;
2241     struct GNUNET_PeerIdentity *pi;
2242     char cbuf[size];
2243     unsigned int i;
2244
2245     msg = (struct GNUNET_MESH_ManipulatePath *) cbuf;
2246     msg->header.size = htons (size);
2247     msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY);
2248     msg->tid = htonl (t->id.tid);
2249     pi = (struct GNUNET_PeerIdentity *) &msg[1];
2250     for (i = 0; i < p->length; i++)
2251     {
2252       GNUNET_PEER_resolve (p->peers[i], &pi[i]);
2253     }
2254     send_prebuilt_message (&msg->header, tree_get_first_hop (t->tree, destination), t);
2255   }
2256   path_destroy (p);
2257 }
2258
2259
2260 /**
2261  * Sends a PATH ACK message in reponse to a received PATH_CREATE directed to us.
2262  *
2263  * @param t Tunnel which to confirm.
2264  */
2265 static void
2266 send_path_ack (struct MeshTunnel *t) 
2267 {
2268   struct MeshTransmissionDescriptor *info;
2269   struct GNUNET_PeerIdentity id;
2270   GNUNET_PEER_Id peer;
2271
2272   peer = tree_get_predecessor (t->tree);
2273   GNUNET_PEER_resolve (peer, &id);
2274   info = GNUNET_malloc (sizeof (struct MeshTransmissionDescriptor));
2275   info->origin = &t->id;
2276   info->peer = GNUNET_CONTAINER_multihashmap_get (peers, &id.hashPubKey);
2277   GNUNET_assert (NULL != info->peer);
2278
2279   queue_add (info,
2280              GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
2281              sizeof (struct GNUNET_MESH_PathACK),
2282              info->peer,
2283              t);
2284 }
2285
2286
2287 /**
2288  * Try to establish a new connection to this peer.
2289  * Use the best path for the given tunnel.
2290  * If the peer doesn't have any path to it yet, try to get one.
2291  * If the peer already has some path, send a CREATE PATH towards it.
2292  *
2293  * @param peer PeerInfo of the peer.
2294  * @param t Tunnel for which to create the path, if possible.
2295  */
2296 static void
2297 peer_info_connect (struct MeshPeerInfo *peer, struct MeshTunnel *t)
2298 {
2299   struct MeshPeerPath *p;
2300   struct MeshPathInfo *path_info;
2301
2302   if (NULL != peer->path_head)
2303   {
2304     p = tree_get_path_to_peer (t->tree, peer->id);
2305     if (NULL == p)
2306     {
2307       GNUNET_break (0);
2308       return;
2309     }
2310
2311     // FIXME always send create path to self
2312     if (p->length > 1)
2313     {
2314       send_create_path (peer, p, t);
2315     }
2316     else
2317     {
2318       struct GNUNET_HashCode hash;
2319
2320       path_destroy (p);
2321       send_client_peer_connected (t, myid);
2322       t->local_tid_dest = next_local_tid++;
2323       GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber),
2324                           &hash);
2325       if (GNUNET_OK !=
2326           GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
2327                                              GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2328       {
2329         GNUNET_break (0);
2330         return;
2331       }
2332     }
2333   }
2334   else if (NULL == peer->dhtget)
2335   {
2336     struct GNUNET_PeerIdentity id;
2337
2338     GNUNET_PEER_resolve (peer->id, &id);
2339     path_info = GNUNET_malloc (sizeof (struct MeshPathInfo));
2340     path_info->peer = peer;
2341     path_info->t = t;
2342     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2343                 "  Starting DHT GET for peer %s\n", GNUNET_i2s (&id));
2344     peer->dhtgetcls = path_info;
2345     peer->dhtget = GNUNET_DHT_get_start (dht_handle,    /* handle */
2346                                          GNUNET_BLOCK_TYPE_MESH_PEER, /* type */
2347                                          &id.hashPubKey,     /* key to search */
2348                                          dht_replication_level, /* replication level */
2349                                          GNUNET_DHT_RO_RECORD_ROUTE |
2350                                          GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
2351                                          NULL,       /* xquery */ // FIXME BLOOMFILTER
2352                                          0,     /* xquery bits */ // FIXME BLOOMFILTER SIZE
2353                                          &dht_get_id_handler, path_info);
2354   }
2355   /* Otherwise, there is no path but the DHT get is already started. */
2356 }
2357
2358
2359 /**
2360  * Task to delay the connection of a peer
2361  *
2362  * @param cls Closure (path info with tunnel and peer to connect).
2363  *            Will be free'd on exection.
2364  * @param tc TaskContext
2365  */
2366 static void
2367 peer_info_connect_task (void *cls,
2368                         const struct GNUNET_SCHEDULER_TaskContext *tc)
2369 {
2370   struct MeshPathInfo *path_info = cls;
2371
2372   path_info->peer->connect_task = GNUNET_SCHEDULER_NO_TASK;
2373
2374   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2375   {
2376     GNUNET_free (cls);
2377     return;
2378   }
2379   peer_info_connect (path_info->peer, path_info->t);
2380   GNUNET_free (cls);
2381 }
2382
2383
2384 /**
2385  * Destroy the peer_info and free any allocated resources linked to it
2386  *
2387  * @param pi The peer_info to destroy.
2388  *
2389  * @return GNUNET_OK on success
2390  */
2391 static int
2392 peer_info_destroy (struct MeshPeerInfo *pi)
2393 {
2394   struct GNUNET_PeerIdentity id;
2395   struct MeshPeerPath *p;
2396   struct MeshPeerPath *nextp;
2397
2398   GNUNET_PEER_resolve (pi->id, &id);
2399   GNUNET_PEER_change_rc (pi->id, -1);
2400
2401   if (GNUNET_YES !=
2402       GNUNET_CONTAINER_multihashmap_remove (peers, &id.hashPubKey, pi))
2403   {
2404     GNUNET_break (0);
2405     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2406                 "removing peer %s, not in hashmap\n", GNUNET_i2s (&id));
2407   }
2408   if (NULL != pi->dhtget)
2409   {
2410     GNUNET_DHT_get_stop (pi->dhtget);
2411     GNUNET_free (pi->dhtgetcls);
2412   }
2413   p = pi->path_head;
2414   while (NULL != p)
2415   {
2416     nextp = p->next;
2417     GNUNET_CONTAINER_DLL_remove (pi->path_head, pi->path_tail, p);
2418     path_destroy (p);
2419     p = nextp;
2420   }
2421   if (GNUNET_SCHEDULER_NO_TASK != pi->connect_task)
2422   {
2423     GNUNET_free (GNUNET_SCHEDULER_cancel (pi->connect_task));
2424   }
2425   GNUNET_free (pi);
2426   return GNUNET_OK;
2427 }
2428
2429
2430 /**
2431  * Remove all paths that rely on a direct connection between p1 and p2
2432  * from the peer itself and notify all tunnels about it.
2433  *
2434  * @param peer PeerInfo of affected peer.
2435  * @param p1 GNUNET_PEER_Id of one peer.
2436  * @param p2 GNUNET_PEER_Id of another peer that was connected to the first and
2437  *           no longer is.
2438  *
2439  * TODO: optimize (see below)
2440  */
2441 static void
2442 peer_info_remove_path (struct MeshPeerInfo *peer, GNUNET_PEER_Id p1,
2443                        GNUNET_PEER_Id p2)
2444 {
2445   struct MeshPeerPath *p;
2446   struct MeshPeerPath *aux;
2447   struct MeshPeerInfo *peer_d;
2448   GNUNET_PEER_Id d;
2449   unsigned int destroyed;
2450   unsigned int best;
2451   unsigned int cost;
2452   unsigned int i;
2453
2454   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "peer_info_remove_path\n");
2455   destroyed = 0;
2456   p = peer->path_head;
2457   while (NULL != p)
2458   {
2459     aux = p->next;
2460     for (i = 0; i < (p->length - 1); i++)
2461     {
2462       if ((p->peers[i] == p1 && p->peers[i + 1] == p2) ||
2463           (p->peers[i] == p2 && p->peers[i + 1] == p1))
2464       {
2465         GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, p);
2466         path_destroy (p);
2467         destroyed++;
2468         break;
2469       }
2470     }
2471     p = aux;
2472   }
2473   if (0 == destroyed)
2474     return;
2475
2476   for (i = 0; i < peer->ntunnels; i++)
2477   {
2478     d = tunnel_notify_connection_broken (peer->tunnels[i], p1, p2);
2479     if (0 == d)
2480       continue;
2481     /* TODO
2482      * Problem: one or more peers have been deleted from the tunnel tree.
2483      * We don't know who they are to try to add them again.
2484      * We need to try to find a new path for each of the disconnected peers.
2485      * Some of them might already have a path to reach them that does not
2486      * involve p1 and p2. Adding all anew might render in a better tree than
2487      * the trivial immediate fix.
2488      *
2489      * Trivial immiediate fix: try to reconnect to the disconnected node. All
2490      * its children will be reachable trough him.
2491      */
2492     peer_d = peer_info_get_short (d);
2493     best = UINT_MAX;
2494     aux = NULL;
2495     for (p = peer_d->path_head; NULL != p; p = p->next)
2496     {
2497       if ((cost = tree_get_path_cost (peer->tunnels[i]->tree, p)) < best)
2498       {
2499         best = cost;
2500         aux = p;
2501       }
2502     }
2503     if (NULL != aux)
2504     {
2505       /* No callback, as peer will be already disconnected and a connection
2506        * scheduled by tunnel_notify_connection_broken.
2507        */
2508       tree_add_path (peer->tunnels[i]->tree, aux, NULL, NULL);
2509     }
2510     else
2511     {
2512       peer_info_connect (peer_d, peer->tunnels[i]);
2513     }
2514   }
2515   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "peer_info_remove_path END\n");
2516 }
2517
2518
2519 /**
2520  * Add the path to the peer and update the path used to reach it in case this
2521  * is the shortest.
2522  *
2523  * @param peer_info Destination peer to add the path to.
2524  * @param path New path to add. Last peer must be the peer in arg 1.
2525  *             Path will be either used of freed if already known.
2526  * @param trusted Do we trust that this path is real?
2527  */
2528 void
2529 peer_info_add_path (struct MeshPeerInfo *peer_info, struct MeshPeerPath *path,
2530                     int trusted)
2531 {
2532   struct MeshPeerPath *aux;
2533   unsigned int l;
2534   unsigned int l2;
2535
2536   if ((NULL == peer_info) || (NULL == path))
2537   {
2538     GNUNET_break (0);
2539     path_destroy (path);
2540     return;
2541   }
2542   if (path->peers[path->length - 1] != peer_info->id)
2543   {
2544     GNUNET_break (0);
2545     path_destroy (path);
2546     return;
2547   }
2548   if (path->length <= 2 && GNUNET_NO == trusted)
2549   {
2550     /* Only allow CORE to tell us about direct paths */
2551     path_destroy (path);
2552     return;
2553   }
2554   GNUNET_assert (peer_info->id == path->peers[path->length - 1]);
2555   for (l = 1; l < path->length; l++)
2556   {
2557     if (path->peers[l] == myid)
2558     {
2559       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shortening path by %u\n", l);
2560       for (l2 = 0; l2 < path->length - l; l2++)
2561       {
2562         path->peers[l2] = path->peers[l + l2];
2563       }
2564       path->length -= l;
2565       l = 1;
2566       path->peers =
2567           GNUNET_realloc (path->peers, path->length * sizeof (GNUNET_PEER_Id));
2568     }
2569   }
2570 #if MESH_DEBUG
2571   {
2572     struct GNUNET_PeerIdentity id;
2573
2574     GNUNET_PEER_resolve (peer_info->id, &id);
2575     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "adding path [%u] to peer %s\n",
2576                 path->length, GNUNET_i2s (&id));
2577   }
2578 #endif
2579   l = path_get_length (path);
2580   if (0 == l)
2581   {
2582     GNUNET_free (path);
2583     return;
2584   }
2585
2586   GNUNET_assert (peer_info->id == path->peers[path->length - 1]);
2587   for (aux = peer_info->path_head; aux != NULL; aux = aux->next)
2588   {
2589     l2 = path_get_length (aux);
2590     if (l2 > l)
2591     {
2592       GNUNET_CONTAINER_DLL_insert_before (peer_info->path_head,
2593                                           peer_info->path_tail, aux, path);
2594       return;
2595     }
2596     else
2597     {
2598       if (l2 == l && memcmp (path->peers, aux->peers, l) == 0)
2599       {
2600         path_destroy (path);
2601         return;
2602       }
2603     }
2604   }
2605   GNUNET_CONTAINER_DLL_insert_tail (peer_info->path_head, peer_info->path_tail,
2606                                     path);
2607   return;
2608 }
2609
2610
2611 /**
2612  * Add the path to the origin peer and update the path used to reach it in case
2613  * this is the shortest.
2614  * The path is given in peer_info -> destination, therefore we turn the path
2615  * upside down first.
2616  *
2617  * @param peer_info Peer to add the path to, being the origin of the path.
2618  * @param path New path to add after being inversed.
2619  * @param trusted Do we trust that this path is real?
2620  */
2621 static void
2622 peer_info_add_path_to_origin (struct MeshPeerInfo *peer_info,
2623                               struct MeshPeerPath *path, int trusted)
2624 {
2625   path_invert (path);
2626   peer_info_add_path (peer_info, path, trusted);
2627 }
2628
2629
2630 /**
2631  * Function called if the connection to the peer has been stalled for a while,
2632  * possibly due to a missed ACK. Poll the peer about its ACK status.
2633  *
2634  * @param cls Closure (cinfo).
2635  * @param tc TaskContext.
2636  */
2637 static void
2638 tunnel_poll (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2639 {
2640   struct MeshTunnelChildInfo *cinfo = cls;
2641   struct GNUNET_MESH_Poll msg;
2642   struct GNUNET_PeerIdentity id;
2643   struct MeshTunnel *t;
2644
2645   cinfo->fc_poll = GNUNET_SCHEDULER_NO_TASK;
2646   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2647   {
2648     return;
2649   }
2650
2651   t = cinfo->t;
2652   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_POLL);
2653   msg.header.size = htons (sizeof (msg));
2654   msg.tid = htonl (t->id.tid);
2655   GNUNET_PEER_resolve (t->id.oid, &msg.oid);
2656   msg.last_ack = htonl (cinfo->fwd_ack);
2657
2658   GNUNET_PEER_resolve (cinfo->id, &id);
2659   send_prebuilt_message (&msg.header, &id, cinfo->t);
2660   cinfo->fc_poll_time = GNUNET_TIME_relative_min (
2661     MESH_MAX_POLL_TIME,
2662     GNUNET_TIME_relative_multiply (cinfo->fc_poll_time, 2));
2663   cinfo->fc_poll = GNUNET_SCHEDULER_add_delayed (cinfo->fc_poll_time,
2664                                                  &tunnel_poll, cinfo);
2665 }
2666
2667
2668 /**
2669  * Build a PeerPath from the paths returned from the DHT, reversing the paths
2670  * to obtain a local peer -> destination path and interning the peer ids.
2671  *
2672  * @return Newly allocated and created path
2673  */
2674 static struct MeshPeerPath *
2675 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
2676                      unsigned int get_path_length,
2677                      const struct GNUNET_PeerIdentity *put_path,
2678                      unsigned int put_path_length)
2679 {
2680   struct MeshPeerPath *p;
2681   GNUNET_PEER_Id id;
2682   int i;
2683
2684   p = path_new (1);
2685   p->peers[0] = myid;
2686   GNUNET_PEER_change_rc (myid, 1);
2687   i = get_path_length;
2688   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   GET has %d hops.\n", i);
2689   for (i--; i >= 0; i--)
2690   {
2691     id = GNUNET_PEER_intern (&get_path[i]);
2692     if (p->length > 0 && id == p->peers[p->length - 1])
2693     {
2694       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Optimizing 1 hop out.\n");
2695       GNUNET_PEER_change_rc (id, -1);
2696     }
2697     else
2698     {
2699       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Adding from GET: %s.\n",
2700                   GNUNET_i2s (&get_path[i]));
2701       p->length++;
2702       p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
2703       p->peers[p->length - 1] = id;
2704     }
2705   }
2706   i = put_path_length;
2707   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   PUT has %d hops.\n", i);
2708   for (i--; i >= 0; i--)
2709   {
2710     id = GNUNET_PEER_intern (&put_path[i]);
2711     if (id == myid)
2712     {
2713       /* PUT path went through us, so discard the path up until now and start
2714        * from here to get a much shorter (and loop-free) path.
2715        */
2716       path_destroy (p);
2717       p = path_new (0);
2718     }
2719     if (p->length > 0 && id == p->peers[p->length - 1])
2720     {
2721       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Optimizing 1 hop out.\n");
2722       GNUNET_PEER_change_rc (id, -1);
2723     }
2724     else
2725     {
2726       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Adding from PUT: %s.\n",
2727                   GNUNET_i2s (&put_path[i]));
2728       p->length++;
2729       p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
2730       p->peers[p->length - 1] = id;
2731     }
2732   }
2733 #if MESH_DEBUG
2734   if (get_path_length > 0)
2735     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (first of GET: %s)\n",
2736                 GNUNET_i2s (&get_path[0]));
2737   if (put_path_length > 0)
2738     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (first of PUT: %s)\n",
2739                 GNUNET_i2s (&put_path[0]));
2740   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   In total: %d hops\n",
2741               p->length);
2742   for (i = 0; i < p->length; i++)
2743   {
2744     struct GNUNET_PeerIdentity peer_id;
2745
2746     GNUNET_PEER_resolve (p->peers[i], &peer_id);
2747     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "       %u: %s\n", p->peers[i],
2748                 GNUNET_i2s (&peer_id));
2749   }
2750 #endif
2751   return p;
2752 }
2753
2754
2755 /**
2756  * Adds a path to the peer_infos of all the peers in the path
2757  *
2758  * @param p Path to process.
2759  * @param confirmed Whether we know if the path works or not.
2760  */
2761 static void
2762 path_add_to_peers (struct MeshPeerPath *p, int confirmed)
2763 {
2764   unsigned int i;
2765
2766   /* TODO: invert and add */
2767   for (i = 0; i < p->length && p->peers[i] != myid; i++) /* skip'em */ ;
2768   for (i++; i < p->length; i++)
2769   {
2770     struct MeshPeerInfo *aux;
2771     struct MeshPeerPath *copy;
2772
2773     aux = peer_info_get_short (p->peers[i]);
2774     copy = path_duplicate (p);
2775     copy->length = i + 1;
2776     peer_info_add_path (aux, copy, GNUNET_NO);
2777   }
2778 }
2779
2780
2781 /**
2782  * Send keepalive packets for a peer
2783  *
2784  * @param cls Closure (tunnel for which to send the keepalive).
2785  * @param tc Notification context.
2786  *
2787  * TODO: implement explicit multicast keepalive?
2788  */
2789 static void
2790 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
2791
2792
2793 /**
2794  * Search for a tunnel among the incoming tunnels
2795  *
2796  * @param tid the local id of the tunnel
2797  *
2798  * @return tunnel handler, NULL if doesn't exist
2799  */
2800 static struct MeshTunnel *
2801 tunnel_get_incoming (MESH_TunnelNumber tid)
2802 {
2803   struct GNUNET_HashCode hash;
2804
2805   GNUNET_assert (tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV);
2806   GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
2807   return GNUNET_CONTAINER_multihashmap_get (incoming_tunnels, &hash);
2808 }
2809
2810
2811 /**
2812  * Search for a tunnel among the tunnels for a client
2813  *
2814  * @param c the client whose tunnels to search in
2815  * @param tid the local id of the tunnel
2816  *
2817  * @return tunnel handler, NULL if doesn't exist
2818  */
2819 static struct MeshTunnel *
2820 tunnel_get_by_local_id (struct MeshClient *c, MESH_TunnelNumber tid)
2821 {
2822   if (tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
2823   {
2824     return tunnel_get_incoming (tid);
2825   }
2826   else
2827   {
2828     struct GNUNET_HashCode hash;
2829
2830     GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
2831     return GNUNET_CONTAINER_multihashmap_get (c->own_tunnels, &hash);
2832   }
2833 }
2834
2835
2836 /**
2837  * Search for a tunnel by global ID using PEER_ID
2838  *
2839  * @param pi owner of the tunnel
2840  * @param tid global tunnel number
2841  *
2842  * @return tunnel handler, NULL if doesn't exist
2843  */
2844 static struct MeshTunnel *
2845 tunnel_get_by_pi (GNUNET_PEER_Id pi, MESH_TunnelNumber tid)
2846 {
2847   struct MESH_TunnelID id;
2848   struct GNUNET_HashCode hash;
2849
2850   id.oid = pi;
2851   id.tid = tid;
2852
2853   GNUNET_CRYPTO_hash (&id, sizeof (struct MESH_TunnelID), &hash);
2854   return GNUNET_CONTAINER_multihashmap_get (tunnels, &hash);
2855 }
2856
2857
2858 /**
2859  * Search for a tunnel by global ID using full PeerIdentities
2860  *
2861  * @param oid owner of the tunnel
2862  * @param tid global tunnel number
2863  *
2864  * @return tunnel handler, NULL if doesn't exist
2865  */
2866 static struct MeshTunnel *
2867 tunnel_get (const struct GNUNET_PeerIdentity *oid, MESH_TunnelNumber tid)
2868 {
2869   return tunnel_get_by_pi (GNUNET_PEER_search (oid), tid);
2870 }
2871
2872
2873 /**
2874  * Delete an active client from the tunnel.
2875  * 
2876  * @param t Tunnel.
2877  * @param c Client.
2878  */
2879 static void
2880 tunnel_delete_active_client (struct MeshTunnel *t, const struct MeshClient *c)
2881 {
2882   unsigned int i;
2883
2884   for (i = 0; i < t->nclients; i++)
2885   {
2886     if (t->clients[i] == c)
2887     {
2888       t->clients[i] = t->clients[t->nclients - 1];
2889       t->clients_fc[i] = t->clients_fc[t->nclients - 1];
2890       GNUNET_array_grow (t->clients, t->nclients, t->nclients - 1);
2891       t->nclients++;
2892       GNUNET_array_grow (t->clients_fc, t->nclients, t->nclients - 1);
2893       break;
2894     }
2895   }
2896 }
2897
2898
2899 /**
2900  * Delete an ignored client from the tunnel.
2901  * 
2902  * @param t Tunnel.
2903  * @param c Client.
2904  */
2905 static void
2906 tunnel_delete_ignored_client (struct MeshTunnel *t, const struct MeshClient *c)
2907 {
2908   unsigned int i;
2909
2910   for (i = 0; i < t->nignore; i++)
2911   {
2912     if (t->ignore[i] == c)
2913     {
2914       t->ignore[i] = t->ignore[t->nignore - 1];
2915       GNUNET_array_grow (t->ignore, t->nignore, t->nignore - 1);
2916       break;
2917     }
2918   }
2919 }
2920
2921
2922 /**
2923  * Delete a client from the tunnel. It should be only done on
2924  * client disconnection, otherwise use client_ignore_tunnel.
2925  * 
2926  * @param t Tunnel.
2927  * @param c Client.
2928  */
2929 static void
2930 tunnel_delete_client (struct MeshTunnel *t, const struct MeshClient *c)
2931 {
2932   tunnel_delete_ignored_client (t, c);
2933   tunnel_delete_active_client (t, c);
2934 }
2935
2936
2937 /**
2938  * @brief Iterator to destroy MeshTunnelChildInfo of tunnel children.
2939  * 
2940  * Destroys queue elements of all waiting transmissions and frees all memory
2941  * used by the struct and its elements.
2942  *
2943  * @param cls Closure (tunnel info).
2944  * @param key Hash of GNUNET_PEER_Id (unused).
2945  * @param value MeshTunnelChildInfo of the child.
2946  *
2947  * @return always GNUNET_YES, to keep iterating
2948  */
2949 static int
2950 tunnel_destroy_child (void *cls,
2951                       const struct GNUNET_HashCode * key,
2952                       void *value)
2953 {
2954   struct MeshTunnelChildInfo *cinfo = value;
2955   struct MeshTunnel *t = cls;
2956   struct MeshPeerQueue *q;
2957   unsigned int c;
2958   unsigned int i;
2959
2960   for (c = 0; c < cinfo->send_buffer_n; c++)
2961   {
2962     i = (cinfo->send_buffer_start + c) % t->fwd_queue_max;
2963     q = cinfo->send_buffer[i];
2964     cinfo->send_buffer[i] = NULL;
2965     if (NULL != q)
2966       queue_destroy (q, GNUNET_YES);
2967     else
2968       GNUNET_break (0);
2969     GNUNET_log (GNUNET_ERROR_TYPE_INFO, "%u %u\n", c, cinfo->send_buffer_n);
2970   }
2971   GNUNET_free_non_null (cinfo->send_buffer);
2972   if (GNUNET_SCHEDULER_NO_TASK != cinfo->fc_poll)
2973   {
2974     GNUNET_SCHEDULER_cancel (cinfo->fc_poll);
2975     cinfo->fc_poll = GNUNET_SCHEDULER_NO_TASK;
2976   }
2977   GNUNET_free (cinfo);
2978   return GNUNET_YES;
2979 }
2980
2981
2982 /**
2983  * Callback used to notify a client owner of a tunnel that a peer has
2984  * disconnected, most likely because of a path change.
2985  *
2986  * @param cls Closure (tunnel this notification is about).
2987  * @param peer_id Short ID of disconnected peer.
2988  */
2989 void
2990 tunnel_notify_client_peer_disconnected (void *cls, GNUNET_PEER_Id peer_id)
2991 {
2992   struct MeshTunnel *t = cls;
2993   struct MeshPeerInfo *peer;
2994   struct MeshPathInfo *path_info;
2995
2996   client_notify_peer_disconnected (t->owner, t, peer_id);
2997
2998   peer = peer_info_get_short (peer_id);
2999   path_info = GNUNET_malloc (sizeof (struct MeshPathInfo));
3000   path_info->peer = peer;
3001   path_info->t = t;
3002   peer->connect_task = GNUNET_SCHEDULER_add_now (&peer_info_connect_task,
3003                                                  path_info);
3004 }
3005
3006
3007 /**
3008  * Add a peer to a tunnel, accomodating paths accordingly and initializing all
3009  * needed rescources.
3010  * If peer already exists, reevaluate shortest path and change if different.
3011  *
3012  * @param t Tunnel we want to add a new peer to
3013  * @param peer PeerInfo of the peer being added
3014  *
3015  */
3016 static void
3017 tunnel_add_peer (struct MeshTunnel *t, struct MeshPeerInfo *peer)
3018 {
3019   struct GNUNET_PeerIdentity id;
3020   struct MeshPeerPath *best_p;
3021   struct MeshPeerPath *p;
3022   unsigned int best_cost;
3023   unsigned int cost;
3024
3025   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "tunnel_add_peer\n");
3026   GNUNET_PEER_resolve (peer->id, &id);
3027   if (GNUNET_NO ==
3028       GNUNET_CONTAINER_multihashmap_contains (t->peers, &id.hashPubKey))
3029   {
3030     t->peers_total++;
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  * @param atsi performance data
5066  * @param atsi_count number of records in 'atsi'
5067  *
5068  * @return GNUNET_OK to keep the connection open,
5069  *         GNUNET_SYSERR to close it (signal serious error)
5070  */
5071 static int
5072 handle_mesh_path_create (void *cls, const struct GNUNET_PeerIdentity *peer,
5073                          const struct GNUNET_MessageHeader *message,
5074                          const struct GNUNET_ATS_Information *atsi,
5075                          unsigned int atsi_count)
5076 {
5077   unsigned int own_pos;
5078   uint16_t size;
5079   uint16_t i;
5080   MESH_TunnelNumber tid;
5081   struct GNUNET_MESH_ManipulatePath *msg;
5082   struct GNUNET_PeerIdentity *pi;
5083   struct GNUNET_HashCode hash;
5084   struct MeshPeerPath *path;
5085   struct MeshPeerInfo *dest_peer_info;
5086   struct MeshPeerInfo *orig_peer_info;
5087   struct MeshTunnel *t;
5088
5089   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5090               "Received a path create msg [%s]\n",
5091               GNUNET_i2s (&my_full_id));
5092   size = ntohs (message->size);
5093   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
5094   {
5095     GNUNET_break_op (0);
5096     return GNUNET_OK;
5097   }
5098
5099   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
5100   if (size % sizeof (struct GNUNET_PeerIdentity))
5101   {
5102     GNUNET_break_op (0);
5103     return GNUNET_OK;
5104   }
5105   size /= sizeof (struct GNUNET_PeerIdentity);
5106   if (size < 2)
5107   {
5108     GNUNET_break_op (0);
5109     return GNUNET_OK;
5110   }
5111   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
5112   msg = (struct GNUNET_MESH_ManipulatePath *) message;
5113
5114   tid = ntohl (msg->tid);
5115   pi = (struct GNUNET_PeerIdentity *) &msg[1];
5116   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5117               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi), tid);
5118   t = tunnel_get (pi, tid);
5119   if (NULL == t) // FIXME only for INCOMING tunnels?
5120   {
5121     uint32_t opt;
5122
5123     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating tunnel\n");
5124     t = tunnel_new (GNUNET_PEER_intern (pi), tid, NULL, 0);
5125     if (NULL == t)
5126     {
5127       // FIXME notify failure
5128       return GNUNET_OK;
5129     }
5130     opt = ntohl (msg->opt);
5131     t->speed_min = (0 != (opt & MESH_TUNNEL_OPT_SPEED_MIN)) ?
5132                    GNUNET_YES : GNUNET_NO;
5133     if (0 != (opt & MESH_TUNNEL_OPT_NOBUFFER))
5134     {
5135       t->nobuffer = GNUNET_YES;
5136       t->last_fwd_ack = t->fwd_pid + 1;
5137     }
5138     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5139                 "  speed_min: %d, nobuffer:%d\n",
5140                 t->speed_min, t->nobuffer);
5141
5142     if (GNUNET_YES == t->nobuffer)
5143     {
5144       t->bck_queue_max = 1;
5145       t->fwd_queue_max = 1;
5146     }
5147
5148     // FIXME only assign a local tid if a local client is interested (on demand)
5149     while (NULL != tunnel_get_incoming (next_local_tid))
5150       next_local_tid = (next_local_tid + 1) | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
5151     t->local_tid_dest = next_local_tid++;
5152     next_local_tid = next_local_tid | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
5153     // FIXME end
5154
5155     tunnel_reset_timeout (t);
5156     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
5157     if (GNUNET_OK !=
5158         GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
5159                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
5160     {
5161       tunnel_destroy (t);
5162       GNUNET_break (0);
5163       return GNUNET_OK;
5164     }
5165   }
5166   dest_peer_info =
5167       GNUNET_CONTAINER_multihashmap_get (peers, &pi[size - 1].hashPubKey);
5168   if (NULL == dest_peer_info)
5169   {
5170     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5171                 "  Creating PeerInfo for destination.\n");
5172     dest_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
5173     dest_peer_info->id = GNUNET_PEER_intern (&pi[size - 1]);
5174     GNUNET_CONTAINER_multihashmap_put (peers, &pi[size - 1].hashPubKey,
5175                                        dest_peer_info,
5176                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
5177   }
5178   orig_peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &pi->hashPubKey);
5179   if (NULL == orig_peer_info)
5180   {
5181     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5182                 "  Creating PeerInfo for origin.\n");
5183     orig_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
5184     orig_peer_info->id = GNUNET_PEER_intern (pi);
5185     GNUNET_CONTAINER_multihashmap_put (peers, &pi->hashPubKey, orig_peer_info,
5186                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
5187   }
5188   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
5189   path = path_new (size);
5190   own_pos = 0;
5191   for (i = 0; i < size; i++)
5192   {
5193     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
5194                 GNUNET_i2s (&pi[i]));
5195     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
5196     if (path->peers[i] == myid)
5197       own_pos = i;
5198   }
5199   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
5200   if (own_pos == 0)
5201   {
5202     /* cannot be self, must be 'not found' */
5203     /* create path: self not found in path through self */
5204     GNUNET_break_op (0);
5205     path_destroy (path);
5206     tunnel_destroy (t);
5207     return GNUNET_OK;
5208   }
5209   path_add_to_peers (path, GNUNET_NO);
5210   tunnel_add_path (t, path, own_pos);
5211   if (own_pos == size - 1)
5212   {
5213     /* It is for us! Send ack. */
5214     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
5215     peer_info_add_path_to_origin (orig_peer_info, path, GNUNET_NO);
5216     if (NULL == t->peers)
5217     {
5218       /* New tunnel! Notify clients on first payload message. */
5219       t->peers = GNUNET_CONTAINER_multihashmap_create (4, GNUNET_NO);
5220     }
5221     GNUNET_break (GNUNET_SYSERR !=
5222                   GNUNET_CONTAINER_multihashmap_put (t->peers,
5223                                                      &my_full_id.hashPubKey,
5224                                                      peer_info_get
5225                                                      (&my_full_id),
5226                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE));
5227     send_path_ack (t);
5228   }
5229   else
5230   {
5231     struct MeshPeerPath *path2;
5232
5233     /* It's for somebody else! Retransmit. */
5234     path2 = path_duplicate (path);
5235     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Retransmitting.\n");
5236     peer_info_add_path (dest_peer_info, path2, GNUNET_NO);
5237     path2 = path_duplicate (path);
5238     peer_info_add_path_to_origin (orig_peer_info, path2, GNUNET_NO);
5239     send_create_path (dest_peer_info, path, t);
5240   }
5241   return GNUNET_OK;
5242 }
5243
5244
5245 /**
5246  * Core handler for path destruction
5247  *
5248  * @param cls closure
5249  * @param message message
5250  * @param peer peer identity this notification is about
5251  * @param atsi performance data
5252  * @param atsi_count number of records in 'atsi'
5253  *
5254  * @return GNUNET_OK to keep the connection open,
5255  *         GNUNET_SYSERR to close it (signal serious error)
5256  */
5257 static int
5258 handle_mesh_path_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
5259                           const struct GNUNET_MessageHeader *message,
5260                           const struct GNUNET_ATS_Information *atsi,
5261                           unsigned int atsi_count)
5262 {
5263   struct GNUNET_MESH_ManipulatePath *msg;
5264   struct GNUNET_PeerIdentity *pi;
5265   struct MeshPeerPath *path;
5266   struct MeshTunnel *t;
5267   unsigned int own_pos;
5268   unsigned int i;
5269   size_t size;
5270
5271   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5272               "Received a PATH DESTROY msg from %s\n", GNUNET_i2s (peer));
5273   size = ntohs (message->size);
5274   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
5275   {
5276     GNUNET_break_op (0);
5277     return GNUNET_OK;
5278   }
5279
5280   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
5281   if (size % sizeof (struct GNUNET_PeerIdentity))
5282   {
5283     GNUNET_break_op (0);
5284     return GNUNET_OK;
5285   }
5286   size /= sizeof (struct GNUNET_PeerIdentity);
5287   if (size < 2)
5288   {
5289     GNUNET_break_op (0);
5290     return GNUNET_OK;
5291   }
5292   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
5293
5294   msg = (struct GNUNET_MESH_ManipulatePath *) message;
5295   pi = (struct GNUNET_PeerIdentity *) &msg[1];
5296   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5297               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi),
5298               msg->tid);
5299   t = tunnel_get (pi, ntohl (msg->tid));
5300   if (NULL == t)
5301   {
5302     /* TODO notify back: we don't know this tunnel */
5303     GNUNET_break_op (0);
5304     return GNUNET_OK;
5305   }
5306   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
5307   path = path_new (size);
5308   own_pos = 0;
5309   for (i = 0; i < size; i++)
5310   {
5311     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
5312                 GNUNET_i2s (&pi[i]));
5313     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
5314     if (path->peers[i] == myid)
5315       own_pos = i;
5316   }
5317   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
5318   if (own_pos < path->length - 1)
5319     send_prebuilt_message (message, &pi[own_pos + 1], t);
5320   else
5321     send_client_tunnel_disconnect(t, NULL);
5322
5323   tunnel_delete_peer (t, path->peers[path->length - 1]);
5324   path_destroy (path);
5325   return GNUNET_OK;
5326 }
5327
5328
5329 /**
5330  * Core handler for notifications of broken paths
5331  *
5332  * @param cls closure
5333  * @param message message
5334  * @param peer peer identity this notification is about
5335  * @param atsi performance data
5336  * @param atsi_count number of records in 'atsi'
5337  *
5338  * @return GNUNET_OK to keep the connection open,
5339  *         GNUNET_SYSERR to close it (signal serious error)
5340  */
5341 static int
5342 handle_mesh_path_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
5343                          const struct GNUNET_MessageHeader *message,
5344                          const struct GNUNET_ATS_Information *atsi,
5345                          unsigned int atsi_count)
5346 {
5347   struct GNUNET_MESH_PathBroken *msg;
5348   struct MeshTunnel *t;
5349
5350   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5351               "Received a PATH BROKEN msg from %s\n", GNUNET_i2s (peer));
5352   msg = (struct GNUNET_MESH_PathBroken *) message;
5353   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
5354               GNUNET_i2s (&msg->peer1));
5355   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
5356               GNUNET_i2s (&msg->peer2));
5357   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5358   if (NULL == t)
5359   {
5360     GNUNET_break_op (0);
5361     return GNUNET_OK;
5362   }
5363   tunnel_notify_connection_broken (t, GNUNET_PEER_search (&msg->peer1),
5364                                    GNUNET_PEER_search (&msg->peer2));
5365   return GNUNET_OK;
5366
5367 }
5368
5369
5370 /**
5371  * Core handler for tunnel destruction
5372  *
5373  * @param cls closure
5374  * @param message message
5375  * @param peer peer identity this notification is about
5376  * @param atsi performance data
5377  * @param atsi_count number of records in 'atsi'
5378  *
5379  * @return GNUNET_OK to keep the connection open,
5380  *         GNUNET_SYSERR to close it (signal serious error)
5381  */
5382 static int
5383 handle_mesh_tunnel_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
5384                             const struct GNUNET_MessageHeader *message,
5385                             const struct GNUNET_ATS_Information *atsi,
5386                             unsigned int atsi_count)
5387 {
5388   struct GNUNET_MESH_TunnelDestroy *msg;
5389   struct MeshTunnel *t;
5390   GNUNET_PEER_Id parent;
5391   GNUNET_PEER_Id pid;
5392
5393   msg = (struct GNUNET_MESH_TunnelDestroy *) message;
5394   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5395               "Got a TUNNEL DESTROY packet from %s\n",
5396               GNUNET_i2s (peer));
5397   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5398               "  for tunnel %s [%u]\n",
5399               GNUNET_i2s (&msg->oid), ntohl (msg->tid));
5400   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5401   /* Check signature */
5402   if (NULL == t)
5403   {
5404     /* Probably already got the message from another path,
5405      * destroyed the tunnel and retransmitted to children.
5406      * Safe to ignore.
5407      */
5408     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel",
5409                               1, GNUNET_NO);
5410     return GNUNET_OK;
5411   }
5412   parent = tree_get_predecessor (t->tree);
5413   pid = GNUNET_PEER_search (peer);
5414   if (pid != parent)
5415   {
5416     unsigned int nc;
5417
5418     tree_del_peer (t->tree, pid, &tunnel_child_removed, t);
5419     nc = tree_count_children (t->tree);
5420     if (nc > 0 || NULL != t->owner || t->nclients > 0)
5421     {
5422       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5423                   "still in use: %u cl, %u ch\n",
5424                   t->nclients, nc);
5425       return GNUNET_OK;
5426     }
5427   }
5428   if (t->local_tid_dest >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
5429   {
5430     /* Tunnel was incoming, notify clients */
5431     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "INCOMING TUNNEL %X %X\n",
5432                 t->local_tid, t->local_tid_dest);
5433     send_clients_tunnel_destroy (t);
5434   }
5435   tunnel_send_destroy (t, parent);
5436   t->destroy = GNUNET_YES;
5437   // TODO: add timeout to destroy the tunnel anyway
5438   return GNUNET_OK;
5439 }
5440
5441
5442 /**
5443  * Core handler for mesh network traffic going from the origin to a peer
5444  *
5445  * @param cls closure
5446  * @param peer peer identity this notification is about
5447  * @param message message
5448  * @param atsi performance data
5449  * @param atsi_count number of records in 'atsi'
5450  * @return GNUNET_OK to keep the connection open,
5451  *         GNUNET_SYSERR to close it (signal serious error)
5452  */
5453 static int
5454 handle_mesh_data_unicast (void *cls, const struct GNUNET_PeerIdentity *peer,
5455                           const struct GNUNET_MessageHeader *message,
5456                           const struct GNUNET_ATS_Information *atsi,
5457                           unsigned int atsi_count)
5458 {
5459   struct GNUNET_MESH_Unicast *msg;
5460   struct GNUNET_PeerIdentity *neighbor;
5461   struct MeshTunnelChildInfo *cinfo;
5462   struct MeshTunnel *t;
5463   GNUNET_PEER_Id dest_id;
5464   uint32_t pid;
5465   uint32_t ttl;
5466   size_t size;
5467
5468   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a unicast packet from %s\n",
5469               GNUNET_i2s (peer));
5470   /* Check size */
5471   size = ntohs (message->size);
5472   if (size <
5473       sizeof (struct GNUNET_MESH_Unicast) +
5474       sizeof (struct GNUNET_MessageHeader))
5475   {
5476     GNUNET_break (0);
5477     return GNUNET_OK;
5478   }
5479   msg = (struct GNUNET_MESH_Unicast *) message;
5480   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %s\n",
5481               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
5482   /* Check tunnel */
5483   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5484   if (NULL == t)
5485   {
5486     /* TODO notify back: we don't know this tunnel */
5487     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
5488     GNUNET_break_op (0);
5489     return GNUNET_OK;
5490   }
5491   pid = ntohl (msg->pid);
5492   if (t->fwd_pid == pid)
5493   {
5494     GNUNET_STATISTICS_update (stats, "# duplicate PID drops", 1, GNUNET_NO);
5495     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5496                 " Already seen pid %u, DROPPING!\n", pid);
5497     return GNUNET_OK;
5498   }
5499   else
5500   {
5501     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5502                 " pid %u not seen yet, forwarding\n", pid);
5503   }
5504
5505   t->skip += (pid - t->fwd_pid) - 1;
5506   t->fwd_pid = pid;
5507
5508   if (GMC_is_pid_bigger (pid, t->last_fwd_ack))
5509   {
5510     GNUNET_STATISTICS_update (stats, "# unsolicited unicast", 1, GNUNET_NO);
5511     GNUNET_break_op (0);
5512     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5513                 "Received PID %u, ACK %u\n",
5514                 pid, t->last_fwd_ack);
5515     return GNUNET_OK;
5516   }
5517
5518   tunnel_reset_timeout (t);
5519   dest_id = GNUNET_PEER_search (&msg->destination);
5520   if (dest_id == myid)
5521   {
5522     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5523                 "  it's for us! sending to clients...\n");
5524     GNUNET_STATISTICS_update (stats, "# unicast received", 1, GNUNET_NO);
5525     send_subscribed_clients (message, &msg[1].header, t);
5526     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_UNICAST);
5527     return GNUNET_OK;
5528   }
5529   ttl = ntohl (msg->ttl);
5530   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ttl);
5531   if (ttl == 0)
5532   {
5533     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
5534     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
5535     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5536     return GNUNET_OK;
5537   }
5538   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5539               "  not for us, retransmitting...\n");
5540
5541   neighbor = tree_get_first_hop (t->tree, dest_id);
5542   cinfo = tunnel_get_neighbor_fc (t, neighbor);
5543   cinfo->fwd_pid = pid;
5544   GNUNET_CONTAINER_multihashmap_iterate (t->children_fc,
5545                                          &tunnel_add_skip,
5546                                          &neighbor);
5547   if (GNUNET_YES == t->nobuffer &&
5548       GNUNET_YES == GMC_is_pid_bigger (pid, cinfo->fwd_ack))
5549   {
5550     GNUNET_STATISTICS_update (stats, "# unsolicited unicast", 1, GNUNET_NO);
5551     GNUNET_log (GNUNET_ERROR_TYPE_INFO, "  %u > %u\n", pid, cinfo->fwd_ack);
5552     GNUNET_break_op (0);
5553     return GNUNET_OK;
5554   }
5555   send_prebuilt_message (message, neighbor, t);
5556   GNUNET_STATISTICS_update (stats, "# unicast forwarded", 1, GNUNET_NO);
5557   return GNUNET_OK;
5558 }
5559
5560
5561 /**
5562  * Core handler for mesh network traffic going from the origin to all peers
5563  *
5564  * @param cls closure
5565  * @param message message
5566  * @param peer peer identity this notification is about
5567  * @param atsi performance data
5568  * @param atsi_count number of records in 'atsi'
5569  * @return GNUNET_OK to keep the connection open,
5570  *         GNUNET_SYSERR to close it (signal serious error)
5571  *
5572  * TODO: Check who we got this from, to validate route.
5573  */
5574 static int
5575 handle_mesh_data_multicast (void *cls, const struct GNUNET_PeerIdentity *peer,
5576                             const struct GNUNET_MessageHeader *message,
5577                             const struct GNUNET_ATS_Information *atsi,
5578                             unsigned int atsi_count)
5579 {
5580   struct GNUNET_MESH_Multicast *msg;
5581   struct MeshTunnel *t;
5582   size_t size;
5583   uint32_t pid;
5584
5585   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a multicast packet from %s\n",
5586               GNUNET_i2s (peer));
5587   size = ntohs (message->size);
5588   if (sizeof (struct GNUNET_MESH_Multicast) +
5589       sizeof (struct GNUNET_MessageHeader) > size)
5590   {
5591     GNUNET_break_op (0);
5592     return GNUNET_OK;
5593   }
5594   msg = (struct GNUNET_MESH_Multicast *) message;
5595   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5596
5597   if (NULL == t)
5598   {
5599     /* TODO notify that we dont know that tunnel */
5600     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
5601     GNUNET_break_op (0);
5602     return GNUNET_OK;
5603   }
5604   pid = ntohl (msg->pid);
5605   if (t->fwd_pid == pid)
5606   {
5607     /* already seen this packet, drop */
5608     GNUNET_STATISTICS_update (stats, "# duplicate PID drops", 1, GNUNET_NO);
5609     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5610                 " Already seen pid %u, DROPPING!\n", pid);
5611     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5612     return GNUNET_OK;
5613   }
5614   else
5615   {
5616     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5617                 " pid %u not seen yet, forwarding\n", pid);
5618   }
5619   t->skip += (pid - t->fwd_pid) - 1;
5620   t->fwd_pid = pid;
5621   tunnel_reset_timeout (t);
5622
5623   /* Transmit to locally interested clients */
5624   if (NULL != t->peers &&
5625       GNUNET_CONTAINER_multihashmap_contains (t->peers, &my_full_id.hashPubKey))
5626   {
5627     GNUNET_STATISTICS_update (stats, "# multicast received", 1, GNUNET_NO);
5628     send_subscribed_clients (message, &msg[1].header, t);
5629     tunnel_send_fwd_ack(t, GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
5630   }
5631   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ntohl (msg->ttl));
5632   if (ntohl (msg->ttl) == 0)
5633   {
5634     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
5635     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
5636     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5637     return GNUNET_OK;
5638   }
5639   GNUNET_STATISTICS_update (stats, "# multicast forwarded", 1, GNUNET_NO);
5640   tunnel_send_multicast (t, message);
5641   return GNUNET_OK;
5642 }
5643
5644
5645 /**
5646  * Core handler for mesh network traffic toward the owner of a tunnel
5647  *
5648  * @param cls closure
5649  * @param message message
5650  * @param peer peer identity this notification is about
5651  * @param atsi performance data
5652  * @param atsi_count number of records in 'atsi'
5653  *
5654  * @return GNUNET_OK to keep the connection open,
5655  *         GNUNET_SYSERR to close it (signal serious error)
5656  */
5657 static int
5658 handle_mesh_data_to_orig (void *cls, const struct GNUNET_PeerIdentity *peer,
5659                           const struct GNUNET_MessageHeader *message,
5660                           const struct GNUNET_ATS_Information *atsi,
5661                           unsigned int atsi_count)
5662 {
5663   struct GNUNET_MESH_ToOrigin *msg;
5664   struct GNUNET_PeerIdentity id;
5665   struct MeshPeerInfo *peer_info;
5666   struct MeshTunnel *t;
5667   struct MeshTunnelChildInfo *cinfo;
5668   GNUNET_PEER_Id predecessor;
5669   size_t size;
5670   uint32_t pid;
5671
5672   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a ToOrigin packet from %s\n",
5673               GNUNET_i2s (peer));
5674   size = ntohs (message->size);
5675   if (size < sizeof (struct GNUNET_MESH_ToOrigin) +     /* Payload must be */
5676       sizeof (struct GNUNET_MessageHeader))     /* at least a header */
5677   {
5678     GNUNET_break_op (0);
5679     return GNUNET_OK;
5680   }
5681   msg = (struct GNUNET_MESH_ToOrigin *) message;
5682   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %s\n",
5683               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
5684   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5685   pid = ntohl (msg->pid);
5686
5687   if (NULL == t)
5688   {
5689     /* TODO notify that we dont know this tunnel (whom)? */
5690     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
5691     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5692                 "Received to_origin with PID %u on unknown tunnel %s [%u]\n",
5693                 pid, GNUNET_i2s (&msg->oid), ntohl (msg->tid));
5694     return GNUNET_OK;
5695   }
5696
5697   cinfo = tunnel_get_neighbor_fc(t, peer);
5698   if (NULL == cinfo)
5699   {
5700     GNUNET_break (0);
5701     return GNUNET_OK;
5702   }
5703
5704   if (cinfo->bck_pid == pid)
5705   {
5706     /* already seen this packet, drop */
5707     GNUNET_STATISTICS_update (stats, "# duplicate PID drops BCK", 1, GNUNET_NO);
5708     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5709                 " Already seen pid %u, DROPPING!\n", pid);
5710     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5711     return GNUNET_OK;
5712   }
5713
5714   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5715               " pid %u not seen yet, forwarding\n", pid);
5716   cinfo->bck_pid = pid;
5717
5718   if (NULL != t->owner)
5719   {
5720     char cbuf[size];
5721     struct GNUNET_MESH_ToOrigin *copy;
5722
5723     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5724                 "  it's for us! sending to clients...\n");
5725     /* TODO signature verification */
5726     memcpy (cbuf, message, size);
5727     copy = (struct GNUNET_MESH_ToOrigin *) cbuf;
5728     copy->tid = htonl (t->local_tid);
5729     t->bck_pid++;
5730     copy->pid = htonl (t->bck_pid);
5731     GNUNET_STATISTICS_update (stats, "# to origin received", 1, GNUNET_NO);
5732     GNUNET_SERVER_notification_context_unicast (nc, t->owner->handle,
5733                                                 &copy->header, GNUNET_NO);
5734     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
5735     return GNUNET_OK;
5736   }
5737   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5738               "  not for us, retransmitting...\n");
5739
5740   peer_info = peer_info_get (&msg->oid);
5741   if (NULL == peer_info)
5742   {
5743     /* unknown origin of tunnel */
5744     GNUNET_break (0);
5745     return GNUNET_OK;
5746   }
5747   predecessor = tree_get_predecessor (t->tree);
5748   if (0 == predecessor)
5749   {
5750     if (GNUNET_YES == t->destroy)
5751     {
5752       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5753                   "to orig received on a dying tunnel %s [%X]\n",
5754                   GNUNET_i2s (&msg->oid), ntohl(msg->tid));
5755       return GNUNET_OK;
5756     }
5757     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
5758                 "unknown to origin at %s\n",
5759                 GNUNET_i2s (&my_full_id));
5760     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
5761                 "from peer %s\n",
5762                 GNUNET_i2s (peer));
5763     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
5764                 "for tunnel %s [%X]\n",
5765                 GNUNET_i2s (&msg->oid), ntohl(msg->tid));
5766     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
5767                 "current tree:\n");
5768     tree_debug (t->tree);
5769     return GNUNET_OK;
5770   }
5771   GNUNET_PEER_resolve (predecessor, &id);
5772   send_prebuilt_message (message, &id, t);
5773   GNUNET_STATISTICS_update (stats, "# to origin forwarded", 1, GNUNET_NO);
5774
5775   return GNUNET_OK;
5776 }
5777
5778
5779 /**
5780  * Core handler for mesh network traffic point-to-point acks.
5781  *
5782  * @param cls closure
5783  * @param message message
5784  * @param peer peer identity this notification is about
5785  * @param atsi performance data
5786  * @param atsi_count number of records in 'atsi'
5787  *
5788  * @return GNUNET_OK to keep the connection open,
5789  *         GNUNET_SYSERR to close it (signal serious error)
5790  */
5791 static int
5792 handle_mesh_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5793                  const struct GNUNET_MessageHeader *message,
5794                  const struct GNUNET_ATS_Information *atsi,
5795                  unsigned int atsi_count)
5796 {
5797   struct GNUNET_MESH_ACK *msg;
5798   struct MeshTunnel *t;
5799   uint32_t ack;
5800
5801   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK packet from %s!\n",
5802               GNUNET_i2s (peer));
5803   msg = (struct GNUNET_MESH_ACK *) message;
5804
5805   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5806
5807   if (NULL == t)
5808   {
5809     /* TODO notify that we dont know this tunnel (whom)? */
5810     GNUNET_STATISTICS_update (stats, "# ack on unknown tunnel", 1, GNUNET_NO);
5811     return GNUNET_OK;
5812   }
5813   ack = ntohl (msg->pid);
5814   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ACK %u\n", ack);
5815
5816   /* Is this a forward or backward ACK? */
5817   if (tree_get_predecessor(t->tree) != GNUNET_PEER_search(peer))
5818   {
5819     struct MeshTunnelChildInfo *cinfo;
5820
5821     debug_bck_ack++;
5822     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
5823     cinfo = tunnel_get_neighbor_fc (t, peer);
5824     cinfo->fwd_ack = ack;
5825     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5826     tunnel_unlock_fwd_queues (t);
5827     if (GNUNET_SCHEDULER_NO_TASK != cinfo->fc_poll)
5828     {
5829       GNUNET_SCHEDULER_cancel (cinfo->fc_poll);
5830       cinfo->fc_poll = GNUNET_SCHEDULER_NO_TASK;
5831       cinfo->fc_poll_time = GNUNET_TIME_UNIT_SECONDS;
5832     }
5833   }
5834   else
5835   {
5836     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
5837     t->bck_ack = ack;
5838     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5839     tunnel_unlock_bck_queue (t);
5840   }
5841   return GNUNET_OK;
5842 }
5843
5844
5845 /**
5846  * Core handler for mesh network traffic point-to-point ack polls.
5847  *
5848  * @param cls closure
5849  * @param message message
5850  * @param peer peer identity this notification is about
5851  * @param atsi performance data
5852  * @param atsi_count number of records in 'atsi'
5853  *
5854  * @return GNUNET_OK to keep the connection open,
5855  *         GNUNET_SYSERR to close it (signal serious error)
5856  */
5857 static int
5858 handle_mesh_poll (void *cls, const struct GNUNET_PeerIdentity *peer,
5859                   const struct GNUNET_MessageHeader *message,
5860                   const struct GNUNET_ATS_Information *atsi,
5861                   unsigned int atsi_count)
5862 {
5863   struct GNUNET_MESH_Poll *msg;
5864   struct MeshTunnel *t;
5865
5866   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an POLL packet from %s!\n",
5867               GNUNET_i2s (peer));
5868
5869   msg = (struct GNUNET_MESH_Poll *) message;
5870
5871   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5872
5873   if (NULL == t)
5874   {
5875     /* TODO notify that we dont know this tunnel (whom)? */
5876     GNUNET_STATISTICS_update (stats, "# poll on unknown tunnel", 1, GNUNET_NO);
5877     GNUNET_break_op (0);
5878     return GNUNET_OK;
5879   }
5880
5881   /* Is this a forward or backward ACK? */
5882   if (tree_get_predecessor(t->tree) != GNUNET_PEER_search(peer))
5883   {
5884     struct MeshTunnelChildInfo *cinfo;
5885
5886     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  from FWD\n");
5887     cinfo = tunnel_get_neighbor_fc (t, peer);
5888     cinfo->bck_ack = cinfo->fwd_pid; // mark as ready to send
5889     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_POLL);
5890   }
5891   else
5892   {
5893     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  from BCK\n");
5894     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_POLL);
5895   }
5896
5897   return GNUNET_OK;
5898 }
5899
5900 /**
5901  * Core handler for path ACKs
5902  *
5903  * @param cls closure
5904  * @param message message
5905  * @param peer peer identity this notification is about
5906  * @param atsi performance data
5907  * @param atsi_count number of records in 'atsi'
5908  *
5909  * @return GNUNET_OK to keep the connection open,
5910  *         GNUNET_SYSERR to close it (signal serious error)
5911  */
5912 static int
5913 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5914                       const struct GNUNET_MessageHeader *message,
5915                       const struct GNUNET_ATS_Information *atsi,
5916                       unsigned int atsi_count)
5917 {
5918   struct GNUNET_MESH_PathACK *msg;
5919   struct GNUNET_PeerIdentity id;
5920   struct MeshPeerInfo *peer_info;
5921   struct MeshPeerPath *p;
5922   struct MeshTunnel *t;
5923
5924   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a path ACK msg [%s]\n",
5925               GNUNET_i2s (&my_full_id));
5926   msg = (struct GNUNET_MESH_PathACK *) message;
5927   t = tunnel_get (&msg->oid, ntohl(msg->tid));
5928   if (NULL == t)
5929   {
5930     /* TODO notify that we don't know the tunnel */
5931     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel", 1, GNUNET_NO);
5932     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  don't know the tunnel %s [%X]!\n",
5933                 GNUNET_i2s (&msg->oid), ntohl(msg->tid));
5934     return GNUNET_OK;
5935   }
5936   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %s [%X]\n",
5937               GNUNET_i2s (&msg->oid), ntohl(msg->tid));
5938
5939   peer_info = peer_info_get (&msg->peer_id);
5940   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by peer %s\n",
5941               GNUNET_i2s (&msg->peer_id));
5942   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  via peer %s\n",
5943               GNUNET_i2s (peer));
5944
5945   if (NULL != t->regex_search && t->regex_search->peer == peer_info->id)
5946   {
5947     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5948                 "connect_by_string completed, stopping search\n");
5949     regex_cancel_search (t->regex_search);
5950     t->regex_search = NULL;
5951   }
5952
5953   /* Add paths to peers? */
5954   p = tree_get_path_to_peer (t->tree, peer_info->id);
5955   if (NULL != p)
5956   {
5957     path_add_to_peers (p, GNUNET_YES);
5958     path_destroy (p);
5959   }
5960   else
5961   {
5962     GNUNET_break (0);
5963   }
5964
5965   /* Message for us? */
5966   if (0 == memcmp (&msg->oid, &my_full_id, sizeof (struct GNUNET_PeerIdentity)))
5967   {
5968     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
5969     if (NULL == t->owner)
5970     {
5971       GNUNET_break_op (0);
5972       return GNUNET_OK;
5973     }
5974     if (NULL != t->dht_get_type)
5975     {
5976       GNUNET_DHT_get_stop (t->dht_get_type);
5977       t->dht_get_type = NULL;
5978     }
5979     if (tree_get_status (t->tree, peer_info->id) != MESH_PEER_READY)
5980     {
5981       tree_set_status (t->tree, peer_info->id, MESH_PEER_READY);
5982       send_client_peer_connected (t, peer_info->id);
5983     }
5984     return GNUNET_OK;
5985   }
5986
5987   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5988               "  not for us, retransmitting...\n");
5989   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
5990   peer_info = peer_info_get (&msg->oid);
5991   if (NULL == peer_info)
5992   {
5993     /* If we know the tunnel, we should DEFINITELY know the peer */
5994     GNUNET_break (0);
5995     return GNUNET_OK;
5996   }
5997   send_prebuilt_message (message, &id, t);
5998   return GNUNET_OK;
5999 }
6000
6001
6002 /**
6003  * Core handler for mesh keepalives.
6004  *
6005  * @param cls closure
6006  * @param message message
6007  * @param peer peer identity this notification is about
6008  * @param atsi performance data
6009  * @param atsi_count number of records in 'atsi'
6010  * @return GNUNET_OK to keep the connection open,
6011  *         GNUNET_SYSERR to close it (signal serious error)
6012  *
6013  * TODO: Check who we got this from, to validate route.
6014  */
6015 static int
6016 handle_mesh_keepalive (void *cls, const struct GNUNET_PeerIdentity *peer,
6017                        const struct GNUNET_MessageHeader *message,
6018                        const struct GNUNET_ATS_Information *atsi,
6019                        unsigned int atsi_count)
6020 {
6021   struct GNUNET_MESH_TunnelKeepAlive *msg;
6022   struct MeshTunnel *t;
6023
6024   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a keepalive packet from %s\n",
6025               GNUNET_i2s (peer));
6026
6027   msg = (struct GNUNET_MESH_TunnelKeepAlive *) message;
6028   t = tunnel_get (&msg->oid, ntohl (msg->tid));
6029
6030   if (NULL == t)
6031   {
6032     /* TODO notify that we dont know that tunnel */
6033     GNUNET_STATISTICS_update (stats, "# keepalive on unknown tunnel", 1,
6034                               GNUNET_NO);
6035     return GNUNET_OK;
6036   }
6037
6038   tunnel_reset_timeout (t);
6039
6040   GNUNET_STATISTICS_update (stats, "# keepalives forwarded", 1, GNUNET_NO);
6041   tunnel_send_multicast (t, message);
6042   return GNUNET_OK;
6043   }
6044
6045
6046
6047 /**
6048  * Functions to handle messages from core
6049  */
6050 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
6051   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
6052   {&handle_mesh_path_destroy, GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY, 0},
6053   {&handle_mesh_path_broken, GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN,
6054    sizeof (struct GNUNET_MESH_PathBroken)},
6055   {&handle_mesh_tunnel_destroy, GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY,
6056    sizeof (struct GNUNET_MESH_TunnelDestroy)},
6057   {&handle_mesh_data_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
6058   {&handle_mesh_data_multicast, GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
6059   {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE,
6060     sizeof (struct GNUNET_MESH_TunnelKeepAlive)},
6061   {&handle_mesh_data_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
6062   {&handle_mesh_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
6063     sizeof (struct GNUNET_MESH_ACK)},
6064   {&handle_mesh_poll, GNUNET_MESSAGE_TYPE_MESH_POLL,
6065     sizeof (struct GNUNET_MESH_Poll)},
6066   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
6067    sizeof (struct GNUNET_MESH_PathACK)},
6068   {NULL, 0, 0}
6069 };
6070
6071
6072
6073 /******************************************************************************/
6074 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
6075 /******************************************************************************/
6076
6077 /**
6078  * deregister_app: iterator for removing each application registered by a client
6079  *
6080  * @param cls closure
6081  * @param key the hash of the application id (used to access the hashmap)
6082  * @param value the value stored at the key (client)
6083  *
6084  * @return GNUNET_OK on success
6085  */
6086 static int
6087 deregister_app (void *cls, const struct GNUNET_HashCode * key, void *value)
6088 {
6089   struct GNUNET_CONTAINER_MultiHashMap *h = cls;
6090   GNUNET_break (GNUNET_YES ==
6091                 GNUNET_CONTAINER_multihashmap_remove (h, key, value));
6092   return GNUNET_OK;
6093 }
6094
6095 #if LATER
6096 /**
6097  * notify_client_connection_failure: notify a client that the connection to the
6098  * requested remote peer is not possible (for instance, no route found)
6099  * Function called when the socket is ready to queue more data. "buf" will be
6100  * NULL and "size" zero if the socket was closed for writing in the meantime.
6101  *
6102  * @param cls closure
6103  * @param size number of bytes available in buf
6104  * @param buf where the callee should write the message
6105  * @return number of bytes written to buf
6106  */
6107 static size_t
6108 notify_client_connection_failure (void *cls, size_t size, void *buf)
6109 {
6110   int size_needed;
6111   struct MeshPeerInfo *peer_info;
6112   struct GNUNET_MESH_PeerControl *msg;
6113   struct GNUNET_PeerIdentity id;
6114
6115   if (0 == size && NULL == buf)
6116   {
6117     // TODO retry? cancel?
6118     return 0;
6119   }
6120
6121   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
6122   peer_info = (struct MeshPeerInfo *) cls;
6123   msg = (struct GNUNET_MESH_PeerControl *) buf;
6124   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
6125   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
6126 //     msg->tunnel_id = htonl(peer_info->t->tid);
6127   GNUNET_PEER_resolve (peer_info->id, &id);
6128   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
6129
6130   return size_needed;
6131 }
6132 #endif
6133
6134
6135 /**
6136  * Send keepalive packets for a peer
6137  *
6138  * @param cls Closure (tunnel for which to send the keepalive).
6139  * @param tc Notification context.
6140  */
6141 static void
6142 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
6143 {
6144   struct MeshTunnel *t = cls;
6145   struct GNUNET_MESH_TunnelKeepAlive *msg;
6146   size_t size = sizeof (struct GNUNET_MESH_TunnelKeepAlive);
6147   char cbuf[size];
6148
6149   t->path_refresh_task = GNUNET_SCHEDULER_NO_TASK;
6150   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
6151   {
6152     return;
6153   }
6154
6155   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6156               "sending keepalive for tunnel %d\n", t->id.tid);
6157
6158   msg = (struct GNUNET_MESH_TunnelKeepAlive *) cbuf;
6159   msg->header.size = htons (size);
6160   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE);
6161   msg->oid = my_full_id;
6162   msg->tid = htonl (t->id.tid);
6163   tunnel_send_multicast (t, &msg->header);
6164
6165   t->path_refresh_task =
6166       GNUNET_SCHEDULER_add_delayed (refresh_path_time, &path_refresh, t);
6167   tunnel_reset_timeout(t);
6168 }
6169
6170
6171 /**
6172  * Function to process paths received for a new peer addition. The recorded
6173  * paths form the initial tunnel, which can be optimized later.
6174  * Called on each result obtained for the DHT search.
6175  *
6176  * @param cls closure
6177  * @param exp when will this value expire
6178  * @param key key of the result
6179  * @param get_path path of the get request
6180  * @param get_path_length lenght of get_path
6181  * @param put_path path of the put request
6182  * @param put_path_length length of the put_path
6183  * @param type type of the result
6184  * @param size number of bytes in data
6185  * @param data pointer to the result data
6186  *
6187  * TODO: re-issue the request after certain time? cancel after X results?
6188  */
6189 static void
6190 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
6191                     const struct GNUNET_HashCode * key,
6192                     const struct GNUNET_PeerIdentity *get_path,
6193                     unsigned int get_path_length,
6194                     const struct GNUNET_PeerIdentity *put_path,
6195                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
6196                     size_t size, const void *data)
6197 {
6198   struct MeshPathInfo *path_info = cls;
6199   struct MeshPeerPath *p;
6200   struct GNUNET_PeerIdentity pi;
6201   int i;
6202
6203   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
6204   GNUNET_PEER_resolve (path_info->peer->id, &pi);
6205   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", GNUNET_i2s (&pi));
6206
6207   p = path_build_from_dht (get_path, get_path_length, put_path,
6208                            put_path_length);
6209   path_add_to_peers (p, GNUNET_NO);
6210   path_destroy(p);
6211   for (i = 0; i < path_info->peer->ntunnels; i++)
6212   {
6213     tunnel_add_peer (path_info->peer->tunnels[i], path_info->peer);
6214     peer_info_connect (path_info->peer, path_info->t);
6215   }
6216
6217   return;
6218 }
6219
6220
6221 /**
6222  * Function to process paths received for a new peer addition. The recorded
6223  * paths form the initial tunnel, which can be optimized later.
6224  * Called on each result obtained for the DHT search.
6225  *
6226  * @param cls closure
6227  * @param exp when will this value expire
6228  * @param key key of the result
6229  * @param get_path path of the get request
6230  * @param get_path_length lenght of get_path
6231  * @param put_path path of the put request
6232  * @param put_path_length length of the put_path
6233  * @param type type of the result
6234  * @param size number of bytes in data
6235  * @param data pointer to the result data
6236  */
6237 static void
6238 dht_get_type_handler (void *cls, struct GNUNET_TIME_Absolute exp,
6239                       const struct GNUNET_HashCode * key,
6240                       const struct GNUNET_PeerIdentity *get_path,
6241                       unsigned int get_path_length,
6242                       const struct GNUNET_PeerIdentity *put_path,
6243                       unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
6244                       size_t size, const void *data)
6245 {
6246   const struct PBlock *pb = data;
6247   const struct GNUNET_PeerIdentity *pi = &pb->id;
6248   struct MeshTunnel *t = cls;
6249   struct MeshPeerInfo *peer_info;
6250   struct MeshPeerPath *p;
6251
6252   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got type DHT result!\n");
6253   if (size != sizeof (struct PBlock))
6254   {
6255     GNUNET_break_op (0);
6256     return;
6257   }
6258   if (ntohl(pb->type) != t->type)
6259   {
6260     GNUNET_break_op (0);
6261     return;
6262   }
6263   GNUNET_assert (NULL != t->owner);
6264   peer_info = peer_info_get (pi);
6265   (void) GNUNET_CONTAINER_multihashmap_put (t->peers, &pi->hashPubKey,
6266                                             peer_info,
6267                                             GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
6268
6269   p = path_build_from_dht (get_path, get_path_length, put_path,
6270                            put_path_length);
6271   path_add_to_peers (p, GNUNET_NO);
6272   path_destroy(p);
6273   tunnel_add_peer (t, peer_info);
6274   peer_info_connect (peer_info, t);
6275 }
6276
6277
6278 /******************************************************************************/
6279 /*********************       MESH LOCAL HANDLES      **************************/
6280 /******************************************************************************/
6281
6282
6283 /**
6284  * Handler for client disconnection
6285  *
6286  * @param cls closure
6287  * @param client identification of the client; NULL
6288  *        for the last call when the server is destroyed
6289  */
6290 static void
6291 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
6292 {
6293   struct MeshClient *c;
6294   struct MeshClient *next;
6295   unsigned int i;
6296
6297   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected\n");
6298   if (client == NULL)
6299   {
6300     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (SERVER DOWN)\n");
6301     return;
6302   }
6303
6304   c = clients;
6305   while (NULL != c)
6306   {
6307     if (c->handle != client)
6308     {
6309       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ... searching\n");
6310       c = c->next;
6311       continue;
6312     }
6313     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u)\n",
6314                 c->id);
6315     GNUNET_SERVER_client_drop (c->handle);
6316     c->shutting_down = GNUNET_YES;
6317     GNUNET_assert (NULL != c->own_tunnels);
6318     GNUNET_assert (NULL != c->incoming_tunnels);
6319     GNUNET_CONTAINER_multihashmap_iterate (c->own_tunnels,
6320                                            &tunnel_destroy_iterator, c);
6321     GNUNET_CONTAINER_multihashmap_iterate (c->incoming_tunnels,
6322                                            &tunnel_destroy_iterator, c);
6323     GNUNET_CONTAINER_multihashmap_iterate (c->ignore_tunnels,
6324                                            &tunnel_destroy_iterator, c);
6325     GNUNET_CONTAINER_multihashmap_destroy (c->own_tunnels);
6326     GNUNET_CONTAINER_multihashmap_destroy (c->incoming_tunnels);
6327     GNUNET_CONTAINER_multihashmap_destroy (c->ignore_tunnels);
6328
6329     /* deregister clients applications */
6330     if (NULL != c->apps)
6331     {
6332       GNUNET_CONTAINER_multihashmap_iterate (c->apps, &deregister_app, c->apps);
6333       GNUNET_CONTAINER_multihashmap_destroy (c->apps);
6334     }
6335     if (0 == GNUNET_CONTAINER_multihashmap_size (applications) &&
6336         GNUNET_SCHEDULER_NO_TASK != announce_applications_task)
6337     {
6338       GNUNET_SCHEDULER_cancel (announce_applications_task);
6339       announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
6340     }
6341     if (NULL != c->types)
6342       GNUNET_CONTAINER_multihashmap_destroy (c->types);
6343     for (i = 0; i < c->n_regex; i++)
6344     {
6345       GNUNET_free (c->regexes[i].regex);
6346       if (NULL != c->regexes[i].h)
6347         GNUNET_REGEX_announce_cancel (c->regexes[i].h);
6348     }
6349     GNUNET_free_non_null (c->regexes);
6350     if (GNUNET_SCHEDULER_NO_TASK != c->regex_announce_task)
6351       GNUNET_SCHEDULER_cancel (c->regex_announce_task);
6352     next = c->next;
6353     GNUNET_CONTAINER_DLL_remove (clients, clients_tail, c);
6354     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT FREE at %p\n", c);
6355     GNUNET_free (c);
6356     GNUNET_STATISTICS_update (stats, "# clients", -1, GNUNET_NO);
6357     c = next;
6358   }
6359   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   done!\n");
6360   return;
6361 }
6362
6363
6364 /**
6365  * Handler for new clients
6366  *
6367  * @param cls closure
6368  * @param client identification of the client
6369  * @param message the actual message, which includes messages the client wants
6370  */
6371 static void
6372 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
6373                          const struct GNUNET_MessageHeader *message)
6374 {
6375   struct GNUNET_MESH_ClientConnect *cc_msg;
6376   struct MeshClient *c;
6377   GNUNET_MESH_ApplicationType *a;
6378   unsigned int size;
6379   uint16_t ntypes;
6380   uint16_t *t;
6381   uint16_t napps;
6382   uint16_t i;
6383
6384   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected\n");
6385   /* Check data sanity */
6386   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
6387   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
6388   ntypes = ntohs (cc_msg->types);
6389   napps = ntohs (cc_msg->applications);
6390   if (size !=
6391       ntypes * sizeof (uint16_t) + napps * sizeof (GNUNET_MESH_ApplicationType))
6392   {
6393     GNUNET_break (0);
6394     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6395     return;
6396   }
6397
6398   /* Create new client structure */
6399   c = GNUNET_malloc (sizeof (struct MeshClient));
6400   c->id = next_client_id++;
6401   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT NEW %u\n", c->id);
6402   c->handle = client;
6403   GNUNET_SERVER_client_keep (client);
6404   a = (GNUNET_MESH_ApplicationType *) &cc_msg[1];
6405   if (napps > 0)
6406   {
6407     GNUNET_MESH_ApplicationType at;
6408     struct GNUNET_HashCode hc;
6409
6410     c->apps = GNUNET_CONTAINER_multihashmap_create (napps, GNUNET_NO);
6411     for (i = 0; i < napps; i++)
6412     {
6413       at = ntohl (a[i]);
6414       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  app type: %u\n", at);
6415       GNUNET_CRYPTO_hash (&at, sizeof (at), &hc);
6416       /* store in clients hashmap */
6417       GNUNET_CONTAINER_multihashmap_put (c->apps, &hc, (void *) (long) at,
6418                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6419       /* store in global hashmap, for announcements */
6420       GNUNET_CONTAINER_multihashmap_put (applications, &hc, c,
6421                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6422     }
6423     if (GNUNET_SCHEDULER_NO_TASK == announce_applications_task)
6424       announce_applications_task =
6425           GNUNET_SCHEDULER_add_now (&announce_applications, NULL);
6426
6427   }
6428   if (ntypes > 0)
6429   {
6430     uint16_t u16;
6431     struct GNUNET_HashCode hc;
6432
6433     t = (uint16_t *) & a[napps];
6434     c->types = GNUNET_CONTAINER_multihashmap_create (ntypes, GNUNET_NO);
6435     for (i = 0; i < ntypes; i++)
6436     {
6437       u16 = ntohs (t[i]);
6438       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  msg type: %u\n", u16);
6439       GNUNET_CRYPTO_hash (&u16, sizeof (u16), &hc);
6440
6441       /* store in clients hashmap */
6442       GNUNET_CONTAINER_multihashmap_put (c->types, &hc, c,
6443                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6444       /* store in global hashmap */
6445       GNUNET_CONTAINER_multihashmap_put (types, &hc, c,
6446                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6447     }
6448   }
6449   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6450               " client has %u+%u subscriptions\n", napps, ntypes);
6451
6452   GNUNET_CONTAINER_DLL_insert (clients, clients_tail, c);
6453   c->own_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6454   c->incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6455   c->ignore_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6456   GNUNET_SERVER_notification_context_add (nc, client);
6457   GNUNET_STATISTICS_update (stats, "# clients", 1, GNUNET_NO);
6458
6459   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6460   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
6461 }
6462
6463
6464 /**
6465  * Handler for clients announcing available services by a regular expression.
6466  *
6467  * @param cls closure
6468  * @param client identification of the client
6469  * @param message the actual message, which includes messages the client wants
6470  */
6471 static void
6472 handle_local_announce_regex (void *cls, struct GNUNET_SERVER_Client *client,
6473                              const struct GNUNET_MessageHeader *message)
6474 {
6475   const struct GNUNET_MESH_RegexAnnounce *msg;
6476   struct MeshRegexDescriptor rd;
6477   struct MeshClient *c;
6478   char *regex;
6479   size_t len;
6480   size_t offset;
6481
6482   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "announce regex started\n");
6483
6484   /* Sanity check for client registration */
6485   if (NULL == (c = client_get (client)))
6486   {
6487     GNUNET_break (0);
6488     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6489     return;
6490   }
6491   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6492
6493   msg = (const struct GNUNET_MESH_RegexAnnounce *) message;
6494
6495   len = ntohs (message->size) - sizeof(struct GNUNET_MESH_RegexAnnounce);
6496   if (NULL != c->partial_regex)
6497   {
6498     regex = c->partial_regex;
6499     offset = strlen (c->partial_regex);
6500     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6501                 "  continuation, already have %u bytes\n",
6502                 offset);
6503   }
6504   else
6505   {
6506     regex = NULL;
6507     offset = 0;
6508   }
6509
6510   regex = GNUNET_realloc (regex, offset + len + 1);
6511   memcpy (&regex[offset], &msg[1], len);
6512   regex[offset + len] = '\0';
6513   if (0 == ntohs (msg->last))
6514   {
6515     c->partial_regex = regex;
6516     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6517                 "  not ended, stored %u bytes for later\n",
6518                 len);
6519     GNUNET_SERVER_receive_done (client, GNUNET_OK);
6520     return;
6521   }
6522   rd.regex = regex;
6523   rd.compression = ntohs (msg->compression_characters);
6524   rd.h = NULL;
6525   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  length %u\n", len);
6526   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regex %s\n", regex);
6527   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  cm %u\n", ntohs(rd.compression));
6528   GNUNET_array_append (c->regexes, c->n_regex, rd);
6529   c->partial_regex = NULL;
6530   if (GNUNET_SCHEDULER_NO_TASK == c->regex_announce_task)
6531   {
6532     c->regex_announce_task = GNUNET_SCHEDULER_add_now(&regex_announce, c);
6533   }
6534   else
6535   {
6536     regex_put(&rd);
6537   }
6538   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6539   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "announce regex processed\n");
6540 }
6541
6542
6543 /**
6544  * Handler for requests of new tunnels
6545  *
6546  * @param cls closure
6547  * @param client identification of the client
6548  * @param message the actual message
6549  */
6550 static void
6551 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
6552                             const struct GNUNET_MessageHeader *message)
6553 {
6554   struct GNUNET_MESH_TunnelMessage *t_msg;
6555   struct MeshTunnel *t;
6556   struct MeshClient *c;
6557   MESH_TunnelNumber tid;
6558
6559   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel requested\n");
6560
6561   /* Sanity check for client registration */
6562   if (NULL == (c = client_get (client)))
6563   {
6564     GNUNET_break (0);
6565     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6566     return;
6567   }
6568   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6569
6570   /* Message sanity check */
6571   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
6572   {
6573     GNUNET_break (0);
6574     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6575     return;
6576   }
6577
6578   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6579   /* Sanity check for tunnel numbering */
6580   tid = ntohl (t_msg->tunnel_id);
6581   if (0 == (tid & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
6582   {
6583     GNUNET_break (0);
6584     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6585     return;
6586   }
6587   /* Sanity check for duplicate tunnel IDs */
6588   if (NULL != tunnel_get_by_local_id (c, tid))
6589   {
6590     GNUNET_break (0);
6591     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6592     return;
6593   }
6594
6595   while (NULL != tunnel_get_by_pi (myid, next_tid))
6596     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
6597   t = tunnel_new (myid, next_tid++, c, tid);
6598   if (NULL == t)
6599   {
6600     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Tunnel creation failed.\n");
6601     GNUNET_break (0);
6602     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6603     return;
6604   }
6605   next_tid = next_tid & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
6606   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED TUNNEL %s [%x] (%x)\n",
6607               GNUNET_i2s (&my_full_id), t->id.tid, t->local_tid);
6608   t->peers = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6609
6610   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel created\n");
6611   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6612   return;
6613 }
6614
6615
6616 /**
6617  * Handler for requests of deleting tunnels
6618  *
6619  * @param cls closure
6620  * @param client identification of the client
6621  * @param message the actual message
6622  */
6623 static void
6624 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
6625                              const struct GNUNET_MessageHeader *message)
6626 {
6627   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
6628   struct MeshClient *c;
6629   struct MeshTunnel *t;
6630   MESH_TunnelNumber tid;
6631
6632   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6633               "Got a DESTROY TUNNEL from client!\n");
6634
6635   /* Sanity check for client registration */
6636   if (NULL == (c = client_get (client)))
6637   {
6638     GNUNET_break (0);
6639     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6640     return;
6641   }
6642   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6643
6644   /* Message sanity check */
6645   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
6646   {
6647     GNUNET_break (0);
6648     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6649     return;
6650   }
6651
6652   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6653
6654   /* Retrieve tunnel */
6655   tid = ntohl (tunnel_msg->tunnel_id);
6656   t = tunnel_get_by_local_id(c, tid);
6657   if (NULL == t)
6658   {
6659     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
6660     GNUNET_break (0);
6661     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6662     return;
6663   }
6664   if (c != t->owner || tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
6665   {
6666     client_ignore_tunnel (c, t);
6667     tunnel_destroy_empty (t);
6668     GNUNET_SERVER_receive_done (client, GNUNET_OK);
6669     return;
6670   }
6671   send_client_tunnel_disconnect (t, c);
6672   client_delete_tunnel (c, t);
6673
6674   /* Don't try to ACK the client about the tunnel_destroy multicast packet */
6675   t->owner = NULL;
6676   tunnel_send_destroy (t, 0);
6677   t->destroy = GNUNET_YES;
6678   /* The tunnel will be destroyed when the last message is transmitted. */
6679   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6680   return;
6681 }
6682
6683
6684 /**
6685  * Handler for requests of seeting tunnel's speed.
6686  *
6687  * @param cls Closure (unused).
6688  * @param client Identification of the client.
6689  * @param message The actual message.
6690  */
6691 static void
6692 handle_local_tunnel_speed (void *cls, struct GNUNET_SERVER_Client *client,
6693                            const struct GNUNET_MessageHeader *message)
6694 {
6695   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
6696   struct MeshClient *c;
6697   struct MeshTunnel *t;
6698   MESH_TunnelNumber tid;
6699
6700   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6701               "Got a SPEED request from client!\n");
6702
6703   /* Sanity check for client registration */
6704   if (NULL == (c = client_get (client)))
6705   {
6706     GNUNET_break (0);
6707     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6708     return;
6709   }
6710
6711   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6712
6713   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6714
6715   /* Retrieve tunnel */
6716   tid = ntohl (tunnel_msg->tunnel_id);
6717   t = tunnel_get_by_local_id(c, tid);
6718   if (NULL == t)
6719   {
6720     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  tunnel %X not found\n", tid);
6721     GNUNET_break (0);
6722     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6723     return;
6724   }
6725
6726   switch (ntohs(message->type))
6727   {
6728       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MIN:
6729           t->speed_min = GNUNET_YES;
6730           break;
6731       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MAX:
6732           t->speed_min = GNUNET_NO;
6733           break;
6734       default:
6735           GNUNET_break (0);
6736   }
6737   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6738 }
6739
6740
6741 /**
6742  * Handler for requests of seeting tunnel's buffering policy.
6743  *
6744  * @param cls Closure (unused).
6745  * @param client Identification of the client.
6746  * @param message The actual message.
6747  */
6748 static void
6749 handle_local_tunnel_buffer (void *cls, struct GNUNET_SERVER_Client *client,
6750                             const struct GNUNET_MessageHeader *message)
6751 {
6752   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
6753   struct MeshClient *c;
6754   struct MeshTunnel *t;
6755   MESH_TunnelNumber tid;
6756
6757   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6758               "Got a BUFFER request from client!\n");
6759
6760   /* Sanity check for client registration */
6761   if (NULL == (c = client_get (client)))
6762   {
6763     GNUNET_break (0);
6764     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6765     return;
6766   }
6767   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6768
6769   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6770
6771   /* Retrieve tunnel */
6772   tid = ntohl (tunnel_msg->tunnel_id);
6773   t = tunnel_get_by_local_id(c, tid);
6774   if (NULL == t)
6775   {
6776     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
6777     GNUNET_break (0);
6778     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6779     return;
6780   }
6781
6782   switch (ntohs(message->type))
6783   {
6784       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER:
6785           t->nobuffer = GNUNET_NO;
6786           break;
6787       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER:
6788           t->nobuffer = GNUNET_YES;
6789           break;
6790       default:
6791           GNUNET_break (0);
6792   }
6793
6794   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6795 }
6796
6797
6798 /**
6799  * Handler for connection requests to new peers
6800  *
6801  * @param cls closure
6802  * @param client identification of the client
6803  * @param message the actual message (PeerControl)
6804  */
6805 static void
6806 handle_local_connect_add (void *cls, struct GNUNET_SERVER_Client *client,
6807                           const struct GNUNET_MessageHeader *message)
6808 {
6809   struct GNUNET_MESH_PeerControl *peer_msg;
6810   struct MeshPeerInfo *peer_info;
6811   struct MeshClient *c;
6812   struct MeshTunnel *t;
6813   MESH_TunnelNumber tid;
6814
6815   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got connection request\n");
6816   /* Sanity check for client registration */
6817   if (NULL == (c = client_get (client)))
6818   {
6819     GNUNET_break (0);
6820     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6821     return;
6822   }
6823   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6824
6825   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6826
6827   /* Sanity check for message size */
6828   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6829   {
6830     GNUNET_break (0);
6831     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6832     return;
6833   }
6834
6835   /* Tunnel exists? */
6836   tid = ntohl (peer_msg->tunnel_id);
6837   t = tunnel_get_by_local_id (c, tid);
6838   if (NULL == t)
6839   {
6840     GNUNET_break (0);
6841     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6842     return;
6843   }
6844
6845   /* Does client own tunnel? */
6846   if (t->owner->handle != client)
6847   {
6848     GNUNET_break (0);
6849     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6850     return;
6851   }
6852   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "     for %s\n",
6853               GNUNET_i2s (&peer_msg->peer));
6854   peer_info = peer_info_get (&peer_msg->peer);
6855
6856   tunnel_add_peer (t, peer_info);
6857   peer_info_connect (peer_info, t);
6858
6859   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6860   return;
6861 }
6862
6863
6864 /**
6865  * Handler for disconnection requests of peers in a tunnel
6866  *
6867  * @param cls closure
6868  * @param client identification of the client
6869  * @param message the actual message (PeerControl)
6870  */
6871 static void
6872 handle_local_connect_del (void *cls, struct GNUNET_SERVER_Client *client,
6873                           const struct GNUNET_MessageHeader *message)
6874 {
6875   struct GNUNET_MESH_PeerControl *peer_msg;
6876   struct MeshPeerInfo *peer_info;
6877   struct MeshClient *c;
6878   struct MeshTunnel *t;
6879   MESH_TunnelNumber tid;
6880
6881   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER DEL request\n");
6882   /* Sanity check for client registration */
6883   if (NULL == (c = client_get (client)))
6884   {
6885     GNUNET_break (0);
6886     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6887     return;
6888   }
6889   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6890
6891   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6892
6893   /* Sanity check for message size */
6894   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6895   {
6896     GNUNET_break (0);
6897     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6898     return;
6899   }
6900
6901   /* Tunnel exists? */
6902   tid = ntohl (peer_msg->tunnel_id);
6903   t = tunnel_get_by_local_id (c, tid);
6904   if (NULL == t)
6905   {
6906     GNUNET_break (0);
6907     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6908     return;
6909   }
6910   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
6911
6912   /* Does client own tunnel? */
6913   if (t->owner->handle != client)
6914   {
6915     GNUNET_break (0);
6916     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6917     return;
6918   }
6919
6920   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for peer %s\n",
6921               GNUNET_i2s (&peer_msg->peer));
6922   /* Is the peer in the tunnel? */
6923   peer_info =
6924       GNUNET_CONTAINER_multihashmap_get (t->peers, &peer_msg->peer.hashPubKey);
6925   if (NULL == peer_info)
6926   {
6927     GNUNET_break (0);
6928     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6929     return;
6930   }
6931
6932   /* Ok, delete peer from tunnel */
6933   GNUNET_CONTAINER_multihashmap_remove_all (t->peers,
6934                                             &peer_msg->peer.hashPubKey);
6935
6936   send_destroy_path (t, peer_info->id);
6937   tunnel_delete_peer (t, peer_info->id);
6938   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6939   return;
6940 }
6941
6942 /**
6943  * Handler for blacklist requests of peers in a tunnel
6944  *
6945  * @param cls closure
6946  * @param client identification of the client
6947  * @param message the actual message (PeerControl)
6948  * 
6949  * FIXME implement DHT block bloomfilter
6950  */
6951 static void
6952 handle_local_blacklist (void *cls, struct GNUNET_SERVER_Client *client,
6953                           const struct GNUNET_MessageHeader *message)
6954 {
6955   struct GNUNET_MESH_PeerControl *peer_msg;
6956   struct MeshClient *c;
6957   struct MeshTunnel *t;
6958   MESH_TunnelNumber tid;
6959
6960   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER BLACKLIST request\n");
6961   /* Sanity check for client registration */
6962   if (NULL == (c = client_get (client)))
6963   {
6964     GNUNET_break (0);
6965     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6966     return;
6967   }
6968   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6969
6970   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6971
6972   /* Sanity check for message size */
6973   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6974   {
6975     GNUNET_break (0);
6976     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6977     return;
6978   }
6979
6980   /* Tunnel exists? */
6981   tid = ntohl (peer_msg->tunnel_id);
6982   t = tunnel_get_by_local_id (c, tid);
6983   if (NULL == t)
6984   {
6985     GNUNET_break (0);
6986     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6987     return;
6988   }
6989   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
6990
6991   GNUNET_array_append(t->blacklisted, t->nblacklisted,
6992                       GNUNET_PEER_intern(&peer_msg->peer));
6993 }
6994
6995
6996 /**
6997  * Handler for unblacklist requests of peers in a tunnel
6998  *
6999  * @param cls closure
7000  * @param client identification of the client
7001  * @param message the actual message (PeerControl)
7002  */
7003 static void
7004 handle_local_unblacklist (void *cls, struct GNUNET_SERVER_Client *client,
7005                           const struct GNUNET_MessageHeader *message)
7006 {
7007   struct GNUNET_MESH_PeerControl *peer_msg;
7008   struct MeshClient *c;
7009   struct MeshTunnel *t;
7010   MESH_TunnelNumber tid;
7011   GNUNET_PEER_Id pid;
7012   unsigned int i;
7013
7014   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER UNBLACKLIST request\n");
7015   /* Sanity check for client registration */
7016   if (NULL == (c = client_get (client)))
7017   {
7018     GNUNET_break (0);
7019     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7020     return;
7021   }
7022   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7023
7024   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
7025
7026   /* Sanity check for message size */
7027   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
7028   {
7029     GNUNET_break (0);
7030     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7031     return;
7032   }
7033
7034   /* Tunnel exists? */
7035   tid = ntohl (peer_msg->tunnel_id);
7036   t = tunnel_get_by_local_id (c, tid);
7037   if (NULL == t)
7038   {
7039     GNUNET_break (0);
7040     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7041     return;
7042   }
7043   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
7044
7045   /* if peer is not known, complain */
7046   pid = GNUNET_PEER_search (&peer_msg->peer);
7047   if (0 == pid)
7048   {
7049     GNUNET_break (0);
7050     return;
7051   }
7052
7053   /* search and remove from list */
7054   for (i = 0; i < t->nblacklisted; i++)
7055   {
7056     if (t->blacklisted[i] == pid)
7057     {
7058       t->blacklisted[i] = t->blacklisted[t->nblacklisted - 1];
7059       GNUNET_array_grow (t->blacklisted, t->nblacklisted, t->nblacklisted - 1);
7060       return;
7061     }
7062   }
7063
7064   /* if peer hasn't been blacklisted, complain */
7065   GNUNET_break (0);
7066 }
7067
7068
7069 /**
7070  * Handler for connection requests to new peers by type
7071  *
7072  * @param cls closure
7073  * @param client identification of the client
7074  * @param message the actual message (ConnectPeerByType)
7075  */
7076 static void
7077 handle_local_connect_by_type (void *cls, struct GNUNET_SERVER_Client *client,
7078                               const struct GNUNET_MessageHeader *message)
7079 {
7080   struct GNUNET_MESH_ConnectPeerByType *connect_msg;
7081   struct MeshClient *c;
7082   struct MeshTunnel *t;
7083   struct GNUNET_HashCode hash;
7084   MESH_TunnelNumber tid;
7085
7086   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got connect by type request\n");
7087   /* Sanity check for client registration */
7088   if (NULL == (c = client_get (client)))
7089   {
7090     GNUNET_break (0);
7091     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7092     return;
7093   }
7094   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7095
7096   connect_msg = (struct GNUNET_MESH_ConnectPeerByType *) message;
7097
7098   /* Sanity check for message size */
7099   if (sizeof (struct GNUNET_MESH_ConnectPeerByType) !=
7100       ntohs (connect_msg->header.size))
7101   {
7102     GNUNET_break (0);
7103     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7104     return;
7105   }
7106
7107   /* Tunnel exists? */
7108   tid = ntohl (connect_msg->tunnel_id);
7109   t = tunnel_get_by_local_id (c, tid);
7110   if (NULL == t)
7111   {
7112     GNUNET_break (0);
7113     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7114     return;
7115   }
7116
7117   /* Does client own tunnel? */
7118   if (t->owner->handle != client)
7119   {
7120     GNUNET_break (0);
7121     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7122     return;
7123   }
7124
7125   /* Do WE have the service? */
7126   t->type = ntohl (connect_msg->type);
7127   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " type requested: %u\n", t->type);
7128   GNUNET_CRYPTO_hash (&t->type, sizeof (GNUNET_MESH_ApplicationType), &hash);
7129   if (GNUNET_CONTAINER_multihashmap_contains (applications, &hash) ==
7130       GNUNET_YES)
7131   {
7132     /* Yes! Fast forward, add ourselves to the tunnel and send the
7133      * good news to the client, and alert the destination client of
7134      * an incoming tunnel.
7135      *
7136      * FIXME send a path create to self, avoid code duplication
7137      */
7138     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " available locally\n");
7139     GNUNET_CONTAINER_multihashmap_put (t->peers, &my_full_id.hashPubKey,
7140                                        peer_info_get (&my_full_id),
7141                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
7142
7143     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " notifying client\n");
7144     send_client_peer_connected (t, myid);
7145     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Done\n");
7146     GNUNET_SERVER_receive_done (client, GNUNET_OK);
7147
7148     t->local_tid_dest = next_local_tid++;
7149     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
7150     GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
7151                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
7152
7153     return;
7154   }
7155   /* Ok, lets find a peer offering the service */
7156   if (NULL != t->dht_get_type)
7157   {
7158     GNUNET_DHT_get_stop (t->dht_get_type);
7159   }
7160   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " looking in DHT for %s\n",
7161               GNUNET_h2s (&hash));
7162   t->dht_get_type =
7163       GNUNET_DHT_get_start (dht_handle, 
7164                             GNUNET_BLOCK_TYPE_MESH_PEER_BY_TYPE,
7165                             &hash,
7166                             dht_replication_level,
7167                             GNUNET_DHT_RO_RECORD_ROUTE |
7168                             GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
7169                             NULL, 0,
7170                             &dht_get_type_handler, t);
7171
7172   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7173   return;
7174 }
7175
7176
7177 /**
7178  * Handler for connection requests to new peers by a string service description.
7179  *
7180  * @param cls closure
7181  * @param client identification of the client
7182  * @param message the actual message, which includes messages the client wants
7183  */
7184 static void
7185 handle_local_connect_by_string (void *cls, struct GNUNET_SERVER_Client *client,
7186                                 const struct GNUNET_MessageHeader *message)
7187 {
7188   struct GNUNET_MESH_ConnectPeerByString *msg;
7189   struct MeshRegexSearchInfo *info;
7190   struct GNUNET_HashCode key;
7191   struct MeshTunnel *t;
7192   struct MeshClient *c;
7193   MESH_TunnelNumber tid;
7194   const char *string;
7195   size_t size;
7196   size_t len;
7197
7198   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7199               "Connect by string started\n");
7200   msg = (struct GNUNET_MESH_ConnectPeerByString *) message;
7201   size = htons (message->size);
7202
7203   /* Sanity check for client registration */
7204   if (NULL == (c = client_get (client)))
7205   {
7206     GNUNET_break (0);
7207     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7208     return;
7209   }
7210   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7211
7212   /* Message size sanity check */
7213   if (sizeof(struct GNUNET_MESH_ConnectPeerByString) >= size)
7214   {
7215     GNUNET_break (0);
7216     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7217     return;
7218   }
7219
7220   /* Tunnel exists? */
7221   tid = ntohl (msg->tunnel_id);
7222   t = tunnel_get_by_local_id (c, tid);
7223   if (NULL == t)
7224   {
7225     GNUNET_break (0);
7226     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7227     return;
7228   }
7229
7230   /* Does client own tunnel? */
7231   if (t->owner->handle != client)
7232   {
7233     GNUNET_break (0);
7234     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7235     return;
7236   }
7237
7238   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7239               "  on tunnel %s [%u]\n",
7240               GNUNET_i2s(&my_full_id),
7241               t->id.tid);
7242
7243   /* Only one connect_by_string allowed at the same time! */
7244   /* FIXME: allow more, return handle at api level to cancel, document */
7245   if (NULL != t->regex_search)
7246   {
7247     GNUNET_break (0);
7248     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7249     return;
7250   }
7251
7252   /* Find string itself */
7253   len = size - sizeof(struct GNUNET_MESH_ConnectPeerByString);
7254   string = (const char *) &msg[1];
7255
7256   /* Initialize context */
7257   size = GNUNET_REGEX_get_first_key (string, len, &key);
7258   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7259               "  consumed %u bits out of %u\n", size, len);
7260   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7261               "  looking for %s\n", GNUNET_h2s (&key));
7262
7263   info = GNUNET_malloc (sizeof (struct MeshRegexSearchInfo));
7264   info->t = t;
7265   info->description = GNUNET_strndup (string, len);
7266   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   string: %s\n", info->description);
7267
7268   t->regex_search = info;
7269
7270   info->search_handle = GNUNET_REGEX_search (dht_handle,
7271                                              info->description,
7272                                              &regex_found_handler, info,
7273                                              stats);
7274
7275   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7276   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "connect by string processed\n");
7277 }
7278
7279
7280 /**
7281  * Handler for client traffic directed to one peer
7282  *
7283  * @param cls closure
7284  * @param client identification of the client
7285  * @param message the actual message
7286  */
7287 static void
7288 handle_local_unicast (void *cls, struct GNUNET_SERVER_Client *client,
7289                       const struct GNUNET_MessageHeader *message)
7290 {
7291   struct MeshClient *c;
7292   struct MeshTunnel *t;
7293   struct MeshPeerInfo *pi;
7294   struct GNUNET_MESH_Unicast *data_msg;
7295   MESH_TunnelNumber tid;
7296   size_t size;
7297
7298   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7299               "Got a unicast request from a client!\n");
7300
7301   /* Sanity check for client registration */
7302   if (NULL == (c = client_get (client)))
7303   {
7304     GNUNET_break (0);
7305     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7306     return;
7307   }
7308   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7309
7310   data_msg = (struct GNUNET_MESH_Unicast *) message;
7311
7312   /* Sanity check for message size */
7313   size = ntohs (message->size);
7314   if (sizeof (struct GNUNET_MESH_Unicast) +
7315       sizeof (struct GNUNET_MessageHeader) > size)
7316   {
7317     GNUNET_break (0);
7318     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7319     return;
7320   }
7321
7322   /* Tunnel exists? */
7323   tid = ntohl (data_msg->tid);
7324   t = tunnel_get_by_local_id (c, tid);
7325   if (NULL == t)
7326   {
7327     GNUNET_break (0);
7328     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7329     return;
7330   }
7331
7332   /*  Is it a local tunnel? Then, does client own the tunnel? */
7333   if (t->owner->handle != client)
7334   {
7335     GNUNET_break (0);
7336     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7337     return;
7338   }
7339
7340   pi = GNUNET_CONTAINER_multihashmap_get (t->peers,
7341                                           &data_msg->destination.hashPubKey);
7342   /* Is the selected peer in the tunnel? */
7343   if (NULL == pi)
7344   {
7345     GNUNET_break (0);
7346     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7347     return;
7348   }
7349
7350   /* PID should be as expected */
7351   if (ntohl (data_msg->pid) != t->fwd_pid + 1)
7352   {
7353     GNUNET_break (0);
7354     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7355               "Unicast PID, expected %u, got %u\n",
7356               t->fwd_pid + 1, ntohl (data_msg->pid));
7357     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7358     return;
7359   }
7360
7361   /* Ok, everything is correct, send the message
7362    * (pretend we got it from a mesh peer)
7363    */
7364   {
7365     /* Work around const limitation */
7366     char buf[ntohs (message->size)] GNUNET_ALIGN;
7367     struct GNUNET_MESH_Unicast *copy;
7368
7369     copy = (struct GNUNET_MESH_Unicast *) buf;
7370     memcpy (buf, data_msg, size);
7371     copy->oid = my_full_id;
7372     copy->tid = htonl (t->id.tid);
7373     copy->ttl = htonl (default_ttl);
7374     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7375                 "  calling generic handler...\n");
7376     handle_mesh_data_unicast (NULL, &my_full_id, &copy->header, NULL, 0);
7377   }
7378   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "receive done OK\n");
7379   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7380
7381   return;
7382 }
7383
7384
7385 /**
7386  * Handler for client traffic directed to the origin
7387  *
7388  * @param cls closure
7389  * @param client identification of the client
7390  * @param message the actual message
7391  */
7392 static void
7393 handle_local_to_origin (void *cls, struct GNUNET_SERVER_Client *client,
7394                         const struct GNUNET_MessageHeader *message)
7395 {
7396   struct GNUNET_MESH_ToOrigin *data_msg;
7397   struct MeshTunnelClientInfo *clinfo;
7398   struct MeshClient *c;
7399   struct MeshTunnel *t;
7400   MESH_TunnelNumber tid;
7401   size_t size;
7402
7403   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7404               "Got a ToOrigin request from a client!\n");
7405   /* Sanity check for client registration */
7406   if (NULL == (c = client_get (client)))
7407   {
7408     GNUNET_break (0);
7409     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7410     return;
7411   }
7412   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7413
7414   data_msg = (struct GNUNET_MESH_ToOrigin *) message;
7415
7416   /* Sanity check for message size */
7417   size = ntohs (message->size);
7418   if (sizeof (struct GNUNET_MESH_ToOrigin) +
7419       sizeof (struct GNUNET_MessageHeader) > size)
7420   {
7421     GNUNET_break (0);
7422     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7423     return;
7424   }
7425
7426   /* Tunnel exists? */
7427   tid = ntohl (data_msg->tid);
7428   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
7429   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
7430   {
7431     GNUNET_break (0);
7432     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7433     return;
7434   }
7435   t = tunnel_get_by_local_id (c, tid);
7436   if (NULL == t)
7437   {
7438     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
7439     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
7440     GNUNET_break (0);
7441     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7442     return;
7443   }
7444
7445   /*  It should be sent by someone who has this as incoming tunnel. */
7446   if (GNUNET_NO == client_knows_tunnel (c, t))
7447   {
7448     GNUNET_break (0);
7449     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7450     return;
7451   }
7452
7453   /* PID should be as expected */
7454   clinfo = tunnel_get_client_fc (t, c);
7455   if (ntohl (data_msg->pid) != clinfo->bck_pid + 1)
7456   {
7457     GNUNET_break (0);
7458     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7459                 "To Origin PID, expected %u, got %u\n",
7460                 clinfo->bck_pid + 1,
7461                 ntohl (data_msg->pid));
7462     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7463     return;
7464   }
7465   clinfo->bck_pid++;
7466
7467   /* Ok, everything is correct, send the message
7468    * (pretend we got it from a mesh peer)
7469    */
7470   {
7471     char buf[ntohs (message->size)] GNUNET_ALIGN;
7472     struct GNUNET_MESH_ToOrigin *copy;
7473
7474     /* Work around const limitation */
7475     copy = (struct GNUNET_MESH_ToOrigin *) buf;
7476     memcpy (buf, data_msg, size);
7477     GNUNET_PEER_resolve (t->id.oid, &copy->oid);
7478     copy->tid = htonl (t->id.tid);
7479     copy->ttl = htonl (default_ttl);
7480     copy->pid = htonl (t->bck_pid + 1);
7481
7482     copy->sender = my_full_id;
7483     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7484                 "  calling generic handler...\n");
7485     handle_mesh_data_to_orig (NULL, &my_full_id, &copy->header, NULL, 0);
7486   }
7487   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7488
7489   return;
7490 }
7491
7492
7493 /**
7494  * Handler for client traffic directed to all peers in a tunnel
7495  *
7496  * @param cls closure
7497  * @param client identification of the client
7498  * @param message the actual message
7499  */
7500 static void
7501 handle_local_multicast (void *cls, struct GNUNET_SERVER_Client *client,
7502                         const struct GNUNET_MessageHeader *message)
7503 {
7504   struct MeshClient *c;
7505   struct MeshTunnel *t;
7506   struct GNUNET_MESH_Multicast *data_msg;
7507   MESH_TunnelNumber tid;
7508
7509   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7510               "Got a multicast request from a client!\n");
7511
7512   /* Sanity check for client registration */
7513   if (NULL == (c = client_get (client)))
7514   {
7515     GNUNET_break (0);
7516     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7517     return;
7518   }
7519   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7520
7521   data_msg = (struct GNUNET_MESH_Multicast *) message;
7522
7523   /* Sanity check for message size */
7524   if (sizeof (struct GNUNET_MESH_Multicast) +
7525       sizeof (struct GNUNET_MessageHeader) > ntohs (data_msg->header.size))
7526   {
7527     GNUNET_break (0);
7528     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7529     return;
7530   }
7531
7532   /* Tunnel exists? */
7533   tid = ntohl (data_msg->tid);
7534   t = tunnel_get_by_local_id (c, tid);
7535   if (NULL == t)
7536   {
7537     GNUNET_break (0);
7538     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
7539     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
7540     GNUNET_break (0);
7541     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7542     return;
7543   }
7544
7545   /* Does client own tunnel? */
7546   if (t->owner->handle != client)
7547   {
7548     GNUNET_break (0);
7549     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7550     return;
7551   }
7552
7553   /* PID should be as expected */
7554   if (ntohl (data_msg->pid) != t->fwd_pid + 1)
7555   {
7556     GNUNET_break (0);
7557     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7558               "Multicast PID, expected %u, got %u\n",
7559               t->fwd_pid + 1, ntohl (data_msg->pid));
7560     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7561     return;
7562   }
7563
7564   {
7565     char buf[ntohs (message->size)] GNUNET_ALIGN;
7566     struct GNUNET_MESH_Multicast *copy;
7567
7568     copy = (struct GNUNET_MESH_Multicast *) buf;
7569     memcpy (buf, message, ntohs (message->size));
7570     copy->oid = my_full_id;
7571     copy->tid = htonl (t->id.tid);
7572     copy->ttl = htonl (default_ttl);
7573     GNUNET_assert (ntohl (copy->pid) == (t->fwd_pid + 1));
7574     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7575                 "  calling generic handler...\n");
7576     handle_mesh_data_multicast (client, &my_full_id, &copy->header, NULL, 0);
7577   }
7578
7579   GNUNET_SERVER_receive_done (t->owner->handle, GNUNET_OK);
7580   return;
7581 }
7582
7583
7584 /**
7585  * Handler for client's ACKs for payload traffic.
7586  *
7587  * @param cls Closure (unused).
7588  * @param client Identification of the client.
7589  * @param message The actual message.
7590  */
7591 static void
7592 handle_local_ack (void *cls, struct GNUNET_SERVER_Client *client,
7593                   const struct GNUNET_MessageHeader *message)
7594 {
7595   struct GNUNET_MESH_LocalAck *msg;
7596   struct MeshTunnel *t;
7597   struct MeshClient *c;
7598   MESH_TunnelNumber tid;
7599   uint32_t ack;
7600
7601   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a local ACK\n");
7602   /* Sanity check for client registration */
7603   if (NULL == (c = client_get (client)))
7604   {
7605     GNUNET_break (0);
7606     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7607     return;
7608   }
7609   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7610
7611   msg = (struct GNUNET_MESH_LocalAck *) message;
7612
7613   /* Tunnel exists? */
7614   tid = ntohl (msg->tunnel_id);
7615   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
7616   t = tunnel_get_by_local_id (c, tid);
7617   if (NULL == t)
7618   {
7619     GNUNET_break (0);
7620     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
7621     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
7622     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7623     return;
7624   }
7625
7626   ack = ntohl (msg->max_pid);
7627   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ack %u\n", ack);
7628
7629   /* Does client own tunnel? I.E: Is this an ACK for BCK traffic? */
7630   if (NULL != t->owner && t->owner->handle == client)
7631   {
7632     /* The client owns the tunnel, ACK is for data to_origin, send BCK ACK. */
7633     t->bck_ack = ack;
7634     tunnel_send_bck_ack(t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
7635   }
7636   else
7637   {
7638     /* The client doesn't own the tunnel, this ACK is for FWD traffic. */
7639     tunnel_set_client_fwd_ack (t, c, ack);
7640     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
7641   }
7642
7643   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7644
7645   return;
7646 }
7647
7648
7649 /**
7650  * Iterator over all peers to send a monitoring client info about a tunnel.
7651  *
7652  * @param cls Closure (message being built).
7653  * @param key Key (hashed tunnel ID, unused).
7654  * @param value Peer info.
7655  *
7656  * @return GNUNET_YES, to keep iterating.
7657  */
7658 static int
7659 monitor_peers_iterator (void *cls,
7660                         const struct GNUNET_HashCode * key,
7661                         void *value)
7662 {
7663   struct GNUNET_MESH_LocalMonitor *msg = cls;
7664   struct GNUNET_PeerIdentity *id;
7665   struct MeshPeerInfo *info = value;
7666
7667   id = (struct GNUNET_PeerIdentity *) &msg[1];
7668   GNUNET_PEER_resolve (info->id, &id[msg->npeers]);
7669   msg->npeers++;
7670
7671   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
7672               "*    sending info about peer %s [%u]\n",
7673               GNUNET_i2s (&id[msg->npeers - 1]), msg->npeers);
7674
7675   return GNUNET_YES;
7676 }
7677
7678
7679
7680 /**
7681  * Iterator over all tunnels to send a monitoring client info about each tunnel.
7682  *
7683  * @param cls Closure (client handle).
7684  * @param key Key (hashed tunnel ID, unused).
7685  * @param value Tunnel info.
7686  *
7687  * @return GNUNET_YES, to keep iterating.
7688  */
7689 static int
7690 monitor_all_tunnels_iterator (void *cls,
7691                               const struct GNUNET_HashCode * key,
7692                               void *value)
7693 {
7694   struct GNUNET_SERVER_Client *client = cls;
7695   struct MeshTunnel *t = value;
7696   struct GNUNET_MESH_LocalMonitor *msg;
7697   uint32_t npeers;
7698   
7699   npeers = GNUNET_CONTAINER_multihashmap_size (t->peers);
7700   msg = GNUNET_malloc (sizeof(struct GNUNET_MESH_LocalMonitor) +
7701   npeers * sizeof (struct GNUNET_PeerIdentity));
7702   GNUNET_PEER_resolve(t->id.oid, &msg->owner);
7703   msg->tunnel_id = htonl (t->id.tid);
7704   msg->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor) +
7705   npeers * sizeof (struct GNUNET_PeerIdentity));
7706   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS);
7707   msg->npeers = 0;
7708   (void) GNUNET_CONTAINER_multihashmap_iterate (t->peers,
7709                                                 monitor_peers_iterator,
7710                                                 msg);
7711   
7712   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
7713               "*  sending info about tunnel %s [%u] (%u peers)\n",
7714               GNUNET_i2s (&msg->owner), t->id.tid, npeers);
7715   
7716   if (msg->npeers != npeers)
7717   {
7718     GNUNET_break (0);
7719     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7720                 "Get tunnels fail: size %u - iter %u\n",
7721                 npeers, msg->npeers);
7722   }
7723   
7724     msg->npeers = htonl (npeers);
7725     GNUNET_SERVER_notification_context_unicast (nc, client,
7726                                                 &msg->header, GNUNET_NO);
7727     return GNUNET_YES;
7728 }
7729
7730
7731 /**
7732  * Handler for client's MONITOR request.
7733  *
7734  * @param cls Closure (unused).
7735  * @param client Identification of the client.
7736  * @param message The actual message.
7737  */
7738 static void
7739 handle_local_get_tunnels (void *cls, struct GNUNET_SERVER_Client *client,
7740                           const struct GNUNET_MessageHeader *message)
7741 {
7742   struct MeshClient *c;
7743
7744   /* Sanity check for client registration */
7745   if (NULL == (c = client_get (client)))
7746   {
7747     GNUNET_break (0);
7748     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7749     return;
7750   }
7751
7752   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
7753               "Received get tunnels request from client %u\n",
7754               c->id);
7755   GNUNET_CONTAINER_multihashmap_iterate (tunnels,
7756                                          monitor_all_tunnels_iterator,
7757                                          client);
7758   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
7759               "Get tunnels request from client %u completed\n",
7760               c->id);
7761   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7762 }
7763
7764
7765 /**
7766  * Data needed to build a Monitor_Tunnel message.
7767  */
7768 struct MeshMonitorTunnelContext
7769 {
7770   /**
7771    * Partial message, including peer count.
7772    */
7773   struct GNUNET_MESH_LocalMonitor *msg;
7774
7775   /**
7776    * Hashmap with positions: peer->position.
7777    */
7778   struct GNUNET_CONTAINER_MultiHashMap *lookup;
7779
7780   /**
7781    * Index of the parent of each peer in the message, realtive to the absolute
7782    * order in the array (can be in a previous message).
7783    */
7784   uint32_t parents[1024];
7785
7786   /**
7787    * Peers visited so far in the tree, aka position of the current peer.
7788    */
7789   unsigned int npeers;
7790
7791   /**
7792    * Client requesting the info.
7793    */
7794   struct MeshClient *c;
7795 };
7796
7797
7798 /**
7799  * Send a client a message about the structure of a tunnel.
7800  *
7801  * @param ctx Context of the tunnel iteration, with info regarding the state
7802  *            of the execution and the number of peers visited for this message.
7803  */
7804 static void
7805 send_client_tunnel_info (struct MeshMonitorTunnelContext *ctx)
7806 {
7807   struct GNUNET_MESH_LocalMonitor *resp = ctx->msg;
7808   struct GNUNET_PeerIdentity *pid;
7809   unsigned int *parent;
7810   size_t size;
7811
7812   size = sizeof (struct GNUNET_MESH_LocalMonitor);
7813   size += (sizeof (struct GNUNET_PeerIdentity) + sizeof (int)) * resp->npeers;
7814   resp->header.size = htons (size);
7815   pid = (struct GNUNET_PeerIdentity *) &resp[1];
7816   parent = (unsigned int *) &pid[resp->npeers];
7817   memcpy (parent, ctx->parents, sizeof(uint32_t) * resp->npeers);
7818   GNUNET_SERVER_notification_context_unicast (nc, ctx->c->handle,
7819                                               &resp->header, GNUNET_NO);
7820 }
7821
7822 /**
7823  * Iterator over a tunnel tree to build a message containing all peers
7824  * the in the tunnel, including relay nodes.
7825  *
7826  * @param cls Closure (pointer to pointer of message being built).
7827  * @param peer Short ID of a peer.
7828  * @param parent Short ID of the @c peer 's parent.
7829  */
7830 static void
7831 tunnel_tree_iterator (void *cls,
7832                       GNUNET_PEER_Id peer,
7833                       GNUNET_PEER_Id parent)
7834 {
7835   struct MeshMonitorTunnelContext *ctx = cls;
7836   struct GNUNET_MESH_LocalMonitor *msg;
7837   struct GNUNET_PeerIdentity *pid;
7838   struct GNUNET_PeerIdentity ppid;
7839
7840   msg = ctx->msg;
7841   pid = (struct GNUNET_PeerIdentity *) &msg[1];
7842   GNUNET_PEER_resolve (peer, &pid[msg->npeers]);
7843   GNUNET_CONTAINER_multihashmap_put (ctx->lookup,
7844                                      &pid[msg->npeers].hashPubKey,
7845                                      (void *) (long) ctx->npeers,
7846                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
7847   GNUNET_PEER_resolve (parent, &ppid);
7848   ctx->parents[msg->npeers] =
7849       htonl ((long) GNUNET_CONTAINER_multihashmap_get (ctx->lookup,
7850                                                        &ppid.hashPubKey));
7851
7852   ctx->npeers++;
7853   msg->npeers++;
7854
7855   if (sizeof (struct GNUNET_MESH_LocalMonitor) +
7856       (msg->npeers + 1) *
7857       (sizeof (struct GNUNET_PeerIdentity) + sizeof (uint32_t))
7858       > USHRT_MAX)
7859   {
7860     send_client_tunnel_info (ctx);
7861     msg->npeers = 0;
7862   }
7863 }
7864
7865
7866 /**
7867  * Handler for client's MONITOR_TUNNEL request.
7868  *
7869  * @param cls Closure (unused).
7870  * @param client Identification of the client.
7871  * @param message The actual message.
7872  */
7873 static void
7874 handle_local_show_tunnel (void *cls, struct GNUNET_SERVER_Client *client,
7875                           const struct GNUNET_MessageHeader *message)
7876 {
7877   const struct GNUNET_MESH_LocalMonitor *msg;
7878   struct GNUNET_MESH_LocalMonitor *resp;
7879   struct MeshMonitorTunnelContext ctx;
7880   struct MeshClient *c;
7881   struct MeshTunnel *t;
7882
7883   /* Sanity check for client registration */
7884   if (NULL == (c = client_get (client)))
7885   {
7886     GNUNET_break (0);
7887     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7888     return;
7889   }
7890
7891   msg = (struct GNUNET_MESH_LocalMonitor *) message;
7892   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
7893               "Received tunnel info request from client %u for tunnel %s[%X]\n",
7894               c->id,
7895               &msg->owner,
7896               ntohl (msg->tunnel_id));
7897   t = tunnel_get (&msg->owner, ntohl (msg->tunnel_id));
7898   if (NULL == t)
7899   {
7900     /* We don't know the tunnel */
7901     struct GNUNET_MESH_LocalMonitor warn;
7902
7903     warn = *msg;
7904     warn.npeers = htonl (UINT_MAX);
7905     GNUNET_SERVER_notification_context_unicast (nc, client,
7906                                                 &warn.header,
7907                                                 GNUNET_NO);
7908     GNUNET_SERVER_receive_done (client, GNUNET_OK);
7909     return;
7910   }
7911
7912   /* Initialize context */
7913   resp = GNUNET_malloc (USHRT_MAX); /* avoid realloc'ing on each step */
7914   *resp = *msg;
7915   resp->npeers = 0;
7916   ctx.msg = resp;
7917   ctx.lookup = GNUNET_CONTAINER_multihashmap_create (4 * t->peers_total,
7918                                                      GNUNET_YES);
7919   ctx.c = c;
7920
7921   /* Collect and send information */
7922   tree_iterate_all (t->tree, &tunnel_tree_iterator, &ctx);
7923   send_client_tunnel_info (&ctx);
7924
7925   /* Free context */
7926   GNUNET_CONTAINER_multihashmap_destroy (ctx.lookup);
7927   GNUNET_free (resp);
7928
7929   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
7930               "Monitor tunnel request from client %u completed\n",
7931               c->id);
7932   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7933 }
7934
7935
7936 /**
7937  * Functions to handle messages from clients
7938  */
7939 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
7940   {&handle_local_new_client, NULL,
7941    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
7942   {&handle_local_announce_regex, NULL,
7943    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ANNOUNCE_REGEX, 0},
7944   {&handle_local_tunnel_create, NULL,
7945    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
7946    sizeof (struct GNUNET_MESH_TunnelMessage)},
7947   {&handle_local_tunnel_destroy, NULL,
7948    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
7949    sizeof (struct GNUNET_MESH_TunnelMessage)},
7950   {&handle_local_tunnel_speed, NULL,
7951    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MIN,
7952    sizeof (struct GNUNET_MESH_TunnelMessage)},
7953   {&handle_local_tunnel_speed, NULL,
7954    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MAX,
7955    sizeof (struct GNUNET_MESH_TunnelMessage)},
7956   {&handle_local_tunnel_buffer, NULL,
7957    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER,
7958    sizeof (struct GNUNET_MESH_TunnelMessage)},
7959   {&handle_local_tunnel_buffer, NULL,
7960    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER,
7961    sizeof (struct GNUNET_MESH_TunnelMessage)},
7962   {&handle_local_connect_add, NULL,
7963    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD,
7964    sizeof (struct GNUNET_MESH_PeerControl)},
7965   {&handle_local_connect_del, NULL,
7966    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL,
7967    sizeof (struct GNUNET_MESH_PeerControl)},
7968   {&handle_local_blacklist, NULL,
7969    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_BLACKLIST,
7970    sizeof (struct GNUNET_MESH_PeerControl)},
7971   {&handle_local_unblacklist, NULL,
7972    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_UNBLACKLIST,
7973    sizeof (struct GNUNET_MESH_PeerControl)},
7974   {&handle_local_connect_by_type, NULL,
7975    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE,
7976    sizeof (struct GNUNET_MESH_ConnectPeerByType)},
7977   {&handle_local_connect_by_string, NULL,
7978    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_STRING, 0},
7979   {&handle_local_unicast, NULL,
7980    GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
7981   {&handle_local_to_origin, NULL,
7982    GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
7983   {&handle_local_multicast, NULL,
7984    GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
7985   {&handle_local_ack, NULL,
7986    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK,
7987    sizeof (struct GNUNET_MESH_LocalAck)},
7988   {&handle_local_get_tunnels, NULL,
7989    GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS,
7990    sizeof (struct GNUNET_MessageHeader)},
7991   {&handle_local_show_tunnel, NULL,
7992    GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNEL,
7993      sizeof (struct GNUNET_MESH_LocalMonitor)},
7994   {NULL, NULL, 0, 0}
7995 };
7996
7997
7998 /**
7999  * To be called on core init/fail.
8000  *
8001  * @param cls service closure
8002  * @param server handle to the server for this service
8003  * @param identity the public identity of this peer
8004  */
8005 static void
8006 core_init (void *cls, struct GNUNET_CORE_Handle *server,
8007            const struct GNUNET_PeerIdentity *identity)
8008 {
8009   static int i = 0;
8010   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
8011   core_handle = server;
8012   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)) ||
8013       NULL == server)
8014   {
8015     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
8016     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8017                 " core id %s\n",
8018                 GNUNET_i2s (identity));
8019     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8020                 " my id %s\n",
8021                 GNUNET_i2s (&my_full_id));
8022     GNUNET_SCHEDULER_shutdown (); // Try gracefully
8023     if (10 < i++)
8024       GNUNET_abort(); // Try harder
8025   }
8026   return;
8027 }
8028
8029
8030 /**
8031  * Method called whenever a given peer connects.
8032  *
8033  * @param cls closure
8034  * @param peer peer identity this notification is about
8035  * @param atsi performance data for the connection
8036  * @param atsi_count number of records in 'atsi'
8037  */
8038 static void
8039 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
8040               const struct GNUNET_ATS_Information *atsi,
8041               unsigned int atsi_count)
8042 {
8043   struct MeshPeerInfo *peer_info;
8044   struct MeshPeerPath *path;
8045
8046   DEBUG_CONN ("Peer connected\n");
8047   DEBUG_CONN ("     %s\n", GNUNET_i2s (&my_full_id));
8048   peer_info = peer_info_get (peer);
8049   if (myid == peer_info->id)
8050   {
8051     DEBUG_CONN ("     (self)\n");
8052     return;
8053   }
8054   else
8055   {
8056     DEBUG_CONN ("     %s\n", GNUNET_i2s (peer));
8057   }
8058   path = path_new (2);
8059   path->peers[0] = myid;
8060   path->peers[1] = peer_info->id;
8061   GNUNET_PEER_change_rc (myid, 1);
8062   GNUNET_PEER_change_rc (peer_info->id, 1);
8063   peer_info_add_path (peer_info, path, GNUNET_YES);
8064   GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
8065   return;
8066 }
8067
8068
8069 /**
8070  * Method called whenever a peer disconnects.
8071  *
8072  * @param cls closure
8073  * @param peer peer identity this notification is about
8074  */
8075 static void
8076 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
8077 {
8078   struct MeshPeerInfo *pi;
8079   struct MeshPeerQueue *q;
8080   struct MeshPeerQueue *n;
8081
8082   DEBUG_CONN ("Peer disconnected\n");
8083   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
8084   if (NULL == pi)
8085   {
8086     GNUNET_break (0);
8087     return;
8088   }
8089   q = pi->queue_head;
8090   while (NULL != q)
8091   {
8092       n = q->next;
8093       /* TODO try to reroute this traffic instead */
8094       queue_destroy(q, GNUNET_YES);
8095       q = n;
8096   }
8097   if (NULL != pi->core_transmit)
8098   {
8099     GNUNET_CORE_notify_transmit_ready_cancel(pi->core_transmit);
8100     pi->core_transmit = NULL;
8101   }
8102   peer_info_remove_path (pi, pi->id, myid);
8103   if (myid == pi->id)
8104   {
8105     DEBUG_CONN ("     (self)\n");
8106   }
8107   GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
8108   return;
8109 }
8110
8111
8112 /******************************************************************************/
8113 /************************      MAIN FUNCTIONS      ****************************/
8114 /******************************************************************************/
8115
8116 /**
8117  * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
8118  *
8119  * @param cls closure
8120  * @param key current key code
8121  * @param value value in the hash map
8122  * @return GNUNET_YES if we should continue to iterate,
8123  *         GNUNET_NO if not.
8124  */
8125 static int
8126 shutdown_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
8127 {
8128   struct MeshTunnel *t = value;
8129
8130   tunnel_destroy (t);
8131   return GNUNET_YES;
8132 }
8133
8134 /**
8135  * Iterator over peer hash map entries to destroy the tunnel during shutdown.
8136  *
8137  * @param cls closure
8138  * @param key current key code
8139  * @param value value in the hash map
8140  * @return GNUNET_YES if we should continue to iterate,
8141  *         GNUNET_NO if not.
8142  */
8143 static int
8144 shutdown_peer (void *cls, const struct GNUNET_HashCode * key, void *value)
8145 {
8146   struct MeshPeerInfo *p = value;
8147   struct MeshPeerQueue *q;
8148   struct MeshPeerQueue *n;
8149
8150   q = p->queue_head;
8151   while (NULL != q)
8152   {
8153       n = q->next;
8154       if (q->peer == p)
8155       {
8156         queue_destroy(q, GNUNET_YES);
8157       }
8158       q = n;
8159   }
8160   peer_info_destroy (p);
8161   return GNUNET_YES;
8162 }
8163
8164
8165 /**
8166  * Task run during shutdown.
8167  *
8168  * @param cls unused
8169  * @param tc unused
8170  */
8171 static void
8172 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
8173 {
8174   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
8175
8176   if (core_handle != NULL)
8177   {
8178     GNUNET_CORE_disconnect (core_handle);
8179     core_handle = NULL;
8180   }
8181   if (NULL != keygen)
8182   {
8183     GNUNET_CRYPTO_rsa_key_create_stop (keygen);
8184     keygen = NULL;
8185   }
8186   GNUNET_CONTAINER_multihashmap_iterate (tunnels, &shutdown_tunnel, NULL);
8187   GNUNET_CONTAINER_multihashmap_iterate (peers, &shutdown_peer, NULL);
8188   if (dht_handle != NULL)
8189   {
8190     GNUNET_DHT_disconnect (dht_handle);
8191     dht_handle = NULL;
8192   }
8193   if (nc != NULL)
8194   {
8195     GNUNET_SERVER_notification_context_destroy (nc);
8196     nc = NULL;
8197   }
8198   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
8199   {
8200     GNUNET_SCHEDULER_cancel (announce_id_task);
8201     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
8202   }
8203   if (GNUNET_SCHEDULER_NO_TASK != announce_applications_task)
8204   {
8205     GNUNET_SCHEDULER_cancel (announce_applications_task);
8206     announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
8207   }
8208   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
8209 }
8210
8211
8212 /**
8213  * Callback for hostkey read/generation
8214  *
8215  * @param cls Closure (Configuration handle).
8216  * @param pk the private key
8217  * @param emsg error message
8218  */
8219 static void
8220 key_generation_cb (void *cls,
8221                    struct GNUNET_CRYPTO_RsaPrivateKey *pk,
8222                    const char *emsg)
8223 {
8224   const struct GNUNET_CONFIGURATION_Handle *c = cls;
8225   struct MeshPeerInfo *peer;
8226   struct MeshPeerPath *p;
8227
8228   keygen = NULL;  
8229   if (NULL == pk)
8230   {
8231     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8232                 _("Mesh service could not access hostkey: %s. Exiting.\n"),
8233                 emsg);
8234     GNUNET_SCHEDULER_shutdown ();
8235     return;
8236   }
8237   my_private_key = pk;
8238   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
8239   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
8240                       &my_full_id.hashPubKey);
8241   myid = GNUNET_PEER_intern (&my_full_id);
8242   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
8243               "Mesh for peer [%s] starting\n",
8244               GNUNET_i2s(&my_full_id));
8245
8246 //   transport_handle = GNUNET_TRANSPORT_connect(c,
8247 //                                               &my_full_id,
8248 //                                               NULL,
8249 //                                               NULL,
8250 //                                               NULL,
8251 //                                               NULL);
8252
8253   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
8254                                      NULL,      /* Closure passed to MESH functions */
8255                                      &core_init,        /* Call core_init once connected */
8256                                      &core_connect,     /* Handle connects */
8257                                      &core_disconnect,  /* remove peers on disconnects */
8258                                      NULL,      /* Don't notify about all incoming messages */
8259                                      GNUNET_NO, /* For header only in notification */
8260                                      NULL,      /* Don't notify about all outbound messages */
8261                                      GNUNET_NO, /* For header-only out notification */
8262                                      core_handlers);    /* Register these handlers */
8263   
8264   if (core_handle == NULL)
8265   {
8266     GNUNET_break (0);
8267     GNUNET_SCHEDULER_shutdown ();
8268     return;
8269   }
8270
8271   next_tid = 0;
8272   next_local_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
8273
8274
8275   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
8276   nc = GNUNET_SERVER_notification_context_create (server_handle, 1);
8277   GNUNET_SERVER_disconnect_notify (server_handle,
8278                                    &handle_local_client_disconnect, NULL);
8279
8280
8281   clients = NULL;
8282   clients_tail = NULL;
8283   next_client_id = 0;
8284
8285   announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
8286   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
8287
8288   /* Create a peer_info for the local peer */
8289   peer = peer_info_get (&my_full_id);
8290   p = path_new (1);
8291   p->peers[0] = myid;
8292   GNUNET_PEER_change_rc (myid, 1);
8293   peer_info_add_path (peer, p, GNUNET_YES);
8294   GNUNET_SERVER_resume (server_handle);
8295   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Mesh service running\n");
8296 }
8297
8298
8299 /**
8300  * Process mesh requests.
8301  *
8302  * @param cls closure
8303  * @param server the initialized server
8304  * @param c configuration to use
8305  */
8306 static void
8307 run (void *cls, struct GNUNET_SERVER_Handle *server,
8308      const struct GNUNET_CONFIGURATION_Handle *c)
8309 {
8310   char *keyfile;
8311
8312   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
8313   server_handle = server;
8314
8315   if (GNUNET_OK !=
8316       GNUNET_CONFIGURATION_get_value_filename (c, "GNUNETD", "HOSTKEY",
8317                                                &keyfile))
8318   {
8319     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8320                 _
8321                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8322                 "mesh", "hostkey");
8323     GNUNET_SCHEDULER_shutdown ();
8324     return;
8325   }
8326
8327   if (GNUNET_OK !=
8328       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_PATH_TIME",
8329                                            &refresh_path_time))
8330   {
8331     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8332                 _
8333                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8334                 "mesh", "refresh path time");
8335     GNUNET_SCHEDULER_shutdown ();
8336     return;
8337   }
8338
8339   if (GNUNET_OK !=
8340       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "APP_ANNOUNCE_TIME",
8341                                            &app_announce_time))
8342   {
8343     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8344                 _
8345                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8346                 "mesh", "app announce time");
8347     GNUNET_SCHEDULER_shutdown ();
8348     return;
8349   }
8350   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
8351               "APP_ANNOUNCE_TIME %llu ms\n", 
8352               app_announce_time.rel_value);
8353   if (GNUNET_OK !=
8354       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "ID_ANNOUNCE_TIME",
8355                                            &id_announce_time))
8356   {
8357     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8358                 _
8359                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8360                 "mesh", "id announce time");
8361     GNUNET_SCHEDULER_shutdown ();
8362     return;
8363   }
8364
8365   if (GNUNET_OK !=
8366       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "CONNECT_TIMEOUT",
8367                                            &connect_timeout))
8368   {
8369     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8370                 _
8371                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8372                 "mesh", "connect timeout");
8373     GNUNET_SCHEDULER_shutdown ();
8374     return;
8375   }
8376
8377   if (GNUNET_OK !=
8378       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
8379                                              &max_msgs_queue))
8380   {
8381     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8382                 _
8383                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8384                 "mesh", "max msgs queue");
8385     GNUNET_SCHEDULER_shutdown ();
8386     return;
8387   }
8388
8389   if (GNUNET_OK !=
8390       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_TUNNELS",
8391                                              &max_tunnels))
8392   {
8393     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8394                 _
8395                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8396                 "mesh", "max tunnels");
8397     GNUNET_SCHEDULER_shutdown ();
8398     return;
8399   }
8400
8401   if (GNUNET_OK !=
8402       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
8403                                              &default_ttl))
8404   {
8405     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
8406                 _
8407                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
8408                 "mesh", "default ttl", 64);
8409     default_ttl = 64;
8410   }
8411
8412   if (GNUNET_OK !=
8413       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_PEERS",
8414                                              &max_peers))
8415   {
8416     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
8417                 _("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
8418                 "mesh", "max peers", 1000);
8419     max_peers = 1000;
8420   }
8421
8422   if (GNUNET_OK !=
8423       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DHT_REPLICATION_LEVEL",
8424                                              &dht_replication_level))
8425   {
8426     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
8427                 _
8428                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
8429                 "mesh", "dht replication level", 3);
8430     dht_replication_level = 3;
8431   }
8432
8433   tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
8434   incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
8435   peers = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
8436   applications = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
8437   types = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
8438
8439   dht_handle = GNUNET_DHT_connect (c, 64);
8440   if (NULL == dht_handle)
8441   {
8442     GNUNET_break (0);
8443   }
8444   stats = GNUNET_STATISTICS_create ("mesh", c);
8445
8446   GNUNET_SERVER_suspend (server_handle);
8447   /* Scheduled the task to clean up when shutdown is called */
8448   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
8449                                 NULL);
8450   keygen = GNUNET_CRYPTO_rsa_key_create_start (keyfile,
8451                                                &key_generation_cb,
8452                                                (void *) c);
8453   GNUNET_free (keyfile);
8454 }
8455
8456
8457 /**
8458  * The main function for the mesh service.
8459  *
8460  * @param argc number of arguments from the command line
8461  * @param argv command line arguments
8462  * @return 0 ok, 1 on error
8463  */
8464 int
8465 main (int argc, char *const *argv)
8466 {
8467   int ret;
8468   int r;
8469
8470   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
8471   r = GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
8472                           NULL);
8473   ret = (GNUNET_OK == r) ? 0 : 1;
8474   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");
8475
8476   INTERVAL_SHOW;
8477
8478   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
8479               "Mesh for peer [%s] FWD ACKs %u, BCK ACKs %u\n",
8480               GNUNET_i2s(&my_full_id), debug_fwd_ack, debug_bck_ack);
8481
8482   return ret;
8483 }