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