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