fix core api
[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 {
5075   unsigned int own_pos;
5076   uint16_t size;
5077   uint16_t i;
5078   MESH_TunnelNumber tid;
5079   struct GNUNET_MESH_ManipulatePath *msg;
5080   struct GNUNET_PeerIdentity *pi;
5081   struct GNUNET_HashCode hash;
5082   struct MeshPeerPath *path;
5083   struct MeshPeerInfo *dest_peer_info;
5084   struct MeshPeerInfo *orig_peer_info;
5085   struct MeshTunnel *t;
5086
5087   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5088               "Received a path create msg [%s]\n",
5089               GNUNET_i2s (&my_full_id));
5090   size = ntohs (message->size);
5091   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
5092   {
5093     GNUNET_break_op (0);
5094     return GNUNET_OK;
5095   }
5096
5097   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
5098   if (size % sizeof (struct GNUNET_PeerIdentity))
5099   {
5100     GNUNET_break_op (0);
5101     return GNUNET_OK;
5102   }
5103   size /= sizeof (struct GNUNET_PeerIdentity);
5104   if (size < 2)
5105   {
5106     GNUNET_break_op (0);
5107     return GNUNET_OK;
5108   }
5109   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
5110   msg = (struct GNUNET_MESH_ManipulatePath *) message;
5111
5112   tid = ntohl (msg->tid);
5113   pi = (struct GNUNET_PeerIdentity *) &msg[1];
5114   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5115               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi), tid);
5116   t = tunnel_get (pi, tid);
5117   if (NULL == t) // FIXME only for INCOMING tunnels?
5118   {
5119     uint32_t opt;
5120
5121     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating tunnel\n");
5122     t = tunnel_new (GNUNET_PEER_intern (pi), tid, NULL, 0);
5123     if (NULL == t)
5124     {
5125       // FIXME notify failure
5126       return GNUNET_OK;
5127     }
5128     opt = ntohl (msg->opt);
5129     t->speed_min = (0 != (opt & MESH_TUNNEL_OPT_SPEED_MIN)) ?
5130                    GNUNET_YES : GNUNET_NO;
5131     if (0 != (opt & MESH_TUNNEL_OPT_NOBUFFER))
5132     {
5133       t->nobuffer = GNUNET_YES;
5134       t->last_fwd_ack = t->fwd_pid + 1;
5135     }
5136     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5137                 "  speed_min: %d, nobuffer:%d\n",
5138                 t->speed_min, t->nobuffer);
5139
5140     if (GNUNET_YES == t->nobuffer)
5141     {
5142       t->bck_queue_max = 1;
5143       t->fwd_queue_max = 1;
5144     }
5145
5146     // FIXME only assign a local tid if a local client is interested (on demand)
5147     while (NULL != tunnel_get_incoming (next_local_tid))
5148       next_local_tid = (next_local_tid + 1) | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
5149     t->local_tid_dest = next_local_tid++;
5150     next_local_tid = next_local_tid | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
5151     // FIXME end
5152
5153     tunnel_reset_timeout (t);
5154     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
5155     if (GNUNET_OK !=
5156         GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
5157                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
5158     {
5159       tunnel_destroy (t);
5160       GNUNET_break (0);
5161       return GNUNET_OK;
5162     }
5163   }
5164   dest_peer_info =
5165       GNUNET_CONTAINER_multihashmap_get (peers, &pi[size - 1].hashPubKey);
5166   if (NULL == dest_peer_info)
5167   {
5168     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5169                 "  Creating PeerInfo for destination.\n");
5170     dest_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
5171     dest_peer_info->id = GNUNET_PEER_intern (&pi[size - 1]);
5172     GNUNET_CONTAINER_multihashmap_put (peers, &pi[size - 1].hashPubKey,
5173                                        dest_peer_info,
5174                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
5175   }
5176   orig_peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &pi->hashPubKey);
5177   if (NULL == orig_peer_info)
5178   {
5179     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5180                 "  Creating PeerInfo for origin.\n");
5181     orig_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
5182     orig_peer_info->id = GNUNET_PEER_intern (pi);
5183     GNUNET_CONTAINER_multihashmap_put (peers, &pi->hashPubKey, orig_peer_info,
5184                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
5185   }
5186   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
5187   path = path_new (size);
5188   own_pos = 0;
5189   for (i = 0; i < size; i++)
5190   {
5191     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
5192                 GNUNET_i2s (&pi[i]));
5193     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
5194     if (path->peers[i] == myid)
5195       own_pos = i;
5196   }
5197   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
5198   if (own_pos == 0)
5199   {
5200     /* cannot be self, must be 'not found' */
5201     /* create path: self not found in path through self */
5202     GNUNET_break_op (0);
5203     path_destroy (path);
5204     tunnel_destroy (t);
5205     return GNUNET_OK;
5206   }
5207   path_add_to_peers (path, GNUNET_NO);
5208   tunnel_add_path (t, path, own_pos);
5209   if (own_pos == size - 1)
5210   {
5211     /* It is for us! Send ack. */
5212     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
5213     peer_info_add_path_to_origin (orig_peer_info, path, GNUNET_NO);
5214     if (NULL == t->peers)
5215     {
5216       /* New tunnel! Notify clients on first payload message. */
5217       t->peers = GNUNET_CONTAINER_multihashmap_create (4, GNUNET_NO);
5218     }
5219     GNUNET_break (GNUNET_SYSERR !=
5220                   GNUNET_CONTAINER_multihashmap_put (t->peers,
5221                                                      &my_full_id.hashPubKey,
5222                                                      peer_info_get
5223                                                      (&my_full_id),
5224                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE));
5225     send_path_ack (t);
5226   }
5227   else
5228   {
5229     struct MeshPeerPath *path2;
5230
5231     /* It's for somebody else! Retransmit. */
5232     path2 = path_duplicate (path);
5233     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Retransmitting.\n");
5234     peer_info_add_path (dest_peer_info, path2, GNUNET_NO);
5235     path2 = path_duplicate (path);
5236     peer_info_add_path_to_origin (orig_peer_info, path2, GNUNET_NO);
5237     send_create_path (dest_peer_info, path, t);
5238   }
5239   return GNUNET_OK;
5240 }
5241
5242
5243 /**
5244  * Core handler for path destruction
5245  *
5246  * @param cls closure
5247  * @param message message
5248  * @param peer peer identity this notification is about
5249  * @param atsi performance data
5250  * @param atsi_count number of records in 'atsi'
5251  *
5252  * @return GNUNET_OK to keep the connection open,
5253  *         GNUNET_SYSERR to close it (signal serious error)
5254  */
5255 static int
5256 handle_mesh_path_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
5257                           const struct GNUNET_MessageHeader *message)
5258 {
5259   struct GNUNET_MESH_ManipulatePath *msg;
5260   struct GNUNET_PeerIdentity *pi;
5261   struct MeshPeerPath *path;
5262   struct MeshTunnel *t;
5263   unsigned int own_pos;
5264   unsigned int i;
5265   size_t size;
5266
5267   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5268               "Received a PATH DESTROY msg from %s\n", GNUNET_i2s (peer));
5269   size = ntohs (message->size);
5270   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
5271   {
5272     GNUNET_break_op (0);
5273     return GNUNET_OK;
5274   }
5275
5276   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
5277   if (size % sizeof (struct GNUNET_PeerIdentity))
5278   {
5279     GNUNET_break_op (0);
5280     return GNUNET_OK;
5281   }
5282   size /= sizeof (struct GNUNET_PeerIdentity);
5283   if (size < 2)
5284   {
5285     GNUNET_break_op (0);
5286     return GNUNET_OK;
5287   }
5288   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
5289
5290   msg = (struct GNUNET_MESH_ManipulatePath *) message;
5291   pi = (struct GNUNET_PeerIdentity *) &msg[1];
5292   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5293               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi),
5294               msg->tid);
5295   t = tunnel_get (pi, ntohl (msg->tid));
5296   if (NULL == t)
5297   {
5298     /* TODO notify back: we don't know this tunnel */
5299     GNUNET_break_op (0);
5300     return GNUNET_OK;
5301   }
5302   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
5303   path = path_new (size);
5304   own_pos = 0;
5305   for (i = 0; i < size; i++)
5306   {
5307     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
5308                 GNUNET_i2s (&pi[i]));
5309     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
5310     if (path->peers[i] == myid)
5311       own_pos = i;
5312   }
5313   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
5314   if (own_pos < path->length - 1)
5315     send_prebuilt_message (message, &pi[own_pos + 1], t);
5316   else
5317     send_client_tunnel_disconnect(t, NULL);
5318
5319   tunnel_delete_peer (t, path->peers[path->length - 1]);
5320   path_destroy (path);
5321   return GNUNET_OK;
5322 }
5323
5324
5325 /**
5326  * Core handler for notifications of broken paths
5327  *
5328  * @param cls closure
5329  * @param message message
5330  * @param peer peer identity this notification is about
5331  * @param atsi performance data
5332  * @param atsi_count number of records in 'atsi'
5333  *
5334  * @return GNUNET_OK to keep the connection open,
5335  *         GNUNET_SYSERR to close it (signal serious error)
5336  */
5337 static int
5338 handle_mesh_path_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
5339                          const struct GNUNET_MessageHeader *message)
5340 {
5341   struct GNUNET_MESH_PathBroken *msg;
5342   struct MeshTunnel *t;
5343
5344   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5345               "Received a PATH BROKEN msg from %s\n", GNUNET_i2s (peer));
5346   msg = (struct GNUNET_MESH_PathBroken *) message;
5347   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
5348               GNUNET_i2s (&msg->peer1));
5349   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
5350               GNUNET_i2s (&msg->peer2));
5351   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5352   if (NULL == t)
5353   {
5354     GNUNET_break_op (0);
5355     return GNUNET_OK;
5356   }
5357   tunnel_notify_connection_broken (t, GNUNET_PEER_search (&msg->peer1),
5358                                    GNUNET_PEER_search (&msg->peer2));
5359   return GNUNET_OK;
5360
5361 }
5362
5363
5364 /**
5365  * Core handler for tunnel destruction
5366  *
5367  * @param cls closure
5368  * @param message message
5369  * @param peer peer identity this notification is about
5370  * @param atsi performance data
5371  * @param atsi_count number of records in 'atsi'
5372  *
5373  * @return GNUNET_OK to keep the connection open,
5374  *         GNUNET_SYSERR to close it (signal serious error)
5375  */
5376 static int
5377 handle_mesh_tunnel_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
5378                             const struct GNUNET_MessageHeader *message)
5379 {
5380   struct GNUNET_MESH_TunnelDestroy *msg;
5381   struct MeshTunnel *t;
5382   GNUNET_PEER_Id parent;
5383   GNUNET_PEER_Id pid;
5384
5385   msg = (struct GNUNET_MESH_TunnelDestroy *) message;
5386   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5387               "Got a TUNNEL DESTROY packet from %s\n",
5388               GNUNET_i2s (peer));
5389   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5390               "  for tunnel %s [%u]\n",
5391               GNUNET_i2s (&msg->oid), ntohl (msg->tid));
5392   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5393   /* Check signature */
5394   if (NULL == t)
5395   {
5396     /* Probably already got the message from another path,
5397      * destroyed the tunnel and retransmitted to children.
5398      * Safe to ignore.
5399      */
5400     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel",
5401                               1, GNUNET_NO);
5402     return GNUNET_OK;
5403   }
5404   parent = tree_get_predecessor (t->tree);
5405   pid = GNUNET_PEER_search (peer);
5406   if (pid != parent)
5407   {
5408     unsigned int nc;
5409
5410     tree_del_peer (t->tree, pid, &tunnel_child_removed, t);
5411     nc = tree_count_children (t->tree);
5412     if (nc > 0 || NULL != t->owner || t->nclients > 0)
5413     {
5414       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5415                   "still in use: %u cl, %u ch\n",
5416                   t->nclients, nc);
5417       return GNUNET_OK;
5418     }
5419   }
5420   if (t->local_tid_dest >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
5421   {
5422     /* Tunnel was incoming, notify clients */
5423     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "INCOMING TUNNEL %X %X\n",
5424                 t->local_tid, t->local_tid_dest);
5425     send_clients_tunnel_destroy (t);
5426   }
5427   tunnel_send_destroy (t, parent);
5428   t->destroy = GNUNET_YES;
5429   // TODO: add timeout to destroy the tunnel anyway
5430   return GNUNET_OK;
5431 }
5432
5433
5434 /**
5435  * Core handler for mesh network traffic going from the origin to a peer
5436  *
5437  * @param cls closure
5438  * @param peer peer identity this notification is about
5439  * @param message message
5440  * @param atsi performance data
5441  * @param atsi_count number of records in 'atsi'
5442  * @return GNUNET_OK to keep the connection open,
5443  *         GNUNET_SYSERR to close it (signal serious error)
5444  */
5445 static int
5446 handle_mesh_data_unicast (void *cls, const struct GNUNET_PeerIdentity *peer,
5447                           const struct GNUNET_MessageHeader *message)
5448 {
5449   struct GNUNET_MESH_Unicast *msg;
5450   struct GNUNET_PeerIdentity *neighbor;
5451   struct MeshTunnelChildInfo *cinfo;
5452   struct MeshTunnel *t;
5453   GNUNET_PEER_Id dest_id;
5454   uint32_t pid;
5455   uint32_t ttl;
5456   size_t size;
5457
5458   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a unicast packet from %s\n",
5459               GNUNET_i2s (peer));
5460   /* Check size */
5461   size = ntohs (message->size);
5462   if (size <
5463       sizeof (struct GNUNET_MESH_Unicast) +
5464       sizeof (struct GNUNET_MessageHeader))
5465   {
5466     GNUNET_break (0);
5467     return GNUNET_OK;
5468   }
5469   msg = (struct GNUNET_MESH_Unicast *) message;
5470   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %s\n",
5471               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
5472   /* Check tunnel */
5473   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5474   if (NULL == t)
5475   {
5476     /* TODO notify back: we don't know this tunnel */
5477     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
5478     GNUNET_break_op (0);
5479     return GNUNET_OK;
5480   }
5481   pid = ntohl (msg->pid);
5482   if (t->fwd_pid == pid)
5483   {
5484     GNUNET_STATISTICS_update (stats, "# duplicate PID drops", 1, GNUNET_NO);
5485     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5486                 " Already seen pid %u, DROPPING!\n", pid);
5487     return GNUNET_OK;
5488   }
5489   else
5490   {
5491     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5492                 " pid %u not seen yet, forwarding\n", pid);
5493   }
5494
5495   t->skip += (pid - t->fwd_pid) - 1;
5496   t->fwd_pid = pid;
5497
5498   if (GMC_is_pid_bigger (pid, t->last_fwd_ack))
5499   {
5500     GNUNET_STATISTICS_update (stats, "# unsolicited unicast", 1, GNUNET_NO);
5501     GNUNET_break_op (0);
5502     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5503                 "Received PID %u, ACK %u\n",
5504                 pid, t->last_fwd_ack);
5505     return GNUNET_OK;
5506   }
5507
5508   tunnel_reset_timeout (t);
5509   dest_id = GNUNET_PEER_search (&msg->destination);
5510   if (dest_id == myid)
5511   {
5512     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5513                 "  it's for us! sending to clients...\n");
5514     GNUNET_STATISTICS_update (stats, "# unicast received", 1, GNUNET_NO);
5515     send_subscribed_clients (message, &msg[1].header, t);
5516     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_UNICAST);
5517     return GNUNET_OK;
5518   }
5519   ttl = ntohl (msg->ttl);
5520   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ttl);
5521   if (ttl == 0)
5522   {
5523     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
5524     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
5525     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5526     return GNUNET_OK;
5527   }
5528   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5529               "  not for us, retransmitting...\n");
5530
5531   neighbor = tree_get_first_hop (t->tree, dest_id);
5532   cinfo = tunnel_get_neighbor_fc (t, neighbor);
5533   cinfo->fwd_pid = pid;
5534   GNUNET_CONTAINER_multihashmap_iterate (t->children_fc,
5535                                          &tunnel_add_skip,
5536                                          &neighbor);
5537   if (GNUNET_YES == t->nobuffer &&
5538       GNUNET_YES == GMC_is_pid_bigger (pid, cinfo->fwd_ack))
5539   {
5540     GNUNET_STATISTICS_update (stats, "# unsolicited unicast", 1, GNUNET_NO);
5541     GNUNET_log (GNUNET_ERROR_TYPE_INFO, "  %u > %u\n", pid, cinfo->fwd_ack);
5542     GNUNET_break_op (0);
5543     return GNUNET_OK;
5544   }
5545   send_prebuilt_message (message, neighbor, t);
5546   GNUNET_STATISTICS_update (stats, "# unicast forwarded", 1, GNUNET_NO);
5547   return GNUNET_OK;
5548 }
5549
5550
5551 /**
5552  * Core handler for mesh network traffic going from the origin to all peers
5553  *
5554  * @param cls closure
5555  * @param message message
5556  * @param peer peer identity this notification is about
5557  * @param atsi performance data
5558  * @param atsi_count number of records in 'atsi'
5559  * @return GNUNET_OK to keep the connection open,
5560  *         GNUNET_SYSERR to close it (signal serious error)
5561  *
5562  * TODO: Check who we got this from, to validate route.
5563  */
5564 static int
5565 handle_mesh_data_multicast (void *cls, const struct GNUNET_PeerIdentity *peer,
5566                             const struct GNUNET_MessageHeader *message)
5567 {
5568   struct GNUNET_MESH_Multicast *msg;
5569   struct MeshTunnel *t;
5570   size_t size;
5571   uint32_t pid;
5572
5573   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a multicast packet from %s\n",
5574               GNUNET_i2s (peer));
5575   size = ntohs (message->size);
5576   if (sizeof (struct GNUNET_MESH_Multicast) +
5577       sizeof (struct GNUNET_MessageHeader) > size)
5578   {
5579     GNUNET_break_op (0);
5580     return GNUNET_OK;
5581   }
5582   msg = (struct GNUNET_MESH_Multicast *) message;
5583   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5584
5585   if (NULL == t)
5586   {
5587     /* TODO notify that we dont know that tunnel */
5588     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
5589     GNUNET_break_op (0);
5590     return GNUNET_OK;
5591   }
5592   pid = ntohl (msg->pid);
5593   if (t->fwd_pid == pid)
5594   {
5595     /* already seen this packet, drop */
5596     GNUNET_STATISTICS_update (stats, "# duplicate PID drops", 1, GNUNET_NO);
5597     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5598                 " Already seen pid %u, DROPPING!\n", pid);
5599     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5600     return GNUNET_OK;
5601   }
5602   else
5603   {
5604     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5605                 " pid %u not seen yet, forwarding\n", pid);
5606   }
5607   t->skip += (pid - t->fwd_pid) - 1;
5608   t->fwd_pid = pid;
5609   tunnel_reset_timeout (t);
5610
5611   /* Transmit to locally interested clients */
5612   if (NULL != t->peers &&
5613       GNUNET_CONTAINER_multihashmap_contains (t->peers, &my_full_id.hashPubKey))
5614   {
5615     GNUNET_STATISTICS_update (stats, "# multicast received", 1, GNUNET_NO);
5616     send_subscribed_clients (message, &msg[1].header, t);
5617     tunnel_send_fwd_ack(t, GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
5618   }
5619   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ntohl (msg->ttl));
5620   if (ntohl (msg->ttl) == 0)
5621   {
5622     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
5623     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
5624     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5625     return GNUNET_OK;
5626   }
5627   GNUNET_STATISTICS_update (stats, "# multicast forwarded", 1, GNUNET_NO);
5628   tunnel_send_multicast (t, message);
5629   return GNUNET_OK;
5630 }
5631
5632
5633 /**
5634  * Core handler for mesh network traffic toward the owner of a tunnel
5635  *
5636  * @param cls closure
5637  * @param message message
5638  * @param peer peer identity this notification is about
5639  * @param atsi performance data
5640  * @param atsi_count number of records in 'atsi'
5641  *
5642  * @return GNUNET_OK to keep the connection open,
5643  *         GNUNET_SYSERR to close it (signal serious error)
5644  */
5645 static int
5646 handle_mesh_data_to_orig (void *cls, const struct GNUNET_PeerIdentity *peer,
5647                           const struct GNUNET_MessageHeader *message)
5648 {
5649   struct GNUNET_MESH_ToOrigin *msg;
5650   struct GNUNET_PeerIdentity id;
5651   struct MeshPeerInfo *peer_info;
5652   struct MeshTunnel *t;
5653   struct MeshTunnelChildInfo *cinfo;
5654   GNUNET_PEER_Id predecessor;
5655   size_t size;
5656   uint32_t pid;
5657
5658   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a ToOrigin packet from %s\n",
5659               GNUNET_i2s (peer));
5660   size = ntohs (message->size);
5661   if (size < sizeof (struct GNUNET_MESH_ToOrigin) +     /* Payload must be */
5662       sizeof (struct GNUNET_MessageHeader))     /* at least a header */
5663   {
5664     GNUNET_break_op (0);
5665     return GNUNET_OK;
5666   }
5667   msg = (struct GNUNET_MESH_ToOrigin *) message;
5668   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %s\n",
5669               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
5670   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5671   pid = ntohl (msg->pid);
5672
5673   if (NULL == t)
5674   {
5675     /* TODO notify that we dont know this tunnel (whom)? */
5676     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
5677     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5678                 "Received to_origin with PID %u on unknown tunnel %s [%u]\n",
5679                 pid, GNUNET_i2s (&msg->oid), ntohl (msg->tid));
5680     return GNUNET_OK;
5681   }
5682
5683   cinfo = tunnel_get_neighbor_fc(t, peer);
5684   if (NULL == cinfo)
5685   {
5686     GNUNET_break (0);
5687     return GNUNET_OK;
5688   }
5689
5690   if (cinfo->bck_pid == pid)
5691   {
5692     /* already seen this packet, drop */
5693     GNUNET_STATISTICS_update (stats, "# duplicate PID drops BCK", 1, GNUNET_NO);
5694     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5695                 " Already seen pid %u, DROPPING!\n", pid);
5696     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5697     return GNUNET_OK;
5698   }
5699
5700   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5701               " pid %u not seen yet, forwarding\n", pid);
5702   cinfo->bck_pid = pid;
5703
5704   if (NULL != t->owner)
5705   {
5706     char cbuf[size];
5707     struct GNUNET_MESH_ToOrigin *copy;
5708
5709     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5710                 "  it's for us! sending to clients...\n");
5711     /* TODO signature verification */
5712     memcpy (cbuf, message, size);
5713     copy = (struct GNUNET_MESH_ToOrigin *) cbuf;
5714     copy->tid = htonl (t->local_tid);
5715     t->bck_pid++;
5716     copy->pid = htonl (t->bck_pid);
5717     GNUNET_STATISTICS_update (stats, "# to origin received", 1, GNUNET_NO);
5718     GNUNET_SERVER_notification_context_unicast (nc, t->owner->handle,
5719                                                 &copy->header, GNUNET_NO);
5720     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
5721     return GNUNET_OK;
5722   }
5723   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5724               "  not for us, retransmitting...\n");
5725
5726   peer_info = peer_info_get (&msg->oid);
5727   if (NULL == peer_info)
5728   {
5729     /* unknown origin of tunnel */
5730     GNUNET_break (0);
5731     return GNUNET_OK;
5732   }
5733   predecessor = tree_get_predecessor (t->tree);
5734   if (0 == predecessor)
5735   {
5736     if (GNUNET_YES == t->destroy)
5737     {
5738       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5739                   "to orig received on a dying tunnel %s [%X]\n",
5740                   GNUNET_i2s (&msg->oid), ntohl(msg->tid));
5741       return GNUNET_OK;
5742     }
5743     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
5744                 "unknown to origin at %s\n",
5745                 GNUNET_i2s (&my_full_id));
5746     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
5747                 "from peer %s\n",
5748                 GNUNET_i2s (peer));
5749     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
5750                 "for tunnel %s [%X]\n",
5751                 GNUNET_i2s (&msg->oid), ntohl(msg->tid));
5752     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
5753                 "current tree:\n");
5754     tree_debug (t->tree);
5755     return GNUNET_OK;
5756   }
5757   GNUNET_PEER_resolve (predecessor, &id);
5758   send_prebuilt_message (message, &id, t);
5759   GNUNET_STATISTICS_update (stats, "# to origin forwarded", 1, GNUNET_NO);
5760
5761   return GNUNET_OK;
5762 }
5763
5764
5765 /**
5766  * Core handler for mesh network traffic point-to-point acks.
5767  *
5768  * @param cls closure
5769  * @param message message
5770  * @param peer peer identity this notification is about
5771  * @param atsi performance data
5772  * @param atsi_count number of records in 'atsi'
5773  *
5774  * @return GNUNET_OK to keep the connection open,
5775  *         GNUNET_SYSERR to close it (signal serious error)
5776  */
5777 static int
5778 handle_mesh_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5779                  const struct GNUNET_MessageHeader *message)
5780 {
5781   struct GNUNET_MESH_ACK *msg;
5782   struct MeshTunnel *t;
5783   uint32_t ack;
5784
5785   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK packet from %s!\n",
5786               GNUNET_i2s (peer));
5787   msg = (struct GNUNET_MESH_ACK *) message;
5788
5789   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5790
5791   if (NULL == t)
5792   {
5793     /* TODO notify that we dont know this tunnel (whom)? */
5794     GNUNET_STATISTICS_update (stats, "# ack on unknown tunnel", 1, GNUNET_NO);
5795     return GNUNET_OK;
5796   }
5797   ack = ntohl (msg->pid);
5798   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ACK %u\n", ack);
5799
5800   /* Is this a forward or backward ACK? */
5801   if (tree_get_predecessor(t->tree) != GNUNET_PEER_search(peer))
5802   {
5803     struct MeshTunnelChildInfo *cinfo;
5804
5805     debug_bck_ack++;
5806     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
5807     cinfo = tunnel_get_neighbor_fc (t, peer);
5808     cinfo->fwd_ack = ack;
5809     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5810     tunnel_unlock_fwd_queues (t);
5811     if (GNUNET_SCHEDULER_NO_TASK != cinfo->fc_poll)
5812     {
5813       GNUNET_SCHEDULER_cancel (cinfo->fc_poll);
5814       cinfo->fc_poll = GNUNET_SCHEDULER_NO_TASK;
5815       cinfo->fc_poll_time = GNUNET_TIME_UNIT_SECONDS;
5816     }
5817   }
5818   else
5819   {
5820     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
5821     t->bck_ack = ack;
5822     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5823     tunnel_unlock_bck_queue (t);
5824   }
5825   return GNUNET_OK;
5826 }
5827
5828
5829 /**
5830  * Core handler for mesh network traffic point-to-point ack polls.
5831  *
5832  * @param cls closure
5833  * @param message message
5834  * @param peer peer identity this notification is about
5835  * @param atsi performance data
5836  * @param atsi_count number of records in 'atsi'
5837  *
5838  * @return GNUNET_OK to keep the connection open,
5839  *         GNUNET_SYSERR to close it (signal serious error)
5840  */
5841 static int
5842 handle_mesh_poll (void *cls, const struct GNUNET_PeerIdentity *peer,
5843                   const struct GNUNET_MessageHeader *message)
5844 {
5845   struct GNUNET_MESH_Poll *msg;
5846   struct MeshTunnel *t;
5847
5848   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an POLL packet from %s!\n",
5849               GNUNET_i2s (peer));
5850
5851   msg = (struct GNUNET_MESH_Poll *) message;
5852
5853   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5854
5855   if (NULL == t)
5856   {
5857     /* TODO notify that we dont know this tunnel (whom)? */
5858     GNUNET_STATISTICS_update (stats, "# poll on unknown tunnel", 1, GNUNET_NO);
5859     GNUNET_break_op (0);
5860     return GNUNET_OK;
5861   }
5862
5863   /* Is this a forward or backward ACK? */
5864   if (tree_get_predecessor(t->tree) != GNUNET_PEER_search(peer))
5865   {
5866     struct MeshTunnelChildInfo *cinfo;
5867
5868     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  from FWD\n");
5869     cinfo = tunnel_get_neighbor_fc (t, peer);
5870     cinfo->bck_ack = cinfo->fwd_pid; // mark as ready to send
5871     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_POLL);
5872   }
5873   else
5874   {
5875     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  from BCK\n");
5876     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_POLL);
5877   }
5878
5879   return GNUNET_OK;
5880 }
5881
5882 /**
5883  * Core handler for path ACKs
5884  *
5885  * @param cls closure
5886  * @param message message
5887  * @param peer peer identity this notification is about
5888  * @param atsi performance data
5889  * @param atsi_count number of records in 'atsi'
5890  *
5891  * @return GNUNET_OK to keep the connection open,
5892  *         GNUNET_SYSERR to close it (signal serious error)
5893  */
5894 static int
5895 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5896                       const struct GNUNET_MessageHeader *message)
5897 {
5898   struct GNUNET_MESH_PathACK *msg;
5899   struct GNUNET_PeerIdentity id;
5900   struct MeshPeerInfo *peer_info;
5901   struct MeshPeerPath *p;
5902   struct MeshTunnel *t;
5903
5904   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a path ACK msg [%s]\n",
5905               GNUNET_i2s (&my_full_id));
5906   msg = (struct GNUNET_MESH_PathACK *) message;
5907   t = tunnel_get (&msg->oid, ntohl(msg->tid));
5908   if (NULL == t)
5909   {
5910     /* TODO notify that we don't know the tunnel */
5911     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel", 1, GNUNET_NO);
5912     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  don't know the tunnel %s [%X]!\n",
5913                 GNUNET_i2s (&msg->oid), ntohl(msg->tid));
5914     return GNUNET_OK;
5915   }
5916   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %s [%X]\n",
5917               GNUNET_i2s (&msg->oid), ntohl(msg->tid));
5918
5919   peer_info = peer_info_get (&msg->peer_id);
5920   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by peer %s\n",
5921               GNUNET_i2s (&msg->peer_id));
5922   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  via peer %s\n",
5923               GNUNET_i2s (peer));
5924
5925   if (NULL != t->regex_search && t->regex_search->peer == peer_info->id)
5926   {
5927     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5928                 "connect_by_string completed, stopping search\n");
5929     regex_cancel_search (t->regex_search);
5930     t->regex_search = NULL;
5931   }
5932
5933   /* Add paths to peers? */
5934   p = tree_get_path_to_peer (t->tree, peer_info->id);
5935   if (NULL != p)
5936   {
5937     path_add_to_peers (p, GNUNET_YES);
5938     path_destroy (p);
5939   }
5940   else
5941   {
5942     GNUNET_break (0);
5943   }
5944
5945   /* Message for us? */
5946   if (0 == memcmp (&msg->oid, &my_full_id, sizeof (struct GNUNET_PeerIdentity)))
5947   {
5948     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
5949     if (NULL == t->owner)
5950     {
5951       GNUNET_break_op (0);
5952       return GNUNET_OK;
5953     }
5954     if (NULL != t->dht_get_type)
5955     {
5956       GNUNET_DHT_get_stop (t->dht_get_type);
5957       t->dht_get_type = NULL;
5958     }
5959     if (tree_get_status (t->tree, peer_info->id) != MESH_PEER_READY)
5960     {
5961       tree_set_status (t->tree, peer_info->id, MESH_PEER_READY);
5962       send_client_peer_connected (t, peer_info->id);
5963     }
5964     return GNUNET_OK;
5965   }
5966
5967   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5968               "  not for us, retransmitting...\n");
5969   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
5970   peer_info = peer_info_get (&msg->oid);
5971   if (NULL == peer_info)
5972   {
5973     /* If we know the tunnel, we should DEFINITELY know the peer */
5974     GNUNET_break (0);
5975     return GNUNET_OK;
5976   }
5977   send_prebuilt_message (message, &id, t);
5978   return GNUNET_OK;
5979 }
5980
5981
5982 /**
5983  * Core handler for mesh keepalives.
5984  *
5985  * @param cls closure
5986  * @param message message
5987  * @param peer peer identity this notification is about
5988  * @param atsi performance data
5989  * @param atsi_count number of records in 'atsi'
5990  * @return GNUNET_OK to keep the connection open,
5991  *         GNUNET_SYSERR to close it (signal serious error)
5992  *
5993  * TODO: Check who we got this from, to validate route.
5994  */
5995 static int
5996 handle_mesh_keepalive (void *cls, const struct GNUNET_PeerIdentity *peer,
5997                        const struct GNUNET_MessageHeader *message)
5998 {
5999   struct GNUNET_MESH_TunnelKeepAlive *msg;
6000   struct MeshTunnel *t;
6001
6002   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a keepalive packet from %s\n",
6003               GNUNET_i2s (peer));
6004
6005   msg = (struct GNUNET_MESH_TunnelKeepAlive *) message;
6006   t = tunnel_get (&msg->oid, ntohl (msg->tid));
6007
6008   if (NULL == t)
6009   {
6010     /* TODO notify that we dont know that tunnel */
6011     GNUNET_STATISTICS_update (stats, "# keepalive on unknown tunnel", 1,
6012                               GNUNET_NO);
6013     return GNUNET_OK;
6014   }
6015
6016   tunnel_reset_timeout (t);
6017
6018   GNUNET_STATISTICS_update (stats, "# keepalives forwarded", 1, GNUNET_NO);
6019   tunnel_send_multicast (t, message);
6020   return GNUNET_OK;
6021   }
6022
6023
6024
6025 /**
6026  * Functions to handle messages from core
6027  */
6028 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
6029   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
6030   {&handle_mesh_path_destroy, GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY, 0},
6031   {&handle_mesh_path_broken, GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN,
6032    sizeof (struct GNUNET_MESH_PathBroken)},
6033   {&handle_mesh_tunnel_destroy, GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY,
6034    sizeof (struct GNUNET_MESH_TunnelDestroy)},
6035   {&handle_mesh_data_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
6036   {&handle_mesh_data_multicast, GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
6037   {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE,
6038     sizeof (struct GNUNET_MESH_TunnelKeepAlive)},
6039   {&handle_mesh_data_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
6040   {&handle_mesh_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
6041     sizeof (struct GNUNET_MESH_ACK)},
6042   {&handle_mesh_poll, GNUNET_MESSAGE_TYPE_MESH_POLL,
6043     sizeof (struct GNUNET_MESH_Poll)},
6044   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
6045    sizeof (struct GNUNET_MESH_PathACK)},
6046   {NULL, 0, 0}
6047 };
6048
6049
6050
6051 /******************************************************************************/
6052 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
6053 /******************************************************************************/
6054
6055 /**
6056  * deregister_app: iterator for removing each application registered by a client
6057  *
6058  * @param cls closure
6059  * @param key the hash of the application id (used to access the hashmap)
6060  * @param value the value stored at the key (client)
6061  *
6062  * @return GNUNET_OK on success
6063  */
6064 static int
6065 deregister_app (void *cls, const struct GNUNET_HashCode * key, void *value)
6066 {
6067   struct GNUNET_CONTAINER_MultiHashMap *h = cls;
6068   GNUNET_break (GNUNET_YES ==
6069                 GNUNET_CONTAINER_multihashmap_remove (h, key, value));
6070   return GNUNET_OK;
6071 }
6072
6073 #if LATER
6074 /**
6075  * notify_client_connection_failure: notify a client that the connection to the
6076  * requested remote peer is not possible (for instance, no route found)
6077  * Function called when the socket is ready to queue more data. "buf" will be
6078  * NULL and "size" zero if the socket was closed for writing in the meantime.
6079  *
6080  * @param cls closure
6081  * @param size number of bytes available in buf
6082  * @param buf where the callee should write the message
6083  * @return number of bytes written to buf
6084  */
6085 static size_t
6086 notify_client_connection_failure (void *cls, size_t size, void *buf)
6087 {
6088   int size_needed;
6089   struct MeshPeerInfo *peer_info;
6090   struct GNUNET_MESH_PeerControl *msg;
6091   struct GNUNET_PeerIdentity id;
6092
6093   if (0 == size && NULL == buf)
6094   {
6095     // TODO retry? cancel?
6096     return 0;
6097   }
6098
6099   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
6100   peer_info = (struct MeshPeerInfo *) cls;
6101   msg = (struct GNUNET_MESH_PeerControl *) buf;
6102   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
6103   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
6104 //     msg->tunnel_id = htonl(peer_info->t->tid);
6105   GNUNET_PEER_resolve (peer_info->id, &id);
6106   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
6107
6108   return size_needed;
6109 }
6110 #endif
6111
6112
6113 /**
6114  * Send keepalive packets for a peer
6115  *
6116  * @param cls Closure (tunnel for which to send the keepalive).
6117  * @param tc Notification context.
6118  */
6119 static void
6120 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
6121 {
6122   struct MeshTunnel *t = cls;
6123   struct GNUNET_MESH_TunnelKeepAlive *msg;
6124   size_t size = sizeof (struct GNUNET_MESH_TunnelKeepAlive);
6125   char cbuf[size];
6126
6127   t->path_refresh_task = GNUNET_SCHEDULER_NO_TASK;
6128   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
6129   {
6130     return;
6131   }
6132
6133   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6134               "sending keepalive for tunnel %d\n", t->id.tid);
6135
6136   msg = (struct GNUNET_MESH_TunnelKeepAlive *) cbuf;
6137   msg->header.size = htons (size);
6138   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE);
6139   msg->oid = my_full_id;
6140   msg->tid = htonl (t->id.tid);
6141   tunnel_send_multicast (t, &msg->header);
6142
6143   t->path_refresh_task =
6144       GNUNET_SCHEDULER_add_delayed (refresh_path_time, &path_refresh, t);
6145   tunnel_reset_timeout(t);
6146 }
6147
6148
6149 /**
6150  * Function to process paths received for a new peer addition. The recorded
6151  * paths form the initial tunnel, which can be optimized later.
6152  * Called on each result obtained for the DHT search.
6153  *
6154  * @param cls closure
6155  * @param exp when will this value expire
6156  * @param key key of the result
6157  * @param get_path path of the get request
6158  * @param get_path_length lenght of get_path
6159  * @param put_path path of the put request
6160  * @param put_path_length length of the put_path
6161  * @param type type of the result
6162  * @param size number of bytes in data
6163  * @param data pointer to the result data
6164  *
6165  * TODO: re-issue the request after certain time? cancel after X results?
6166  */
6167 static void
6168 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
6169                     const struct GNUNET_HashCode * key,
6170                     const struct GNUNET_PeerIdentity *get_path,
6171                     unsigned int get_path_length,
6172                     const struct GNUNET_PeerIdentity *put_path,
6173                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
6174                     size_t size, const void *data)
6175 {
6176   struct MeshPathInfo *path_info = cls;
6177   struct MeshPeerPath *p;
6178   struct GNUNET_PeerIdentity pi;
6179   int i;
6180
6181   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
6182   GNUNET_PEER_resolve (path_info->peer->id, &pi);
6183   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", GNUNET_i2s (&pi));
6184
6185   p = path_build_from_dht (get_path, get_path_length, put_path,
6186                            put_path_length);
6187   path_add_to_peers (p, GNUNET_NO);
6188   path_destroy(p);
6189   for (i = 0; i < path_info->peer->ntunnels; i++)
6190   {
6191     tunnel_add_peer (path_info->peer->tunnels[i], path_info->peer);
6192     peer_info_connect (path_info->peer, path_info->t);
6193   }
6194
6195   return;
6196 }
6197
6198
6199 /**
6200  * Function to process paths received for a new peer addition. The recorded
6201  * paths form the initial tunnel, which can be optimized later.
6202  * Called on each result obtained for the DHT search.
6203  *
6204  * @param cls closure
6205  * @param exp when will this value expire
6206  * @param key key of the result
6207  * @param get_path path of the get request
6208  * @param get_path_length lenght of get_path
6209  * @param put_path path of the put request
6210  * @param put_path_length length of the put_path
6211  * @param type type of the result
6212  * @param size number of bytes in data
6213  * @param data pointer to the result data
6214  */
6215 static void
6216 dht_get_type_handler (void *cls, struct GNUNET_TIME_Absolute exp,
6217                       const struct GNUNET_HashCode * key,
6218                       const struct GNUNET_PeerIdentity *get_path,
6219                       unsigned int get_path_length,
6220                       const struct GNUNET_PeerIdentity *put_path,
6221                       unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
6222                       size_t size, const void *data)
6223 {
6224   const struct PBlock *pb = data;
6225   const struct GNUNET_PeerIdentity *pi = &pb->id;
6226   struct MeshTunnel *t = cls;
6227   struct MeshPeerInfo *peer_info;
6228   struct MeshPeerPath *p;
6229
6230   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got type DHT result!\n");
6231   if (size != sizeof (struct PBlock))
6232   {
6233     GNUNET_break_op (0);
6234     return;
6235   }
6236   if (ntohl(pb->type) != t->type)
6237   {
6238     GNUNET_break_op (0);
6239     return;
6240   }
6241   GNUNET_assert (NULL != t->owner);
6242   peer_info = peer_info_get (pi);
6243   (void) GNUNET_CONTAINER_multihashmap_put (t->peers, &pi->hashPubKey,
6244                                             peer_info,
6245                                             GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
6246
6247   p = path_build_from_dht (get_path, get_path_length, put_path,
6248                            put_path_length);
6249   path_add_to_peers (p, GNUNET_NO);
6250   path_destroy(p);
6251   tunnel_add_peer (t, peer_info);
6252   peer_info_connect (peer_info, t);
6253 }
6254
6255
6256 /******************************************************************************/
6257 /*********************       MESH LOCAL HANDLES      **************************/
6258 /******************************************************************************/
6259
6260
6261 /**
6262  * Handler for client disconnection
6263  *
6264  * @param cls closure
6265  * @param client identification of the client; NULL
6266  *        for the last call when the server is destroyed
6267  */
6268 static void
6269 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
6270 {
6271   struct MeshClient *c;
6272   struct MeshClient *next;
6273   unsigned int i;
6274
6275   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected\n");
6276   if (client == NULL)
6277   {
6278     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (SERVER DOWN)\n");
6279     return;
6280   }
6281
6282   c = clients;
6283   while (NULL != c)
6284   {
6285     if (c->handle != client)
6286     {
6287       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ... searching\n");
6288       c = c->next;
6289       continue;
6290     }
6291     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u)\n",
6292                 c->id);
6293     GNUNET_SERVER_client_drop (c->handle);
6294     c->shutting_down = GNUNET_YES;
6295     GNUNET_assert (NULL != c->own_tunnels);
6296     GNUNET_assert (NULL != c->incoming_tunnels);
6297     GNUNET_CONTAINER_multihashmap_iterate (c->own_tunnels,
6298                                            &tunnel_destroy_iterator, c);
6299     GNUNET_CONTAINER_multihashmap_iterate (c->incoming_tunnels,
6300                                            &tunnel_destroy_iterator, c);
6301     GNUNET_CONTAINER_multihashmap_iterate (c->ignore_tunnels,
6302                                            &tunnel_destroy_iterator, c);
6303     GNUNET_CONTAINER_multihashmap_destroy (c->own_tunnels);
6304     GNUNET_CONTAINER_multihashmap_destroy (c->incoming_tunnels);
6305     GNUNET_CONTAINER_multihashmap_destroy (c->ignore_tunnels);
6306
6307     /* deregister clients applications */
6308     if (NULL != c->apps)
6309     {
6310       GNUNET_CONTAINER_multihashmap_iterate (c->apps, &deregister_app, c->apps);
6311       GNUNET_CONTAINER_multihashmap_destroy (c->apps);
6312     }
6313     if (0 == GNUNET_CONTAINER_multihashmap_size (applications) &&
6314         GNUNET_SCHEDULER_NO_TASK != announce_applications_task)
6315     {
6316       GNUNET_SCHEDULER_cancel (announce_applications_task);
6317       announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
6318     }
6319     if (NULL != c->types)
6320       GNUNET_CONTAINER_multihashmap_destroy (c->types);
6321     for (i = 0; i < c->n_regex; i++)
6322     {
6323       GNUNET_free (c->regexes[i].regex);
6324       if (NULL != c->regexes[i].h)
6325         GNUNET_REGEX_announce_cancel (c->regexes[i].h);
6326     }
6327     GNUNET_free_non_null (c->regexes);
6328     if (GNUNET_SCHEDULER_NO_TASK != c->regex_announce_task)
6329       GNUNET_SCHEDULER_cancel (c->regex_announce_task);
6330     next = c->next;
6331     GNUNET_CONTAINER_DLL_remove (clients, clients_tail, c);
6332     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT FREE at %p\n", c);
6333     GNUNET_free (c);
6334     GNUNET_STATISTICS_update (stats, "# clients", -1, GNUNET_NO);
6335     c = next;
6336   }
6337   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   done!\n");
6338   return;
6339 }
6340
6341
6342 /**
6343  * Handler for new clients
6344  *
6345  * @param cls closure
6346  * @param client identification of the client
6347  * @param message the actual message, which includes messages the client wants
6348  */
6349 static void
6350 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
6351                          const struct GNUNET_MessageHeader *message)
6352 {
6353   struct GNUNET_MESH_ClientConnect *cc_msg;
6354   struct MeshClient *c;
6355   GNUNET_MESH_ApplicationType *a;
6356   unsigned int size;
6357   uint16_t ntypes;
6358   uint16_t *t;
6359   uint16_t napps;
6360   uint16_t i;
6361
6362   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected\n");
6363   /* Check data sanity */
6364   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
6365   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
6366   ntypes = ntohs (cc_msg->types);
6367   napps = ntohs (cc_msg->applications);
6368   if (size !=
6369       ntypes * sizeof (uint16_t) + napps * sizeof (GNUNET_MESH_ApplicationType))
6370   {
6371     GNUNET_break (0);
6372     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6373     return;
6374   }
6375
6376   /* Create new client structure */
6377   c = GNUNET_malloc (sizeof (struct MeshClient));
6378   c->id = next_client_id++;
6379   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT NEW %u\n", c->id);
6380   c->handle = client;
6381   GNUNET_SERVER_client_keep (client);
6382   a = (GNUNET_MESH_ApplicationType *) &cc_msg[1];
6383   if (napps > 0)
6384   {
6385     GNUNET_MESH_ApplicationType at;
6386     struct GNUNET_HashCode hc;
6387
6388     c->apps = GNUNET_CONTAINER_multihashmap_create (napps, GNUNET_NO);
6389     for (i = 0; i < napps; i++)
6390     {
6391       at = ntohl (a[i]);
6392       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  app type: %u\n", at);
6393       GNUNET_CRYPTO_hash (&at, sizeof (at), &hc);
6394       /* store in clients hashmap */
6395       GNUNET_CONTAINER_multihashmap_put (c->apps, &hc, (void *) (long) at,
6396                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6397       /* store in global hashmap, for announcements */
6398       GNUNET_CONTAINER_multihashmap_put (applications, &hc, c,
6399                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6400     }
6401     if (GNUNET_SCHEDULER_NO_TASK == announce_applications_task)
6402       announce_applications_task =
6403           GNUNET_SCHEDULER_add_now (&announce_applications, NULL);
6404
6405   }
6406   if (ntypes > 0)
6407   {
6408     uint16_t u16;
6409     struct GNUNET_HashCode hc;
6410
6411     t = (uint16_t *) & a[napps];
6412     c->types = GNUNET_CONTAINER_multihashmap_create (ntypes, GNUNET_NO);
6413     for (i = 0; i < ntypes; i++)
6414     {
6415       u16 = ntohs (t[i]);
6416       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  msg type: %u\n", u16);
6417       GNUNET_CRYPTO_hash (&u16, sizeof (u16), &hc);
6418
6419       /* store in clients hashmap */
6420       GNUNET_CONTAINER_multihashmap_put (c->types, &hc, c,
6421                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6422       /* store in global hashmap */
6423       GNUNET_CONTAINER_multihashmap_put (types, &hc, c,
6424                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6425     }
6426   }
6427   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6428               " client has %u+%u subscriptions\n", napps, ntypes);
6429
6430   GNUNET_CONTAINER_DLL_insert (clients, clients_tail, c);
6431   c->own_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6432   c->incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6433   c->ignore_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6434   GNUNET_SERVER_notification_context_add (nc, client);
6435   GNUNET_STATISTICS_update (stats, "# clients", 1, GNUNET_NO);
6436
6437   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6438   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
6439 }
6440
6441
6442 /**
6443  * Handler for clients announcing available services by a regular expression.
6444  *
6445  * @param cls closure
6446  * @param client identification of the client
6447  * @param message the actual message, which includes messages the client wants
6448  */
6449 static void
6450 handle_local_announce_regex (void *cls, struct GNUNET_SERVER_Client *client,
6451                              const struct GNUNET_MessageHeader *message)
6452 {
6453   const struct GNUNET_MESH_RegexAnnounce *msg;
6454   struct MeshRegexDescriptor rd;
6455   struct MeshClient *c;
6456   char *regex;
6457   size_t len;
6458   size_t offset;
6459
6460   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "announce regex started\n");
6461
6462   /* Sanity check for client registration */
6463   if (NULL == (c = client_get (client)))
6464   {
6465     GNUNET_break (0);
6466     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6467     return;
6468   }
6469   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6470
6471   msg = (const struct GNUNET_MESH_RegexAnnounce *) message;
6472
6473   len = ntohs (message->size) - sizeof(struct GNUNET_MESH_RegexAnnounce);
6474   if (NULL != c->partial_regex)
6475   {
6476     regex = c->partial_regex;
6477     offset = strlen (c->partial_regex);
6478     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6479                 "  continuation, already have %u bytes\n",
6480                 offset);
6481   }
6482   else
6483   {
6484     regex = NULL;
6485     offset = 0;
6486   }
6487
6488   regex = GNUNET_realloc (regex, offset + len + 1);
6489   memcpy (&regex[offset], &msg[1], len);
6490   regex[offset + len] = '\0';
6491   if (0 == ntohs (msg->last))
6492   {
6493     c->partial_regex = regex;
6494     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6495                 "  not ended, stored %u bytes for later\n",
6496                 len);
6497     GNUNET_SERVER_receive_done (client, GNUNET_OK);
6498     return;
6499   }
6500   rd.regex = regex;
6501   rd.compression = ntohs (msg->compression_characters);
6502   rd.h = NULL;
6503   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  length %u\n", len);
6504   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regex %s\n", regex);
6505   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  cm %u\n", ntohs(rd.compression));
6506   GNUNET_array_append (c->regexes, c->n_regex, rd);
6507   c->partial_regex = NULL;
6508   if (GNUNET_SCHEDULER_NO_TASK == c->regex_announce_task)
6509   {
6510     c->regex_announce_task = GNUNET_SCHEDULER_add_now(&regex_announce, c);
6511   }
6512   else
6513   {
6514     regex_put(&rd);
6515   }
6516   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6517   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "announce regex processed\n");
6518 }
6519
6520
6521 /**
6522  * Handler for requests of new tunnels
6523  *
6524  * @param cls closure
6525  * @param client identification of the client
6526  * @param message the actual message
6527  */
6528 static void
6529 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
6530                             const struct GNUNET_MessageHeader *message)
6531 {
6532   struct GNUNET_MESH_TunnelMessage *t_msg;
6533   struct MeshTunnel *t;
6534   struct MeshClient *c;
6535   MESH_TunnelNumber tid;
6536
6537   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel requested\n");
6538
6539   /* Sanity check for client registration */
6540   if (NULL == (c = client_get (client)))
6541   {
6542     GNUNET_break (0);
6543     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6544     return;
6545   }
6546   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6547
6548   /* Message sanity check */
6549   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
6550   {
6551     GNUNET_break (0);
6552     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6553     return;
6554   }
6555
6556   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6557   /* Sanity check for tunnel numbering */
6558   tid = ntohl (t_msg->tunnel_id);
6559   if (0 == (tid & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
6560   {
6561     GNUNET_break (0);
6562     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6563     return;
6564   }
6565   /* Sanity check for duplicate tunnel IDs */
6566   if (NULL != tunnel_get_by_local_id (c, tid))
6567   {
6568     GNUNET_break (0);
6569     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6570     return;
6571   }
6572
6573   while (NULL != tunnel_get_by_pi (myid, next_tid))
6574     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
6575   t = tunnel_new (myid, next_tid++, c, tid);
6576   if (NULL == t)
6577   {
6578     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Tunnel creation failed.\n");
6579     GNUNET_break (0);
6580     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6581     return;
6582   }
6583   next_tid = next_tid & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
6584   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED TUNNEL %s [%x] (%x)\n",
6585               GNUNET_i2s (&my_full_id), t->id.tid, t->local_tid);
6586   t->peers = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6587
6588   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel created\n");
6589   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6590   return;
6591 }
6592
6593
6594 /**
6595  * Handler for requests of deleting tunnels
6596  *
6597  * @param cls closure
6598  * @param client identification of the client
6599  * @param message the actual message
6600  */
6601 static void
6602 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
6603                              const struct GNUNET_MessageHeader *message)
6604 {
6605   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
6606   struct MeshClient *c;
6607   struct MeshTunnel *t;
6608   MESH_TunnelNumber tid;
6609
6610   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6611               "Got a DESTROY TUNNEL from client!\n");
6612
6613   /* Sanity check for client registration */
6614   if (NULL == (c = client_get (client)))
6615   {
6616     GNUNET_break (0);
6617     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6618     return;
6619   }
6620   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6621
6622   /* Message sanity check */
6623   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
6624   {
6625     GNUNET_break (0);
6626     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6627     return;
6628   }
6629
6630   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6631
6632   /* Retrieve tunnel */
6633   tid = ntohl (tunnel_msg->tunnel_id);
6634   t = tunnel_get_by_local_id(c, tid);
6635   if (NULL == t)
6636   {
6637     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
6638     GNUNET_break (0);
6639     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6640     return;
6641   }
6642   if (c != t->owner || tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
6643   {
6644     client_ignore_tunnel (c, t);
6645     tunnel_destroy_empty (t);
6646     GNUNET_SERVER_receive_done (client, GNUNET_OK);
6647     return;
6648   }
6649   send_client_tunnel_disconnect (t, c);
6650   client_delete_tunnel (c, t);
6651
6652   /* Don't try to ACK the client about the tunnel_destroy multicast packet */
6653   t->owner = NULL;
6654   tunnel_send_destroy (t, 0);
6655   t->destroy = GNUNET_YES;
6656   /* The tunnel will be destroyed when the last message is transmitted. */
6657   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6658   return;
6659 }
6660
6661
6662 /**
6663  * Handler for requests of seeting tunnel's speed.
6664  *
6665  * @param cls Closure (unused).
6666  * @param client Identification of the client.
6667  * @param message The actual message.
6668  */
6669 static void
6670 handle_local_tunnel_speed (void *cls, struct GNUNET_SERVER_Client *client,
6671                            const struct GNUNET_MessageHeader *message)
6672 {
6673   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
6674   struct MeshClient *c;
6675   struct MeshTunnel *t;
6676   MESH_TunnelNumber tid;
6677
6678   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6679               "Got a SPEED request from client!\n");
6680
6681   /* Sanity check for client registration */
6682   if (NULL == (c = client_get (client)))
6683   {
6684     GNUNET_break (0);
6685     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6686     return;
6687   }
6688
6689   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6690
6691   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6692
6693   /* Retrieve tunnel */
6694   tid = ntohl (tunnel_msg->tunnel_id);
6695   t = tunnel_get_by_local_id(c, tid);
6696   if (NULL == t)
6697   {
6698     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  tunnel %X not found\n", tid);
6699     GNUNET_break (0);
6700     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6701     return;
6702   }
6703
6704   switch (ntohs(message->type))
6705   {
6706       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MIN:
6707           t->speed_min = GNUNET_YES;
6708           break;
6709       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MAX:
6710           t->speed_min = GNUNET_NO;
6711           break;
6712       default:
6713           GNUNET_break (0);
6714   }
6715   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6716 }
6717
6718
6719 /**
6720  * Handler for requests of seeting tunnel's buffering policy.
6721  *
6722  * @param cls Closure (unused).
6723  * @param client Identification of the client.
6724  * @param message The actual message.
6725  */
6726 static void
6727 handle_local_tunnel_buffer (void *cls, struct GNUNET_SERVER_Client *client,
6728                             const struct GNUNET_MessageHeader *message)
6729 {
6730   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
6731   struct MeshClient *c;
6732   struct MeshTunnel *t;
6733   MESH_TunnelNumber tid;
6734
6735   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6736               "Got a BUFFER request from client!\n");
6737
6738   /* Sanity check for client registration */
6739   if (NULL == (c = client_get (client)))
6740   {
6741     GNUNET_break (0);
6742     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6743     return;
6744   }
6745   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6746
6747   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6748
6749   /* Retrieve tunnel */
6750   tid = ntohl (tunnel_msg->tunnel_id);
6751   t = tunnel_get_by_local_id(c, tid);
6752   if (NULL == t)
6753   {
6754     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
6755     GNUNET_break (0);
6756     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6757     return;
6758   }
6759
6760   switch (ntohs(message->type))
6761   {
6762       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER:
6763           t->nobuffer = GNUNET_NO;
6764           break;
6765       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER:
6766           t->nobuffer = GNUNET_YES;
6767           break;
6768       default:
6769           GNUNET_break (0);
6770   }
6771
6772   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6773 }
6774
6775
6776 /**
6777  * Handler for connection requests to new peers
6778  *
6779  * @param cls closure
6780  * @param client identification of the client
6781  * @param message the actual message (PeerControl)
6782  */
6783 static void
6784 handle_local_connect_add (void *cls, struct GNUNET_SERVER_Client *client,
6785                           const struct GNUNET_MessageHeader *message)
6786 {
6787   struct GNUNET_MESH_PeerControl *peer_msg;
6788   struct MeshPeerInfo *peer_info;
6789   struct MeshClient *c;
6790   struct MeshTunnel *t;
6791   MESH_TunnelNumber tid;
6792
6793   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got connection request\n");
6794   /* Sanity check for client registration */
6795   if (NULL == (c = client_get (client)))
6796   {
6797     GNUNET_break (0);
6798     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6799     return;
6800   }
6801   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6802
6803   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6804
6805   /* Sanity check for message size */
6806   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6807   {
6808     GNUNET_break (0);
6809     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6810     return;
6811   }
6812
6813   /* Tunnel exists? */
6814   tid = ntohl (peer_msg->tunnel_id);
6815   t = tunnel_get_by_local_id (c, tid);
6816   if (NULL == t)
6817   {
6818     GNUNET_break (0);
6819     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6820     return;
6821   }
6822
6823   /* Does client own tunnel? */
6824   if (t->owner->handle != client)
6825   {
6826     GNUNET_break (0);
6827     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6828     return;
6829   }
6830   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "     for %s\n",
6831               GNUNET_i2s (&peer_msg->peer));
6832   peer_info = peer_info_get (&peer_msg->peer);
6833
6834   tunnel_add_peer (t, peer_info);
6835   peer_info_connect (peer_info, t);
6836
6837   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6838   return;
6839 }
6840
6841
6842 /**
6843  * Handler for disconnection requests of peers in a tunnel
6844  *
6845  * @param cls closure
6846  * @param client identification of the client
6847  * @param message the actual message (PeerControl)
6848  */
6849 static void
6850 handle_local_connect_del (void *cls, struct GNUNET_SERVER_Client *client,
6851                           const struct GNUNET_MessageHeader *message)
6852 {
6853   struct GNUNET_MESH_PeerControl *peer_msg;
6854   struct MeshPeerInfo *peer_info;
6855   struct MeshClient *c;
6856   struct MeshTunnel *t;
6857   MESH_TunnelNumber tid;
6858
6859   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER DEL request\n");
6860   /* Sanity check for client registration */
6861   if (NULL == (c = client_get (client)))
6862   {
6863     GNUNET_break (0);
6864     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6865     return;
6866   }
6867   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6868
6869   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6870
6871   /* Sanity check for message size */
6872   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6873   {
6874     GNUNET_break (0);
6875     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6876     return;
6877   }
6878
6879   /* Tunnel exists? */
6880   tid = ntohl (peer_msg->tunnel_id);
6881   t = tunnel_get_by_local_id (c, tid);
6882   if (NULL == t)
6883   {
6884     GNUNET_break (0);
6885     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6886     return;
6887   }
6888   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
6889
6890   /* Does client own tunnel? */
6891   if (t->owner->handle != client)
6892   {
6893     GNUNET_break (0);
6894     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6895     return;
6896   }
6897
6898   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for peer %s\n",
6899               GNUNET_i2s (&peer_msg->peer));
6900   /* Is the peer in the tunnel? */
6901   peer_info =
6902       GNUNET_CONTAINER_multihashmap_get (t->peers, &peer_msg->peer.hashPubKey);
6903   if (NULL == peer_info)
6904   {
6905     GNUNET_break (0);
6906     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6907     return;
6908   }
6909
6910   /* Ok, delete peer from tunnel */
6911   GNUNET_CONTAINER_multihashmap_remove_all (t->peers,
6912                                             &peer_msg->peer.hashPubKey);
6913
6914   send_destroy_path (t, peer_info->id);
6915   tunnel_delete_peer (t, peer_info->id);
6916   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6917   return;
6918 }
6919
6920 /**
6921  * Handler for blacklist requests of peers in a tunnel
6922  *
6923  * @param cls closure
6924  * @param client identification of the client
6925  * @param message the actual message (PeerControl)
6926  * 
6927  * FIXME implement DHT block bloomfilter
6928  */
6929 static void
6930 handle_local_blacklist (void *cls, struct GNUNET_SERVER_Client *client,
6931                           const struct GNUNET_MessageHeader *message)
6932 {
6933   struct GNUNET_MESH_PeerControl *peer_msg;
6934   struct MeshClient *c;
6935   struct MeshTunnel *t;
6936   MESH_TunnelNumber tid;
6937
6938   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER BLACKLIST request\n");
6939   /* Sanity check for client registration */
6940   if (NULL == (c = client_get (client)))
6941   {
6942     GNUNET_break (0);
6943     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6944     return;
6945   }
6946   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6947
6948   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6949
6950   /* Sanity check for message size */
6951   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6952   {
6953     GNUNET_break (0);
6954     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6955     return;
6956   }
6957
6958   /* Tunnel exists? */
6959   tid = ntohl (peer_msg->tunnel_id);
6960   t = tunnel_get_by_local_id (c, tid);
6961   if (NULL == t)
6962   {
6963     GNUNET_break (0);
6964     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6965     return;
6966   }
6967   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
6968
6969   GNUNET_array_append(t->blacklisted, t->nblacklisted,
6970                       GNUNET_PEER_intern(&peer_msg->peer));
6971 }
6972
6973
6974 /**
6975  * Handler for unblacklist requests of peers in a tunnel
6976  *
6977  * @param cls closure
6978  * @param client identification of the client
6979  * @param message the actual message (PeerControl)
6980  */
6981 static void
6982 handle_local_unblacklist (void *cls, struct GNUNET_SERVER_Client *client,
6983                           const struct GNUNET_MessageHeader *message)
6984 {
6985   struct GNUNET_MESH_PeerControl *peer_msg;
6986   struct MeshClient *c;
6987   struct MeshTunnel *t;
6988   MESH_TunnelNumber tid;
6989   GNUNET_PEER_Id pid;
6990   unsigned int i;
6991
6992   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER UNBLACKLIST request\n");
6993   /* Sanity check for client registration */
6994   if (NULL == (c = client_get (client)))
6995   {
6996     GNUNET_break (0);
6997     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6998     return;
6999   }
7000   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7001
7002   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
7003
7004   /* Sanity check for message size */
7005   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
7006   {
7007     GNUNET_break (0);
7008     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7009     return;
7010   }
7011
7012   /* Tunnel exists? */
7013   tid = ntohl (peer_msg->tunnel_id);
7014   t = tunnel_get_by_local_id (c, tid);
7015   if (NULL == t)
7016   {
7017     GNUNET_break (0);
7018     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7019     return;
7020   }
7021   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
7022
7023   /* if peer is not known, complain */
7024   pid = GNUNET_PEER_search (&peer_msg->peer);
7025   if (0 == pid)
7026   {
7027     GNUNET_break (0);
7028     return;
7029   }
7030
7031   /* search and remove from list */
7032   for (i = 0; i < t->nblacklisted; i++)
7033   {
7034     if (t->blacklisted[i] == pid)
7035     {
7036       t->blacklisted[i] = t->blacklisted[t->nblacklisted - 1];
7037       GNUNET_array_grow (t->blacklisted, t->nblacklisted, t->nblacklisted - 1);
7038       return;
7039     }
7040   }
7041
7042   /* if peer hasn't been blacklisted, complain */
7043   GNUNET_break (0);
7044 }
7045
7046
7047 /**
7048  * Handler for connection requests to new peers by type
7049  *
7050  * @param cls closure
7051  * @param client identification of the client
7052  * @param message the actual message (ConnectPeerByType)
7053  */
7054 static void
7055 handle_local_connect_by_type (void *cls, struct GNUNET_SERVER_Client *client,
7056                               const struct GNUNET_MessageHeader *message)
7057 {
7058   struct GNUNET_MESH_ConnectPeerByType *connect_msg;
7059   struct MeshClient *c;
7060   struct MeshTunnel *t;
7061   struct GNUNET_HashCode hash;
7062   MESH_TunnelNumber tid;
7063
7064   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got connect by type request\n");
7065   /* Sanity check for client registration */
7066   if (NULL == (c = client_get (client)))
7067   {
7068     GNUNET_break (0);
7069     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7070     return;
7071   }
7072   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7073
7074   connect_msg = (struct GNUNET_MESH_ConnectPeerByType *) message;
7075
7076   /* Sanity check for message size */
7077   if (sizeof (struct GNUNET_MESH_ConnectPeerByType) !=
7078       ntohs (connect_msg->header.size))
7079   {
7080     GNUNET_break (0);
7081     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7082     return;
7083   }
7084
7085   /* Tunnel exists? */
7086   tid = ntohl (connect_msg->tunnel_id);
7087   t = tunnel_get_by_local_id (c, tid);
7088   if (NULL == t)
7089   {
7090     GNUNET_break (0);
7091     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7092     return;
7093   }
7094
7095   /* Does client own tunnel? */
7096   if (t->owner->handle != client)
7097   {
7098     GNUNET_break (0);
7099     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7100     return;
7101   }
7102
7103   /* Do WE have the service? */
7104   t->type = ntohl (connect_msg->type);
7105   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " type requested: %u\n", t->type);
7106   GNUNET_CRYPTO_hash (&t->type, sizeof (GNUNET_MESH_ApplicationType), &hash);
7107   if (GNUNET_CONTAINER_multihashmap_contains (applications, &hash) ==
7108       GNUNET_YES)
7109   {
7110     /* Yes! Fast forward, add ourselves to the tunnel and send the
7111      * good news to the client, and alert the destination client of
7112      * an incoming tunnel.
7113      *
7114      * FIXME send a path create to self, avoid code duplication
7115      */
7116     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " available locally\n");
7117     GNUNET_CONTAINER_multihashmap_put (t->peers, &my_full_id.hashPubKey,
7118                                        peer_info_get (&my_full_id),
7119                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
7120
7121     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " notifying client\n");
7122     send_client_peer_connected (t, myid);
7123     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Done\n");
7124     GNUNET_SERVER_receive_done (client, GNUNET_OK);
7125
7126     t->local_tid_dest = next_local_tid++;
7127     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
7128     GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
7129                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
7130
7131     return;
7132   }
7133   /* Ok, lets find a peer offering the service */
7134   if (NULL != t->dht_get_type)
7135   {
7136     GNUNET_DHT_get_stop (t->dht_get_type);
7137   }
7138   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " looking in DHT for %s\n",
7139               GNUNET_h2s (&hash));
7140   t->dht_get_type =
7141       GNUNET_DHT_get_start (dht_handle, 
7142                             GNUNET_BLOCK_TYPE_MESH_PEER_BY_TYPE,
7143                             &hash,
7144                             dht_replication_level,
7145                             GNUNET_DHT_RO_RECORD_ROUTE |
7146                             GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
7147                             NULL, 0,
7148                             &dht_get_type_handler, t);
7149
7150   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7151   return;
7152 }
7153
7154
7155 /**
7156  * Handler for connection requests to new peers by a string service description.
7157  *
7158  * @param cls closure
7159  * @param client identification of the client
7160  * @param message the actual message, which includes messages the client wants
7161  */
7162 static void
7163 handle_local_connect_by_string (void *cls, struct GNUNET_SERVER_Client *client,
7164                                 const struct GNUNET_MessageHeader *message)
7165 {
7166   struct GNUNET_MESH_ConnectPeerByString *msg;
7167   struct MeshRegexSearchInfo *info;
7168   struct GNUNET_HashCode key;
7169   struct MeshTunnel *t;
7170   struct MeshClient *c;
7171   MESH_TunnelNumber tid;
7172   const char *string;
7173   size_t size;
7174   size_t len;
7175
7176   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7177               "Connect by string started\n");
7178   msg = (struct GNUNET_MESH_ConnectPeerByString *) message;
7179   size = htons (message->size);
7180
7181   /* Sanity check for client registration */
7182   if (NULL == (c = client_get (client)))
7183   {
7184     GNUNET_break (0);
7185     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7186     return;
7187   }
7188   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7189
7190   /* Message size sanity check */
7191   if (sizeof(struct GNUNET_MESH_ConnectPeerByString) >= size)
7192   {
7193     GNUNET_break (0);
7194     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7195     return;
7196   }
7197
7198   /* Tunnel exists? */
7199   tid = ntohl (msg->tunnel_id);
7200   t = tunnel_get_by_local_id (c, tid);
7201   if (NULL == t)
7202   {
7203     GNUNET_break (0);
7204     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7205     return;
7206   }
7207
7208   /* Does client own tunnel? */
7209   if (t->owner->handle != client)
7210   {
7211     GNUNET_break (0);
7212     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7213     return;
7214   }
7215
7216   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7217               "  on tunnel %s [%u]\n",
7218               GNUNET_i2s(&my_full_id),
7219               t->id.tid);
7220
7221   /* Only one connect_by_string allowed at the same time! */
7222   /* FIXME: allow more, return handle at api level to cancel, document */
7223   if (NULL != t->regex_search)
7224   {
7225     GNUNET_break (0);
7226     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7227     return;
7228   }
7229
7230   /* Find string itself */
7231   len = size - sizeof(struct GNUNET_MESH_ConnectPeerByString);
7232   string = (const char *) &msg[1];
7233
7234   /* Initialize context */
7235   size = GNUNET_REGEX_get_first_key (string, len, &key);
7236   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7237               "  consumed %u bits out of %u\n", size, len);
7238   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7239               "  looking for %s\n", GNUNET_h2s (&key));
7240
7241   info = GNUNET_malloc (sizeof (struct MeshRegexSearchInfo));
7242   info->t = t;
7243   info->description = GNUNET_strndup (string, len);
7244   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   string: %s\n", info->description);
7245
7246   t->regex_search = info;
7247
7248   info->search_handle = GNUNET_REGEX_search (dht_handle,
7249                                              info->description,
7250                                              &regex_found_handler, info,
7251                                              stats);
7252
7253   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7254   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "connect by string processed\n");
7255 }
7256
7257
7258 /**
7259  * Handler for client traffic directed to one peer
7260  *
7261  * @param cls closure
7262  * @param client identification of the client
7263  * @param message the actual message
7264  */
7265 static void
7266 handle_local_unicast (void *cls, struct GNUNET_SERVER_Client *client,
7267                       const struct GNUNET_MessageHeader *message)
7268 {
7269   struct MeshClient *c;
7270   struct MeshTunnel *t;
7271   struct MeshPeerInfo *pi;
7272   struct GNUNET_MESH_Unicast *data_msg;
7273   MESH_TunnelNumber tid;
7274   size_t size;
7275
7276   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7277               "Got a unicast request from a client!\n");
7278
7279   /* Sanity check for client registration */
7280   if (NULL == (c = client_get (client)))
7281   {
7282     GNUNET_break (0);
7283     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7284     return;
7285   }
7286   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7287
7288   data_msg = (struct GNUNET_MESH_Unicast *) message;
7289
7290   /* Sanity check for message size */
7291   size = ntohs (message->size);
7292   if (sizeof (struct GNUNET_MESH_Unicast) +
7293       sizeof (struct GNUNET_MessageHeader) > size)
7294   {
7295     GNUNET_break (0);
7296     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7297     return;
7298   }
7299
7300   /* Tunnel exists? */
7301   tid = ntohl (data_msg->tid);
7302   t = tunnel_get_by_local_id (c, tid);
7303   if (NULL == t)
7304   {
7305     GNUNET_break (0);
7306     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7307     return;
7308   }
7309
7310   /*  Is it a local tunnel? Then, does client own the tunnel? */
7311   if (t->owner->handle != client)
7312   {
7313     GNUNET_break (0);
7314     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7315     return;
7316   }
7317
7318   pi = GNUNET_CONTAINER_multihashmap_get (t->peers,
7319                                           &data_msg->destination.hashPubKey);
7320   /* Is the selected peer in the tunnel? */
7321   if (NULL == pi)
7322   {
7323     GNUNET_break (0);
7324     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7325     return;
7326   }
7327
7328   /* PID should be as expected */
7329   if (ntohl (data_msg->pid) != t->fwd_pid + 1)
7330   {
7331     GNUNET_break (0);
7332     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7333               "Unicast PID, expected %u, got %u\n",
7334               t->fwd_pid + 1, ntohl (data_msg->pid));
7335     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7336     return;
7337   }
7338
7339   /* Ok, everything is correct, send the message
7340    * (pretend we got it from a mesh peer)
7341    */
7342   {
7343     /* Work around const limitation */
7344     char buf[ntohs (message->size)] GNUNET_ALIGN;
7345     struct GNUNET_MESH_Unicast *copy;
7346
7347     copy = (struct GNUNET_MESH_Unicast *) buf;
7348     memcpy (buf, data_msg, size);
7349     copy->oid = my_full_id;
7350     copy->tid = htonl (t->id.tid);
7351     copy->ttl = htonl (default_ttl);
7352     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7353                 "  calling generic handler...\n");
7354     handle_mesh_data_unicast (NULL, &my_full_id, &copy->header);
7355   }
7356   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "receive done OK\n");
7357   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7358
7359   return;
7360 }
7361
7362
7363 /**
7364  * Handler for client traffic directed to the origin
7365  *
7366  * @param cls closure
7367  * @param client identification of the client
7368  * @param message the actual message
7369  */
7370 static void
7371 handle_local_to_origin (void *cls, struct GNUNET_SERVER_Client *client,
7372                         const struct GNUNET_MessageHeader *message)
7373 {
7374   struct GNUNET_MESH_ToOrigin *data_msg;
7375   struct MeshTunnelClientInfo *clinfo;
7376   struct MeshClient *c;
7377   struct MeshTunnel *t;
7378   MESH_TunnelNumber tid;
7379   size_t size;
7380
7381   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7382               "Got a ToOrigin request from a client!\n");
7383   /* Sanity check for client registration */
7384   if (NULL == (c = client_get (client)))
7385   {
7386     GNUNET_break (0);
7387     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7388     return;
7389   }
7390   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7391
7392   data_msg = (struct GNUNET_MESH_ToOrigin *) message;
7393
7394   /* Sanity check for message size */
7395   size = ntohs (message->size);
7396   if (sizeof (struct GNUNET_MESH_ToOrigin) +
7397       sizeof (struct GNUNET_MessageHeader) > size)
7398   {
7399     GNUNET_break (0);
7400     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7401     return;
7402   }
7403
7404   /* Tunnel exists? */
7405   tid = ntohl (data_msg->tid);
7406   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
7407   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
7408   {
7409     GNUNET_break (0);
7410     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7411     return;
7412   }
7413   t = tunnel_get_by_local_id (c, tid);
7414   if (NULL == t)
7415   {
7416     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
7417     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
7418     GNUNET_break (0);
7419     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7420     return;
7421   }
7422
7423   /*  It should be sent by someone who has this as incoming tunnel. */
7424   if (GNUNET_NO == client_knows_tunnel (c, t))
7425   {
7426     GNUNET_break (0);
7427     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7428     return;
7429   }
7430
7431   /* PID should be as expected */
7432   clinfo = tunnel_get_client_fc (t, c);
7433   if (ntohl (data_msg->pid) != clinfo->bck_pid + 1)
7434   {
7435     GNUNET_break (0);
7436     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7437                 "To Origin PID, expected %u, got %u\n",
7438                 clinfo->bck_pid + 1,
7439                 ntohl (data_msg->pid));
7440     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7441     return;
7442   }
7443   clinfo->bck_pid++;
7444
7445   /* Ok, everything is correct, send the message
7446    * (pretend we got it from a mesh peer)
7447    */
7448   {
7449     char buf[ntohs (message->size)] GNUNET_ALIGN;
7450     struct GNUNET_MESH_ToOrigin *copy;
7451
7452     /* Work around const limitation */
7453     copy = (struct GNUNET_MESH_ToOrigin *) buf;
7454     memcpy (buf, data_msg, size);
7455     GNUNET_PEER_resolve (t->id.oid, &copy->oid);
7456     copy->tid = htonl (t->id.tid);
7457     copy->ttl = htonl (default_ttl);
7458     copy->pid = htonl (t->bck_pid + 1);
7459
7460     copy->sender = my_full_id;
7461     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7462                 "  calling generic handler...\n");
7463     handle_mesh_data_to_orig (NULL, &my_full_id, &copy->header);
7464
7465   }
7466   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7467
7468   return;
7469 }
7470
7471
7472 /**
7473  * Handler for client traffic directed to all peers in a tunnel
7474  *
7475  * @param cls closure
7476  * @param client identification of the client
7477  * @param message the actual message
7478  */
7479 static void
7480 handle_local_multicast (void *cls, struct GNUNET_SERVER_Client *client,
7481                         const struct GNUNET_MessageHeader *message)
7482 {
7483   struct MeshClient *c;
7484   struct MeshTunnel *t;
7485   struct GNUNET_MESH_Multicast *data_msg;
7486   MESH_TunnelNumber tid;
7487
7488   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7489               "Got a multicast request from a client!\n");
7490
7491   /* Sanity check for client registration */
7492   if (NULL == (c = client_get (client)))
7493   {
7494     GNUNET_break (0);
7495     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7496     return;
7497   }
7498   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7499
7500   data_msg = (struct GNUNET_MESH_Multicast *) message;
7501
7502   /* Sanity check for message size */
7503   if (sizeof (struct GNUNET_MESH_Multicast) +
7504       sizeof (struct GNUNET_MessageHeader) > ntohs (data_msg->header.size))
7505   {
7506     GNUNET_break (0);
7507     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7508     return;
7509   }
7510
7511   /* Tunnel exists? */
7512   tid = ntohl (data_msg->tid);
7513   t = tunnel_get_by_local_id (c, tid);
7514   if (NULL == t)
7515   {
7516     GNUNET_break (0);
7517     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
7518     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
7519     GNUNET_break (0);
7520     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7521     return;
7522   }
7523
7524   /* Does client own tunnel? */
7525   if (t->owner->handle != client)
7526   {
7527     GNUNET_break (0);
7528     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7529     return;
7530   }
7531
7532   /* PID should be as expected */
7533   if (ntohl (data_msg->pid) != t->fwd_pid + 1)
7534   {
7535     GNUNET_break (0);
7536     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7537               "Multicast PID, expected %u, got %u\n",
7538               t->fwd_pid + 1, ntohl (data_msg->pid));
7539     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7540     return;
7541   }
7542
7543   {
7544     char buf[ntohs (message->size)] GNUNET_ALIGN;
7545     struct GNUNET_MESH_Multicast *copy;
7546
7547     copy = (struct GNUNET_MESH_Multicast *) buf;
7548     memcpy (buf, message, ntohs (message->size));
7549     copy->oid = my_full_id;
7550     copy->tid = htonl (t->id.tid);
7551     copy->ttl = htonl (default_ttl);
7552     GNUNET_assert (ntohl (copy->pid) == (t->fwd_pid + 1));
7553     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7554                 "  calling generic handler...\n");
7555     handle_mesh_data_multicast (client, &my_full_id, &copy->header);
7556   }
7557
7558   GNUNET_SERVER_receive_done (t->owner->handle, GNUNET_OK);
7559   return;
7560 }
7561
7562
7563 /**
7564  * Handler for client's ACKs for payload traffic.
7565  *
7566  * @param cls Closure (unused).
7567  * @param client Identification of the client.
7568  * @param message The actual message.
7569  */
7570 static void
7571 handle_local_ack (void *cls, struct GNUNET_SERVER_Client *client,
7572                   const struct GNUNET_MessageHeader *message)
7573 {
7574   struct GNUNET_MESH_LocalAck *msg;
7575   struct MeshTunnel *t;
7576   struct MeshClient *c;
7577   MESH_TunnelNumber tid;
7578   uint32_t ack;
7579
7580   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a local ACK\n");
7581   /* Sanity check for client registration */
7582   if (NULL == (c = client_get (client)))
7583   {
7584     GNUNET_break (0);
7585     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7586     return;
7587   }
7588   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7589
7590   msg = (struct GNUNET_MESH_LocalAck *) message;
7591
7592   /* Tunnel exists? */
7593   tid = ntohl (msg->tunnel_id);
7594   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
7595   t = tunnel_get_by_local_id (c, tid);
7596   if (NULL == t)
7597   {
7598     GNUNET_break (0);
7599     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
7600     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
7601     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7602     return;
7603   }
7604
7605   ack = ntohl (msg->max_pid);
7606   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ack %u\n", ack);
7607
7608   /* Does client own tunnel? I.E: Is this an ACK for BCK traffic? */
7609   if (NULL != t->owner && t->owner->handle == client)
7610   {
7611     /* The client owns the tunnel, ACK is for data to_origin, send BCK ACK. */
7612     t->bck_ack = ack;
7613     tunnel_send_bck_ack(t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
7614   }
7615   else
7616   {
7617     /* The client doesn't own the tunnel, this ACK is for FWD traffic. */
7618     tunnel_set_client_fwd_ack (t, c, ack);
7619     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
7620   }
7621
7622   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7623
7624   return;
7625 }
7626
7627
7628 /**
7629  * Iterator over all peers to send a monitoring client info about a tunnel.
7630  *
7631  * @param cls Closure (message being built).
7632  * @param key Key (hashed tunnel ID, unused).
7633  * @param value Peer info.
7634  *
7635  * @return GNUNET_YES, to keep iterating.
7636  */
7637 static int
7638 monitor_peers_iterator (void *cls,
7639                         const struct GNUNET_HashCode * key,
7640                         void *value)
7641 {
7642   struct GNUNET_MESH_LocalMonitor *msg = cls;
7643   struct GNUNET_PeerIdentity *id;
7644   struct MeshPeerInfo *info = value;
7645
7646   id = (struct GNUNET_PeerIdentity *) &msg[1];
7647   GNUNET_PEER_resolve (info->id, &id[msg->npeers]);
7648   msg->npeers++;
7649
7650   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
7651               "*    sending info about peer %s [%u]\n",
7652               GNUNET_i2s (&id[msg->npeers - 1]), msg->npeers);
7653
7654   return GNUNET_YES;
7655 }
7656
7657
7658
7659 /**
7660  * Iterator over all tunnels to send a monitoring client info about each tunnel.
7661  *
7662  * @param cls Closure (client handle).
7663  * @param key Key (hashed tunnel ID, unused).
7664  * @param value Tunnel info.
7665  *
7666  * @return GNUNET_YES, to keep iterating.
7667  */
7668 static int
7669 monitor_all_tunnels_iterator (void *cls,
7670                               const struct GNUNET_HashCode * key,
7671                               void *value)
7672 {
7673   struct GNUNET_SERVER_Client *client = cls;
7674   struct MeshTunnel *t = value;
7675   struct GNUNET_MESH_LocalMonitor *msg;
7676   uint32_t npeers;
7677   
7678   npeers = GNUNET_CONTAINER_multihashmap_size (t->peers);
7679   msg = GNUNET_malloc (sizeof(struct GNUNET_MESH_LocalMonitor) +
7680   npeers * sizeof (struct GNUNET_PeerIdentity));
7681   GNUNET_PEER_resolve(t->id.oid, &msg->owner);
7682   msg->tunnel_id = htonl (t->id.tid);
7683   msg->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor) +
7684   npeers * sizeof (struct GNUNET_PeerIdentity));
7685   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS);
7686   msg->npeers = 0;
7687   (void) GNUNET_CONTAINER_multihashmap_iterate (t->peers,
7688                                                 monitor_peers_iterator,
7689                                                 msg);
7690   
7691   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
7692               "*  sending info about tunnel %s [%u] (%u peers)\n",
7693               GNUNET_i2s (&msg->owner), t->id.tid, npeers);
7694   
7695   if (msg->npeers != npeers)
7696   {
7697     GNUNET_break (0);
7698     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7699                 "Get tunnels fail: size %u - iter %u\n",
7700                 npeers, msg->npeers);
7701   }
7702   
7703     msg->npeers = htonl (npeers);
7704     GNUNET_SERVER_notification_context_unicast (nc, client,
7705                                                 &msg->header, GNUNET_NO);
7706     return GNUNET_YES;
7707 }
7708
7709
7710 /**
7711  * Handler for client's MONITOR request.
7712  *
7713  * @param cls Closure (unused).
7714  * @param client Identification of the client.
7715  * @param message The actual message.
7716  */
7717 static void
7718 handle_local_get_tunnels (void *cls, struct GNUNET_SERVER_Client *client,
7719                           const struct GNUNET_MessageHeader *message)
7720 {
7721   struct MeshClient *c;
7722
7723   /* Sanity check for client registration */
7724   if (NULL == (c = client_get (client)))
7725   {
7726     GNUNET_break (0);
7727     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7728     return;
7729   }
7730
7731   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
7732               "Received get tunnels request from client %u\n",
7733               c->id);
7734   GNUNET_CONTAINER_multihashmap_iterate (tunnels,
7735                                          monitor_all_tunnels_iterator,
7736                                          client);
7737   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
7738               "Get tunnels request from client %u completed\n",
7739               c->id);
7740   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7741 }
7742
7743
7744 /**
7745  * Data needed to build a Monitor_Tunnel message.
7746  */
7747 struct MeshMonitorTunnelContext
7748 {
7749   /**
7750    * Partial message, including peer count.
7751    */
7752   struct GNUNET_MESH_LocalMonitor *msg;
7753
7754   /**
7755    * Hashmap with positions: peer->position.
7756    */
7757   struct GNUNET_CONTAINER_MultiHashMap *lookup;
7758
7759   /**
7760    * Index of the parent of each peer in the message, realtive to the absolute
7761    * order in the array (can be in a previous message).
7762    */
7763   uint32_t parents[1024];
7764
7765   /**
7766    * Peers visited so far in the tree, aka position of the current peer.
7767    */
7768   unsigned int npeers;
7769
7770   /**
7771    * Client requesting the info.
7772    */
7773   struct MeshClient *c;
7774 };
7775
7776
7777 /**
7778  * Send a client a message about the structure of a tunnel.
7779  *
7780  * @param ctx Context of the tunnel iteration, with info regarding the state
7781  *            of the execution and the number of peers visited for this message.
7782  */
7783 static void
7784 send_client_tunnel_info (struct MeshMonitorTunnelContext *ctx)
7785 {
7786   struct GNUNET_MESH_LocalMonitor *resp = ctx->msg;
7787   struct GNUNET_PeerIdentity *pid;
7788   unsigned int *parent;
7789   size_t size;
7790
7791   size = sizeof (struct GNUNET_MESH_LocalMonitor);
7792   size += (sizeof (struct GNUNET_PeerIdentity) + sizeof (int)) * resp->npeers;
7793   resp->header.size = htons (size);
7794   pid = (struct GNUNET_PeerIdentity *) &resp[1];
7795   parent = (unsigned int *) &pid[resp->npeers];
7796   memcpy (parent, ctx->parents, sizeof(uint32_t) * resp->npeers);
7797   GNUNET_SERVER_notification_context_unicast (nc, ctx->c->handle,
7798                                               &resp->header, GNUNET_NO);
7799 }
7800
7801 /**
7802  * Iterator over a tunnel tree to build a message containing all peers
7803  * the in the tunnel, including relay nodes.
7804  *
7805  * @param cls Closure (pointer to pointer of message being built).
7806  * @param peer Short ID of a peer.
7807  * @param parent Short ID of the @c peer 's parent.
7808  */
7809 static void
7810 tunnel_tree_iterator (void *cls,
7811                       GNUNET_PEER_Id peer,
7812                       GNUNET_PEER_Id parent)
7813 {
7814   struct MeshMonitorTunnelContext *ctx = cls;
7815   struct GNUNET_MESH_LocalMonitor *msg;
7816   struct GNUNET_PeerIdentity *pid;
7817   struct GNUNET_PeerIdentity ppid;
7818
7819   msg = ctx->msg;
7820   pid = (struct GNUNET_PeerIdentity *) &msg[1];
7821   GNUNET_PEER_resolve (peer, &pid[msg->npeers]);
7822   GNUNET_CONTAINER_multihashmap_put (ctx->lookup,
7823                                      &pid[msg->npeers].hashPubKey,
7824                                      (void *) (long) ctx->npeers,
7825                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
7826   GNUNET_PEER_resolve (parent, &ppid);
7827   ctx->parents[msg->npeers] =
7828       htonl ((long) GNUNET_CONTAINER_multihashmap_get (ctx->lookup,
7829                                                        &ppid.hashPubKey));
7830
7831   ctx->npeers++;
7832   msg->npeers++;
7833
7834   if (sizeof (struct GNUNET_MESH_LocalMonitor) +
7835       (msg->npeers + 1) *
7836       (sizeof (struct GNUNET_PeerIdentity) + sizeof (uint32_t))
7837       > USHRT_MAX)
7838   {
7839     send_client_tunnel_info (ctx);
7840     msg->npeers = 0;
7841   }
7842 }
7843
7844
7845 /**
7846  * Handler for client's MONITOR_TUNNEL request.
7847  *
7848  * @param cls Closure (unused).
7849  * @param client Identification of the client.
7850  * @param message The actual message.
7851  */
7852 static void
7853 handle_local_show_tunnel (void *cls, struct GNUNET_SERVER_Client *client,
7854                           const struct GNUNET_MessageHeader *message)
7855 {
7856   const struct GNUNET_MESH_LocalMonitor *msg;
7857   struct GNUNET_MESH_LocalMonitor *resp;
7858   struct MeshMonitorTunnelContext ctx;
7859   struct MeshClient *c;
7860   struct MeshTunnel *t;
7861
7862   /* Sanity check for client registration */
7863   if (NULL == (c = client_get (client)))
7864   {
7865     GNUNET_break (0);
7866     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7867     return;
7868   }
7869
7870   msg = (struct GNUNET_MESH_LocalMonitor *) message;
7871   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
7872               "Received tunnel info request from client %u for tunnel %s[%X]\n",
7873               c->id,
7874               &msg->owner,
7875               ntohl (msg->tunnel_id));
7876   t = tunnel_get (&msg->owner, ntohl (msg->tunnel_id));
7877   if (NULL == t)
7878   {
7879     /* We don't know the tunnel */
7880     struct GNUNET_MESH_LocalMonitor warn;
7881
7882     warn = *msg;
7883     warn.npeers = htonl (UINT_MAX);
7884     GNUNET_SERVER_notification_context_unicast (nc, client,
7885                                                 &warn.header,
7886                                                 GNUNET_NO);
7887     GNUNET_SERVER_receive_done (client, GNUNET_OK);
7888     return;
7889   }
7890
7891   /* Initialize context */
7892   resp = GNUNET_malloc (USHRT_MAX); /* avoid realloc'ing on each step */
7893   *resp = *msg;
7894   resp->npeers = 0;
7895   ctx.msg = resp;
7896   ctx.lookup = GNUNET_CONTAINER_multihashmap_create (4 * t->peers_total,
7897                                                      GNUNET_YES);
7898   ctx.c = c;
7899
7900   /* Collect and send information */
7901   tree_iterate_all (t->tree, &tunnel_tree_iterator, &ctx);
7902   send_client_tunnel_info (&ctx);
7903
7904   /* Free context */
7905   GNUNET_CONTAINER_multihashmap_destroy (ctx.lookup);
7906   GNUNET_free (resp);
7907
7908   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
7909               "Monitor tunnel request from client %u completed\n",
7910               c->id);
7911   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7912 }
7913
7914
7915 /**
7916  * Functions to handle messages from clients
7917  */
7918 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
7919   {&handle_local_new_client, NULL,
7920    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
7921   {&handle_local_announce_regex, NULL,
7922    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ANNOUNCE_REGEX, 0},
7923   {&handle_local_tunnel_create, NULL,
7924    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
7925    sizeof (struct GNUNET_MESH_TunnelMessage)},
7926   {&handle_local_tunnel_destroy, NULL,
7927    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
7928    sizeof (struct GNUNET_MESH_TunnelMessage)},
7929   {&handle_local_tunnel_speed, NULL,
7930    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MIN,
7931    sizeof (struct GNUNET_MESH_TunnelMessage)},
7932   {&handle_local_tunnel_speed, NULL,
7933    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MAX,
7934    sizeof (struct GNUNET_MESH_TunnelMessage)},
7935   {&handle_local_tunnel_buffer, NULL,
7936    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER,
7937    sizeof (struct GNUNET_MESH_TunnelMessage)},
7938   {&handle_local_tunnel_buffer, NULL,
7939    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER,
7940    sizeof (struct GNUNET_MESH_TunnelMessage)},
7941   {&handle_local_connect_add, NULL,
7942    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD,
7943    sizeof (struct GNUNET_MESH_PeerControl)},
7944   {&handle_local_connect_del, NULL,
7945    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL,
7946    sizeof (struct GNUNET_MESH_PeerControl)},
7947   {&handle_local_blacklist, NULL,
7948    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_BLACKLIST,
7949    sizeof (struct GNUNET_MESH_PeerControl)},
7950   {&handle_local_unblacklist, NULL,
7951    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_UNBLACKLIST,
7952    sizeof (struct GNUNET_MESH_PeerControl)},
7953   {&handle_local_connect_by_type, NULL,
7954    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE,
7955    sizeof (struct GNUNET_MESH_ConnectPeerByType)},
7956   {&handle_local_connect_by_string, NULL,
7957    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_STRING, 0},
7958   {&handle_local_unicast, NULL,
7959    GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
7960   {&handle_local_to_origin, NULL,
7961    GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
7962   {&handle_local_multicast, NULL,
7963    GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
7964   {&handle_local_ack, NULL,
7965    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK,
7966    sizeof (struct GNUNET_MESH_LocalAck)},
7967   {&handle_local_get_tunnels, NULL,
7968    GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS,
7969    sizeof (struct GNUNET_MessageHeader)},
7970   {&handle_local_show_tunnel, NULL,
7971    GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNEL,
7972      sizeof (struct GNUNET_MESH_LocalMonitor)},
7973   {NULL, NULL, 0, 0}
7974 };
7975
7976
7977 /**
7978  * To be called on core init/fail.
7979  *
7980  * @param cls service closure
7981  * @param server handle to the server for this service
7982  * @param identity the public identity of this peer
7983  */
7984 static void
7985 core_init (void *cls, struct GNUNET_CORE_Handle *server,
7986            const struct GNUNET_PeerIdentity *identity)
7987 {
7988   static int i = 0;
7989   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
7990   core_handle = server;
7991   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)) ||
7992       NULL == server)
7993   {
7994     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
7995     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7996                 " core id %s\n",
7997                 GNUNET_i2s (identity));
7998     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7999                 " my id %s\n",
8000                 GNUNET_i2s (&my_full_id));
8001     GNUNET_SCHEDULER_shutdown (); // Try gracefully
8002     if (10 < i++)
8003       GNUNET_abort(); // Try harder
8004   }
8005   return;
8006 }
8007
8008
8009 /**
8010  * Method called whenever a given peer connects.
8011  *
8012  * @param cls closure
8013  * @param peer peer identity this notification is about
8014  * @param atsi performance data for the connection
8015  * @param atsi_count number of records in 'atsi'
8016  */
8017 static void
8018 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer)
8019 {
8020   struct MeshPeerInfo *peer_info;
8021   struct MeshPeerPath *path;
8022
8023   DEBUG_CONN ("Peer connected\n");
8024   DEBUG_CONN ("     %s\n", GNUNET_i2s (&my_full_id));
8025   peer_info = peer_info_get (peer);
8026   if (myid == peer_info->id)
8027   {
8028     DEBUG_CONN ("     (self)\n");
8029     return;
8030   }
8031   else
8032   {
8033     DEBUG_CONN ("     %s\n", GNUNET_i2s (peer));
8034   }
8035   path = path_new (2);
8036   path->peers[0] = myid;
8037   path->peers[1] = peer_info->id;
8038   GNUNET_PEER_change_rc (myid, 1);
8039   GNUNET_PEER_change_rc (peer_info->id, 1);
8040   peer_info_add_path (peer_info, path, GNUNET_YES);
8041   GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
8042   return;
8043 }
8044
8045
8046 /**
8047  * Method called whenever a peer disconnects.
8048  *
8049  * @param cls closure
8050  * @param peer peer identity this notification is about
8051  */
8052 static void
8053 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
8054 {
8055   struct MeshPeerInfo *pi;
8056   struct MeshPeerQueue *q;
8057   struct MeshPeerQueue *n;
8058
8059   DEBUG_CONN ("Peer disconnected\n");
8060   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
8061   if (NULL == pi)
8062   {
8063     GNUNET_break (0);
8064     return;
8065   }
8066   q = pi->queue_head;
8067   while (NULL != q)
8068   {
8069       n = q->next;
8070       /* TODO try to reroute this traffic instead */
8071       queue_destroy(q, GNUNET_YES);
8072       q = n;
8073   }
8074   if (NULL != pi->core_transmit)
8075   {
8076     GNUNET_CORE_notify_transmit_ready_cancel(pi->core_transmit);
8077     pi->core_transmit = NULL;
8078   }
8079   peer_info_remove_path (pi, pi->id, myid);
8080   if (myid == pi->id)
8081   {
8082     DEBUG_CONN ("     (self)\n");
8083   }
8084   GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
8085   return;
8086 }
8087
8088
8089 /******************************************************************************/
8090 /************************      MAIN FUNCTIONS      ****************************/
8091 /******************************************************************************/
8092
8093 /**
8094  * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
8095  *
8096  * @param cls closure
8097  * @param key current key code
8098  * @param value value in the hash map
8099  * @return GNUNET_YES if we should continue to iterate,
8100  *         GNUNET_NO if not.
8101  */
8102 static int
8103 shutdown_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
8104 {
8105   struct MeshTunnel *t = value;
8106
8107   tunnel_destroy (t);
8108   return GNUNET_YES;
8109 }
8110
8111 /**
8112  * Iterator over peer hash map entries to destroy the tunnel during shutdown.
8113  *
8114  * @param cls closure
8115  * @param key current key code
8116  * @param value value in the hash map
8117  * @return GNUNET_YES if we should continue to iterate,
8118  *         GNUNET_NO if not.
8119  */
8120 static int
8121 shutdown_peer (void *cls, const struct GNUNET_HashCode * key, void *value)
8122 {
8123   struct MeshPeerInfo *p = value;
8124   struct MeshPeerQueue *q;
8125   struct MeshPeerQueue *n;
8126
8127   q = p->queue_head;
8128   while (NULL != q)
8129   {
8130       n = q->next;
8131       if (q->peer == p)
8132       {
8133         queue_destroy(q, GNUNET_YES);
8134       }
8135       q = n;
8136   }
8137   peer_info_destroy (p);
8138   return GNUNET_YES;
8139 }
8140
8141
8142 /**
8143  * Task run during shutdown.
8144  *
8145  * @param cls unused
8146  * @param tc unused
8147  */
8148 static void
8149 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
8150 {
8151   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
8152
8153   if (core_handle != NULL)
8154   {
8155     GNUNET_CORE_disconnect (core_handle);
8156     core_handle = NULL;
8157   }
8158   if (NULL != keygen)
8159   {
8160     GNUNET_CRYPTO_rsa_key_create_stop (keygen);
8161     keygen = NULL;
8162   }
8163   GNUNET_CONTAINER_multihashmap_iterate (tunnels, &shutdown_tunnel, NULL);
8164   GNUNET_CONTAINER_multihashmap_iterate (peers, &shutdown_peer, NULL);
8165   if (dht_handle != NULL)
8166   {
8167     GNUNET_DHT_disconnect (dht_handle);
8168     dht_handle = NULL;
8169   }
8170   if (nc != NULL)
8171   {
8172     GNUNET_SERVER_notification_context_destroy (nc);
8173     nc = NULL;
8174   }
8175   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
8176   {
8177     GNUNET_SCHEDULER_cancel (announce_id_task);
8178     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
8179   }
8180   if (GNUNET_SCHEDULER_NO_TASK != announce_applications_task)
8181   {
8182     GNUNET_SCHEDULER_cancel (announce_applications_task);
8183     announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
8184   }
8185   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
8186 }
8187
8188
8189 /**
8190  * Callback for hostkey read/generation
8191  *
8192  * @param cls Closure (Configuration handle).
8193  * @param pk the private key
8194  * @param emsg error message
8195  */
8196 static void
8197 key_generation_cb (void *cls,
8198                    struct GNUNET_CRYPTO_RsaPrivateKey *pk,
8199                    const char *emsg)
8200 {
8201   const struct GNUNET_CONFIGURATION_Handle *c = cls;
8202   struct MeshPeerInfo *peer;
8203   struct MeshPeerPath *p;
8204
8205   keygen = NULL;  
8206   if (NULL == pk)
8207   {
8208     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8209                 _("Mesh service could not access hostkey: %s. Exiting.\n"),
8210                 emsg);
8211     GNUNET_SCHEDULER_shutdown ();
8212     return;
8213   }
8214   my_private_key = pk;
8215   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
8216   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
8217                       &my_full_id.hashPubKey);
8218   myid = GNUNET_PEER_intern (&my_full_id);
8219   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
8220               "Mesh for peer [%s] starting\n",
8221               GNUNET_i2s(&my_full_id));
8222
8223 //   transport_handle = GNUNET_TRANSPORT_connect(c,
8224 //                                               &my_full_id,
8225 //                                               NULL,
8226 //                                               NULL,
8227 //                                               NULL,
8228 //                                               NULL);
8229
8230   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
8231                                      NULL,      /* Closure passed to MESH functions */
8232                                      &core_init,        /* Call core_init once connected */
8233                                      &core_connect,     /* Handle connects */
8234                                      &core_disconnect,  /* remove peers on disconnects */
8235                                      NULL,      /* Don't notify about all incoming messages */
8236                                      GNUNET_NO, /* For header only in notification */
8237                                      NULL,      /* Don't notify about all outbound messages */
8238                                      GNUNET_NO, /* For header-only out notification */
8239                                      core_handlers);    /* Register these handlers */
8240   
8241   if (core_handle == NULL)
8242   {
8243     GNUNET_break (0);
8244     GNUNET_SCHEDULER_shutdown ();
8245     return;
8246   }
8247
8248   next_tid = 0;
8249   next_local_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
8250
8251
8252   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
8253   nc = GNUNET_SERVER_notification_context_create (server_handle, 1);
8254   GNUNET_SERVER_disconnect_notify (server_handle,
8255                                    &handle_local_client_disconnect, NULL);
8256
8257
8258   clients = NULL;
8259   clients_tail = NULL;
8260   next_client_id = 0;
8261
8262   announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
8263   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
8264
8265   /* Create a peer_info for the local peer */
8266   peer = peer_info_get (&my_full_id);
8267   p = path_new (1);
8268   p->peers[0] = myid;
8269   GNUNET_PEER_change_rc (myid, 1);
8270   peer_info_add_path (peer, p, GNUNET_YES);
8271   GNUNET_SERVER_resume (server_handle);
8272   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Mesh service running\n");
8273 }
8274
8275
8276 /**
8277  * Process mesh requests.
8278  *
8279  * @param cls closure
8280  * @param server the initialized server
8281  * @param c configuration to use
8282  */
8283 static void
8284 run (void *cls, struct GNUNET_SERVER_Handle *server,
8285      const struct GNUNET_CONFIGURATION_Handle *c)
8286 {
8287   char *keyfile;
8288
8289   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
8290   server_handle = server;
8291
8292   if (GNUNET_OK !=
8293       GNUNET_CONFIGURATION_get_value_filename (c, "GNUNETD", "HOSTKEY",
8294                                                &keyfile))
8295   {
8296     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8297                 _
8298                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8299                 "mesh", "hostkey");
8300     GNUNET_SCHEDULER_shutdown ();
8301     return;
8302   }
8303
8304   if (GNUNET_OK !=
8305       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_PATH_TIME",
8306                                            &refresh_path_time))
8307   {
8308     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8309                 _
8310                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8311                 "mesh", "refresh path time");
8312     GNUNET_SCHEDULER_shutdown ();
8313     return;
8314   }
8315
8316   if (GNUNET_OK !=
8317       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "APP_ANNOUNCE_TIME",
8318                                            &app_announce_time))
8319   {
8320     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8321                 _
8322                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8323                 "mesh", "app announce time");
8324     GNUNET_SCHEDULER_shutdown ();
8325     return;
8326   }
8327   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
8328               "APP_ANNOUNCE_TIME %llu ms\n", 
8329               app_announce_time.rel_value);
8330   if (GNUNET_OK !=
8331       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "ID_ANNOUNCE_TIME",
8332                                            &id_announce_time))
8333   {
8334     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8335                 _
8336                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8337                 "mesh", "id announce time");
8338     GNUNET_SCHEDULER_shutdown ();
8339     return;
8340   }
8341
8342   if (GNUNET_OK !=
8343       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "CONNECT_TIMEOUT",
8344                                            &connect_timeout))
8345   {
8346     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8347                 _
8348                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8349                 "mesh", "connect timeout");
8350     GNUNET_SCHEDULER_shutdown ();
8351     return;
8352   }
8353
8354   if (GNUNET_OK !=
8355       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
8356                                              &max_msgs_queue))
8357   {
8358     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8359                 _
8360                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8361                 "mesh", "max msgs queue");
8362     GNUNET_SCHEDULER_shutdown ();
8363     return;
8364   }
8365
8366   if (GNUNET_OK !=
8367       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_TUNNELS",
8368                                              &max_tunnels))
8369   {
8370     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8371                 _
8372                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8373                 "mesh", "max tunnels");
8374     GNUNET_SCHEDULER_shutdown ();
8375     return;
8376   }
8377
8378   if (GNUNET_OK !=
8379       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
8380                                              &default_ttl))
8381   {
8382     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
8383                 _
8384                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
8385                 "mesh", "default ttl", 64);
8386     default_ttl = 64;
8387   }
8388
8389   if (GNUNET_OK !=
8390       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_PEERS",
8391                                              &max_peers))
8392   {
8393     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
8394                 _("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
8395                 "mesh", "max peers", 1000);
8396     max_peers = 1000;
8397   }
8398
8399   if (GNUNET_OK !=
8400       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DHT_REPLICATION_LEVEL",
8401                                              &dht_replication_level))
8402   {
8403     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
8404                 _
8405                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
8406                 "mesh", "dht replication level", 3);
8407     dht_replication_level = 3;
8408   }
8409
8410   tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
8411   incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
8412   peers = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
8413   applications = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
8414   types = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
8415
8416   dht_handle = GNUNET_DHT_connect (c, 64);
8417   if (NULL == dht_handle)
8418   {
8419     GNUNET_break (0);
8420   }
8421   stats = GNUNET_STATISTICS_create ("mesh", c);
8422
8423   GNUNET_SERVER_suspend (server_handle);
8424   /* Scheduled the task to clean up when shutdown is called */
8425   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
8426                                 NULL);
8427   keygen = GNUNET_CRYPTO_rsa_key_create_start (keyfile,
8428                                                &key_generation_cb,
8429                                                (void *) c);
8430   GNUNET_free (keyfile);
8431 }
8432
8433
8434 /**
8435  * The main function for the mesh service.
8436  *
8437  * @param argc number of arguments from the command line
8438  * @param argv command line arguments
8439  * @return 0 ok, 1 on error
8440  */
8441 int
8442 main (int argc, char *const *argv)
8443 {
8444   int ret;
8445   int r;
8446
8447   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
8448   r = GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
8449                           NULL);
8450   ret = (GNUNET_OK == r) ? 0 : 1;
8451   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");
8452
8453   INTERVAL_SHOW;
8454
8455   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
8456               "Mesh for peer [%s] FWD ACKs %u, BCK ACKs %u\n",
8457               GNUNET_i2s(&my_full_id), debug_fwd_ack, debug_bck_ack);
8458
8459   return ret;
8460 }