- fix bck ACK value
[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 = t->bck_queue_max - t->bck_queue_n + cinfo->bck_pid;
4009   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4010               "    Sending BCK ACK %u\n",
4011               cinfo->bck_ack);
4012   send_ack (t, &peer, cinfo->bck_ack);
4013 }
4014
4015
4016 /**
4017  * @brief Send BCK ACKs to clients to allow them more to_origin traffic
4018  * 
4019  * Iterates over all clients and sends BCK ACKs to the ones that need it.
4020  *
4021  * FIXME fc: what happens if we have 2 clients but q_size is 1?
4022  *           - implement a size 1 buffer in each client_fc AND children_fc
4023  *           to hold at least 1 message per "child".
4024  *             problem: violates no buffer policy
4025  *           - ack 0 and make "children" poll for transmission slots
4026  *             problem: big overhead, extra latency even in low traffic
4027  *                      settings
4028  * 
4029  * @param t Tunnel on which to send the BCK ACKs.
4030  */
4031 static void
4032 tunnel_send_clients_bck_ack (struct MeshTunnel *t)
4033 {
4034   unsigned int i;
4035   unsigned int tunnel_delta;
4036
4037   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Sending BCK ACK to clients\n");
4038
4039   tunnel_delta = t->bck_queue_max - t->bck_queue_n;
4040   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   tunnel delta: %u\n", tunnel_delta);
4041
4042   /* Find client whom to allow to send to origin (with lowest buffer space) */
4043   for (i = 0; i < t->nclients; i++)
4044   {
4045     struct MeshTunnelClientInfo *clinfo;
4046     unsigned int delta;
4047
4048     clinfo = &t->clients_fc[i];
4049     delta = clinfo->bck_ack - clinfo->bck_pid;
4050     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    client %u delta: %u\n",
4051          t->clients[i]->id, delta);
4052
4053     if ((GNUNET_NO == t->nobuffer && tunnel_delta > delta) ||
4054         (GNUNET_YES == t->nobuffer && 0 == delta))
4055     {
4056       uint32_t ack;
4057
4058       ack = clinfo->bck_pid;
4059       ack += t->nobuffer ? 1 : tunnel_delta;
4060       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4061                   "    sending ack to client %u: %u\n",
4062                   t->clients[i]->id, ack);
4063       send_local_ack (t, t->clients[i], ack);
4064       clinfo->bck_ack = ack;
4065     }
4066     else
4067     {
4068       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4069                   "    not sending ack to client %u (td %u, d %u)\n",
4070                   t->clients[i]->id, tunnel_delta, delta);
4071     }
4072   }
4073 }
4074
4075
4076 /**
4077  * Send an ACK informing the children nodes and destination clients about
4078  * the available buffer space.
4079  * If buffering is off, send only on behalf of root (can be self).
4080  * If buffering is on, send when sent to predecessor and buffer space is free.
4081  * Note that although the name is bck_ack, the BCK mean backwards *traffic*,
4082  * the ACK itself goes "forward" (towards children/clients).
4083  * 
4084  * @param t Tunnel on which to send the ACK.
4085  * @param type Type of message that triggered the ACK transmission.
4086  */
4087 static void
4088 tunnel_send_bck_ack (struct MeshTunnel *t, uint16_t type)
4089 {
4090   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4091               "Sending BCK ACK on tunnel %u [%u] due to %s\n",
4092               t->id.oid, t->id.tid, GNUNET_MESH_DEBUG_M2S(type));
4093   /* Is it after data to_origin retransmission? */
4094   switch (type)
4095   {
4096     case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4097       if (GNUNET_YES == t->nobuffer)
4098       {
4099         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4100                     "    Not sending ACK, nobuffer\n");
4101         return;
4102       }
4103       break;
4104     case GNUNET_MESSAGE_TYPE_MESH_ACK:
4105     case GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK:
4106     case GNUNET_MESSAGE_TYPE_MESH_POLL:
4107       break;
4108     default:
4109       GNUNET_break (0);
4110   }
4111
4112   tunnel_send_clients_bck_ack (t);
4113   tree_iterate_children (t->tree, &tunnel_send_child_bck_ack, t);
4114 }
4115
4116
4117 /**
4118  * @brief Re-initiate traffic to this peer if necessary.
4119  *
4120  * Check if there is traffic queued towards this peer
4121  * and the core transmit handle is NULL (traffic was stalled).
4122  * If so, call core tmt rdy.
4123  *
4124  * @param cls Closure (unused)
4125  * @param peer_id Short ID of peer to which initiate traffic.
4126  */
4127 static void
4128 peer_unlock_queue(void *cls, GNUNET_PEER_Id peer_id)
4129 {
4130   struct MeshPeerInfo *peer;
4131   struct GNUNET_PeerIdentity id;
4132   struct MeshPeerQueue *q;
4133   size_t size;
4134
4135   peer = peer_info_get_short(peer_id);
4136   if (NULL != peer->core_transmit)
4137     return;
4138
4139   q = queue_get_next(peer);
4140   if (NULL == q)
4141   {
4142     /* Might br multicast traffic already sent to this particular peer but
4143      * not to other children in this tunnel.
4144      * This way t->queue_n would be > 0 but the queue of this particular peer
4145      * would be empty.
4146      */
4147     return;
4148   }
4149   size = q->size;
4150   GNUNET_PEER_resolve (peer->id, &id);
4151   peer->core_transmit =
4152         GNUNET_CORE_notify_transmit_ready(core_handle,
4153                                           0,
4154                                           0,
4155                                           GNUNET_TIME_UNIT_FOREVER_REL,
4156                                           &id,
4157                                           size,
4158                                           &queue_send,
4159                                           peer);
4160         return;
4161 }
4162
4163
4164 /**
4165  * @brief Allow transmission of FWD traffic on this tunnel
4166  *
4167  * Check if there is traffic queued towards any children
4168  * and the core transmit handle is NULL, and if so, call core tmt rdy.
4169  *
4170  * @param t Tunnel on which to unlock FWD traffic.
4171  */
4172 static void
4173 tunnel_unlock_fwd_queues (struct MeshTunnel *t)
4174 {
4175   if (0 == t->fwd_queue_n)
4176     return;
4177
4178   tree_iterate_children (t->tree, &peer_unlock_queue, NULL);
4179 }
4180
4181
4182 /**
4183  * @brief Allow transmission of BCK traffic on this tunnel
4184  *
4185  * Check if there is traffic queued towards the root of the tree
4186  * and the core transmit handle is NULL, and if so, call core tmt rdy.
4187  *
4188  * @param t Tunnel on which to unlock BCK traffic.
4189  */
4190 static void
4191 tunnel_unlock_bck_queue (struct MeshTunnel *t)
4192 {
4193   if (0 == t->bck_queue_n)
4194     return;
4195
4196   peer_unlock_queue(NULL, tree_get_predecessor(t->tree));
4197 }
4198
4199
4200 /**
4201  * Send a message to all peers in this tunnel that the tunnel is no longer
4202  * valid.
4203  *
4204  * @param t The tunnel whose peers to notify.
4205  */
4206 static void
4207 tunnel_send_destroy (struct MeshTunnel *t)
4208 {
4209   struct GNUNET_MESH_TunnelDestroy msg;
4210
4211   msg.header.size = htons (sizeof (msg));
4212   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY);
4213   GNUNET_PEER_resolve (t->id.oid, &msg.oid);
4214   msg.tid = htonl (t->id.tid);
4215   tunnel_send_multicast (t, &msg.header);
4216 }
4217
4218
4219 /**
4220  * Cancel all transmissions towards a neighbor that belong to a certain tunnel.
4221  *
4222  * @param cls Closure (Tunnel which to cancel).
4223  * @param neighbor_id Short ID of the neighbor to whom cancel the transmissions.
4224  */
4225 static void
4226 tunnel_cancel_queues (void *cls, GNUNET_PEER_Id neighbor_id)
4227 {
4228   struct MeshTunnel *t = cls;
4229   struct MeshPeerInfo *peer_info;
4230   struct MeshPeerQueue *pq;
4231   struct MeshPeerQueue *next;
4232
4233   peer_info = peer_info_get_short (neighbor_id);
4234   for (pq = peer_info->queue_head; NULL != pq; pq = next)
4235   {
4236     next = pq->next;
4237     if (pq->tunnel == t)
4238     {
4239       if (GNUNET_MESSAGE_TYPE_MESH_MULTICAST == pq->type ||
4240           GNUNET_MESSAGE_TYPE_MESH_UNICAST == pq->type ||
4241           GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == pq->type)
4242       {
4243         // Should have been removed on destroy children
4244         GNUNET_break (0);
4245       }
4246       queue_destroy (pq, GNUNET_YES);
4247     }
4248   }
4249   if (NULL == peer_info->queue_head && NULL != peer_info->core_transmit)
4250   {
4251     GNUNET_CORE_notify_transmit_ready_cancel(peer_info->core_transmit);
4252     peer_info->core_transmit = NULL;
4253   }
4254 }
4255
4256 /**
4257  * Destroy the tunnel and free any allocated resources linked to it.
4258  *
4259  * @param t the tunnel to destroy
4260  *
4261  * @return GNUNET_OK on success
4262  */
4263 static int
4264 tunnel_destroy (struct MeshTunnel *t)
4265 {
4266   struct MeshClient *c;
4267   struct GNUNET_HashCode hash;
4268   unsigned int i;
4269   int r;
4270
4271   if (NULL == t)
4272     return GNUNET_OK;
4273
4274   r = GNUNET_OK;
4275   c = t->owner;
4276 #if MESH_DEBUG
4277   {
4278     struct GNUNET_PeerIdentity id;
4279
4280     GNUNET_PEER_resolve (t->id.oid, &id);
4281     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s [%x]\n",
4282                 GNUNET_i2s (&id), t->id.tid);
4283     if (NULL != c)
4284       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
4285   }
4286 #endif
4287
4288   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
4289   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &hash, t))
4290   {
4291     GNUNET_break (0);
4292     r = GNUNET_SYSERR;
4293   }
4294
4295   if (NULL != c)
4296   {
4297     GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
4298     if (GNUNET_YES !=
4299         GNUNET_CONTAINER_multihashmap_remove (c->own_tunnels, &hash, t))
4300     {
4301       GNUNET_break (0);
4302       r = GNUNET_SYSERR;
4303     }
4304   }
4305
4306   GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
4307   for (i = 0; i < t->nclients; i++)
4308   {
4309     c = t->clients[i];
4310     if (GNUNET_YES !=
4311           GNUNET_CONTAINER_multihashmap_remove (c->incoming_tunnels, &hash, t))
4312     {
4313       GNUNET_break (0);
4314       r = GNUNET_SYSERR;
4315     }
4316   }
4317   for (i = 0; i < t->nignore; i++)
4318   {
4319     c = t->ignore[i];
4320     if (GNUNET_YES !=
4321           GNUNET_CONTAINER_multihashmap_remove (c->ignore_tunnels, &hash, t))
4322     {
4323       GNUNET_break (0);
4324       r = GNUNET_SYSERR;
4325     }
4326   }
4327
4328   if (t->nclients > 0)
4329   {
4330     if (GNUNET_YES !=
4331         GNUNET_CONTAINER_multihashmap_remove (incoming_tunnels, &hash, t))
4332     {
4333       GNUNET_break (0);
4334       r = GNUNET_SYSERR;
4335     }
4336     GNUNET_free (t->clients);
4337     GNUNET_free (t->clients_fc);
4338   }
4339
4340   if (NULL != t->peers)
4341   {
4342     GNUNET_CONTAINER_multihashmap_iterate (t->peers, &peer_info_delete_tunnel,
4343                                            t);
4344     GNUNET_CONTAINER_multihashmap_destroy (t->peers);
4345   }
4346
4347   GNUNET_CONTAINER_multihashmap_iterate (t->children_fc,
4348                                          &tunnel_destroy_child,
4349                                          t);
4350   GNUNET_CONTAINER_multihashmap_destroy (t->children_fc);
4351   t->children_fc = NULL;
4352
4353   tree_iterate_children (t->tree, &tunnel_cancel_queues, t);
4354   tree_destroy (t->tree);
4355
4356   if (NULL != t->regex_ctx)
4357     regex_cancel_search (t->regex_ctx);
4358   if (NULL != t->dht_get_type)
4359     GNUNET_DHT_get_stop (t->dht_get_type);
4360   if (GNUNET_SCHEDULER_NO_TASK != t->timeout_task)
4361     GNUNET_SCHEDULER_cancel (t->timeout_task);
4362   if (GNUNET_SCHEDULER_NO_TASK != t->path_refresh_task)
4363     GNUNET_SCHEDULER_cancel (t->path_refresh_task);
4364
4365   n_tunnels--;
4366   GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
4367   GNUNET_free (t);
4368   return r;
4369 }
4370
4371
4372 /**
4373  * Create a new tunnel
4374  * 
4375  * @param owner Who is the owner of the tunnel (short ID).
4376  * @param tid Tunnel Number of the tunnel.
4377  * @param client Clients that owns the tunnel, NULL for foreign tunnels.
4378  * @param local Tunnel Number for the tunnel, for the client point of view.
4379  * 
4380  * @return A new initialized tunnel. NULL on error.
4381  */
4382 static struct MeshTunnel *
4383 tunnel_new (GNUNET_PEER_Id owner,
4384             MESH_TunnelNumber tid,
4385             struct MeshClient *client,
4386             MESH_TunnelNumber local)
4387 {
4388   struct MeshTunnel *t;
4389   struct GNUNET_HashCode hash;
4390
4391   if (n_tunnels >= max_tunnels && NULL == client)
4392     return NULL;
4393
4394   t = GNUNET_malloc (sizeof (struct MeshTunnel));
4395   t->id.oid = owner;
4396   t->id.tid = tid;
4397   t->fwd_queue_max = (max_msgs_queue / max_tunnels) + 1;
4398   t->bck_queue_max = t->fwd_queue_max;
4399   t->tree = tree_new (owner);
4400   t->owner = client;
4401   t->fwd_pid = (uint32_t) -1; // Next (expected) = 0
4402   t->bck_pid = (uint32_t) -1; // Next (expected) = 0
4403   t->bck_ack = INITIAL_WINDOW_SIZE - 1;
4404   t->last_fwd_ack = INITIAL_WINDOW_SIZE - 1;
4405   t->local_tid = local;
4406   t->children_fc = GNUNET_CONTAINER_multihashmap_create (8, GNUNET_NO);
4407   n_tunnels++;
4408   GNUNET_STATISTICS_update (stats, "# tunnels", 1, GNUNET_NO);
4409
4410   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
4411   if (GNUNET_OK !=
4412       GNUNET_CONTAINER_multihashmap_put (tunnels, &hash, t,
4413                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
4414   {
4415     GNUNET_break (0);
4416     tunnel_destroy (t);
4417     if (NULL != client)
4418     {
4419       GNUNET_break (0);
4420       GNUNET_SERVER_receive_done (client->handle, GNUNET_SYSERR);
4421     }
4422     return NULL;
4423   }
4424
4425   if (NULL != client)
4426   {
4427     GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
4428     if (GNUNET_OK !=
4429         GNUNET_CONTAINER_multihashmap_put (client->own_tunnels, &hash, t,
4430                                           GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
4431     {
4432       tunnel_destroy (t);
4433       GNUNET_break (0);
4434       GNUNET_SERVER_receive_done (client->handle, GNUNET_SYSERR);
4435       return NULL;
4436     }
4437   }
4438
4439   return t;
4440 }
4441
4442
4443 /**
4444  * Removes an explicit path from a tunnel, freeing all intermediate nodes
4445  * that are no longer needed, as well as nodes of no longer reachable peers.
4446  * The tunnel itself is also destoyed if results in a remote empty tunnel.
4447  *
4448  * @param t Tunnel from which to remove the path.
4449  * @param peer Short id of the peer which should be removed.
4450  */
4451 static void
4452 tunnel_delete_peer (struct MeshTunnel *t, GNUNET_PEER_Id peer)
4453 {
4454   if (GNUNET_NO == tree_del_peer (t->tree, peer, NULL, NULL))
4455     tunnel_destroy (t);
4456 }
4457
4458
4459 /**
4460  * tunnel_destroy_iterator: iterator for deleting each tunnel that belongs to a
4461  * client when the client disconnects. If the client is not the owner, the
4462  * owner will get notified if no more clients are in the tunnel and the client
4463  * get removed from the tunnel's list.
4464  *
4465  * @param cls closure (client that is disconnecting)
4466  * @param key the hash of the local tunnel id (used to access the hashmap)
4467  * @param value the value stored at the key (tunnel to destroy)
4468  *
4469  * @return GNUNET_OK, keep iterating.
4470  */
4471 static int
4472 tunnel_destroy_iterator (void *cls, const struct GNUNET_HashCode * key, void *value)
4473 {
4474   struct MeshTunnel *t = value;
4475   struct MeshClient *c = cls;
4476
4477   send_client_tunnel_disconnect(t, c);
4478   if (c != t->owner)
4479   {
4480     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4481                 "Client %u is destination, keeping the tunnel alive.\n", c->id);
4482     tunnel_delete_client(t, c);
4483     client_delete_tunnel(c, t);
4484     return GNUNET_OK;
4485   }
4486   tunnel_send_destroy(t);
4487   t->owner = NULL;
4488   t->destroy = GNUNET_YES;
4489
4490   return GNUNET_OK;
4491 }
4492
4493
4494 /**
4495  * Timeout function, destroys tunnel if called
4496  *
4497  * @param cls Closure (tunnel to destroy).
4498  * @param tc TaskContext
4499  */
4500 static void
4501 tunnel_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4502 {
4503   struct MeshTunnel *t = cls;
4504   struct GNUNET_PeerIdentity id;
4505
4506   t->timeout_task = GNUNET_SCHEDULER_NO_TASK;
4507   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4508     return;
4509   GNUNET_PEER_resolve(t->id.oid, &id);
4510   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4511               "Tunnel %s [%X] timed out. Destroying.\n",
4512               GNUNET_i2s(&id), t->id.tid);
4513   send_clients_tunnel_destroy (t);
4514   tunnel_destroy (t);
4515 }
4516
4517 /**
4518  * Resets the tunnel timeout. Starts it if no timeout was running.
4519  *
4520  * @param t Tunnel whose timeout to reset.
4521  *
4522  * TODO use heap to improve efficiency of scheduler.
4523  */
4524 static void
4525 tunnel_reset_timeout (struct MeshTunnel *t)
4526 {
4527   if (GNUNET_SCHEDULER_NO_TASK != t->timeout_task)
4528     GNUNET_SCHEDULER_cancel (t->timeout_task);
4529   t->timeout_task =
4530       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
4531                                     (refresh_path_time, 4), &tunnel_timeout, t);
4532 }
4533
4534
4535 /******************************************************************************/
4536 /****************      MESH NETWORK HANDLER HELPERS     ***********************/
4537 /******************************************************************************/
4538
4539 /**
4540  * Function to send a create path packet to a peer.
4541  *
4542  * @param cls closure
4543  * @param size number of bytes available in buf
4544  * @param buf where the callee should write the message
4545  * @return number of bytes written to buf
4546  */
4547 static size_t
4548 send_core_path_create (void *cls, size_t size, void *buf)
4549 {
4550   struct MeshPathInfo *info = cls;
4551   struct GNUNET_MESH_ManipulatePath *msg;
4552   struct GNUNET_PeerIdentity *peer_ptr;
4553   struct MeshTunnel *t = info->t;
4554   struct MeshPeerPath *p = info->path;
4555   size_t size_needed;
4556   uint32_t opt;
4557   int i;
4558
4559   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATE PATH sending...\n");
4560   size_needed =
4561       sizeof (struct GNUNET_MESH_ManipulatePath) +
4562       p->length * sizeof (struct GNUNET_PeerIdentity);
4563
4564   if (size < size_needed || NULL == buf)
4565   {
4566     GNUNET_break (0);
4567     return 0;
4568   }
4569   msg = (struct GNUNET_MESH_ManipulatePath *) buf;
4570   msg->header.size = htons (size_needed);
4571   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE);
4572   msg->tid = ntohl (t->id.tid);
4573
4574   opt = 0;
4575   if (GNUNET_YES == t->speed_min)
4576     opt |= MESH_TUNNEL_OPT_SPEED_MIN;
4577   if (GNUNET_YES == t->nobuffer)
4578     opt |= MESH_TUNNEL_OPT_NOBUFFER;
4579   msg->opt = htonl(opt);
4580   msg->reserved = 0;
4581
4582   peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
4583   for (i = 0; i < p->length; i++)
4584   {
4585     GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
4586   }
4587
4588   path_destroy (p);
4589   GNUNET_free (info);
4590
4591   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4592               "CREATE PATH (%u bytes long) sent!\n", size_needed);
4593   return size_needed;
4594 }
4595
4596
4597 /**
4598  * Fill the core buffer 
4599  *
4600  * @param cls closure (data itself)
4601  * @param size number of bytes available in buf
4602  * @param buf where the callee should write the message
4603  *
4604  * @return number of bytes written to buf
4605  */
4606 static size_t
4607 send_core_data_multicast (void *cls, size_t size, void *buf)
4608 {
4609   struct MeshTransmissionDescriptor *info = cls;
4610   size_t total_size;
4611
4612   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Multicast callback.\n");
4613   GNUNET_assert (NULL != info);
4614   GNUNET_assert (NULL != info->peer);
4615   total_size = info->mesh_data->data_len;
4616   GNUNET_assert (total_size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
4617
4618   if (total_size > size)
4619   {
4620     GNUNET_break (0);
4621     return 0;
4622   }
4623   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " copying data...\n");
4624   memcpy (buf, info->mesh_data->data, total_size);
4625 #if MESH_DEBUG
4626   {
4627     struct GNUNET_MESH_Multicast *mc;
4628     struct GNUNET_MessageHeader *mh;
4629
4630     mh = buf;
4631     if (ntohs (mh->type) == GNUNET_MESSAGE_TYPE_MESH_MULTICAST)
4632     {
4633       mc = (struct GNUNET_MESH_Multicast *) mh;
4634       mh = (struct GNUNET_MessageHeader *) &mc[1];
4635       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4636                   " multicast, payload type %s\n",
4637                   GNUNET_MESH_DEBUG_M2S (ntohs (mh->type)));
4638       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4639                   " multicast, payload size %u\n", ntohs (mh->size));
4640     }
4641     else
4642     {
4643       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " type %s\n",
4644                   GNUNET_MESH_DEBUG_M2S (ntohs (mh->type)));
4645     }
4646   }
4647 #endif
4648   data_descriptor_decrement_rc (info->mesh_data);
4649   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "freeing info...\n");
4650   GNUNET_free (info);
4651   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "return %u\n", total_size);
4652   return total_size;
4653 }
4654
4655
4656 /**
4657  * Creates a path ack message in buf and frees all unused resources.
4658  *
4659  * @param cls closure (MeshTransmissionDescriptor)
4660  * @param size number of bytes available in buf
4661  * @param buf where the callee should write the message
4662  * @return number of bytes written to buf
4663  */
4664 static size_t
4665 send_core_path_ack (void *cls, size_t size, void *buf)
4666 {
4667   struct MeshTransmissionDescriptor *info = cls;
4668   struct GNUNET_MESH_PathACK *msg = buf;
4669
4670   GNUNET_assert (NULL != info);
4671   if (sizeof (struct GNUNET_MESH_PathACK) > size)
4672   {
4673     GNUNET_break (0);
4674     return 0;
4675   }
4676   msg->header.size = htons (sizeof (struct GNUNET_MESH_PathACK));
4677   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_ACK);
4678   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
4679   msg->tid = htonl (info->origin->tid);
4680   msg->peer_id = my_full_id;
4681
4682   GNUNET_free (info);
4683   /* TODO add signature */
4684
4685   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "PATH ACK sent!\n");
4686   return sizeof (struct GNUNET_MESH_PathACK);
4687 }
4688
4689
4690 /**
4691  * Free a transmission that was already queued with all resources
4692  * associated to the request.
4693  *
4694  * @param queue Queue handler to cancel.
4695  * @param clear_cls Is it necessary to free associated cls?
4696  */
4697 static void
4698 queue_destroy (struct MeshPeerQueue *queue, int clear_cls)
4699 {
4700   struct MeshTransmissionDescriptor *dd;
4701   struct MeshPathInfo *path_info;
4702   struct MeshTunnelChildInfo *cinfo;
4703   struct GNUNET_PeerIdentity id;
4704   unsigned int i;
4705   unsigned int max;
4706
4707   if (GNUNET_YES == clear_cls)
4708   {
4709     switch (queue->type)
4710     {
4711       case GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY:
4712         GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "   cancelling TUNNEL_DESTROY\n");
4713         /* fall through */
4714       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4715       case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
4716       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4717       case GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE:
4718         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4719                     "   prebuilt message\n");
4720         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4721                     "   type %s\n",
4722                     GNUNET_MESH_DEBUG_M2S(queue->type));
4723         dd = queue->cls;
4724         data_descriptor_decrement_rc (dd->mesh_data);
4725         break;
4726       case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
4727         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   type create path\n");
4728         path_info = queue->cls;
4729         path_destroy (path_info->path);
4730         break;
4731       default:
4732         GNUNET_break (0);
4733         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4734                     "   type %s unknown!\n",
4735                     GNUNET_MESH_DEBUG_M2S(queue->type));
4736     }
4737     GNUNET_free_non_null (queue->cls);
4738   }
4739   GNUNET_CONTAINER_DLL_remove (queue->peer->queue_head,
4740                                queue->peer->queue_tail,
4741                                queue);
4742
4743   /* Delete from child_fc in the appropiate tunnel */
4744   max = queue->tunnel->fwd_queue_max;
4745   GNUNET_PEER_resolve (queue->peer->id, &id);
4746   cinfo = tunnel_get_neighbor_fc (queue->tunnel, &id);
4747   if (NULL != cinfo)
4748   {
4749     for (i = 0; i < cinfo->send_buffer_n; i++)
4750     {
4751       unsigned int i2;
4752       i2 = (cinfo->send_buffer_start + i) % max;
4753       if (cinfo->send_buffer[i2] == queue)
4754       {
4755         /* Found corresponding entry in the send_buffer. Move all others back. */
4756         unsigned int j;
4757         unsigned int j2;
4758         unsigned int j3;
4759
4760         for (j = i, j2 = 0, j3 = 0; j < cinfo->send_buffer_n - 1; j++)
4761         {
4762           j2 = (cinfo->send_buffer_start + j) % max;
4763           j3 = (cinfo->send_buffer_start + j + 1) % max;
4764           cinfo->send_buffer[j2] = cinfo->send_buffer[j3];
4765         }
4766
4767         cinfo->send_buffer[j3] = NULL;
4768         cinfo->send_buffer_n--;
4769       }
4770     }
4771   }
4772
4773   GNUNET_free (queue);
4774 }
4775
4776
4777 /**
4778  * @brief Get the next transmittable message from the queue.
4779  *
4780  * This will be the head, except in the case of being a data packet
4781  * not allowed by the destination peer.
4782  *
4783  * @param peer Destination peer.
4784  *
4785  * @return The next viable MeshPeerQueue element to send to that peer.
4786  *         NULL when there are no transmittable messages.
4787  */
4788 struct MeshPeerQueue *
4789 queue_get_next (const struct MeshPeerInfo *peer)
4790 {
4791   struct MeshPeerQueue *q;
4792   struct MeshTunnel *t;
4793   struct MeshTransmissionDescriptor *info;
4794   struct MeshTunnelChildInfo *cinfo;
4795   struct GNUNET_MESH_Unicast *ucast;
4796   struct GNUNET_MESH_ToOrigin *to_orig;
4797   struct GNUNET_MESH_Multicast *mcast;
4798   struct GNUNET_PeerIdentity id;
4799   uint32_t pid;
4800   uint32_t ack;
4801
4802   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   selecting message\n");
4803   for (q = peer->queue_head; NULL != q; q = q->next)
4804   {
4805     t = q->tunnel;
4806     info = q->cls;
4807     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4808                 "*********     %s\n",
4809                 GNUNET_MESH_DEBUG_M2S(q->type));
4810     switch (q->type)
4811     {
4812       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4813         ucast = (struct GNUNET_MESH_Unicast *) info->mesh_data->data;
4814         pid = ntohl (ucast->pid);
4815         GNUNET_PEER_resolve (info->peer->id, &id);
4816         cinfo = tunnel_get_neighbor_fc(t, &id);
4817         ack = cinfo->fwd_ack;
4818         break;
4819       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4820         to_orig = (struct GNUNET_MESH_ToOrigin *) info->mesh_data->data;
4821         pid = ntohl (to_orig->pid);
4822         ack = t->bck_ack;
4823         break;
4824       case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
4825         mcast = (struct GNUNET_MESH_Multicast *) info->mesh_data->data;
4826         if (GNUNET_MESSAGE_TYPE_MESH_MULTICAST != ntohs(mcast->header.type)) 
4827         {
4828           // Not a multicast payload: multicast control traffic (destroy, etc)
4829           return q;
4830         }
4831         pid = ntohl (mcast->pid);
4832         GNUNET_PEER_resolve (info->peer->id, &id);
4833         cinfo = tunnel_get_neighbor_fc(t, &id);
4834         ack = cinfo->fwd_ack;
4835         break;
4836       default:
4837         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4838                     "*********   OK!\n");
4839         return q;
4840     }
4841         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4842                     "*********     ACK: %u, PID: %u\n",
4843                     ack, pid);
4844     if (GNUNET_NO == GMC_is_pid_bigger(pid, ack))
4845     {
4846       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4847                   "*********   OK!\n");
4848       return q;
4849     }
4850     else
4851     {
4852       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4853                   "*********     NEXT!\n");
4854     }
4855   }
4856   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4857                 "*********   nothing found\n");
4858   return NULL;
4859 }
4860
4861
4862 /**
4863   * Core callback to write a queued packet to core buffer
4864   *
4865   * @param cls Closure (peer info).
4866   * @param size Number of bytes available in buf.
4867   * @param buf Where the to write the message.
4868   *
4869   * @return number of bytes written to buf
4870   */
4871 static size_t
4872 queue_send (void *cls, size_t size, void *buf)
4873 {
4874     struct MeshPeerInfo *peer = cls;
4875     struct GNUNET_MessageHeader *msg;
4876     struct MeshPeerQueue *queue;
4877     struct MeshTunnel *t;
4878     struct MeshTunnelChildInfo *cinfo;
4879     struct GNUNET_PeerIdentity dst_id;
4880     size_t data_size;
4881
4882     peer->core_transmit = NULL;
4883     cinfo = NULL;
4884
4885     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "********* Queue send\n");
4886     queue = queue_get_next (peer);
4887
4888     /* Queue has no internal mesh traffic nor sendable payload */
4889     if (NULL == queue)
4890     {
4891       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   not ready, return\n");
4892       if (NULL == peer->queue_head)
4893         GNUNET_break (0); // Should've been canceled
4894       return 0;
4895     }
4896     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   not empty\n");
4897
4898     GNUNET_PEER_resolve (peer->id, &dst_id);
4899     /* Check if buffer size is enough for the message */
4900     if (queue->size > size)
4901     {
4902         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4903                     "*********   not enough room, reissue\n");
4904         peer->core_transmit =
4905             GNUNET_CORE_notify_transmit_ready (core_handle,
4906                                                0,
4907                                                0,
4908                                                GNUNET_TIME_UNIT_FOREVER_REL,
4909                                                &dst_id,
4910                                                queue->size,
4911                                                &queue_send,
4912                                                peer);
4913         return 0;
4914     }
4915     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   size ok\n");
4916
4917     t = queue->tunnel;
4918     if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == queue->type)
4919     {
4920       t->fwd_queue_n--;
4921       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4922                   "*********   unicast: t->q (%u/%u)\n",
4923                   t->fwd_queue_n, t->fwd_queue_max);
4924     }
4925     else if (GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == queue->type)
4926     {
4927       t->bck_queue_n--;
4928       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   to origin\n");
4929     }
4930
4931     /* Fill buf */
4932     switch (queue->type)
4933     {
4934       case 0:
4935       case GNUNET_MESSAGE_TYPE_MESH_ACK:
4936       case GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN:
4937       case GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY:
4938       case GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY:
4939         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4940                     "*********   raw: %s\n",
4941                     GNUNET_MESH_DEBUG_M2S (queue->type));
4942         /* Fall through */
4943       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4944       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4945         data_size = send_core_data_raw (queue->cls, size, buf);
4946         msg = (struct GNUNET_MessageHeader *) buf;
4947         switch (ntohs (msg->type)) // Type of preconstructed message
4948         {
4949           case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4950             tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_UNICAST);
4951             break;
4952           case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4953             tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
4954             break;
4955           default:
4956               break;
4957         }
4958         break;
4959       case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
4960         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   multicast\n");
4961         {
4962           struct MeshTransmissionDescriptor *info = queue->cls;
4963
4964           if ((1 == info->mesh_data->reference_counter
4965               && GNUNET_YES == t->speed_min)
4966               ||
4967               (info->mesh_data->total_out == info->mesh_data->reference_counter
4968               && GNUNET_NO == t->speed_min))
4969           {
4970             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4971                         "*********   considered sent\n");
4972             t->fwd_queue_n--;
4973           }
4974         }
4975         data_size = send_core_data_multicast(queue->cls, size, buf);
4976         tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
4977         break;
4978       case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
4979         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path create\n");
4980         data_size = send_core_path_create (queue->cls, size, buf);
4981         break;
4982       case GNUNET_MESSAGE_TYPE_MESH_PATH_ACK:
4983         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path ack\n");
4984         data_size = send_core_path_ack (queue->cls, size, buf);
4985         break;
4986       case GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE:
4987         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path keepalive\n");
4988         data_size = send_core_data_multicast (queue->cls, size, buf);
4989         break;
4990       default:
4991         GNUNET_break (0);
4992         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4993                     "*********   type unknown: %u\n",
4994                     queue->type);
4995         data_size = 0;
4996     }
4997     switch (queue->type)
4998     {
4999       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
5000       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
5001       case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
5002         cinfo = tunnel_get_neighbor_fc (t, &dst_id);
5003         if (cinfo->send_buffer[cinfo->send_buffer_start] != queue)
5004         {
5005           GNUNET_break (0);
5006           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5007                       "at pos %u (%p) != %p\n",
5008                       cinfo->send_buffer_start,
5009                       cinfo->send_buffer[cinfo->send_buffer_start],
5010                       queue);
5011         }
5012         if (cinfo->send_buffer_n > 0)
5013         {
5014           cinfo->send_buffer[cinfo->send_buffer_start] = NULL;
5015           cinfo->send_buffer_n--;
5016           cinfo->send_buffer_start++;
5017           cinfo->send_buffer_start %= t->fwd_queue_max;
5018         }
5019         else
5020         {
5021           GNUNET_break (0);
5022         }
5023         break;
5024       default:
5025         break;
5026     }
5027
5028     /* Free queue, but cls was freed by send_core_* */
5029     queue_destroy (queue, GNUNET_NO);
5030
5031     if (GNUNET_YES == t->destroy)
5032     {
5033       // FIXME fc tunnel destroy all pending traffic? wait for it?
5034       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********  destroying tunnel!\n");
5035       tunnel_destroy (t);
5036     }
5037
5038     /* If more data in queue, send next */
5039     queue = queue_get_next(peer);
5040     if (NULL != queue)
5041     {
5042         struct GNUNET_PeerIdentity id;
5043
5044         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   more data!\n");
5045         GNUNET_PEER_resolve (peer->id, &id);
5046         peer->core_transmit =
5047             GNUNET_CORE_notify_transmit_ready(core_handle,
5048                                               0,
5049                                               0,
5050                                               GNUNET_TIME_UNIT_FOREVER_REL,
5051                                               &id,
5052                                               queue->size,
5053                                               &queue_send,
5054                                               peer);
5055     }
5056     else
5057     {
5058       if (NULL != peer->queue_head)
5059       {
5060         GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5061                     "*********   %s stalled\n",
5062                     GNUNET_i2s(&my_full_id));
5063         if (NULL == cinfo)
5064           cinfo = tunnel_get_neighbor_fc (t, &dst_id);
5065         cinfo->fc_poll = GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_SECONDS,
5066                                                      &tunnel_poll, cinfo);
5067       }
5068     }
5069     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   return %d\n", data_size);
5070     return data_size;
5071 }
5072
5073
5074 /**
5075  * @brief Queue and pass message to core when possible.
5076  * 
5077  * If type is payload (UNICAST, TO_ORIGIN, MULTICAST) checks for queue status
5078  * and accounts for it. In case the queue is full, the message is dropped and
5079  * a break issued.
5080  * 
5081  * Otherwise, message is treated as internal and allowed to go regardless of 
5082  * queue status.
5083  *
5084  * @param cls Closure (@c type dependant). It will be used by queue_send to
5085  *            build the message to be sent if not already prebuilt.
5086  * @param type Type of the message, 0 for a raw message.
5087  * @param size Size of the message.
5088  * @param dst Neighbor to send message to.
5089  * @param t Tunnel this message belongs to.
5090  */
5091 static void
5092 queue_add (void *cls, uint16_t type, size_t size,
5093            struct MeshPeerInfo *dst, struct MeshTunnel *t)
5094 {
5095   struct MeshPeerQueue *queue;
5096   struct MeshTunnelChildInfo *cinfo;
5097   struct GNUNET_PeerIdentity id;
5098   unsigned int *max;
5099   unsigned int *n;
5100   unsigned int i;
5101
5102   n = NULL;
5103   if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == type ||
5104       GNUNET_MESSAGE_TYPE_MESH_MULTICAST == type)
5105   {
5106     n = &t->fwd_queue_n;
5107     max = &t->fwd_queue_max;
5108   }
5109   else if (GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == type)
5110   {
5111     n = &t->bck_queue_n;
5112     max = &t->bck_queue_max;
5113   }
5114   if (NULL != n)
5115   {
5116     if (*n >= *max)
5117     {
5118       struct MeshTransmissionDescriptor *td = cls;
5119       struct GNUNET_MESH_ToOrigin *to;
5120
5121       to = td->mesh_data->data;
5122       GNUNET_break(0);
5123       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5124                   "bck pid %u, bck ack %u, msg pid %u\n",
5125                   t->bck_pid, t->bck_ack, ntohl(to->pid));
5126       GNUNET_STATISTICS_update(stats, "# messages dropped (buffer full)",
5127                                1, GNUNET_NO);
5128       return;                       // Drop message
5129     }
5130     (*n)++;
5131   }
5132   queue = GNUNET_malloc (sizeof (struct MeshPeerQueue));
5133   queue->cls = cls;
5134   queue->type = type;
5135   queue->size = size;
5136   queue->peer = dst;
5137   queue->tunnel = t;
5138   GNUNET_CONTAINER_DLL_insert_tail (dst->queue_head, dst->queue_tail, queue);
5139   GNUNET_PEER_resolve (dst->id, &id);
5140   if (NULL == dst->core_transmit)
5141   {
5142       dst->core_transmit =
5143           GNUNET_CORE_notify_transmit_ready (core_handle,
5144                                              0,
5145                                              0,
5146                                              GNUNET_TIME_UNIT_FOREVER_REL,
5147                                              &id,
5148                                              size,
5149                                              &queue_send,
5150                                              dst);
5151   }
5152   if (NULL == n) // Is this internal mesh traffic?
5153     return;
5154
5155   // It's payload, keep track of buffer per peer.
5156   cinfo = tunnel_get_neighbor_fc(t, &id);
5157   i = (cinfo->send_buffer_start + cinfo->send_buffer_n) % t->fwd_queue_max;
5158   if (NULL != cinfo->send_buffer[i])
5159   {
5160     GNUNET_break (cinfo->send_buffer_n == t->fwd_queue_max); // aka i == start
5161     queue_destroy (cinfo->send_buffer[cinfo->send_buffer_start], GNUNET_YES);
5162     cinfo->send_buffer_start++;
5163     cinfo->send_buffer_start %= t->fwd_queue_max;
5164   }
5165   else
5166   {
5167     cinfo->send_buffer_n++;
5168   }
5169   cinfo->send_buffer[i] = queue;
5170   if (cinfo->send_buffer_n > t->fwd_queue_max)
5171   {
5172     GNUNET_break (0);
5173     cinfo->send_buffer_n = t->fwd_queue_max;
5174   }
5175 }
5176
5177
5178 /******************************************************************************/
5179 /********************      MESH NETWORK HANDLERS     **************************/
5180 /******************************************************************************/
5181
5182
5183 /**
5184  * Core handler for path creation
5185  *
5186  * @param cls closure
5187  * @param message message
5188  * @param peer peer identity this notification is about
5189  * @param atsi performance data
5190  * @param atsi_count number of records in 'atsi'
5191  *
5192  * @return GNUNET_OK to keep the connection open,
5193  *         GNUNET_SYSERR to close it (signal serious error)
5194  */
5195 static int
5196 handle_mesh_path_create (void *cls, const struct GNUNET_PeerIdentity *peer,
5197                          const struct GNUNET_MessageHeader *message,
5198                          const struct GNUNET_ATS_Information *atsi,
5199                          unsigned int atsi_count)
5200 {
5201   unsigned int own_pos;
5202   uint16_t size;
5203   uint16_t i;
5204   MESH_TunnelNumber tid;
5205   struct GNUNET_MESH_ManipulatePath *msg;
5206   struct GNUNET_PeerIdentity *pi;
5207   struct GNUNET_HashCode hash;
5208   struct MeshPeerPath *path;
5209   struct MeshPeerInfo *dest_peer_info;
5210   struct MeshPeerInfo *orig_peer_info;
5211   struct MeshTunnel *t;
5212
5213   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5214               "Received a path create msg [%s]\n",
5215               GNUNET_i2s (&my_full_id));
5216   size = ntohs (message->size);
5217   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
5218   {
5219     GNUNET_break_op (0);
5220     return GNUNET_OK;
5221   }
5222
5223   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
5224   if (size % sizeof (struct GNUNET_PeerIdentity))
5225   {
5226     GNUNET_break_op (0);
5227     return GNUNET_OK;
5228   }
5229   size /= sizeof (struct GNUNET_PeerIdentity);
5230   if (size < 2)
5231   {
5232     GNUNET_break_op (0);
5233     return GNUNET_OK;
5234   }
5235   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
5236   msg = (struct GNUNET_MESH_ManipulatePath *) message;
5237
5238   tid = ntohl (msg->tid);
5239   pi = (struct GNUNET_PeerIdentity *) &msg[1];
5240   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5241               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi), tid);
5242   t = tunnel_get (pi, tid);
5243   if (NULL == t) // FIXME only for INCOMING tunnels?
5244   {
5245     uint32_t opt;
5246
5247     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating tunnel\n");
5248     t = tunnel_new (GNUNET_PEER_intern (pi), tid, NULL, 0);
5249     if (NULL == t)
5250     {
5251       // FIXME notify failure
5252       return GNUNET_OK;
5253     }
5254     opt = ntohl (msg->opt);
5255     t->speed_min = (0 != (opt & MESH_TUNNEL_OPT_SPEED_MIN)) ?
5256                    GNUNET_YES : GNUNET_NO;
5257     if (0 != (opt & MESH_TUNNEL_OPT_NOBUFFER))
5258     {
5259       t->nobuffer = GNUNET_YES;
5260       t->last_fwd_ack = t->fwd_pid + 1;
5261     }
5262     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5263                 "  speed_min: %d, nobuffer:%d\n",
5264                 t->speed_min, t->nobuffer);
5265
5266     if (GNUNET_YES == t->nobuffer)
5267     {
5268       t->bck_queue_max = 1;
5269       t->fwd_queue_max = 1;
5270     }
5271
5272     // FIXME only assign a local tid if a local client is interested (on demand)
5273     while (NULL != tunnel_get_incoming (next_local_tid))
5274       next_local_tid = (next_local_tid + 1) | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
5275     t->local_tid_dest = next_local_tid++;
5276     next_local_tid = next_local_tid | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
5277     // FIXME end
5278
5279     tunnel_reset_timeout (t);
5280     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
5281     if (GNUNET_OK !=
5282         GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
5283                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
5284     {
5285       tunnel_destroy (t);
5286       GNUNET_break (0);
5287       return GNUNET_OK;
5288     }
5289   }
5290   dest_peer_info =
5291       GNUNET_CONTAINER_multihashmap_get (peers, &pi[size - 1].hashPubKey);
5292   if (NULL == dest_peer_info)
5293   {
5294     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5295                 "  Creating PeerInfo for destination.\n");
5296     dest_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
5297     dest_peer_info->id = GNUNET_PEER_intern (&pi[size - 1]);
5298     GNUNET_CONTAINER_multihashmap_put (peers, &pi[size - 1].hashPubKey,
5299                                        dest_peer_info,
5300                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
5301   }
5302   orig_peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &pi->hashPubKey);
5303   if (NULL == orig_peer_info)
5304   {
5305     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5306                 "  Creating PeerInfo for origin.\n");
5307     orig_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
5308     orig_peer_info->id = GNUNET_PEER_intern (pi);
5309     GNUNET_CONTAINER_multihashmap_put (peers, &pi->hashPubKey, orig_peer_info,
5310                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
5311   }
5312   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
5313   path = path_new (size);
5314   own_pos = 0;
5315   for (i = 0; i < size; i++)
5316   {
5317     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
5318                 GNUNET_i2s (&pi[i]));
5319     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
5320     if (path->peers[i] == myid)
5321       own_pos = i;
5322   }
5323   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
5324   if (own_pos == 0)
5325   {
5326     /* cannot be self, must be 'not found' */
5327     /* create path: self not found in path through self */
5328     GNUNET_break_op (0);
5329     path_destroy (path);
5330     tunnel_destroy (t);
5331     return GNUNET_OK;
5332   }
5333   path_add_to_peers (path, GNUNET_NO);
5334   tunnel_add_path (t, path, own_pos);
5335   if (own_pos == size - 1)
5336   {
5337     /* It is for us! Send ack. */
5338     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
5339     peer_info_add_path_to_origin (orig_peer_info, path, GNUNET_NO);
5340     if (NULL == t->peers)
5341     {
5342       /* New tunnel! Notify clients on first payload message. */
5343       t->peers = GNUNET_CONTAINER_multihashmap_create (4, GNUNET_NO);
5344     }
5345     GNUNET_break (GNUNET_SYSERR !=
5346                   GNUNET_CONTAINER_multihashmap_put (t->peers,
5347                                                      &my_full_id.hashPubKey,
5348                                                      peer_info_get
5349                                                      (&my_full_id),
5350                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE));
5351     send_path_ack (t);
5352   }
5353   else
5354   {
5355     struct MeshPeerPath *path2;
5356
5357     /* It's for somebody else! Retransmit. */
5358     path2 = path_duplicate (path);
5359     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Retransmitting.\n");
5360     peer_info_add_path (dest_peer_info, path2, GNUNET_NO);
5361     path2 = path_duplicate (path);
5362     peer_info_add_path_to_origin (orig_peer_info, path2, GNUNET_NO);
5363     send_create_path (dest_peer_info, path, t);
5364   }
5365   return GNUNET_OK;
5366 }
5367
5368
5369 /**
5370  * Core handler for path destruction
5371  *
5372  * @param cls closure
5373  * @param message message
5374  * @param peer peer identity this notification is about
5375  * @param atsi performance data
5376  * @param atsi_count number of records in 'atsi'
5377  *
5378  * @return GNUNET_OK to keep the connection open,
5379  *         GNUNET_SYSERR to close it (signal serious error)
5380  */
5381 static int
5382 handle_mesh_path_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
5383                           const struct GNUNET_MessageHeader *message,
5384                           const struct GNUNET_ATS_Information *atsi,
5385                           unsigned int atsi_count)
5386 {
5387   struct GNUNET_MESH_ManipulatePath *msg;
5388   struct GNUNET_PeerIdentity *pi;
5389   struct MeshPeerPath *path;
5390   struct MeshTunnel *t;
5391   unsigned int own_pos;
5392   unsigned int i;
5393   size_t size;
5394
5395   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5396               "Received a PATH DESTROY msg from %s\n", GNUNET_i2s (peer));
5397   size = ntohs (message->size);
5398   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
5399   {
5400     GNUNET_break_op (0);
5401     return GNUNET_OK;
5402   }
5403
5404   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
5405   if (size % sizeof (struct GNUNET_PeerIdentity))
5406   {
5407     GNUNET_break_op (0);
5408     return GNUNET_OK;
5409   }
5410   size /= sizeof (struct GNUNET_PeerIdentity);
5411   if (size < 2)
5412   {
5413     GNUNET_break_op (0);
5414     return GNUNET_OK;
5415   }
5416   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
5417
5418   msg = (struct GNUNET_MESH_ManipulatePath *) message;
5419   pi = (struct GNUNET_PeerIdentity *) &msg[1];
5420   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5421               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi),
5422               msg->tid);
5423   t = tunnel_get (pi, ntohl (msg->tid));
5424   if (NULL == t)
5425   {
5426     /* TODO notify back: we don't know this tunnel */
5427     GNUNET_break_op (0);
5428     return GNUNET_OK;
5429   }
5430   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
5431   path = path_new (size);
5432   own_pos = 0;
5433   for (i = 0; i < size; i++)
5434   {
5435     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
5436                 GNUNET_i2s (&pi[i]));
5437     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
5438     if (path->peers[i] == myid)
5439       own_pos = i;
5440   }
5441   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
5442   if (own_pos < path->length - 1)
5443     send_prebuilt_message (message, &pi[own_pos + 1], t);
5444   else
5445     send_client_tunnel_disconnect(t, NULL);
5446
5447   tunnel_delete_peer (t, path->peers[path->length - 1]);
5448   path_destroy (path);
5449   return GNUNET_OK;
5450 }
5451
5452
5453 /**
5454  * Core handler for notifications of broken paths
5455  *
5456  * @param cls closure
5457  * @param message message
5458  * @param peer peer identity this notification is about
5459  * @param atsi performance data
5460  * @param atsi_count number of records in 'atsi'
5461  *
5462  * @return GNUNET_OK to keep the connection open,
5463  *         GNUNET_SYSERR to close it (signal serious error)
5464  */
5465 static int
5466 handle_mesh_path_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
5467                          const struct GNUNET_MessageHeader *message,
5468                          const struct GNUNET_ATS_Information *atsi,
5469                          unsigned int atsi_count)
5470 {
5471   struct GNUNET_MESH_PathBroken *msg;
5472   struct MeshTunnel *t;
5473
5474   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5475               "Received a PATH BROKEN msg from %s\n", GNUNET_i2s (peer));
5476   msg = (struct GNUNET_MESH_PathBroken *) message;
5477   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
5478               GNUNET_i2s (&msg->peer1));
5479   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
5480               GNUNET_i2s (&msg->peer2));
5481   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5482   if (NULL == t)
5483   {
5484     GNUNET_break_op (0);
5485     return GNUNET_OK;
5486   }
5487   tunnel_notify_connection_broken (t, GNUNET_PEER_search (&msg->peer1),
5488                                    GNUNET_PEER_search (&msg->peer2));
5489   return GNUNET_OK;
5490
5491 }
5492
5493
5494 /**
5495  * Core handler for tunnel destruction
5496  *
5497  * @param cls closure
5498  * @param message message
5499  * @param peer peer identity this notification is about
5500  * @param atsi performance data
5501  * @param atsi_count number of records in 'atsi'
5502  *
5503  * @return GNUNET_OK to keep the connection open,
5504  *         GNUNET_SYSERR to close it (signal serious error)
5505  */
5506 static int
5507 handle_mesh_tunnel_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
5508                             const struct GNUNET_MessageHeader *message,
5509                             const struct GNUNET_ATS_Information *atsi,
5510                             unsigned int atsi_count)
5511 {
5512   struct GNUNET_MESH_TunnelDestroy *msg;
5513   struct MeshTunnel *t;
5514
5515   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5516               "Got a TUNNEL DESTROY packet from %s\n", GNUNET_i2s (peer));
5517   msg = (struct GNUNET_MESH_TunnelDestroy *) message;
5518   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for tunnel %s [%u]\n",
5519               GNUNET_i2s (&msg->oid), ntohl (msg->tid));
5520   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5521   if (NULL == t)
5522   {
5523     /* Probably already got the message from another path,
5524      * destroyed the tunnel and retransmitted to children.
5525      * Safe to ignore.
5526      */
5527     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel", 1, GNUNET_NO);
5528     return GNUNET_OK;
5529   }
5530   if (t->id.oid == myid)
5531   {
5532     GNUNET_break_op (0);
5533     return GNUNET_OK;
5534   }
5535   if (t->local_tid_dest >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
5536   {
5537     /* Tunnel was incoming, notify clients */
5538     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "INCOMING TUNNEL %X %X\n",
5539                 t->local_tid, t->local_tid_dest);
5540     send_clients_tunnel_destroy (t);
5541   }
5542   tunnel_send_destroy (t);
5543   t->destroy = GNUNET_YES;
5544   // TODO: add timeout to destroy the tunnel anyway
5545   return GNUNET_OK;
5546 }
5547
5548
5549 /**
5550  * Core handler for mesh network traffic going from the origin to a peer
5551  *
5552  * @param cls closure
5553  * @param peer peer identity this notification is about
5554  * @param message message
5555  * @param atsi performance data
5556  * @param atsi_count number of records in 'atsi'
5557  * @return GNUNET_OK to keep the connection open,
5558  *         GNUNET_SYSERR to close it (signal serious error)
5559  */
5560 static int
5561 handle_mesh_data_unicast (void *cls, const struct GNUNET_PeerIdentity *peer,
5562                           const struct GNUNET_MessageHeader *message,
5563                           const struct GNUNET_ATS_Information *atsi,
5564                           unsigned int atsi_count)
5565 {
5566   struct GNUNET_MESH_Unicast *msg;
5567   struct GNUNET_PeerIdentity *neighbor;
5568   struct MeshTunnelChildInfo *cinfo;
5569   struct MeshTunnel *t;
5570   GNUNET_PEER_Id dest_id;
5571   uint32_t pid;
5572   uint32_t ttl;
5573   size_t size;
5574
5575   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a unicast packet from %s\n",
5576               GNUNET_i2s (peer));
5577   /* Check size */
5578   size = ntohs (message->size);
5579   if (size <
5580       sizeof (struct GNUNET_MESH_Unicast) +
5581       sizeof (struct GNUNET_MessageHeader))
5582   {
5583     GNUNET_break (0);
5584     return GNUNET_OK;
5585   }
5586   msg = (struct GNUNET_MESH_Unicast *) message;
5587   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %s\n",
5588               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
5589   /* Check tunnel */
5590   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5591   if (NULL == t)
5592   {
5593     /* TODO notify back: we don't know this tunnel */
5594     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
5595     GNUNET_break_op (0);
5596     return GNUNET_OK;
5597   }
5598   pid = ntohl (msg->pid);
5599   if (t->fwd_pid == pid)
5600   {
5601     GNUNET_STATISTICS_update (stats, "# duplicate PID drops", 1, GNUNET_NO);
5602     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5603                 " Already seen pid %u, DROPPING!\n", pid);
5604     return GNUNET_OK;
5605   }
5606   else
5607   {
5608     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5609                 " pid %u not seen yet, forwarding\n", pid);
5610   }
5611
5612   t->skip += (pid - t->fwd_pid) - 1;
5613   t->fwd_pid = pid;
5614
5615   if (GMC_is_pid_bigger (pid, t->last_fwd_ack))
5616   {
5617     GNUNET_STATISTICS_update (stats, "# unsolicited unicast", 1, GNUNET_NO);
5618     GNUNET_break_op (0);
5619     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5620                 "Received PID %u, ACK %u\n",
5621                 pid, t->last_fwd_ack);
5622     return GNUNET_OK;
5623   }
5624
5625   tunnel_reset_timeout (t);
5626   dest_id = GNUNET_PEER_search (&msg->destination);
5627   if (dest_id == myid)
5628   {
5629     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5630                 "  it's for us! sending to clients...\n");
5631     GNUNET_STATISTICS_update (stats, "# unicast received", 1, GNUNET_NO);
5632     send_subscribed_clients (message, &msg[1].header, t);
5633     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_UNICAST);
5634     return GNUNET_OK;
5635   }
5636   ttl = ntohl (msg->ttl);
5637   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ttl);
5638   if (ttl == 0)
5639   {
5640     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
5641     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
5642     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5643     return GNUNET_OK;
5644   }
5645   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5646               "  not for us, retransmitting...\n");
5647
5648   neighbor = tree_get_first_hop (t->tree, dest_id);
5649   cinfo = tunnel_get_neighbor_fc (t, neighbor);
5650   cinfo->fwd_pid = pid;
5651   GNUNET_CONTAINER_multihashmap_iterate (t->children_fc,
5652                                          &tunnel_add_skip,
5653                                          &neighbor);
5654   if (GNUNET_YES == t->nobuffer &&
5655       GNUNET_YES == GMC_is_pid_bigger (pid, cinfo->fwd_ack))
5656   {
5657     GNUNET_STATISTICS_update (stats, "# unsolicited unicast", 1, GNUNET_NO);
5658     GNUNET_log (GNUNET_ERROR_TYPE_INFO, "  %u > %u\n", pid, cinfo->fwd_ack);
5659     GNUNET_break_op (0);
5660     return GNUNET_OK;
5661   }
5662   send_prebuilt_message (message, neighbor, t);
5663   GNUNET_STATISTICS_update (stats, "# unicast forwarded", 1, GNUNET_NO);
5664   return GNUNET_OK;
5665 }
5666
5667
5668 /**
5669  * Core handler for mesh network traffic going from the origin to all peers
5670  *
5671  * @param cls closure
5672  * @param message message
5673  * @param peer peer identity this notification is about
5674  * @param atsi performance data
5675  * @param atsi_count number of records in 'atsi'
5676  * @return GNUNET_OK to keep the connection open,
5677  *         GNUNET_SYSERR to close it (signal serious error)
5678  *
5679  * TODO: Check who we got this from, to validate route.
5680  */
5681 static int
5682 handle_mesh_data_multicast (void *cls, const struct GNUNET_PeerIdentity *peer,
5683                             const struct GNUNET_MessageHeader *message,
5684                             const struct GNUNET_ATS_Information *atsi,
5685                             unsigned int atsi_count)
5686 {
5687   struct GNUNET_MESH_Multicast *msg;
5688   struct MeshTunnel *t;
5689   size_t size;
5690   uint32_t pid;
5691
5692   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a multicast packet from %s\n",
5693               GNUNET_i2s (peer));
5694   size = ntohs (message->size);
5695   if (sizeof (struct GNUNET_MESH_Multicast) +
5696       sizeof (struct GNUNET_MessageHeader) > size)
5697   {
5698     GNUNET_break_op (0);
5699     return GNUNET_OK;
5700   }
5701   msg = (struct GNUNET_MESH_Multicast *) message;
5702   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5703
5704   if (NULL == t)
5705   {
5706     /* TODO notify that we dont know that tunnel */
5707     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
5708     GNUNET_break_op (0);
5709     return GNUNET_OK;
5710   }
5711   pid = ntohl (msg->pid);
5712   if (t->fwd_pid == pid)
5713   {
5714     /* already seen this packet, drop */
5715     GNUNET_STATISTICS_update (stats, "# duplicate PID drops", 1, GNUNET_NO);
5716     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5717                 " Already seen pid %u, DROPPING!\n", pid);
5718     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5719     return GNUNET_OK;
5720   }
5721   else
5722   {
5723     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5724                 " pid %u not seen yet, forwarding\n", pid);
5725   }
5726   t->skip += (pid - t->fwd_pid) - 1;
5727   t->fwd_pid = pid;
5728   tunnel_reset_timeout (t);
5729
5730   /* Transmit to locally interested clients */
5731   if (NULL != t->peers &&
5732       GNUNET_CONTAINER_multihashmap_contains (t->peers, &my_full_id.hashPubKey))
5733   {
5734     GNUNET_STATISTICS_update (stats, "# multicast received", 1, GNUNET_NO);
5735     send_subscribed_clients (message, &msg[1].header, t);
5736     tunnel_send_fwd_ack(t, GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
5737   }
5738   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ntohl (msg->ttl));
5739   if (ntohl (msg->ttl) == 0)
5740   {
5741     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
5742     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
5743     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5744     return GNUNET_OK;
5745   }
5746   GNUNET_STATISTICS_update (stats, "# multicast forwarded", 1, GNUNET_NO);
5747   tunnel_send_multicast (t, message);
5748   return GNUNET_OK;
5749 }
5750
5751
5752 /**
5753  * Core handler for mesh network traffic toward the owner of a tunnel
5754  *
5755  * @param cls closure
5756  * @param message message
5757  * @param peer peer identity this notification is about
5758  * @param atsi performance data
5759  * @param atsi_count number of records in 'atsi'
5760  *
5761  * @return GNUNET_OK to keep the connection open,
5762  *         GNUNET_SYSERR to close it (signal serious error)
5763  */
5764 static int
5765 handle_mesh_data_to_orig (void *cls, const struct GNUNET_PeerIdentity *peer,
5766                           const struct GNUNET_MessageHeader *message,
5767                           const struct GNUNET_ATS_Information *atsi,
5768                           unsigned int atsi_count)
5769 {
5770   struct GNUNET_MESH_ToOrigin *msg;
5771   struct GNUNET_PeerIdentity id;
5772   struct MeshPeerInfo *peer_info;
5773   struct MeshTunnel *t;
5774   struct MeshTunnelChildInfo *cinfo;
5775   size_t size;
5776   uint32_t pid;
5777
5778   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a ToOrigin packet from %s\n",
5779               GNUNET_i2s (peer));
5780   size = ntohs (message->size);
5781   if (size < sizeof (struct GNUNET_MESH_ToOrigin) +     /* Payload must be */
5782       sizeof (struct GNUNET_MessageHeader))     /* at least a header */
5783   {
5784     GNUNET_break_op (0);
5785     return GNUNET_OK;
5786   }
5787   msg = (struct GNUNET_MESH_ToOrigin *) message;
5788   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %s\n",
5789               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
5790   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5791   pid = ntohl (msg->pid);
5792
5793   if (NULL == t)
5794   {
5795     /* TODO notify that we dont know this tunnel (whom)? */
5796     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
5797     GNUNET_break_op (0);
5798     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5799                 "Received to_origin with PID %u on unknown tunnel\n",
5800                 pid);
5801     return GNUNET_OK;
5802   }
5803
5804   cinfo = tunnel_get_neighbor_fc(t, peer);
5805   if (NULL == cinfo)
5806   {
5807     GNUNET_break (0);
5808     return GNUNET_OK;
5809   }
5810
5811   if (cinfo->bck_pid == pid)
5812   {
5813     /* already seen this packet, drop */
5814     GNUNET_STATISTICS_update (stats, "# duplicate PID drops BCK", 1, GNUNET_NO);
5815     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5816                 " Already seen pid %u, DROPPING!\n", pid);
5817     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5818     return GNUNET_OK;
5819   }
5820
5821   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5822               " pid %u not seen yet, forwarding\n", pid);
5823   cinfo->bck_pid = pid;
5824
5825   if (NULL != t->owner)
5826   {
5827     char cbuf[size];
5828     struct GNUNET_MESH_ToOrigin *copy;
5829
5830     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5831                 "  it's for us! sending to clients...\n");
5832     /* TODO signature verification */
5833     memcpy (cbuf, message, size);
5834     copy = (struct GNUNET_MESH_ToOrigin *) cbuf;
5835     copy->tid = htonl (t->local_tid);
5836     t->bck_pid++;
5837     copy->pid = htonl (t->bck_pid);
5838     GNUNET_STATISTICS_update (stats, "# to origin received", 1, GNUNET_NO);
5839     GNUNET_SERVER_notification_context_unicast (nc, t->owner->handle,
5840                                                 &copy->header, GNUNET_NO);
5841     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
5842     return GNUNET_OK;
5843   }
5844   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5845               "  not for us, retransmitting...\n");
5846
5847   peer_info = peer_info_get (&msg->oid);
5848   if (NULL == peer_info)
5849   {
5850     /* unknown origin of tunnel */
5851     GNUNET_break (0);
5852     return GNUNET_OK;
5853   }
5854   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
5855   send_prebuilt_message (message, &id, t);
5856   GNUNET_STATISTICS_update (stats, "# to origin forwarded", 1, GNUNET_NO);
5857
5858   return GNUNET_OK;
5859 }
5860
5861
5862 /**
5863  * Core handler for mesh network traffic point-to-point acks.
5864  *
5865  * @param cls closure
5866  * @param message message
5867  * @param peer peer identity this notification is about
5868  * @param atsi performance data
5869  * @param atsi_count number of records in 'atsi'
5870  *
5871  * @return GNUNET_OK to keep the connection open,
5872  *         GNUNET_SYSERR to close it (signal serious error)
5873  */
5874 static int
5875 handle_mesh_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5876                  const struct GNUNET_MessageHeader *message,
5877                  const struct GNUNET_ATS_Information *atsi,
5878                  unsigned int atsi_count)
5879 {
5880   struct GNUNET_MESH_ACK *msg;
5881   struct MeshTunnel *t;
5882   uint32_t ack;
5883
5884   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK packet from %s!\n",
5885               GNUNET_i2s (peer));
5886   msg = (struct GNUNET_MESH_ACK *) message;
5887
5888   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5889
5890   if (NULL == t)
5891   {
5892     /* TODO notify that we dont know this tunnel (whom)? */
5893     GNUNET_STATISTICS_update (stats, "# ack on unknown tunnel", 1, GNUNET_NO);
5894     GNUNET_break_op (0);
5895     return GNUNET_OK;
5896   }
5897   ack = ntohl (msg->pid);
5898
5899   /* Is this a forward or backward ACK? */
5900   if (tree_get_predecessor(t->tree) != GNUNET_PEER_search(peer))
5901   {
5902     struct MeshTunnelChildInfo *cinfo;
5903
5904     debug_bck_ack++;
5905     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
5906     cinfo = tunnel_get_neighbor_fc (t, peer);
5907     cinfo->fwd_ack = ack;
5908     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5909     tunnel_unlock_fwd_queues (t);
5910   }
5911   else
5912   {
5913     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
5914     t->bck_ack = ack;
5915     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5916     tunnel_unlock_bck_queue (t);
5917   }
5918   return GNUNET_OK;
5919 }
5920
5921
5922 /**
5923  * Core handler for mesh network traffic point-to-point ack polls.
5924  *
5925  * @param cls closure
5926  * @param message message
5927  * @param peer peer identity this notification is about
5928  * @param atsi performance data
5929  * @param atsi_count number of records in 'atsi'
5930  *
5931  * @return GNUNET_OK to keep the connection open,
5932  *         GNUNET_SYSERR to close it (signal serious error)
5933  */
5934 static int
5935 handle_mesh_poll (void *cls, const struct GNUNET_PeerIdentity *peer,
5936                   const struct GNUNET_MessageHeader *message,
5937                   const struct GNUNET_ATS_Information *atsi,
5938                   unsigned int atsi_count)
5939 {
5940   struct GNUNET_MESH_Poll *msg;
5941   struct MeshTunnel *t;
5942
5943   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an POLL packet from %s!\n",
5944               GNUNET_i2s (peer));
5945
5946   msg = (struct GNUNET_MESH_Poll *) message;
5947
5948   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5949
5950   if (NULL == t)
5951   {
5952     /* TODO notify that we dont know this tunnel (whom)? */
5953     GNUNET_STATISTICS_update (stats, "# poll on unknown tunnel", 1, GNUNET_NO);
5954     GNUNET_break_op (0);
5955     return GNUNET_OK;
5956   }
5957
5958   /* Is this a forward or backward ACK? */
5959   if (tree_get_predecessor(t->tree) != GNUNET_PEER_search(peer))
5960   {
5961     struct MeshTunnelChildInfo *cinfo;
5962
5963     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  from FWD\n");
5964     cinfo = tunnel_get_neighbor_fc (t, peer);
5965     cinfo->bck_ack = cinfo->fwd_pid; // mark as ready to send
5966     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_POLL);
5967   }
5968   else
5969   {
5970     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  from BCK\n");
5971     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_POLL);
5972   }
5973
5974   return GNUNET_OK;
5975 }
5976
5977
5978 /**
5979  * Core handler for path ACKs
5980  *
5981  * @param cls closure
5982  * @param message message
5983  * @param peer peer identity this notification is about
5984  * @param atsi performance data
5985  * @param atsi_count number of records in 'atsi'
5986  *
5987  * @return GNUNET_OK to keep the connection open,
5988  *         GNUNET_SYSERR to close it (signal serious error)
5989  */
5990 static int
5991 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5992                       const struct GNUNET_MessageHeader *message,
5993                       const struct GNUNET_ATS_Information *atsi,
5994                       unsigned int atsi_count)
5995 {
5996   struct GNUNET_MESH_PathACK *msg;
5997   struct GNUNET_PeerIdentity id;
5998   struct MeshPeerInfo *peer_info;
5999   struct MeshPeerPath *p;
6000   struct MeshTunnel *t;
6001
6002   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a path ACK msg [%s]\n",
6003               GNUNET_i2s (&my_full_id));
6004   msg = (struct GNUNET_MESH_PathACK *) message;
6005   t = tunnel_get (&msg->oid, ntohl(msg->tid));
6006   if (NULL == t)
6007   {
6008     /* TODO notify that we don't know the tunnel */
6009     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel", 1, GNUNET_NO);
6010     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  don't know the tunnel %s [%X]!\n",
6011                 GNUNET_i2s (&msg->oid), ntohl(msg->tid));
6012     return GNUNET_OK;
6013   }
6014   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %s [%X]\n",
6015               GNUNET_i2s (&msg->oid), ntohl(msg->tid));
6016
6017   peer_info = peer_info_get (&msg->peer_id);
6018   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by peer %s\n",
6019               GNUNET_i2s (&msg->peer_id));
6020   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  via peer %s\n",
6021               GNUNET_i2s (peer));
6022
6023   if (NULL != t->regex_ctx && t->regex_ctx->info->peer == peer_info->id)
6024   {
6025     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6026                 "connect_by_string completed, stopping search\n");
6027     regex_cancel_search (t->regex_ctx);
6028     t->regex_ctx = NULL;
6029   }
6030
6031   /* Add paths to peers? */
6032   p = tree_get_path_to_peer (t->tree, peer_info->id);
6033   if (NULL != p)
6034   {
6035     path_add_to_peers (p, GNUNET_YES);
6036     path_destroy (p);
6037   }
6038   else
6039   {
6040     GNUNET_break (0);
6041   }
6042
6043   /* Message for us? */
6044   if (0 == memcmp (&msg->oid, &my_full_id, sizeof (struct GNUNET_PeerIdentity)))
6045   {
6046     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
6047     if (NULL == t->owner)
6048     {
6049       GNUNET_break_op (0);
6050       return GNUNET_OK;
6051     }
6052     if (NULL != t->dht_get_type)
6053     {
6054       GNUNET_DHT_get_stop (t->dht_get_type);
6055       t->dht_get_type = NULL;
6056     }
6057     if (tree_get_status (t->tree, peer_info->id) != MESH_PEER_READY)
6058     {
6059       tree_set_status (t->tree, peer_info->id, MESH_PEER_READY);
6060       send_client_peer_connected (t, peer_info->id);
6061     }
6062     return GNUNET_OK;
6063   }
6064
6065   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6066               "  not for us, retransmitting...\n");
6067   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
6068   peer_info = peer_info_get (&msg->oid);
6069   if (NULL == peer_info)
6070   {
6071     /* If we know the tunnel, we should DEFINITELY know the peer */
6072     GNUNET_break (0);
6073     return GNUNET_OK;
6074   }
6075   send_prebuilt_message (message, &id, t);
6076   return GNUNET_OK;
6077 }
6078
6079
6080 /**
6081  * Core handler for mesh keepalives.
6082  *
6083  * @param cls closure
6084  * @param message message
6085  * @param peer peer identity this notification is about
6086  * @param atsi performance data
6087  * @param atsi_count number of records in 'atsi'
6088  * @return GNUNET_OK to keep the connection open,
6089  *         GNUNET_SYSERR to close it (signal serious error)
6090  *
6091  * TODO: Check who we got this from, to validate route.
6092  */
6093 static int
6094 handle_mesh_keepalive (void *cls, const struct GNUNET_PeerIdentity *peer,
6095                        const struct GNUNET_MessageHeader *message,
6096                        const struct GNUNET_ATS_Information *atsi,
6097                        unsigned int atsi_count)
6098 {
6099   struct GNUNET_MESH_TunnelKeepAlive *msg;
6100   struct MeshTunnel *t;
6101
6102   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a keepalive packet from %s\n",
6103               GNUNET_i2s (peer));
6104
6105   msg = (struct GNUNET_MESH_TunnelKeepAlive *) message;
6106   t = tunnel_get (&msg->oid, ntohl (msg->tid));
6107
6108   if (NULL == t)
6109   {
6110     /* TODO notify that we dont know that tunnel */
6111     GNUNET_STATISTICS_update (stats, "# keepalive on unknown tunnel", 1, GNUNET_NO);
6112     GNUNET_break_op (0);
6113     return GNUNET_OK;
6114   }
6115
6116   tunnel_reset_timeout (t);
6117
6118   GNUNET_STATISTICS_update (stats, "# keepalives forwarded", 1, GNUNET_NO);
6119   tunnel_send_multicast (t, message);
6120   return GNUNET_OK;
6121   }
6122
6123
6124
6125 /**
6126  * Functions to handle messages from core
6127  */
6128 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
6129   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
6130   {&handle_mesh_path_destroy, GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY, 0},
6131   {&handle_mesh_path_broken, GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN,
6132    sizeof (struct GNUNET_MESH_PathBroken)},
6133   {&handle_mesh_tunnel_destroy, GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY,
6134    sizeof (struct GNUNET_MESH_TunnelDestroy)},
6135   {&handle_mesh_data_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
6136   {&handle_mesh_data_multicast, GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
6137   {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE,
6138     sizeof (struct GNUNET_MESH_TunnelKeepAlive)},
6139   {&handle_mesh_data_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
6140   {&handle_mesh_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
6141     sizeof (struct GNUNET_MESH_ACK)},
6142   {&handle_mesh_poll, GNUNET_MESSAGE_TYPE_MESH_POLL,
6143     sizeof (struct GNUNET_MESH_Poll)},
6144   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
6145    sizeof (struct GNUNET_MESH_PathACK)},
6146   {NULL, 0, 0}
6147 };
6148
6149
6150
6151 /******************************************************************************/
6152 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
6153 /******************************************************************************/
6154
6155 /**
6156  * deregister_app: iterator for removing each application registered by a client
6157  *
6158  * @param cls closure
6159  * @param key the hash of the application id (used to access the hashmap)
6160  * @param value the value stored at the key (client)
6161  *
6162  * @return GNUNET_OK on success
6163  */
6164 static int
6165 deregister_app (void *cls, const struct GNUNET_HashCode * key, void *value)
6166 {
6167   struct GNUNET_CONTAINER_MultiHashMap *h = cls;
6168   GNUNET_break (GNUNET_YES ==
6169                 GNUNET_CONTAINER_multihashmap_remove (h, key, value));
6170   return GNUNET_OK;
6171 }
6172
6173 #if LATER
6174 /**
6175  * notify_client_connection_failure: notify a client that the connection to the
6176  * requested remote peer is not possible (for instance, no route found)
6177  * Function called when the socket is ready to queue more data. "buf" will be
6178  * NULL and "size" zero if the socket was closed for writing in the meantime.
6179  *
6180  * @param cls closure
6181  * @param size number of bytes available in buf
6182  * @param buf where the callee should write the message
6183  * @return number of bytes written to buf
6184  */
6185 static size_t
6186 notify_client_connection_failure (void *cls, size_t size, void *buf)
6187 {
6188   int size_needed;
6189   struct MeshPeerInfo *peer_info;
6190   struct GNUNET_MESH_PeerControl *msg;
6191   struct GNUNET_PeerIdentity id;
6192
6193   if (0 == size && NULL == buf)
6194   {
6195     // TODO retry? cancel?
6196     return 0;
6197   }
6198
6199   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
6200   peer_info = (struct MeshPeerInfo *) cls;
6201   msg = (struct GNUNET_MESH_PeerControl *) buf;
6202   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
6203   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
6204 //     msg->tunnel_id = htonl(peer_info->t->tid);
6205   GNUNET_PEER_resolve (peer_info->id, &id);
6206   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
6207
6208   return size_needed;
6209 }
6210 #endif
6211
6212
6213 /**
6214  * Send keepalive packets for a peer
6215  *
6216  * @param cls Closure (tunnel for which to send the keepalive).
6217  * @param tc Notification context.
6218  */
6219 static void
6220 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
6221 {
6222   struct MeshTunnel *t = cls;
6223   struct GNUNET_MESH_TunnelKeepAlive *msg;
6224   size_t size = sizeof (struct GNUNET_MESH_TunnelKeepAlive);
6225   char cbuf[size];
6226
6227   t->path_refresh_task = GNUNET_SCHEDULER_NO_TASK;
6228   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
6229   {
6230     return;
6231   }
6232
6233   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6234               "sending keepalive for tunnel %d\n", t->id.tid);
6235
6236   msg = (struct GNUNET_MESH_TunnelKeepAlive *) cbuf;
6237   msg->header.size = htons (size);
6238   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE);
6239   msg->oid = my_full_id;
6240   msg->tid = htonl (t->id.tid);
6241   tunnel_send_multicast (t, &msg->header);
6242
6243   t->path_refresh_task =
6244       GNUNET_SCHEDULER_add_delayed (refresh_path_time, &path_refresh, t);
6245   tunnel_reset_timeout(t);
6246 }
6247
6248
6249 /**
6250  * Function to process paths received for a new peer addition. The recorded
6251  * paths form the initial tunnel, which can be optimized later.
6252  * Called on each result obtained for the DHT search.
6253  *
6254  * @param cls closure
6255  * @param exp when will this value expire
6256  * @param key key of the result
6257  * @param get_path path of the get request
6258  * @param get_path_length lenght of get_path
6259  * @param put_path path of the put request
6260  * @param put_path_length length of the put_path
6261  * @param type type of the result
6262  * @param size number of bytes in data
6263  * @param data pointer to the result data
6264  *
6265  * TODO: re-issue the request after certain time? cancel after X results?
6266  */
6267 static void
6268 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
6269                     const struct GNUNET_HashCode * key,
6270                     const struct GNUNET_PeerIdentity *get_path,
6271                     unsigned int get_path_length,
6272                     const struct GNUNET_PeerIdentity *put_path,
6273                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
6274                     size_t size, const void *data)
6275 {
6276   struct MeshPathInfo *path_info = cls;
6277   struct MeshPeerPath *p;
6278   struct GNUNET_PeerIdentity pi;
6279   int i;
6280
6281   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
6282   GNUNET_PEER_resolve (path_info->peer->id, &pi);
6283   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", GNUNET_i2s (&pi));
6284
6285   p = path_build_from_dht (get_path, get_path_length, put_path,
6286                            put_path_length);
6287   path_add_to_peers (p, GNUNET_NO);
6288   path_destroy(p);
6289   for (i = 0; i < path_info->peer->ntunnels; i++)
6290   {
6291     tunnel_add_peer (path_info->peer->tunnels[i], path_info->peer);
6292     peer_info_connect (path_info->peer, path_info->t);
6293   }
6294
6295   return;
6296 }
6297
6298
6299 /**
6300  * Function to process paths received for a new peer addition. The recorded
6301  * paths form the initial tunnel, which can be optimized later.
6302  * Called on each result obtained for the DHT search.
6303  *
6304  * @param cls closure
6305  * @param exp when will this value expire
6306  * @param key key of the result
6307  * @param get_path path of the get request
6308  * @param get_path_length lenght of get_path
6309  * @param put_path path of the put request
6310  * @param put_path_length length of the put_path
6311  * @param type type of the result
6312  * @param size number of bytes in data
6313  * @param data pointer to the result data
6314  */
6315 static void
6316 dht_get_type_handler (void *cls, struct GNUNET_TIME_Absolute exp,
6317                       const struct GNUNET_HashCode * key,
6318                       const struct GNUNET_PeerIdentity *get_path,
6319                       unsigned int get_path_length,
6320                       const struct GNUNET_PeerIdentity *put_path,
6321                       unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
6322                       size_t size, const void *data)
6323 {
6324   const struct PBlock *pb = data;
6325   const struct GNUNET_PeerIdentity *pi = &pb->id;
6326   struct MeshTunnel *t = cls;
6327   struct MeshPeerInfo *peer_info;
6328   struct MeshPeerPath *p;
6329
6330   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got type DHT result!\n");
6331   if (size != sizeof (struct PBlock))
6332   {
6333     GNUNET_break_op (0);
6334     return;
6335   }
6336   if (ntohl(pb->type) != t->type)
6337   {
6338     GNUNET_break_op (0);
6339     return;
6340   }
6341   GNUNET_assert (NULL != t->owner);
6342   peer_info = peer_info_get (pi);
6343   (void) GNUNET_CONTAINER_multihashmap_put (t->peers, &pi->hashPubKey,
6344                                             peer_info,
6345                                             GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
6346
6347   p = path_build_from_dht (get_path, get_path_length, put_path,
6348                            put_path_length);
6349   path_add_to_peers (p, GNUNET_NO);
6350   path_destroy(p);
6351   tunnel_add_peer (t, peer_info);
6352   peer_info_connect (peer_info, t);
6353 }
6354
6355
6356 /**
6357  * Function to process DHT string to regex matching.
6358  * Called on each result obtained for the DHT search.
6359  *
6360  * @param cls closure (search context)
6361  * @param exp when will this value expire
6362  * @param key key of the result
6363  * @param get_path path of the get request (not used)
6364  * @param get_path_length lenght of get_path (not used)
6365  * @param put_path path of the put request (not used)
6366  * @param put_path_length length of the put_path (not used)
6367  * @param type type of the result
6368  * @param size number of bytes in data
6369  * @param data pointer to the result data
6370  */
6371 static void
6372 dht_get_string_accept_handler (void *cls, struct GNUNET_TIME_Absolute exp,
6373                                const struct GNUNET_HashCode * key,
6374                                const struct GNUNET_PeerIdentity *get_path,
6375                                unsigned int get_path_length,
6376                                const struct GNUNET_PeerIdentity *put_path,
6377                                unsigned int put_path_length,
6378                                enum GNUNET_BLOCK_Type type,
6379                                size_t size, const void *data)
6380 {
6381   const struct MeshRegexAccept *block = data;
6382   struct MeshRegexSearchContext *ctx = cls;
6383   struct MeshRegexSearchInfo *info = ctx->info;
6384   struct MeshPeerPath *p;
6385   struct MeshPeerInfo *peer_info;
6386
6387   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got regex results from DHT!\n");
6388   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", info->description);
6389
6390   peer_info = peer_info_get(&block->id);
6391   p = path_build_from_dht (get_path, get_path_length, put_path,
6392                            put_path_length);
6393   path_add_to_peers (p, GNUNET_NO);
6394   path_destroy(p);
6395
6396   tunnel_add_peer (info->t, peer_info);
6397   peer_info_connect (peer_info, info->t);
6398   if (0 == info->peer)
6399   {
6400     info->peer = peer_info->id;
6401   }
6402   else
6403   {
6404     GNUNET_array_append (info->peers, info->n_peers, peer_info->id);
6405   }
6406
6407   info->timeout = GNUNET_SCHEDULER_add_delayed (connect_timeout,
6408                                                 &regex_connect_timeout,
6409                                                 info);
6410
6411   return;
6412 }
6413
6414
6415 /**
6416  * Function to process DHT string to regex matching.
6417  * Called on each result obtained for the DHT search.
6418  *
6419  * @param cls closure (search context)
6420  * @param exp when will this value expire
6421  * @param key key of the result
6422  * @param get_path path of the get request (not used)
6423  * @param get_path_length lenght of get_path (not used)
6424  * @param put_path path of the put request (not used)
6425  * @param put_path_length length of the put_path (not used)
6426  * @param type type of the result
6427  * @param size number of bytes in data
6428  * @param data pointer to the result data
6429  *
6430  * TODO: re-issue the request after certain time? cancel after X results?
6431  */
6432 static void
6433 dht_get_string_handler (void *cls, struct GNUNET_TIME_Absolute exp,
6434                         const struct GNUNET_HashCode * key,
6435                         const struct GNUNET_PeerIdentity *get_path,
6436                         unsigned int get_path_length,
6437                         const struct GNUNET_PeerIdentity *put_path,
6438                         unsigned int put_path_length,
6439                         enum GNUNET_BLOCK_Type type,
6440                         size_t size, const void *data)
6441 {
6442   const struct MeshRegexBlock *block = data;
6443   struct MeshRegexSearchContext *ctx = cls;
6444   struct MeshRegexSearchInfo *info = ctx->info;
6445   void *copy;
6446   size_t len;
6447
6448   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6449               "DHT GET STRING RETURNED RESULTS\n");
6450   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6451               "  key: %s\n", GNUNET_h2s (key));
6452
6453   copy = GNUNET_malloc (size);
6454   memcpy (copy, data, size);
6455   GNUNET_break (GNUNET_OK ==
6456                 GNUNET_CONTAINER_multihashmap_put(info->dht_get_results, key, copy,
6457                                                   GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
6458   len = ntohl (block->n_proof);
6459   {
6460     char proof[len + 1];
6461
6462     memcpy (proof, &block[1], len);
6463     proof[len] = '\0';
6464     if (GNUNET_OK != GNUNET_REGEX_check_proof (proof, key))
6465     {
6466       GNUNET_break_op (0);
6467       return;
6468     }
6469   }
6470   len = strlen (info->description);
6471   if (len == ctx->position) // String processed
6472   {
6473     if (GNUNET_YES == ntohl (block->accepting))
6474     {
6475       regex_find_path(key, ctx);
6476     }
6477     else
6478     {
6479       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  block not accepting!\n");
6480       // FIXME REGEX this block not successful, wait for more? start timeout?
6481     }
6482     return;
6483   }
6484
6485   regex_next_edge (block, size, ctx);
6486
6487   return;
6488 }
6489
6490 /******************************************************************************/
6491 /*********************       MESH LOCAL HANDLES      **************************/
6492 /******************************************************************************/
6493
6494
6495 /**
6496  * Handler for client disconnection
6497  *
6498  * @param cls closure
6499  * @param client identification of the client; NULL
6500  *        for the last call when the server is destroyed
6501  */
6502 static void
6503 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
6504 {
6505   struct MeshClient *c;
6506   struct MeshClient *next;
6507   unsigned int i;
6508
6509   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected\n");
6510   if (client == NULL)
6511   {
6512     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (SERVER DOWN)\n");
6513     return;
6514   }
6515   c = clients;
6516   while (NULL != c)
6517   {
6518     if (c->handle != client)
6519     {
6520       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ... searching\n");
6521       c = c->next;
6522       continue;
6523     }
6524     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u)\n",
6525                 c->id);
6526     GNUNET_SERVER_client_drop (c->handle);
6527     c->shutting_down = GNUNET_YES;
6528     GNUNET_assert (NULL != c->own_tunnels);
6529     GNUNET_assert (NULL != c->incoming_tunnels);
6530     GNUNET_CONTAINER_multihashmap_iterate (c->own_tunnels,
6531                                            &tunnel_destroy_iterator, c);
6532     GNUNET_CONTAINER_multihashmap_iterate (c->incoming_tunnels,
6533                                            &tunnel_destroy_iterator, c);
6534     GNUNET_CONTAINER_multihashmap_iterate (c->ignore_tunnels,
6535                                            &tunnel_destroy_iterator, c);
6536     GNUNET_CONTAINER_multihashmap_destroy (c->own_tunnels);
6537     GNUNET_CONTAINER_multihashmap_destroy (c->incoming_tunnels);
6538     GNUNET_CONTAINER_multihashmap_destroy (c->ignore_tunnels);
6539
6540     /* deregister clients applications */
6541     if (NULL != c->apps)
6542     {
6543       GNUNET_CONTAINER_multihashmap_iterate (c->apps, &deregister_app, c->apps);
6544       GNUNET_CONTAINER_multihashmap_destroy (c->apps);
6545     }
6546     if (0 == GNUNET_CONTAINER_multihashmap_size (applications) &&
6547         GNUNET_SCHEDULER_NO_TASK != announce_applications_task)
6548     {
6549       GNUNET_SCHEDULER_cancel (announce_applications_task);
6550       announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
6551     }
6552     if (NULL != c->types)
6553       GNUNET_CONTAINER_multihashmap_destroy (c->types);
6554     for (i = 0; i < c->n_regex; i++)
6555     {
6556       GNUNET_free (c->regexes[i]);
6557     }
6558     GNUNET_free_non_null (c->regexes);
6559     if (GNUNET_SCHEDULER_NO_TASK != c->regex_announce_task)
6560       GNUNET_SCHEDULER_cancel (c->regex_announce_task);
6561     next = c->next;
6562     GNUNET_CONTAINER_DLL_remove (clients, clients_tail, c);
6563     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT FREE at %p\n", c);
6564     GNUNET_free (c);
6565     GNUNET_STATISTICS_update (stats, "# clients", -1, GNUNET_NO);
6566     c = next;
6567   }
6568   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   done!\n");
6569   return;
6570 }
6571
6572
6573 /**
6574  * Handler for new clients
6575  *
6576  * @param cls closure
6577  * @param client identification of the client
6578  * @param message the actual message, which includes messages the client wants
6579  */
6580 static void
6581 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
6582                          const struct GNUNET_MessageHeader *message)
6583 {
6584   struct GNUNET_MESH_ClientConnect *cc_msg;
6585   struct MeshClient *c;
6586   GNUNET_MESH_ApplicationType *a;
6587   unsigned int size;
6588   uint16_t ntypes;
6589   uint16_t *t;
6590   uint16_t napps;
6591   uint16_t i;
6592
6593   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected\n");
6594   /* Check data sanity */
6595   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
6596   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
6597   ntypes = ntohs (cc_msg->types);
6598   napps = ntohs (cc_msg->applications);
6599   if (size !=
6600       ntypes * sizeof (uint16_t) + napps * sizeof (GNUNET_MESH_ApplicationType))
6601   {
6602     GNUNET_break (0);
6603     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6604     return;
6605   }
6606
6607   /* Create new client structure */
6608   c = GNUNET_malloc (sizeof (struct MeshClient));
6609   c->id = next_client_id++;
6610   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT NEW %u\n", c->id);
6611   c->handle = client;
6612   GNUNET_SERVER_client_keep (client);
6613   a = (GNUNET_MESH_ApplicationType *) &cc_msg[1];
6614   if (napps > 0)
6615   {
6616     GNUNET_MESH_ApplicationType at;
6617     struct GNUNET_HashCode hc;
6618
6619     c->apps = GNUNET_CONTAINER_multihashmap_create (napps, GNUNET_NO);
6620     for (i = 0; i < napps; i++)
6621     {
6622       at = ntohl (a[i]);
6623       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  app type: %u\n", at);
6624       GNUNET_CRYPTO_hash (&at, sizeof (at), &hc);
6625       /* store in clients hashmap */
6626       GNUNET_CONTAINER_multihashmap_put (c->apps, &hc, (void *) (long) at,
6627                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6628       /* store in global hashmap, for announcements */
6629       GNUNET_CONTAINER_multihashmap_put (applications, &hc, c,
6630                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6631     }
6632     if (GNUNET_SCHEDULER_NO_TASK == announce_applications_task)
6633       announce_applications_task =
6634           GNUNET_SCHEDULER_add_now (&announce_applications, NULL);
6635
6636   }
6637   if (ntypes > 0)
6638   {
6639     uint16_t u16;
6640     struct GNUNET_HashCode hc;
6641
6642     t = (uint16_t *) & a[napps];
6643     c->types = GNUNET_CONTAINER_multihashmap_create (ntypes, GNUNET_NO);
6644     for (i = 0; i < ntypes; i++)
6645     {
6646       u16 = ntohs (t[i]);
6647       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  msg type: %u\n", u16);
6648       GNUNET_CRYPTO_hash (&u16, sizeof (u16), &hc);
6649
6650       /* store in clients hashmap */
6651       GNUNET_CONTAINER_multihashmap_put (c->types, &hc, c,
6652                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6653       /* store in global hashmap */
6654       GNUNET_CONTAINER_multihashmap_put (types, &hc, c,
6655                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6656     }
6657   }
6658   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6659               " client has %u+%u subscriptions\n", napps, ntypes);
6660
6661   GNUNET_CONTAINER_DLL_insert (clients, clients_tail, c);
6662   c->own_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6663   c->incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6664   c->ignore_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6665   GNUNET_SERVER_notification_context_add (nc, client);
6666   GNUNET_STATISTICS_update (stats, "# clients", 1, GNUNET_NO);
6667
6668   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6669   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
6670 }
6671
6672
6673 /**
6674  * Handler for clients announcing available services by a regular expression.
6675  *
6676  * @param cls closure
6677  * @param client identification of the client
6678  * @param message the actual message, which includes messages the client wants
6679  */
6680 static void
6681 handle_local_announce_regex (void *cls, struct GNUNET_SERVER_Client *client,
6682                              const struct GNUNET_MessageHeader *message)
6683 {
6684   struct MeshClient *c;
6685   char *regex;
6686   size_t len;
6687
6688   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "announce regex started\n");
6689
6690   /* Sanity check for client registration */
6691   if (NULL == (c = client_get (client)))
6692   {
6693     GNUNET_break (0);
6694     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6695     return;
6696   }
6697   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6698
6699   len = ntohs (message->size) - sizeof(struct GNUNET_MessageHeader);
6700   regex = GNUNET_malloc (len + 1);
6701   memcpy (regex, &message[1], len);
6702   regex[len] = '\0';
6703   GNUNET_array_append (c->regexes, c->n_regex, regex);
6704   if (GNUNET_SCHEDULER_NO_TASK == c->regex_announce_task)
6705   {
6706     c->regex_announce_task = GNUNET_SCHEDULER_add_now(&announce_regex, c);
6707   }
6708   else
6709   {
6710     regex_put(regex);
6711   }
6712   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6713   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "announce regex processed\n");
6714 }
6715
6716
6717 /**
6718  * Handler for requests of new tunnels
6719  *
6720  * @param cls closure
6721  * @param client identification of the client
6722  * @param message the actual message
6723  */
6724 static void
6725 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
6726                             const struct GNUNET_MessageHeader *message)
6727 {
6728   struct GNUNET_MESH_TunnelMessage *t_msg;
6729   struct MeshTunnel *t;
6730   struct MeshClient *c;
6731   MESH_TunnelNumber tid;
6732
6733   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel requested\n");
6734
6735   /* Sanity check for client registration */
6736   if (NULL == (c = client_get (client)))
6737   {
6738     GNUNET_break (0);
6739     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6740     return;
6741   }
6742   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6743
6744   /* Message sanity check */
6745   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
6746   {
6747     GNUNET_break (0);
6748     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6749     return;
6750   }
6751
6752   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6753   /* Sanity check for tunnel numbering */
6754   tid = ntohl (t_msg->tunnel_id);
6755   if (0 == (tid & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
6756   {
6757     GNUNET_break (0);
6758     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6759     return;
6760   }
6761   /* Sanity check for duplicate tunnel IDs */
6762   if (NULL != tunnel_get_by_local_id (c, tid))
6763   {
6764     GNUNET_break (0);
6765     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6766     return;
6767   }
6768
6769   while (NULL != tunnel_get_by_pi (myid, next_tid))
6770     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
6771   t = tunnel_new (myid, next_tid++, c, tid);
6772   if (NULL == t)
6773   {
6774     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Tunnel creation failed.\n");
6775     GNUNET_break (0);
6776     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6777     return;
6778   }
6779   next_tid = next_tid & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
6780   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED TUNNEL %s [%x] (%x)\n",
6781               GNUNET_i2s (&my_full_id), t->id.tid, t->local_tid);
6782   t->peers = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6783
6784   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel created\n");
6785   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6786   return;
6787 }
6788
6789
6790 /**
6791  * Handler for requests of deleting tunnels
6792  *
6793  * @param cls closure
6794  * @param client identification of the client
6795  * @param message the actual message
6796  */
6797 static void
6798 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
6799                              const struct GNUNET_MessageHeader *message)
6800 {
6801   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
6802   struct MeshClient *c;
6803   struct MeshTunnel *t;
6804   MESH_TunnelNumber tid;
6805
6806   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6807               "Got a DESTROY TUNNEL from client!\n");
6808
6809   /* Sanity check for client registration */
6810   if (NULL == (c = client_get (client)))
6811   {
6812     GNUNET_break (0);
6813     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6814     return;
6815   }
6816   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6817
6818   /* Message sanity check */
6819   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
6820   {
6821     GNUNET_break (0);
6822     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6823     return;
6824   }
6825
6826   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6827
6828   /* Retrieve tunnel */
6829   tid = ntohl (tunnel_msg->tunnel_id);
6830   t = tunnel_get_by_local_id(c, tid);
6831   if (NULL == t)
6832   {
6833     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
6834     GNUNET_break (0);
6835     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6836     return;
6837   }
6838   if (c != t->owner || tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
6839   {
6840     client_ignore_tunnel (c, t);
6841 #if 0
6842     // TODO: when to destroy incoming tunnel?
6843     if (t->nclients == 0)
6844     {
6845       GNUNET_assert (GNUNET_YES ==
6846                      GNUNET_CONTAINER_multihashmap_remove (incoming_tunnels,
6847                                                            &hash, t));
6848       GNUNET_assert (GNUNET_YES ==
6849                      GNUNET_CONTAINER_multihashmap_remove (t->peers,
6850                                                            &my_full_id.hashPubKey,
6851                                                            t));
6852     }
6853 #endif
6854     GNUNET_SERVER_receive_done (client, GNUNET_OK);
6855     return;
6856   }
6857   send_client_tunnel_disconnect(t, c);
6858   client_delete_tunnel(c, t);
6859
6860   /* Don't try to ACK the client about the tunnel_destroy multicast packet */
6861   t->owner = NULL;
6862   tunnel_send_destroy (t);
6863   t->destroy = GNUNET_YES;
6864   // The tunnel will be destroyed when the last message is transmitted.
6865   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6866   return;
6867 }
6868
6869
6870 /**
6871  * Handler for requests of seeting tunnel's speed.
6872  *
6873  * @param cls Closure (unused).
6874  * @param client Identification of the client.
6875  * @param message The actual message.
6876  */
6877 static void
6878 handle_local_tunnel_speed (void *cls, struct GNUNET_SERVER_Client *client,
6879                            const struct GNUNET_MessageHeader *message)
6880 {
6881   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
6882   struct MeshClient *c;
6883   struct MeshTunnel *t;
6884   MESH_TunnelNumber tid;
6885
6886   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6887               "Got a SPEED request from client!\n");
6888
6889   /* Sanity check for client registration */
6890   if (NULL == (c = client_get (client)))
6891   {
6892     GNUNET_break (0);
6893     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6894     return;
6895   }
6896
6897   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6898
6899   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6900
6901   /* Retrieve tunnel */
6902   tid = ntohl (tunnel_msg->tunnel_id);
6903   t = tunnel_get_by_local_id(c, tid);
6904   if (NULL == t)
6905   {
6906     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  tunnel %X not found\n", tid);
6907     GNUNET_break (0);
6908     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6909     return;
6910   }
6911
6912   switch (ntohs(message->type))
6913   {
6914       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MIN:
6915           t->speed_min = GNUNET_YES;
6916           break;
6917       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MAX:
6918           t->speed_min = GNUNET_NO;
6919           break;
6920       default:
6921           GNUNET_break (0);
6922   }
6923   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6924 }
6925
6926
6927 /**
6928  * Handler for requests of seeting tunnel's buffering policy.
6929  *
6930  * @param cls Closure (unused).
6931  * @param client Identification of the client.
6932  * @param message The actual message.
6933  */
6934 static void
6935 handle_local_tunnel_buffer (void *cls, struct GNUNET_SERVER_Client *client,
6936                             const struct GNUNET_MessageHeader *message)
6937 {
6938   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
6939   struct MeshClient *c;
6940   struct MeshTunnel *t;
6941   MESH_TunnelNumber tid;
6942
6943   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6944               "Got a BUFFER request from client!\n");
6945
6946   /* Sanity check for client registration */
6947   if (NULL == (c = client_get (client)))
6948   {
6949     GNUNET_break (0);
6950     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6951     return;
6952   }
6953   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6954
6955   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6956
6957   /* Retrieve tunnel */
6958   tid = ntohl (tunnel_msg->tunnel_id);
6959   t = tunnel_get_by_local_id(c, tid);
6960   if (NULL == t)
6961   {
6962     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
6963     GNUNET_break (0);
6964     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6965     return;
6966   }
6967
6968   switch (ntohs(message->type))
6969   {
6970       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER:
6971           t->nobuffer = GNUNET_NO;
6972           break;
6973       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER:
6974           t->nobuffer = GNUNET_YES;
6975           break;
6976       default:
6977           GNUNET_break (0);
6978   }
6979
6980   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6981 }
6982
6983
6984 /**
6985  * Handler for connection requests to new peers
6986  *
6987  * @param cls closure
6988  * @param client identification of the client
6989  * @param message the actual message (PeerControl)
6990  */
6991 static void
6992 handle_local_connect_add (void *cls, struct GNUNET_SERVER_Client *client,
6993                           const struct GNUNET_MessageHeader *message)
6994 {
6995   struct GNUNET_MESH_PeerControl *peer_msg;
6996   struct MeshPeerInfo *peer_info;
6997   struct MeshClient *c;
6998   struct MeshTunnel *t;
6999   MESH_TunnelNumber tid;
7000
7001   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got connection request\n");
7002   /* Sanity check for client registration */
7003   if (NULL == (c = client_get (client)))
7004   {
7005     GNUNET_break (0);
7006     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7007     return;
7008   }
7009   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7010
7011   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
7012
7013   /* Sanity check for message size */
7014   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
7015   {
7016     GNUNET_break (0);
7017     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7018     return;
7019   }
7020
7021   /* Tunnel exists? */
7022   tid = ntohl (peer_msg->tunnel_id);
7023   t = tunnel_get_by_local_id (c, tid);
7024   if (NULL == t)
7025   {
7026     GNUNET_break (0);
7027     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7028     return;
7029   }
7030
7031   /* Does client own tunnel? */
7032   if (t->owner->handle != client)
7033   {
7034     GNUNET_break (0);
7035     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7036     return;
7037   }
7038   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "     for %s\n",
7039               GNUNET_i2s (&peer_msg->peer));
7040   peer_info = peer_info_get (&peer_msg->peer);
7041
7042   tunnel_add_peer (t, peer_info);
7043   peer_info_connect (peer_info, t);
7044
7045   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7046   return;
7047 }
7048
7049
7050 /**
7051  * Handler for disconnection requests of peers in a tunnel
7052  *
7053  * @param cls closure
7054  * @param client identification of the client
7055  * @param message the actual message (PeerControl)
7056  */
7057 static void
7058 handle_local_connect_del (void *cls, struct GNUNET_SERVER_Client *client,
7059                           const struct GNUNET_MessageHeader *message)
7060 {
7061   struct GNUNET_MESH_PeerControl *peer_msg;
7062   struct MeshPeerInfo *peer_info;
7063   struct MeshClient *c;
7064   struct MeshTunnel *t;
7065   MESH_TunnelNumber tid;
7066
7067   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER DEL request\n");
7068   /* Sanity check for client registration */
7069   if (NULL == (c = client_get (client)))
7070   {
7071     GNUNET_break (0);
7072     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7073     return;
7074   }
7075   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7076
7077   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
7078
7079   /* Sanity check for message size */
7080   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
7081   {
7082     GNUNET_break (0);
7083     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7084     return;
7085   }
7086
7087   /* Tunnel exists? */
7088   tid = ntohl (peer_msg->tunnel_id);
7089   t = tunnel_get_by_local_id (c, tid);
7090   if (NULL == t)
7091   {
7092     GNUNET_break (0);
7093     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7094     return;
7095   }
7096   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
7097
7098   /* Does client own tunnel? */
7099   if (t->owner->handle != client)
7100   {
7101     GNUNET_break (0);
7102     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7103     return;
7104   }
7105
7106   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for peer %s\n",
7107               GNUNET_i2s (&peer_msg->peer));
7108   /* Is the peer in the tunnel? */
7109   peer_info =
7110       GNUNET_CONTAINER_multihashmap_get (t->peers, &peer_msg->peer.hashPubKey);
7111   if (NULL == peer_info)
7112   {
7113     GNUNET_break (0);
7114     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7115     return;
7116   }
7117
7118   /* Ok, delete peer from tunnel */
7119   GNUNET_CONTAINER_multihashmap_remove_all (t->peers,
7120                                             &peer_msg->peer.hashPubKey);
7121
7122   send_destroy_path (t, peer_info->id);
7123   tunnel_delete_peer (t, peer_info->id);
7124   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7125   return;
7126 }
7127
7128 /**
7129  * Handler for blacklist requests of peers in a tunnel
7130  *
7131  * @param cls closure
7132  * @param client identification of the client
7133  * @param message the actual message (PeerControl)
7134  * 
7135  * FIXME implement DHT block bloomfilter
7136  */
7137 static void
7138 handle_local_blacklist (void *cls, struct GNUNET_SERVER_Client *client,
7139                           const struct GNUNET_MessageHeader *message)
7140 {
7141   struct GNUNET_MESH_PeerControl *peer_msg;
7142   struct MeshClient *c;
7143   struct MeshTunnel *t;
7144   MESH_TunnelNumber tid;
7145
7146   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER BLACKLIST request\n");
7147   /* Sanity check for client registration */
7148   if (NULL == (c = client_get (client)))
7149   {
7150     GNUNET_break (0);
7151     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7152     return;
7153   }
7154   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7155
7156   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
7157
7158   /* Sanity check for message size */
7159   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
7160   {
7161     GNUNET_break (0);
7162     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7163     return;
7164   }
7165
7166   /* Tunnel exists? */
7167   tid = ntohl (peer_msg->tunnel_id);
7168   t = tunnel_get_by_local_id (c, tid);
7169   if (NULL == t)
7170   {
7171     GNUNET_break (0);
7172     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7173     return;
7174   }
7175   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
7176
7177   GNUNET_array_append(t->blacklisted, t->nblacklisted,
7178                       GNUNET_PEER_intern(&peer_msg->peer));
7179 }
7180
7181
7182 /**
7183  * Handler for unblacklist requests of peers in a tunnel
7184  *
7185  * @param cls closure
7186  * @param client identification of the client
7187  * @param message the actual message (PeerControl)
7188  */
7189 static void
7190 handle_local_unblacklist (void *cls, struct GNUNET_SERVER_Client *client,
7191                           const struct GNUNET_MessageHeader *message)
7192 {
7193   struct GNUNET_MESH_PeerControl *peer_msg;
7194   struct MeshClient *c;
7195   struct MeshTunnel *t;
7196   MESH_TunnelNumber tid;
7197   GNUNET_PEER_Id pid;
7198   unsigned int i;
7199
7200   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER UNBLACKLIST request\n");
7201   /* Sanity check for client registration */
7202   if (NULL == (c = client_get (client)))
7203   {
7204     GNUNET_break (0);
7205     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7206     return;
7207   }
7208   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7209
7210   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
7211
7212   /* Sanity check for message size */
7213   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
7214   {
7215     GNUNET_break (0);
7216     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7217     return;
7218   }
7219
7220   /* Tunnel exists? */
7221   tid = ntohl (peer_msg->tunnel_id);
7222   t = tunnel_get_by_local_id (c, tid);
7223   if (NULL == t)
7224   {
7225     GNUNET_break (0);
7226     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7227     return;
7228   }
7229   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
7230
7231   /* if peer is not known, complain */
7232   pid = GNUNET_PEER_search (&peer_msg->peer);
7233   if (0 == pid)
7234   {
7235     GNUNET_break (0);
7236     return;
7237   }
7238
7239   /* search and remove from list */
7240   for (i = 0; i < t->nblacklisted; i++)
7241   {
7242     if (t->blacklisted[i] == pid)
7243     {
7244       t->blacklisted[i] = t->blacklisted[t->nblacklisted - 1];
7245       GNUNET_array_grow (t->blacklisted, t->nblacklisted, t->nblacklisted - 1);
7246       return;
7247     }
7248   }
7249
7250   /* if peer hasn't been blacklisted, complain */
7251   GNUNET_break (0);
7252 }
7253
7254
7255 /**
7256  * Handler for connection requests to new peers by type
7257  *
7258  * @param cls closure
7259  * @param client identification of the client
7260  * @param message the actual message (ConnectPeerByType)
7261  */
7262 static void
7263 handle_local_connect_by_type (void *cls, struct GNUNET_SERVER_Client *client,
7264                               const struct GNUNET_MessageHeader *message)
7265 {
7266   struct GNUNET_MESH_ConnectPeerByType *connect_msg;
7267   struct MeshClient *c;
7268   struct MeshTunnel *t;
7269   struct GNUNET_HashCode hash;
7270   MESH_TunnelNumber tid;
7271
7272   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got connect by type request\n");
7273   /* Sanity check for client registration */
7274   if (NULL == (c = client_get (client)))
7275   {
7276     GNUNET_break (0);
7277     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7278     return;
7279   }
7280   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7281
7282   connect_msg = (struct GNUNET_MESH_ConnectPeerByType *) message;
7283
7284   /* Sanity check for message size */
7285   if (sizeof (struct GNUNET_MESH_ConnectPeerByType) !=
7286       ntohs (connect_msg->header.size))
7287   {
7288     GNUNET_break (0);
7289     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7290     return;
7291   }
7292
7293   /* Tunnel exists? */
7294   tid = ntohl (connect_msg->tunnel_id);
7295   t = tunnel_get_by_local_id (c, tid);
7296   if (NULL == t)
7297   {
7298     GNUNET_break (0);
7299     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7300     return;
7301   }
7302
7303   /* Does client own tunnel? */
7304   if (t->owner->handle != client)
7305   {
7306     GNUNET_break (0);
7307     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7308     return;
7309   }
7310
7311   /* Do WE have the service? */
7312   t->type = ntohl (connect_msg->type);
7313   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " type requested: %u\n", t->type);
7314   GNUNET_CRYPTO_hash (&t->type, sizeof (GNUNET_MESH_ApplicationType), &hash);
7315   if (GNUNET_CONTAINER_multihashmap_contains (applications, &hash) ==
7316       GNUNET_YES)
7317   {
7318     /* Yes! Fast forward, add ourselves to the tunnel and send the
7319      * good news to the client, and alert the destination client of
7320      * an incoming tunnel.
7321      *
7322      * FIXME send a path create to self, avoid code duplication
7323      */
7324     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " available locally\n");
7325     GNUNET_CONTAINER_multihashmap_put (t->peers, &my_full_id.hashPubKey,
7326                                        peer_info_get (&my_full_id),
7327                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
7328
7329     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " notifying client\n");
7330     send_client_peer_connected (t, myid);
7331     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Done\n");
7332     GNUNET_SERVER_receive_done (client, GNUNET_OK);
7333
7334     t->local_tid_dest = next_local_tid++;
7335     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
7336     GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
7337                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
7338
7339     return;
7340   }
7341   /* Ok, lets find a peer offering the service */
7342   if (NULL != t->dht_get_type)
7343   {
7344     GNUNET_DHT_get_stop (t->dht_get_type);
7345   }
7346   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " looking in DHT for %s\n",
7347               GNUNET_h2s (&hash));
7348   t->dht_get_type =
7349       GNUNET_DHT_get_start (dht_handle, 
7350                             GNUNET_BLOCK_TYPE_MESH_PEER_BY_TYPE,
7351                             &hash,
7352                             dht_replication_level,
7353                             GNUNET_DHT_RO_RECORD_ROUTE |
7354                             GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
7355                             NULL, 0,
7356                             &dht_get_type_handler, t);
7357
7358   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7359   return;
7360 }
7361
7362
7363 /**
7364  * Handler for connection requests to new peers by a string service description.
7365  *
7366  * @param cls closure
7367  * @param client identification of the client
7368  * @param message the actual message, which includes messages the client wants
7369  */
7370 static void
7371 handle_local_connect_by_string (void *cls, struct GNUNET_SERVER_Client *client,
7372                                 const struct GNUNET_MessageHeader *message)
7373 {
7374   struct GNUNET_MESH_ConnectPeerByString *msg;
7375   struct MeshRegexSearchContext *ctx;
7376   struct MeshRegexSearchInfo *info;
7377   struct GNUNET_DHT_GetHandle *get_h;
7378   struct GNUNET_HashCode key;
7379   struct MeshTunnel *t;
7380   struct MeshClient *c;
7381   MESH_TunnelNumber tid;
7382   const char *string;
7383   size_t size;
7384   size_t len;
7385   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7386               "Connect by string started\n");
7387   msg = (struct GNUNET_MESH_ConnectPeerByString *) message;
7388   size = htons (message->size);
7389
7390   /* Sanity check for client registration */
7391   if (NULL == (c = client_get (client)))
7392   {
7393     GNUNET_break (0);
7394     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7395     return;
7396   }
7397   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7398
7399   /* Message size sanity check */
7400   if (sizeof(struct GNUNET_MESH_ConnectPeerByString) >= size)
7401   {
7402     GNUNET_break (0);
7403     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7404     return;
7405   }
7406
7407   /* Tunnel exists? */
7408   tid = ntohl (msg->tunnel_id);
7409   t = tunnel_get_by_local_id (c, tid);
7410   if (NULL == t)
7411   {
7412     GNUNET_break (0);
7413     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7414     return;
7415   }
7416
7417   /* Does client own tunnel? */
7418   if (t->owner->handle != client)
7419   {
7420     GNUNET_break (0);
7421     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7422     return;
7423   }
7424
7425   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7426               "  on tunnel %s [%u]\n",
7427               GNUNET_i2s(&my_full_id),
7428               t->id.tid);
7429
7430   /* Only one connect_by_string allowed at the same time! */
7431   /* FIXME: allow more, return handle at api level to cancel, document */
7432   if (NULL != t->regex_ctx)
7433   {
7434     GNUNET_break (0);
7435     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7436     return;
7437   }
7438
7439   /* Find string itself */
7440   len = size - sizeof(struct GNUNET_MESH_ConnectPeerByString);
7441   string = (const char *) &msg[1];
7442
7443   /* Initialize context */
7444   size = GNUNET_REGEX_get_first_key(string, len, &key);
7445   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7446               "  consumed %u bits out of %u\n", size, len);
7447   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7448               "  looking for %s\n", GNUNET_h2s (&key));
7449
7450   info = GNUNET_malloc (sizeof (struct MeshRegexSearchInfo));
7451   info->t = t;
7452   info->description = GNUNET_malloc (len + 1);
7453   memcpy (info->description, string, len);
7454   info->description[len] = '\0';
7455   info->dht_get_handles = GNUNET_CONTAINER_multihashmap_create(32, GNUNET_NO);
7456   info->dht_get_results = GNUNET_CONTAINER_multihashmap_create(32, GNUNET_NO);
7457   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   string: %s\n", info->description);
7458
7459   ctx = GNUNET_malloc (sizeof (struct MeshRegexSearchContext));
7460   ctx->position = size;
7461   ctx->info = info;
7462   t->regex_ctx = ctx;
7463
7464   GNUNET_array_append (info->contexts, info->n_contexts, ctx);
7465
7466   /* Start search in DHT */
7467   get_h = GNUNET_DHT_get_start (dht_handle,    /* handle */
7468                                 GNUNET_BLOCK_TYPE_MESH_REGEX, /* type */
7469                                 &key,     /* key to search */
7470                                 dht_replication_level, /* replication level */
7471                                 GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
7472                                 NULL,       /* xquery */ // FIXME BLOOMFILTER
7473                                 0,     /* xquery bits */ // FIXME BLOOMFILTER SIZE
7474                                 &dht_get_string_handler, ctx);
7475
7476   GNUNET_break (GNUNET_OK ==
7477                 GNUNET_CONTAINER_multihashmap_put(info->dht_get_handles,
7478                                                   &key,
7479                                                   get_h,
7480                                                   GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
7481
7482   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7483   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "connect by string processed\n");
7484 }
7485
7486
7487 /**
7488  * Handler for client traffic directed to one peer
7489  *
7490  * @param cls closure
7491  * @param client identification of the client
7492  * @param message the actual message
7493  */
7494 static void
7495 handle_local_unicast (void *cls, struct GNUNET_SERVER_Client *client,
7496                       const struct GNUNET_MessageHeader *message)
7497 {
7498   struct MeshClient *c;
7499   struct MeshTunnel *t;
7500   struct MeshPeerInfo *pi;
7501   struct GNUNET_MESH_Unicast *data_msg;
7502   MESH_TunnelNumber tid;
7503   size_t size;
7504
7505   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7506               "Got a unicast request from a client!\n");
7507
7508   /* Sanity check for client registration */
7509   if (NULL == (c = client_get (client)))
7510   {
7511     GNUNET_break (0);
7512     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7513     return;
7514   }
7515   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7516
7517   data_msg = (struct GNUNET_MESH_Unicast *) message;
7518
7519   /* Sanity check for message size */
7520   size = ntohs (message->size);
7521   if (sizeof (struct GNUNET_MESH_Unicast) +
7522       sizeof (struct GNUNET_MessageHeader) > size)
7523   {
7524     GNUNET_break (0);
7525     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7526     return;
7527   }
7528
7529   /* Tunnel exists? */
7530   tid = ntohl (data_msg->tid);
7531   t = tunnel_get_by_local_id (c, tid);
7532   if (NULL == t)
7533   {
7534     GNUNET_break (0);
7535     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7536     return;
7537   }
7538
7539   /*  Is it a local tunnel? Then, does client own the tunnel? */
7540   if (t->owner->handle != client)
7541   {
7542     GNUNET_break (0);
7543     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7544     return;
7545   }
7546
7547   pi = GNUNET_CONTAINER_multihashmap_get (t->peers,
7548                                           &data_msg->destination.hashPubKey);
7549   /* Is the selected peer in the tunnel? */
7550   if (NULL == pi)
7551   {
7552     GNUNET_break (0);
7553     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7554     return;
7555   }
7556
7557   /* PID should be as expected */
7558   if (ntohl (data_msg->pid) != t->fwd_pid + 1)
7559   {
7560     GNUNET_break (0);
7561     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7562               "Unicast PID, expected %u, got %u\n",
7563               t->fwd_pid + 1, ntohl (data_msg->pid));
7564     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7565     return;
7566   }
7567
7568   /* Ok, everything is correct, send the message
7569    * (pretend we got it from a mesh peer)
7570    */
7571   {
7572     /* Work around const limitation */
7573     char buf[ntohs (message->size)] GNUNET_ALIGN;
7574     struct GNUNET_MESH_Unicast *copy;
7575
7576     copy = (struct GNUNET_MESH_Unicast *) buf;
7577     memcpy (buf, data_msg, size);
7578     copy->oid = my_full_id;
7579     copy->tid = htonl (t->id.tid);
7580     copy->ttl = htonl (default_ttl);
7581     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7582                 "  calling generic handler...\n");
7583     handle_mesh_data_unicast (NULL, &my_full_id, &copy->header, NULL, 0);
7584   }
7585   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "receive done OK\n");
7586   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7587
7588   return;
7589 }
7590
7591
7592 /**
7593  * Handler for client traffic directed to the origin
7594  *
7595  * @param cls closure
7596  * @param client identification of the client
7597  * @param message the actual message
7598  */
7599 static void
7600 handle_local_to_origin (void *cls, struct GNUNET_SERVER_Client *client,
7601                         const struct GNUNET_MessageHeader *message)
7602 {
7603   struct GNUNET_MESH_ToOrigin *data_msg;
7604   struct MeshTunnelClientInfo *clinfo;
7605   struct MeshClient *c;
7606   struct MeshTunnel *t;
7607   MESH_TunnelNumber tid;
7608   size_t size;
7609
7610   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7611               "Got a ToOrigin request from a client!\n");
7612   /* Sanity check for client registration */
7613   if (NULL == (c = client_get (client)))
7614   {
7615     GNUNET_break (0);
7616     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7617     return;
7618   }
7619   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7620
7621   data_msg = (struct GNUNET_MESH_ToOrigin *) message;
7622
7623   /* Sanity check for message size */
7624   size = ntohs (message->size);
7625   if (sizeof (struct GNUNET_MESH_ToOrigin) +
7626       sizeof (struct GNUNET_MessageHeader) > size)
7627   {
7628     GNUNET_break (0);
7629     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7630     return;
7631   }
7632
7633   /* Tunnel exists? */
7634   tid = ntohl (data_msg->tid);
7635   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
7636   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
7637   {
7638     GNUNET_break (0);
7639     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7640     return;
7641   }
7642   t = tunnel_get_by_local_id (c, tid);
7643   if (NULL == t)
7644   {
7645     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
7646     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
7647     GNUNET_break (0);
7648     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7649     return;
7650   }
7651
7652   /*  It should be sent by someone who has this as incoming tunnel. */
7653   if (GNUNET_NO == client_knows_tunnel (c, t))
7654   {
7655     GNUNET_break (0);
7656     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7657     return;
7658   }
7659
7660   /* PID should be as expected */
7661   clinfo = tunnel_get_client_fc (t, c);
7662   if (ntohl (data_msg->pid) != clinfo->bck_pid + 1)
7663   {
7664     GNUNET_break (0);
7665     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7666                 "To Origin PID, expected %u, got %u\n",
7667                 clinfo->bck_pid + 1,
7668                 ntohl (data_msg->pid));
7669     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7670     return;
7671   }
7672
7673   /* Ok, everything is correct, send the message
7674    * (pretend we got it from a mesh peer)
7675    */
7676   clinfo->bck_pid++;
7677   {
7678     char buf[ntohs (message->size)] GNUNET_ALIGN;
7679     struct GNUNET_MESH_ToOrigin *copy;
7680
7681     /* Work around const limitation */
7682     copy = (struct GNUNET_MESH_ToOrigin *) buf;
7683     memcpy (buf, data_msg, size);
7684     GNUNET_PEER_resolve (t->id.oid, &copy->oid);
7685     copy->tid = htonl (t->id.tid);
7686     copy->ttl = htonl (default_ttl);
7687     if (ntohl (copy->pid) != (t->bck_pid + 1))
7688     {
7689       GNUNET_break (0);
7690       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7691                   "To Origin PID, expected %u, got %u\n",
7692                   t->bck_pid + 1,
7693                   ntohl (copy->pid));
7694       return;
7695     }
7696     copy->sender = my_full_id;
7697     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7698                 "  calling generic handler...\n");
7699     handle_mesh_data_to_orig (NULL, &my_full_id, &copy->header, NULL, 0);
7700   }
7701   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7702
7703   return;
7704 }
7705
7706
7707 /**
7708  * Handler for client traffic directed to all peers in a tunnel
7709  *
7710  * @param cls closure
7711  * @param client identification of the client
7712  * @param message the actual message
7713  */
7714 static void
7715 handle_local_multicast (void *cls, struct GNUNET_SERVER_Client *client,
7716                         const struct GNUNET_MessageHeader *message)
7717 {
7718   struct MeshClient *c;
7719   struct MeshTunnel *t;
7720   struct GNUNET_MESH_Multicast *data_msg;
7721   MESH_TunnelNumber tid;
7722
7723   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7724               "Got a multicast request from a client!\n");
7725
7726   /* Sanity check for client registration */
7727   if (NULL == (c = client_get (client)))
7728   {
7729     GNUNET_break (0);
7730     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7731     return;
7732   }
7733   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7734
7735   data_msg = (struct GNUNET_MESH_Multicast *) message;
7736
7737   /* Sanity check for message size */
7738   if (sizeof (struct GNUNET_MESH_Multicast) +
7739       sizeof (struct GNUNET_MessageHeader) > ntohs (data_msg->header.size))
7740   {
7741     GNUNET_break (0);
7742     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7743     return;
7744   }
7745
7746   /* Tunnel exists? */
7747   tid = ntohl (data_msg->tid);
7748   t = tunnel_get_by_local_id (c, tid);
7749   if (NULL == t)
7750   {
7751     GNUNET_break (0);
7752     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
7753     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
7754     GNUNET_break (0);
7755     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7756     return;
7757   }
7758
7759   /* Does client own tunnel? */
7760   if (t->owner->handle != client)
7761   {
7762     GNUNET_break (0);
7763     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7764     return;
7765   }
7766
7767   /* PID should be as expected */
7768   if (ntohl (data_msg->pid) != t->fwd_pid + 1)
7769   {
7770     GNUNET_break (0);
7771     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7772               "Multicast PID, expected %u, got %u\n",
7773               t->fwd_pid + 1, ntohl (data_msg->pid));
7774     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7775     return;
7776   }
7777
7778   {
7779     char buf[ntohs (message->size)] GNUNET_ALIGN;
7780     struct GNUNET_MESH_Multicast *copy;
7781
7782     copy = (struct GNUNET_MESH_Multicast *) buf;
7783     memcpy (buf, message, ntohs (message->size));
7784     copy->oid = my_full_id;
7785     copy->tid = htonl (t->id.tid);
7786     copy->ttl = htonl (default_ttl);
7787     GNUNET_assert (ntohl (copy->pid) == (t->fwd_pid + 1));
7788     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7789                 "  calling generic handler...\n");
7790     handle_mesh_data_multicast (client, &my_full_id, &copy->header, NULL, 0);
7791   }
7792
7793   GNUNET_SERVER_receive_done (t->owner->handle, GNUNET_OK);
7794   return;
7795 }
7796
7797
7798 /**
7799  * Handler for client's ACKs for payload traffic.
7800  *
7801  * @param cls Closure (unused).
7802  * @param client Identification of the client.
7803  * @param message The actual message.
7804  */
7805 static void
7806 handle_local_ack (void *cls, struct GNUNET_SERVER_Client *client,
7807                   const struct GNUNET_MessageHeader *message)
7808 {
7809   struct GNUNET_MESH_LocalAck *msg;
7810   struct MeshTunnel *t;
7811   struct MeshClient *c;
7812   MESH_TunnelNumber tid;
7813   uint32_t ack;
7814
7815   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a local ACK\n");
7816   /* Sanity check for client registration */
7817   if (NULL == (c = client_get (client)))
7818   {
7819     GNUNET_break (0);
7820     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7821     return;
7822   }
7823   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7824
7825   msg = (struct GNUNET_MESH_LocalAck *) message;
7826
7827   /* Tunnel exists? */
7828   tid = ntohl (msg->tunnel_id);
7829   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
7830   t = tunnel_get_by_local_id (c, tid);
7831   if (NULL == t)
7832   {
7833     GNUNET_break (0);
7834     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
7835     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
7836     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7837     return;
7838   }
7839
7840   ack = ntohl (msg->max_pid);
7841   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ack %u\n", ack);
7842
7843   /* Does client own tunnel? I.E: Is this and ACK for BCK traffic? */
7844   if (NULL != t->owner && t->owner->handle == client)
7845   {
7846     /* The client owns the tunnel, ACK is for data to_origin, send BCK ACK. */
7847     t->bck_ack = ack;
7848     tunnel_send_bck_ack(t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
7849   }
7850   else
7851   {
7852     /* The client doesn't own the tunnel, this ACK is for FWD traffic. */
7853     tunnel_set_client_fwd_ack (t, c, ack);
7854     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
7855   }
7856
7857   GNUNET_SERVER_receive_done (client, GNUNET_OK);  
7858
7859   return;
7860 }
7861
7862
7863 /**
7864  * Functions to handle messages from clients
7865  */
7866 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
7867   {&handle_local_new_client, NULL,
7868    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
7869   {&handle_local_announce_regex, NULL,
7870    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ANNOUNCE_REGEX, 0},
7871   {&handle_local_tunnel_create, NULL,
7872    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
7873    sizeof (struct GNUNET_MESH_TunnelMessage)},
7874   {&handle_local_tunnel_destroy, NULL,
7875    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
7876    sizeof (struct GNUNET_MESH_TunnelMessage)},
7877   {&handle_local_tunnel_speed, NULL,
7878    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MIN,
7879    sizeof (struct GNUNET_MESH_TunnelMessage)},
7880   {&handle_local_tunnel_speed, NULL,
7881    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MAX,
7882    sizeof (struct GNUNET_MESH_TunnelMessage)},
7883   {&handle_local_tunnel_buffer, NULL,
7884    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER,
7885    sizeof (struct GNUNET_MESH_TunnelMessage)},
7886   {&handle_local_tunnel_buffer, NULL,
7887    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER,
7888    sizeof (struct GNUNET_MESH_TunnelMessage)},
7889   {&handle_local_connect_add, NULL,
7890    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD,
7891    sizeof (struct GNUNET_MESH_PeerControl)},
7892   {&handle_local_connect_del, NULL,
7893    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL,
7894    sizeof (struct GNUNET_MESH_PeerControl)},
7895   {&handle_local_blacklist, NULL,
7896    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_BLACKLIST,
7897    sizeof (struct GNUNET_MESH_PeerControl)},
7898   {&handle_local_unblacklist, NULL,
7899    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_UNBLACKLIST,
7900    sizeof (struct GNUNET_MESH_PeerControl)},
7901   {&handle_local_connect_by_type, NULL,
7902    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE,
7903    sizeof (struct GNUNET_MESH_ConnectPeerByType)},
7904   {&handle_local_connect_by_string, NULL,
7905    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_STRING, 0},
7906   {&handle_local_unicast, NULL,
7907    GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
7908   {&handle_local_to_origin, NULL,
7909    GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
7910   {&handle_local_multicast, NULL,
7911    GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
7912   {&handle_local_ack, NULL,
7913    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK,
7914    sizeof (struct GNUNET_MESH_LocalAck)},
7915   {NULL, NULL, 0, 0}
7916 };
7917
7918
7919 /**
7920  * To be called on core init/fail.
7921  *
7922  * @param cls service closure
7923  * @param server handle to the server for this service
7924  * @param identity the public identity of this peer
7925  */
7926 static void
7927 core_init (void *cls, struct GNUNET_CORE_Handle *server,
7928            const struct GNUNET_PeerIdentity *identity)
7929 {
7930   static int i = 0;
7931   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
7932   core_handle = server;
7933   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)) ||
7934       NULL == server)
7935   {
7936     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
7937     GNUNET_SCHEDULER_shutdown (); // Try gracefully
7938     if (10 < i++)
7939       GNUNET_abort(); // Try harder
7940   }
7941   return;
7942 }
7943
7944
7945 /**
7946  * Method called whenever a given peer connects.
7947  *
7948  * @param cls closure
7949  * @param peer peer identity this notification is about
7950  * @param atsi performance data for the connection
7951  * @param atsi_count number of records in 'atsi'
7952  */
7953 static void
7954 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
7955               const struct GNUNET_ATS_Information *atsi,
7956               unsigned int atsi_count)
7957 {
7958   struct MeshPeerInfo *peer_info;
7959   struct MeshPeerPath *path;
7960
7961   DEBUG_CONN ("Peer connected\n");
7962   DEBUG_CONN ("     %s\n", GNUNET_i2s (&my_full_id));
7963   peer_info = peer_info_get (peer);
7964   if (myid == peer_info->id)
7965   {
7966     DEBUG_CONN ("     (self)\n");
7967     return;
7968   }
7969   else
7970   {
7971     DEBUG_CONN ("     %s\n", GNUNET_i2s (peer));
7972   }
7973   path = path_new (2);
7974   path->peers[0] = myid;
7975   path->peers[1] = peer_info->id;
7976   GNUNET_PEER_change_rc (myid, 1);
7977   GNUNET_PEER_change_rc (peer_info->id, 1);
7978   peer_info_add_path (peer_info, path, GNUNET_YES);
7979   GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
7980   return;
7981 }
7982
7983
7984 /**
7985  * Method called whenever a peer disconnects.
7986  *
7987  * @param cls closure
7988  * @param peer peer identity this notification is about
7989  */
7990 static void
7991 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
7992 {
7993   struct MeshPeerInfo *pi;
7994   struct MeshPeerQueue *q;
7995   struct MeshPeerQueue *n;
7996
7997   DEBUG_CONN ("Peer disconnected\n");
7998   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
7999   if (NULL == pi)
8000   {
8001     GNUNET_break (0);
8002     return;
8003   }
8004   q = pi->queue_head;
8005   while (NULL != q)
8006   {
8007       n = q->next;
8008       /* TODO try to reroute this traffic instead */
8009       queue_destroy(q, GNUNET_YES);
8010       q = n;
8011   }
8012   if (NULL != pi->core_transmit)
8013   {
8014     GNUNET_CORE_notify_transmit_ready_cancel(pi->core_transmit);
8015     pi->core_transmit = NULL;
8016   }
8017   peer_info_remove_path (pi, pi->id, myid);
8018   if (myid == pi->id)
8019   {
8020     DEBUG_CONN ("     (self)\n");
8021   }
8022   GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
8023   return;
8024 }
8025
8026
8027 /******************************************************************************/
8028 /************************      MAIN FUNCTIONS      ****************************/
8029 /******************************************************************************/
8030
8031 /**
8032  * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
8033  *
8034  * @param cls closure
8035  * @param key current key code
8036  * @param value value in the hash map
8037  * @return GNUNET_YES if we should continue to iterate,
8038  *         GNUNET_NO if not.
8039  */
8040 static int
8041 shutdown_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
8042 {
8043   struct MeshTunnel *t = value;
8044
8045   tunnel_destroy (t);
8046   return GNUNET_YES;
8047 }
8048
8049 /**
8050  * Iterator over peer hash map entries to destroy the tunnel during shutdown.
8051  *
8052  * @param cls closure
8053  * @param key current key code
8054  * @param value value in the hash map
8055  * @return GNUNET_YES if we should continue to iterate,
8056  *         GNUNET_NO if not.
8057  */
8058 static int
8059 shutdown_peer (void *cls, const struct GNUNET_HashCode * key, void *value)
8060 {
8061   struct MeshPeerInfo *p = value;
8062   struct MeshPeerQueue *q;
8063   struct MeshPeerQueue *n;
8064
8065   q = p->queue_head;
8066   while (NULL != q)
8067   {
8068       n = q->next;
8069       if (q->peer == p)
8070       {
8071         queue_destroy(q, GNUNET_YES);
8072       }
8073       q = n;
8074   }
8075   peer_info_destroy (p);
8076   return GNUNET_YES;
8077 }
8078
8079
8080 /**
8081  * Task run during shutdown.
8082  *
8083  * @param cls unused
8084  * @param tc unused
8085  */
8086 static void
8087 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
8088 {
8089   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
8090
8091   if (core_handle != NULL)
8092   {
8093     GNUNET_CORE_disconnect (core_handle);
8094     core_handle = NULL;
8095   }
8096  if (NULL != keygen)
8097   {
8098     GNUNET_CRYPTO_rsa_key_create_stop (keygen);
8099     keygen = NULL;
8100   }
8101   GNUNET_CONTAINER_multihashmap_iterate (tunnels, &shutdown_tunnel, NULL);
8102   GNUNET_CONTAINER_multihashmap_iterate (peers, &shutdown_peer, NULL);
8103   if (dht_handle != NULL)
8104   {
8105     GNUNET_DHT_disconnect (dht_handle);
8106     dht_handle = NULL;
8107   }
8108   if (nc != NULL)
8109   {
8110     GNUNET_SERVER_notification_context_destroy (nc);
8111     nc = NULL;
8112   }
8113   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
8114   {
8115     GNUNET_SCHEDULER_cancel (announce_id_task);
8116     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
8117   }
8118   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
8119 }
8120
8121
8122 /**
8123  * Callback for hostkey read/generation
8124  *
8125  * @param cls NULL
8126  * @param pk the private key
8127  * @param emsg error message
8128  */
8129 static void
8130 key_generation_cb (void *cls,
8131                    struct GNUNET_CRYPTO_RsaPrivateKey *pk,
8132                    const char *emsg)
8133 {
8134   struct MeshPeerInfo *peer;
8135   struct MeshPeerPath *p;
8136
8137   keygen = NULL;  
8138   if (NULL == pk)
8139   {
8140     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8141                 _("Mesh service could not access hostkey.  Exiting.\n"));
8142     GNUNET_SCHEDULER_shutdown ();
8143     return;
8144   }
8145   my_private_key = pk;
8146   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
8147   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
8148                       &my_full_id.hashPubKey);
8149   myid = GNUNET_PEER_intern (&my_full_id);
8150   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
8151               "Mesh for peer [%s] starting\n",
8152               GNUNET_i2s(&my_full_id));
8153
8154 //   transport_handle = GNUNET_TRANSPORT_connect(c,
8155 //                                               &my_full_id,
8156 //                                               NULL,
8157 //                                               NULL,
8158 //                                               NULL,
8159 //                                               NULL);
8160
8161
8162
8163   next_tid = 0;
8164   next_local_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
8165
8166
8167   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
8168   nc = GNUNET_SERVER_notification_context_create (server_handle, 1);
8169   GNUNET_SERVER_disconnect_notify (server_handle,
8170                                    &handle_local_client_disconnect, NULL);
8171
8172
8173   clients = NULL;
8174   clients_tail = NULL;
8175   next_client_id = 0;
8176
8177   announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
8178   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
8179
8180   /* Create a peer_info for the local peer */
8181   peer = peer_info_get (&my_full_id);
8182   p = path_new (1);
8183   p->peers[0] = myid;
8184   GNUNET_PEER_change_rc (myid, 1);
8185   peer_info_add_path (peer, p, GNUNET_YES);
8186   GNUNET_SERVER_resume (server_handle);
8187   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Mesh service running\n");
8188 }
8189
8190
8191 /**
8192  * Process mesh requests.
8193  *
8194  * @param cls closure
8195  * @param server the initialized server
8196  * @param c configuration to use
8197  */
8198 static void
8199 run (void *cls, struct GNUNET_SERVER_Handle *server,
8200      const struct GNUNET_CONFIGURATION_Handle *c)
8201 {
8202   char *keyfile;
8203
8204   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
8205   server_handle = server;
8206   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
8207                                      NULL,      /* Closure passed to MESH functions */
8208                                      &core_init,        /* Call core_init once connected */
8209                                      &core_connect,     /* Handle connects */
8210                                      &core_disconnect,  /* remove peers on disconnects */
8211                                      NULL,      /* Don't notify about all incoming messages */
8212                                      GNUNET_NO, /* For header only in notification */
8213                                      NULL,      /* Don't notify about all outbound messages */
8214                                      GNUNET_NO, /* For header-only out notification */
8215                                      core_handlers);    /* Register these handlers */
8216
8217   if (core_handle == NULL)
8218   {
8219     GNUNET_break (0);
8220     GNUNET_SCHEDULER_shutdown ();
8221     return;
8222   }
8223
8224   if (GNUNET_OK !=
8225       GNUNET_CONFIGURATION_get_value_filename (c, "GNUNETD", "HOSTKEY",
8226                                                &keyfile))
8227   {
8228     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8229                 _
8230                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8231                 "mesh", "hostkey");
8232     GNUNET_SCHEDULER_shutdown ();
8233     return;
8234   }
8235
8236   if (GNUNET_OK !=
8237       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_PATH_TIME",
8238                                            &refresh_path_time))
8239   {
8240     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8241                 _
8242                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8243                 "mesh", "refresh path time");
8244     GNUNET_SCHEDULER_shutdown ();
8245     return;
8246   }
8247
8248   if (GNUNET_OK !=
8249       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "APP_ANNOUNCE_TIME",
8250                                            &app_announce_time))
8251   {
8252     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8253                 _
8254                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8255                 "mesh", "app announce time");
8256     GNUNET_SCHEDULER_shutdown ();
8257     return;
8258   }
8259
8260   if (GNUNET_OK !=
8261       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "ID_ANNOUNCE_TIME",
8262                                            &id_announce_time))
8263   {
8264     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8265                 _
8266                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8267                 "mesh", "id announce time");
8268     GNUNET_SCHEDULER_shutdown ();
8269     return;
8270   }
8271   else
8272   {
8273   }
8274
8275   if (GNUNET_OK !=
8276       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "UNACKNOWLEDGED_WAIT",
8277                                            &unacknowledged_wait_time))
8278   {
8279     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8280                 _
8281                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8282                 "mesh", "unacknowledged wait time");
8283     GNUNET_SCHEDULER_shutdown ();
8284     return;
8285   }
8286
8287   if (GNUNET_OK !=
8288       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "CONNECT_TIMEOUT",
8289                                            &connect_timeout))
8290   {
8291     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8292                 _
8293                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8294                 "mesh", "connect timeout");
8295     GNUNET_SCHEDULER_shutdown ();
8296     return;
8297   }
8298
8299   if (GNUNET_OK !=
8300       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
8301                                              &max_msgs_queue))
8302   {
8303     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8304                 _
8305                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8306                 "mesh", "max msgs queue");
8307     GNUNET_SCHEDULER_shutdown ();
8308     return;
8309   }
8310
8311   if (GNUNET_OK !=
8312       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_TUNNELS",
8313                                              &max_tunnels))
8314   {
8315     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8316                 _
8317                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8318                 "mesh", "max tunnels");
8319     GNUNET_SCHEDULER_shutdown ();
8320     return;
8321   }
8322
8323   if (GNUNET_OK !=
8324       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
8325                                              &default_ttl))
8326   {
8327     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
8328                 _
8329                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
8330                 "mesh", "default ttl", 64);
8331     default_ttl = 64;
8332   }
8333
8334   if (GNUNET_OK !=
8335       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DHT_REPLICATION_LEVEL",
8336                                              &dht_replication_level))
8337   {
8338     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
8339                 _
8340                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
8341                 "mesh", "dht replication level", 10);
8342     dht_replication_level = 10;
8343   }
8344
8345   tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
8346   incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
8347   peers = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
8348   applications = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
8349   types = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
8350
8351   dht_handle = GNUNET_DHT_connect (c, 64);
8352   if (NULL == dht_handle)
8353   {
8354     GNUNET_break (0);
8355   }
8356   stats = GNUNET_STATISTICS_create ("mesh", c);
8357
8358   GNUNET_SERVER_suspend (server_handle);
8359   /* Scheduled the task to clean up when shutdown is called */
8360   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
8361                                 NULL);
8362   keygen = GNUNET_CRYPTO_rsa_key_create_start (keyfile, &key_generation_cb, NULL);
8363   GNUNET_free (keyfile);
8364 }
8365
8366
8367 /**
8368  * The main function for the mesh service.
8369  *
8370  * @param argc number of arguments from the command line
8371  * @param argv command line arguments
8372  * @return 0 ok, 1 on error
8373  */
8374 int
8375 main (int argc, char *const *argv)
8376 {
8377   int ret;
8378   int r;
8379
8380   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
8381   r = GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
8382                           NULL);
8383   ret = (GNUNET_OK == r) ? 0 : 1;
8384   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");
8385
8386   INTERVAL_SHOW;
8387
8388   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
8389               "Mesh for peer [%s] FWD ACKs %u, BCK ACKs %u\n",
8390               GNUNET_i2s(&my_full_id), debug_fwd_ack, debug_bck_ack);
8391
8392   return ret;
8393 }