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