- debug, style
[oweals/gnunet.git] / src / mesh / gnunet-service-mesh.c
1 /*
2      This file is part of GNUnet.
3      (C) 2001-2012 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file mesh/gnunet-service-mesh.c
23  * @brief GNUnet MESH service
24  * @author Bartlomiej Polot
25  *
26  * STRUCTURE:
27  * - DATA STRUCTURES
28  * - GLOBAL VARIABLES
29  * - GENERAL HELPERS
30  * - PERIODIC FUNCTIONS
31  * - MESH NETWORK HANDLER HELPERS
32  * - MESH NETWORK HANDLES
33  * - MESH LOCAL HANDLER HELPERS
34  * - MESH LOCAL HANDLES
35  * - MAIN FUNCTIONS (main & run)
36  *
37  * TODO:
38  * - error reporting (CREATE/CHANGE/ADD/DEL?) -- new message!
39  * - partial disconnect reporting -- same as error reporting?
40  * - add ping message
41  * - relay corking down to core
42  * - set ttl relative to tree depth
43  * - Add data ACK count in path ACK
44  * - Make common GNUNET_MESH_Data header for unicast, to_orig, multicast
45  * TODO END
46  */
47
48 #include "platform.h"
49 #include "mesh.h"
50 #include "mesh_protocol.h"
51 #include "mesh_tunnel_tree.h"
52 #include "block_mesh.h"
53 #include "mesh_block_lib.h"
54 #include "gnunet_dht_service.h"
55 #include "gnunet_statistics_service.h"
56 #include "gnunet_regex_lib.h"
57
58 #define MESH_BLOOM_SIZE         128
59
60 #define MESH_DEBUG_DHT          GNUNET_NO
61 #define MESH_DEBUG_CONNECTION   GNUNET_NO
62 #define MESH_DEBUG_TIMING       __LINUX__ && GNUNET_NO
63
64 #if MESH_DEBUG_CONNECTION
65 #define DEBUG_CONN(...) GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
66 #else
67 #define DEBUG_CONN(...)
68 #endif
69
70 #if MESH_DEBUG_DHT
71 #define DEBUG_DHT(...) GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
72 #else
73 #define DEBUG_DHT(...)
74 #endif
75
76 #if MESH_DEBUG_TIMING
77 #include <time.h>
78 double __sum;
79 uint64_t __count;
80 struct timespec __mesh_start;
81 struct timespec __mesh_end;
82 #define INTERVAL_START clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &(__mesh_start))
83 #define INTERVAL_END \
84 do {\
85   clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &(__mesh_end));\
86   double __diff = __mesh_end.tv_nsec - __mesh_start.tv_nsec;\
87   if (__diff < 0) __diff += 1000000000;\
88   __sum += __diff;\
89   __count++;\
90 } while (0)
91 #define INTERVAL_SHOW \
92 if (0 < __count)\
93   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "AVG process time: %f ns\n", __sum/__count)
94 #else
95 #define INTERVAL_START
96 #define INTERVAL_END
97 #define INTERVAL_SHOW
98 #endif
99
100 /******************************************************************************/
101 /************************      DATA STRUCTURES     ****************************/
102 /******************************************************************************/
103
104 /** FWD declaration */
105 struct MeshPeerInfo;
106 struct MeshClient;
107
108
109 /**
110  * Struct representing a piece of data being sent to other peers
111  */
112 struct MeshData
113 {
114   /** Tunnel it belongs to. */
115   struct MeshTunnel *t;
116
117   /** How many remaining neighbors still hav't got it. */
118   unsigned int reference_counter;
119
120   /** How many remaining neighbors we need to send this to. */
121   unsigned int total_out;
122
123   /** Size of the data. */
124   size_t data_len;
125
126   /** Data itself */
127   void *data;
128 };
129
130
131 /**
132  * Struct containing info about a queued transmission to this peer
133  */
134 struct MeshPeerQueue
135 {
136     /**
137       * DLL next
138       */
139   struct MeshPeerQueue *next;
140
141     /**
142       * DLL previous
143       */
144   struct MeshPeerQueue *prev;
145
146     /**
147      * Peer this transmission is directed to.
148      */
149   struct MeshPeerInfo *peer;
150
151     /**
152      * Tunnel this message belongs to.
153      */
154   struct MeshTunnel *tunnel;
155
156     /**
157      * Pointer to info stucture used as cls.
158      */
159   void *cls;
160
161     /**
162      * Type of message
163      */
164   uint16_t type;
165
166     /**
167      * Size of the message
168      */
169   size_t size;
170 };
171
172
173 /**
174  * Struct containing all info possibly needed to build a package when called
175  * back by core.
176  */
177 struct MeshTransmissionDescriptor
178 {
179     /** ID of the tunnel this packet travels in */
180   struct MESH_TunnelID *origin;
181
182     /** Who was this message being sent to */
183   struct MeshPeerInfo *peer;
184
185     /** Ultimate destination of the packet */
186   GNUNET_PEER_Id destination;
187
188     /** Data descriptor */
189   struct MeshData* mesh_data;
190 };
191
192
193 /**
194  * Struct containing all information regarding a given peer
195  */
196 struct MeshPeerInfo
197 {
198     /**
199      * ID of the peer
200      */
201   GNUNET_PEER_Id id;
202
203     /**
204      * Last time we heard from this peer
205      */
206   struct GNUNET_TIME_Absolute last_contact;
207
208     /**
209      * Task handler for delayed connect task;
210      */
211   GNUNET_SCHEDULER_TaskIdentifier connect_task;
212
213     /**
214      * Number of attempts to reconnect so far
215      */
216   int n_reconnect_attempts;
217
218     /**
219      * Paths to reach the peer, ordered by ascending hop count
220      */
221   struct MeshPeerPath *path_head;
222
223     /**
224      * Paths to reach the peer, ordered by ascending hop count
225      */
226   struct MeshPeerPath *path_tail;
227
228     /**
229      * Handle to stop the DHT search for a path to this peer
230      */
231   struct GNUNET_DHT_GetHandle *dhtget;
232
233     /**
234      * Closure given to the DHT GET
235      */
236   struct MeshPathInfo *dhtgetcls;
237
238     /**
239      * Array of tunnels this peer participates in
240      * (most probably a small amount, therefore not a hashmap)
241      * When the path to the peer changes, notify these tunnels to let them
242      * re-adjust their path trees.
243      */
244   struct MeshTunnel **tunnels;
245
246     /**
247      * Number of tunnels this peers participates in
248      */
249   unsigned int ntunnels;
250
251    /**
252     * Transmission queue to core DLL head
253     */
254   struct MeshPeerQueue *queue_head;
255
256    /**
257     * Transmission queue to core DLL tail
258     */
259    struct MeshPeerQueue *queue_tail;
260
261    /**
262     * How many messages are in the queue to this peer.
263     */
264    unsigned int queue_n;
265
266    /**
267     * Handle to for queued transmissions
268     */
269   struct GNUNET_CORE_TransmitHandle *core_transmit;
270 };
271
272
273 /**
274  * Globally unique tunnel identification (owner + number)
275  * DO NOT USE OVER THE NETWORK
276  */
277 struct MESH_TunnelID
278 {
279     /**
280      * Node that owns the tunnel
281      */
282   GNUNET_PEER_Id oid;
283
284     /**
285      * Tunnel number to differentiate all the tunnels owned by the node oid
286      * ( tid < GNUNET_MESH_LOCAL_TUNNEL_ID_CLI )
287      */
288   MESH_TunnelNumber tid;
289 };
290
291
292 /**
293  * Struct containing all information regarding a tunnel
294  * For an intermediate node the improtant info used will be:
295  * - id        Tunnel unique identification
296  * - paths[0]  To know where to send it next
297  * - metainfo: ready, speeds, accounting
298  */
299 struct MeshTunnel
300 {
301     /**
302      * Tunnel ID
303      */
304   struct MESH_TunnelID id;
305
306     /**
307      * Local tunnel number ( >= GNUNET_MESH_LOCAL_TUNNEL_ID_CLI or 0 )
308      */
309   MESH_TunnelNumber local_tid;
310
311     /**
312      * Local tunnel number for local destination clients (incoming number)
313      * ( >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV or 0). All clients share the same
314      * number.
315      */
316   MESH_TunnelNumber local_tid_dest;
317
318     /**
319      * Is the speed on the tunnel limited to the slowest peer?
320      */
321   int speed_min;
322
323     /**
324      * Is the tunnel bufferless (minimum latency)?
325      */
326   int nobuffer;
327
328     /**
329      * Packet ID of the last fwd packet seen (sent/retransmitted/received).
330      */
331   uint32_t fwd_pid;
332
333     /**
334      * Packet ID of the last bck packet sent (unique counter per hop).
335      */
336   uint32_t bck_pid;
337
338   /**
339      * SKIP value for this tunnel.
340      */
341   uint32_t skip;
342
343     /**
344      * MeshTunnelChildInfo of all children, indexed by GNUNET_PEER_Id.
345      * Contains the Flow Control info: FWD ACK value received,
346      * last BCK ACK sent, PID and SKIP values.
347      */
348   struct GNUNET_CONTAINER_MultiHashMap *children_fc;
349
350     /**
351      * Last ACK sent towards the origin (for traffic towards leaf node).
352      */
353   uint32_t last_fwd_ack;
354
355   /**
356    * BCK ACK value received from the hop towards the owner of the tunnel,
357    * (previous node / owner): up to what message PID can we sent back to him.
358    */
359   uint32_t bck_ack;
360
361     /**
362      * How many messages are in the forward queue (towards leaves).
363      */
364   unsigned int fwd_queue_n;
365
366     /**
367      * How many messages do we accept in the forward queue.
368      */
369   unsigned int fwd_queue_max;
370
371     /**
372      * How many messages are in the backward queue (towards origin).
373      */
374   unsigned int bck_queue_n;
375
376     /**
377      * How many messages do we accept in the backward queue.
378     */
379    unsigned int bck_queue_max;
380
381     /**
382      * Task to poll peer in case of a stall.
383      */
384    GNUNET_SCHEDULER_TaskIdentifier fc_poll_bck;
385
386     /**
387      * Last time the tunnel was used
388      */
389   struct GNUNET_TIME_Absolute timestamp;
390
391     /**
392      * Peers in the tunnel, indexed by PeerIdentity -> (MeshPeerInfo)
393      * containing peers added by id or by type, not intermediate peers.
394      */
395   struct GNUNET_CONTAINER_MultiHashMap *peers;
396
397     /**
398      * Number of peers that are connected and potentially ready to receive data
399      */
400   unsigned int peers_ready;
401
402     /**
403      * Number of peers that have been added to the tunnel
404      */
405   unsigned int peers_total;
406
407     /**
408      * Client owner of the tunnel, if any
409      */
410   struct MeshClient *owner;
411
412     /**
413      * Clients that have been informed about and want to stay in the tunnel.
414      */
415   struct MeshClient **clients;
416
417     /**
418      * Flow control info for each client.
419      */
420   struct MeshTunnelClientInfo *clients_fc;
421
422   /**
423      * Number of elements in clients/clients_fc
424      */
425   unsigned int nclients;
426
427     /**
428      * Clients that have been informed but requested to leave the tunnel.
429      */
430   struct MeshClient **ignore;
431
432     /**
433      * Number of elements in clients
434      */
435   unsigned int nignore;
436
437     /**
438      * Blacklisted peers
439      */
440   GNUNET_PEER_Id *blacklisted;
441
442     /**
443      * Number of elements in blacklisted
444      */
445   unsigned int nblacklisted;
446
447   /**
448    * Bloomfilter (for peer identities) to stop circular routes
449    */
450   char bloomfilter[MESH_BLOOM_SIZE];
451
452   /**
453    * Tunnel paths
454    */
455   struct MeshTunnelTree *tree;
456
457   /**
458    * Application type we are looking for in this tunnel
459    */
460   GNUNET_MESH_ApplicationType type;
461
462     /**
463      * Used to search peers offering a service
464      */
465   struct GNUNET_DHT_GetHandle *dht_get_type;
466
467     /**
468      * Initial context of the regex search for a connect_by_string
469      */
470   struct MeshRegexSearchContext *regex_ctx;
471
472     /**
473      * Task to keep the used paths alive
474      */
475   GNUNET_SCHEDULER_TaskIdentifier path_refresh_task;
476
477     /**
478      * Task to destroy the tunnel after timeout
479      *
480      * FIXME: merge the two? a tunnel will have either
481      * a path refresh OR a timeout, never both!
482      */
483   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
484
485     /**
486      * Flag to signal the destruction of the tunnel.
487      * If this is set GNUNET_YES the tunnel will be destroyed
488      * when the queue is empty.
489      */
490   int destroy;
491 };
492
493
494 /**
495  * Info about a child node in a tunnel, needed to perform flow control.
496  */
497 struct MeshTunnelChildInfo
498 {
499     /**
500      * ID of the child node.
501      */
502   GNUNET_PEER_Id id;
503
504     /**
505      * SKIP value.
506      */
507   uint32_t skip;
508
509     /**
510      * Last sent PID.
511      */
512   uint32_t fwd_pid;
513
514     /**
515      * Last received PID.
516      */
517   uint32_t bck_pid;
518
519     /**
520      * Maximum PID allowed (FWD ACK received).
521      */
522   uint32_t fwd_ack;
523
524     /**
525      * Last ACK sent to that child (BCK ACK).
526      */
527   uint32_t bck_ack;
528
529     /**
530      * Circular buffer pointing to MeshPeerQueue elements for all
531      * payload traffic going to this child.
532      * Size determined by the tunnel queue size (@c t->fwd_queue_max).
533      */
534   struct MeshPeerQueue **send_buffer;
535
536     /**
537      * Index of the oldest element in the send_buffer.
538      */
539   unsigned int send_buffer_start;
540
541     /**
542      * How many elements are already in the buffer.
543      */
544   unsigned int send_buffer_n;
545
546     /**
547      * Tunnel this info is about
548      */
549   struct MeshTunnel *t;
550
551     /**
552      * Task to poll peer in case of a stall.
553      */
554    GNUNET_SCHEDULER_TaskIdentifier fc_poll;
555 };
556
557
558 /**
559  * Info about a leaf client of a tunnel, needed to perform flow control.
560  */
561 struct MeshTunnelClientInfo
562 {
563   /**
564    * PID of the last packet sent to the client (FWD).
565    */
566   uint32_t fwd_pid;
567
568   /**
569    * PID of the last packet received from the client (BCK).
570    */
571   uint32_t bck_pid;
572
573   /**
574    * Maximum PID allowed (FWD ACK received).
575    */
576   uint32_t fwd_ack;
577   
578   /**
579    * Last ACK sent to that child (BCK ACK).
580    */
581   uint32_t bck_ack;
582 };
583
584
585
586 /**
587  * Info collected during iteration of child nodes in order to get the ACK value
588  * for a tunnel.
589  */
590 struct MeshTunnelChildIteratorContext
591 {
592     /**
593      * Tunnel whose info is being collected.
594      */
595   struct MeshTunnel *t;
596
597     /**
598      * Is this context initialized? Is the value in max_child_ack valid?
599      */
600   int init;
601
602     /**
603      * Maximum child ACK so far.
604      */
605   uint32_t max_child_ack;
606
607     /**
608      * Number of children nodes
609      */
610   unsigned int nchildren;
611 };
612
613
614 /**
615  * Info needed to work with tunnel paths and peers
616  */
617 struct MeshPathInfo
618 {
619   /**
620    * Tunnel
621    */
622   struct MeshTunnel *t;
623
624   /**
625    * Neighbouring peer to whom we send the packet to
626    */
627   struct MeshPeerInfo *peer;
628
629   /**
630    * Path itself
631    */
632   struct MeshPeerPath *path;
633 };
634
635
636 /**
637  * Struct containing information about a client of the service
638  */
639 struct MeshClient
640 {
641     /**
642      * Linked list next
643      */
644   struct MeshClient *next;
645
646     /**
647      * Linked list prev
648      */
649   struct MeshClient *prev;
650
651     /**
652      * Tunnels that belong to this client, indexed by local id
653      */
654   struct GNUNET_CONTAINER_MultiHashMap *own_tunnels;
655
656    /**
657      * Tunnels this client has accepted, indexed by incoming local id
658      */
659   struct GNUNET_CONTAINER_MultiHashMap *incoming_tunnels;
660
661    /**
662      * Tunnels this client has rejected, indexed by incoming local id
663      */
664   struct GNUNET_CONTAINER_MultiHashMap *ignore_tunnels;
665     /**
666      * Handle to communicate with the client
667      */
668   struct GNUNET_SERVER_Client *handle;
669
670     /**
671      * Applications that this client has claimed to provide
672      */
673   struct GNUNET_CONTAINER_MultiHashMap *apps;
674
675     /**
676      * Messages that this client has declared interest in
677      */
678   struct GNUNET_CONTAINER_MultiHashMap *types;
679
680     /**
681      * Whether the client is active or shutting down (don't send confirmations
682      * to a client that is shutting down.
683      */
684   int shutting_down;
685
686     /**
687      * ID of the client, mainly for debug messages
688      */
689   unsigned int id;
690   
691     /**
692      * Regular expressions describing the services offered by this client.
693      */
694   char **regexes; // FIXME add timeout? API to remove a regex?
695
696     /**
697      * Number of regular expressions in regexes.
698      */
699   unsigned int n_regex;
700
701     /**
702      * Task to refresh all regular expresions in the DHT.
703      */
704   GNUNET_SCHEDULER_TaskIdentifier regex_announce_task;
705
706 };
707
708
709 /**
710  * Struct to keep information of searches of services described by a regex
711  * using a user-provided string service description.
712  */
713 struct MeshRegexSearchInfo
714 {
715     /**
716      * Which tunnel is this for
717      */
718   struct MeshTunnel *t;
719
720     /**
721      * User provided description of the searched service.
722      */
723   char *description;
724
725     /**
726      * Part of the description already consumed by the search.
727      */
728   size_t position;
729
730     /**
731      * Running DHT GETs.
732      */
733   struct GNUNET_CONTAINER_MultiHashMap *dht_get_handles;
734
735     /**
736      * Results from running DHT GETs.
737      */
738   struct GNUNET_CONTAINER_MultiHashMap *dht_get_results;
739
740     /**
741      * Contexts, for each running DHT GET. Free all on end of search.
742      */
743   struct MeshRegexSearchContext **contexts;
744
745     /**
746      * Number of contexts (branches/steps in search).
747      */
748   unsigned int n_contexts;
749
750     /**
751      * Peer that is connecting via connect_by_string. When connected, free ctx.
752      */
753   GNUNET_PEER_Id peer;
754
755     /**
756      * Other peers that are found but not yet being connected to.
757      */
758   GNUNET_PEER_Id *peers;
759
760     /**
761      * Number of elements in peers.
762      */
763   unsigned int n_peers;
764
765     /**
766      * Next peer to try to connect to.
767      */
768   unsigned int i_peer;
769
770     /**
771      * Timeout for a connect attempt.
772      * When reached, try to connect to a different peer, if any. If not,
773      * try the same peer again.
774      */
775   GNUNET_SCHEDULER_TaskIdentifier timeout;
776
777 };
778
779 /**
780  * Struct to keep state of running searches that have consumed a part of
781  * the inital string.
782  */
783 struct MeshRegexSearchContext
784 {
785     /**
786      * Part of the description already consumed by
787      * this particular search branch.
788      */
789   size_t position;
790
791     /**
792      * Information about the search.
793      */
794   struct MeshRegexSearchInfo *info;
795
796     /**
797      * We just want to look for one edge, the longer the better.
798      * Keep its length.
799      */
800   unsigned int longest_match;
801
802     /**
803      * Destination hash of the longest match.
804      */
805   struct GNUNET_HashCode hash;
806 };
807
808 /******************************************************************************/
809 /************************      DEBUG FUNCTIONS     ****************************/
810 /******************************************************************************/
811
812 #if MESH_DEBUG
813 /**
814  * GNUNET_SCHEDULER_Task for printing a message after some operation is done
815  * @param cls string to print
816  * @param success  GNUNET_OK if the PUT was transmitted,
817  *                GNUNET_NO on timeout,
818  *                GNUNET_SYSERR on disconnect from service
819  *                after the PUT message was transmitted
820  *                (so we don't know if it was received or not)
821  */
822
823 #if 0
824 static void
825 mesh_debug (void *cls, int success)
826 {
827   char *s = cls;
828
829   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s (%d)\n", s, success);
830 }
831 #endif
832
833 unsigned int debug_fwd_ack;
834 unsigned int debug_bck_ack;
835
836 #endif
837
838 /******************************************************************************/
839 /***********************      GLOBAL VARIABLES     ****************************/
840 /******************************************************************************/
841
842 /**
843  * Configuration parameters
844  */
845 static struct GNUNET_TIME_Relative refresh_path_time;
846 static struct GNUNET_TIME_Relative app_announce_time;
847 static struct GNUNET_TIME_Relative id_announce_time;
848 static struct GNUNET_TIME_Relative unacknowledged_wait_time;
849 static struct GNUNET_TIME_Relative connect_timeout;
850 static unsigned long long default_ttl;
851 static unsigned long long dht_replication_level;
852 static unsigned long long max_tunnels;
853 static unsigned long long max_msgs_queue;
854
855
856 /**
857  * Hostkey generation context
858  */
859 static struct GNUNET_CRYPTO_RsaKeyGenerationContext *keygen;
860
861 /**
862  * DLL with all the clients, head.
863  */
864 static struct MeshClient *clients;
865
866 /**
867  * DLL with all the clients, tail.
868  */
869 static struct MeshClient *clients_tail;
870
871 /**
872  * Tunnels known, indexed by MESH_TunnelID (MeshTunnel).
873  */
874 static struct GNUNET_CONTAINER_MultiHashMap *tunnels;
875
876 /**
877  * Number of tunnels known.
878  */
879 static unsigned long long n_tunnels;
880
881 /**
882  * Tunnels incoming, indexed by MESH_TunnelNumber
883  * (which is greater than GNUNET_MESH_LOCAL_TUNNEL_ID_SERV).
884  */
885 static struct GNUNET_CONTAINER_MultiHashMap *incoming_tunnels;
886
887 /**
888  * Peers known, indexed by PeerIdentity (MeshPeerInfo).
889  */
890 static struct GNUNET_CONTAINER_MultiHashMap *peers;
891
892 /*
893  * Handle to communicate with transport
894  */
895 // static struct GNUNET_TRANSPORT_Handle *transport_handle;
896
897 /**
898  * Handle to communicate with core.
899  */
900 static struct GNUNET_CORE_Handle *core_handle;
901
902 /**
903  * Handle to use DHT.
904  */
905 static struct GNUNET_DHT_Handle *dht_handle;
906
907 /**
908  * Handle to server.
909  */
910 static struct GNUNET_SERVER_Handle *server_handle;
911
912 /**
913  * Handle to the statistics service.
914  */
915 static struct GNUNET_STATISTICS_Handle *stats;
916
917 /**
918  * Notification context, to send messages to local clients.
919  */
920 static struct GNUNET_SERVER_NotificationContext *nc;
921
922 /**
923  * Local peer own ID (memory efficient handle).
924  */
925 static GNUNET_PEER_Id myid;
926
927 /**
928  * Local peer own ID (full value).
929  */
930 static struct GNUNET_PeerIdentity my_full_id;
931
932 /**
933  * Own private key.
934  */
935 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
936
937 /**
938  * Own public key.
939  */
940 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
941
942 /**
943  * Tunnel ID for the next created tunnel (global tunnel number).
944  */
945 static MESH_TunnelNumber next_tid;
946
947 /**
948  * Tunnel ID for the next incoming tunnel (local tunnel number).
949  */
950 static MESH_TunnelNumber next_local_tid;
951
952 /**
953  * All application types provided by this peer.
954  */
955 static struct GNUNET_CONTAINER_MultiHashMap *applications;
956
957 /**
958  * All message types clients of this peer are interested in.
959  */
960 static struct GNUNET_CONTAINER_MultiHashMap *types;
961
962 /**
963  * Task to periodically announce provided applications.
964  */
965 GNUNET_SCHEDULER_TaskIdentifier announce_applications_task;
966
967 /**
968  * Task to periodically announce itself in the network.
969  */
970 GNUNET_SCHEDULER_TaskIdentifier announce_id_task;
971
972 /**
973  * Next ID to assign to a client.
974  */
975 unsigned int next_client_id;
976
977
978 /******************************************************************************/
979 /***********************         DECLARATIONS        **************************/
980 /******************************************************************************/
981
982 /**
983  * Function to process paths received for a new peer addition. The recorded
984  * paths form the initial tunnel, which can be optimized later.
985  * Called on each result obtained for the DHT search.
986  *
987  * @param cls closure
988  * @param exp when will this value expire
989  * @param key key of the result
990  * @param type type of the result
991  * @param size number of bytes in data
992  * @param data pointer to the result data
993  */
994 static void
995 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
996                     const struct GNUNET_HashCode * key,
997                     const struct GNUNET_PeerIdentity *get_path,
998                     unsigned int get_path_length,
999                     const struct GNUNET_PeerIdentity *put_path,
1000                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
1001                     size_t size, const void *data);
1002
1003
1004 /**
1005  * Function to process DHT string to regex matching.
1006  * Called on each result obtained for the DHT search.
1007  *
1008  * @param cls closure (search context)
1009  * @param exp when will this value expire
1010  * @param key key of the result
1011  * @param get_path path of the get request (not used)
1012  * @param get_path_length lenght of get_path (not used)
1013  * @param put_path path of the put request (not used)
1014  * @param put_path_length length of the put_path (not used)
1015  * @param type type of the result
1016  * @param size number of bytes in data
1017  * @param data pointer to the result data
1018  *
1019  * TODO: re-issue the request after certain time? cancel after X results?
1020  */
1021 static void
1022 dht_get_string_handler (void *cls, struct GNUNET_TIME_Absolute exp,
1023                         const struct GNUNET_HashCode * key,
1024                         const struct GNUNET_PeerIdentity *get_path,
1025                         unsigned int get_path_length,
1026                         const struct GNUNET_PeerIdentity *put_path,
1027                         unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
1028                         size_t size, const void *data);
1029
1030
1031 /**
1032  * Function to process DHT string to regex matching.
1033  * Called on each result obtained for the DHT search.
1034  *
1035  * @param cls closure (search context)
1036  * @param exp when will this value expire
1037  * @param key key of the result
1038  * @param get_path path of the get request (not used)
1039  * @param get_path_length lenght of get_path (not used)
1040  * @param put_path path of the put request (not used)
1041  * @param put_path_length length of the put_path (not used)
1042  * @param type type of the result
1043  * @param size number of bytes in data
1044  * @param data pointer to the result data
1045  */
1046 static void
1047 dht_get_string_accept_handler (void *cls, struct GNUNET_TIME_Absolute exp,
1048                                const struct GNUNET_HashCode * key,
1049                                const struct GNUNET_PeerIdentity *get_path,
1050                                unsigned int get_path_length,
1051                                const struct GNUNET_PeerIdentity *put_path,
1052                                unsigned int put_path_length,
1053                                enum GNUNET_BLOCK_Type type,
1054                                size_t size, const void *data);
1055
1056
1057 /**
1058  * Retrieve the MeshPeerInfo stucture associated with the peer, create one
1059  * and insert it in the appropiate structures if the peer is not known yet.
1060  *
1061  * @param peer Short identity of the peer.
1062  *
1063  * @return Existing or newly created peer info.
1064  */
1065 static struct MeshPeerInfo *
1066 peer_info_get_short (const GNUNET_PEER_Id peer);
1067
1068
1069 /**
1070  * Try to establish a new connection to this peer.
1071  * Use the best path for the given tunnel.
1072  * If the peer doesn't have any path to it yet, try to get one.
1073  * If the peer already has some path, send a CREATE PATH towards it.
1074  *
1075  * @param peer PeerInfo of the peer.
1076  * @param t Tunnel for which to create the path, if possible.
1077  */
1078 static void
1079 peer_info_connect (struct MeshPeerInfo *peer, struct MeshTunnel *t);
1080
1081
1082 /**
1083  * Add a peer to a tunnel, accomodating paths accordingly and initializing all
1084  * needed rescources.
1085  * If peer already exists, reevaluate shortest path and change if different.
1086  *
1087  * @param t Tunnel we want to add a new peer to
1088  * @param peer PeerInfo of the peer being added
1089  *
1090  */
1091 static void
1092 tunnel_add_peer (struct MeshTunnel *t, struct MeshPeerInfo *peer);
1093
1094
1095 /**
1096  * Removes an explicit path from a tunnel, freeing all intermediate nodes
1097  * that are no longer needed, as well as nodes of no longer reachable peers.
1098  * The tunnel itself is also destoyed if results in a remote empty tunnel.
1099  *
1100  * @param t Tunnel from which to remove the path.
1101  * @param peer Short id of the peer which should be removed.
1102  */
1103 static void
1104 tunnel_delete_peer (struct MeshTunnel *t, GNUNET_PEER_Id peer);
1105
1106
1107 /**
1108  * Search for a tunnel by global ID using full PeerIdentities.
1109  *
1110  * @param oid owner of the tunnel.
1111  * @param tid global tunnel number.
1112  *
1113  * @return tunnel handler, NULL if doesn't exist.
1114  */
1115 static struct MeshTunnel *
1116 tunnel_get (struct GNUNET_PeerIdentity *oid, MESH_TunnelNumber tid);
1117
1118
1119 /**
1120  * Delete an active client from the tunnel.
1121  *
1122  * @param t Tunnel.
1123  * @param c Client.
1124  */
1125 static void
1126 tunnel_delete_active_client (struct MeshTunnel *t, const struct MeshClient *c);
1127
1128 /**
1129  * Notify a tunnel that a connection has broken that affects at least
1130  * some of its peers.
1131  *
1132  * @param t Tunnel affected.
1133  * @param p1 Peer that got disconnected from p2.
1134  * @param p2 Peer that got disconnected from p1.
1135  *
1136  * @return Short ID of the peer disconnected (either p1 or p2).
1137  *         0 if the tunnel remained unaffected.
1138  */
1139 static GNUNET_PEER_Id
1140 tunnel_notify_connection_broken (struct MeshTunnel *t, GNUNET_PEER_Id p1,
1141                                  GNUNET_PEER_Id p2);
1142
1143
1144 /**
1145  * Get the current ack value for a tunnel, for data going from root to leaves,
1146  * taking in account the tunnel mode and the status of all children and clients.
1147  *
1148  * @param t Tunnel.
1149  *
1150  * @return Maximum PID allowed.
1151  */
1152 static uint32_t
1153 tunnel_get_fwd_ack (struct MeshTunnel *t);
1154
1155
1156 /**
1157  * Add a client to a tunnel, initializing all needed data structures.
1158  * 
1159  * @param t Tunnel to which add the client.
1160  * @param c Client which to add to the tunnel.
1161  */
1162 static void
1163 tunnel_add_client (struct MeshTunnel *t, struct MeshClient *c);
1164
1165
1166 /**
1167  * Jump to the next edge, with the longest matching token.
1168  *
1169  * @param block Block found in the DHT.
1170  * @param size Size of the block.
1171  * @param ctx Context of the search.
1172  *
1173  * @return GNUNET_YES if should keep iterating, GNUNET_NO otherwise.
1174  */
1175 static void
1176 regex_next_edge (const struct MeshRegexBlock *block,
1177                  size_t size,
1178                  struct MeshRegexSearchContext *ctx);
1179
1180
1181 /**
1182  * Find a path to a peer that offers a regex servcie compatible
1183  * with a given string.
1184  * 
1185  * @param key The key of the accepting state.
1186  * @param ctx Context containing info about the string, tunnel, etc.
1187  */
1188 static void
1189 regex_find_path (const struct GNUNET_HashCode *key,
1190                  struct MeshRegexSearchContext *ctx);
1191
1192
1193 /**
1194  * @brief Queue and pass message to core when possible.
1195  * 
1196  * If type is payload (UNICAST, TO_ORIGIN, MULTICAST) checks for queue status
1197  * and accounts for it. In case the queue is full, the message is dropped and
1198  * a break issued.
1199  * 
1200  * Otherwise, message is treated as internal and allowed to go regardless of 
1201  * queue status.
1202  *
1203  * @param cls Closure (@c type dependant). It will be used by queue_send to
1204  *            build the message to be sent if not already prebuilt.
1205  * @param type Type of the message, 0 for a raw message.
1206  * @param size Size of the message.
1207  * @param dst Neighbor to send message to.
1208  * @param t Tunnel this message belongs to.
1209  */
1210 static void
1211 queue_add (void *cls, uint16_t type, size_t size,
1212            struct MeshPeerInfo *dst, struct MeshTunnel *t);
1213
1214
1215 /**
1216  * Free a transmission that was already queued with all resources
1217  * associated to the request.
1218  *
1219  * @param queue Queue handler to cancel.
1220  * @param clear_cls Is it necessary to free associated cls?
1221  */
1222 static void
1223 queue_destroy (struct MeshPeerQueue *queue, int clear_cls);
1224
1225
1226 /**
1227  * @brief Get the next transmittable message from the queue.
1228  *
1229  * This will be the head, except in the case of being a data packet
1230  * not allowed by the destination peer.
1231  *
1232  * @param peer Destination peer.
1233  *
1234  * @return The next viable MeshPeerQueue element to send to that peer.
1235  *         NULL when there are no transmittable messages.
1236  */
1237 struct MeshPeerQueue *
1238 queue_get_next (const struct MeshPeerInfo *peer);
1239
1240
1241 /**
1242  * Core callback to write a queued packet to core buffer
1243  *
1244  * @param cls Closure (peer info).
1245  * @param size Number of bytes available in buf.
1246  * @param buf Where the to write the message.
1247  *
1248  * @return number of bytes written to buf
1249  */
1250 static size_t
1251 queue_send (void *cls, size_t size, void *buf);
1252
1253 /******************************************************************************/
1254 /************************         ITERATORS        ****************************/
1255 /******************************************************************************/
1256
1257 /**
1258  * Iterator over found existing mesh regex blocks that match an ongoing search.
1259  *
1260  * @param cls closure
1261  * @param key current key code
1262  * @param value value in the hash map
1263  * @return GNUNET_YES if we should continue to iterate,
1264  *         GNUNET_NO if not.
1265  */
1266 static int
1267 regex_result_iterator (void *cls,
1268                        const struct GNUNET_HashCode * key,
1269                        void *value)
1270 {
1271   struct MeshRegexBlock *block = value;
1272   struct MeshRegexSearchContext *ctx = cls;
1273
1274   if (GNUNET_YES == ntohl(block->accepting) &&
1275       ctx->position == strlen (ctx->info->description))
1276   {
1277     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* Found accepting known block\n");
1278     regex_find_path (key, ctx);
1279     return GNUNET_YES; // We found an accept state!
1280   }
1281   else
1282   {
1283     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* %u, %u, [%u]\n",
1284                 ctx->position, strlen(ctx->info->description),
1285                 ntohl(block->accepting));
1286
1287   }
1288   regex_next_edge(block, SIZE_MAX, ctx);
1289
1290   return GNUNET_YES;
1291 }
1292
1293
1294 /**
1295  * Iterator over edges in a regex block retrieved from the DHT.
1296  *
1297  * @param cls Closure (context of the search).
1298  * @param token Token that follows to next state.
1299  * @param len Lenght of token.
1300  * @param key Hash of next state.
1301  *
1302  * @return GNUNET_YES if should keep iterating, GNUNET_NO otherwise.
1303  */
1304 static int
1305 regex_edge_iterator (void *cls,
1306                      const char *token,
1307                      size_t len,
1308                      const struct GNUNET_HashCode *key)
1309 {
1310   struct MeshRegexSearchContext *ctx = cls;
1311   struct MeshRegexSearchInfo *info = ctx->info;
1312   char *current;
1313   size_t current_len;
1314
1315   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*    Start of regex edge iterator\n");
1316   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*     descr : %s\n", info->description);
1317   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*     posit : %u\n", ctx->position);
1318   current = &info->description[ctx->position];
1319   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*     currt : %s\n", current);
1320   current_len = strlen (info->description) - ctx->position;
1321   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*     ctlen : %u\n", current_len);
1322   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*     tklen : %u\n", len);
1323   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*     tk[0] : %c\n", token[0]);
1324   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*     nextk : %s\n", GNUNET_h2s(key));
1325   if (len > current_len)
1326   {
1327     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*     Token too long, END\n");
1328     return GNUNET_YES; // Token too long, wont match
1329   }
1330   if (0 != strncmp (current, token, len))
1331   {
1332     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*     Token doesn't match, END\n");
1333     return GNUNET_YES; // Token doesn't match
1334   }
1335
1336   if (len > ctx->longest_match)
1337   {
1338     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*     Token is longer, KEEP\n");
1339     ctx->longest_match = len;
1340     ctx->hash = *key;
1341   }
1342   else
1343   {
1344     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*     Token is not longer, IGNORE\n");
1345   }
1346
1347   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*    End of regex edge iterator\n");
1348   return GNUNET_YES;
1349 }
1350
1351
1352 /**
1353  * Jump to the next edge, with the longest matching token.
1354  *
1355  * @param block Block found in the DHT.
1356  * @param size Size of the block.
1357  * @param ctx Context of the search.
1358  *
1359  * @return GNUNET_YES if should keep iterating, GNUNET_NO otherwise.
1360  */
1361 static void
1362 regex_next_edge (const struct MeshRegexBlock *block,
1363                  size_t size,
1364                  struct MeshRegexSearchContext *ctx)
1365 {
1366   struct MeshRegexSearchContext *new_ctx;
1367   struct MeshRegexSearchInfo *info = ctx->info;
1368   struct GNUNET_DHT_GetHandle *get_h;
1369
1370   int result;
1371
1372   /* Find the longest match for the current string position, 
1373    * among tokens in the given block */
1374   ctx->longest_match = 0;
1375   result = GNUNET_MESH_regex_block_iterate (block, size,
1376                                             &regex_edge_iterator, ctx);
1377   GNUNET_break (GNUNET_OK == result || SIZE_MAX == size);
1378
1379   /* Did anything match? */
1380   if (0 == ctx->longest_match)
1381     return;
1382
1383   new_ctx = GNUNET_malloc (sizeof (struct MeshRegexSearchContext));
1384   new_ctx->info = info;
1385   new_ctx->position = ctx->position + ctx->longest_match;
1386   GNUNET_array_append (info->contexts, info->n_contexts, new_ctx);
1387
1388   /* Check whether we already have a DHT GET running for it */
1389   if (GNUNET_YES ==
1390       GNUNET_CONTAINER_multihashmap_contains(info->dht_get_handles, &ctx->hash))
1391   {
1392     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*     GET running, END\n");
1393     GNUNET_CONTAINER_multihashmap_get_multiple (info->dht_get_results,
1394                                                 &ctx->hash,
1395                                                 &regex_result_iterator,
1396                                                 new_ctx);
1397     return; // We are already looking for it
1398   }
1399
1400   /* Start search in DHT */
1401   get_h = 
1402       GNUNET_DHT_get_start (dht_handle,    /* handle */
1403                             GNUNET_BLOCK_TYPE_MESH_REGEX, /* type */
1404                             &ctx->hash,     /* key to search */
1405                             dht_replication_level, /* replication level */
1406                             GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
1407                             NULL,       /* xquery */ // FIXME BLOOMFILTER
1408                             0,     /* xquery bits */ // FIXME BLOOMFILTER SIZE
1409                             &dht_get_string_handler, new_ctx);
1410   if (GNUNET_OK !=
1411       GNUNET_CONTAINER_multihashmap_put(info->dht_get_handles,
1412                                         &ctx->hash,
1413                                         get_h,
1414                                         GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
1415   {
1416     GNUNET_break (0);
1417     return;
1418   }
1419 }
1420
1421
1422 /**
1423  * Iterator over hash map entries to cancel DHT GET requests after a
1424  * successful connect_by_string.
1425  *
1426  * @param cls Closure (unused).
1427  * @param key Current key code (unused).
1428  * @param value Value in the hash map (get handle).
1429  * @return GNUNET_YES if we should continue to iterate,
1430  *         GNUNET_NO if not.
1431  */
1432 static int
1433 regex_cancel_dht_get (void *cls,
1434                       const struct GNUNET_HashCode * key,
1435                       void *value)
1436 {
1437   struct GNUNET_DHT_GetHandle *h = value;
1438
1439   GNUNET_DHT_get_stop (h);
1440   return GNUNET_YES;
1441 }
1442
1443
1444 /**
1445  * Iterator over hash map entries to free MeshRegexBlocks stored during the
1446  * search for connect_by_string.
1447  *
1448  * @param cls Closure (unused).
1449  * @param key Current key code (unused).
1450  * @param value MeshRegexBlock in the hash map.
1451  * @return GNUNET_YES if we should continue to iterate,
1452  *         GNUNET_NO if not.
1453  */
1454 static int
1455 regex_free_result (void *cls,
1456                    const struct GNUNET_HashCode * key,
1457                    void *value)
1458 {
1459
1460   GNUNET_free (value);
1461   return GNUNET_YES;
1462 }
1463
1464
1465 /**
1466  * Regex callback iterator to store own service description in the DHT.
1467  *
1468  * @param cls closure.
1469  * @param key hash for current state.
1470  * @param proof proof for current state.
1471  * @param accepting GNUNET_YES if this is an accepting state, GNUNET_NO if not.
1472  * @param num_edges number of edges leaving current state.
1473  * @param edges edges leaving current state.
1474  */
1475 void
1476 regex_iterator (void *cls,
1477                 const struct GNUNET_HashCode *key,
1478                 const char *proof,
1479                 int accepting,
1480                 unsigned int num_edges,
1481                 const struct GNUNET_REGEX_Edge *edges)
1482 {
1483     struct MeshRegexBlock *block;
1484     struct MeshRegexEdge *block_edge;
1485     enum GNUNET_DHT_RouteOption opt;
1486     size_t size;
1487     size_t len;
1488     unsigned int i;
1489     unsigned int offset;
1490     char *aux;
1491
1492     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1493                 "  regex dht put for state %s\n",
1494                 GNUNET_h2s(key));
1495     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1496                 "   proof: %s\n",
1497                 proof);
1498     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1499                 "   num edges: %u\n",
1500                 num_edges);
1501
1502     opt = GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE;
1503     if (GNUNET_YES == accepting)
1504     {
1505         struct MeshRegexAccept block;
1506
1507         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1508                     "   state %s is accepting, putting own id\n",
1509                     GNUNET_h2s(key));
1510         size = sizeof (block);
1511         block.key = *key;
1512         block.id = my_full_id;
1513         (void)
1514         GNUNET_DHT_put(dht_handle, key,
1515                        dht_replication_level,
1516                        opt | GNUNET_DHT_RO_RECORD_ROUTE,
1517                        GNUNET_BLOCK_TYPE_MESH_REGEX_ACCEPT,
1518                        size,
1519                        (char *) &block,
1520                        GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get (),
1521                                                  app_announce_time),
1522                        app_announce_time,
1523                        NULL, NULL);
1524     }
1525     len = strlen(proof);
1526     size = sizeof (struct MeshRegexBlock) + len;
1527     block = GNUNET_malloc (size);
1528
1529     block->key = *key;
1530     block->n_proof = htonl (len);
1531     block->n_edges = htonl (num_edges);
1532     block->accepting = htonl (accepting);
1533
1534     /* Store the proof at the end of the block. */
1535     aux = (char *) &block[1];
1536     memcpy (aux, proof, len);
1537     aux = &aux[len];
1538
1539     /* Store each edge in a variable length MeshEdge struct at the
1540      * very end of the MeshRegexBlock structure.
1541      */
1542     for (i = 0; i < num_edges; i++)
1543     {
1544         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1545                     "    edge %s towards %s\n",
1546                     edges[i].label,
1547                     GNUNET_h2s(&edges[i].destination));
1548
1549         /* aux points at the end of the last block */
1550         len = strlen (edges[i].label);
1551         size += sizeof (struct MeshRegexEdge) + len;
1552         // Calculate offset FIXME is this ok? use size instead?
1553         offset = aux - (char *) block;
1554         block = GNUNET_realloc (block, size);
1555         aux = &((char *) block)[offset];
1556         block_edge = (struct MeshRegexEdge *) aux;
1557         block_edge->key = edges[i].destination;
1558         block_edge->n_token = htonl (len);
1559         aux = (char *) &block_edge[1];
1560         memcpy (aux, edges[i].label, len);
1561         aux = &aux[len];
1562     }
1563     (void)
1564     GNUNET_DHT_put(dht_handle, key,
1565                    dht_replication_level,
1566                    opt,
1567                    GNUNET_BLOCK_TYPE_MESH_REGEX, size,
1568                    (char *) block,
1569                    GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get (),
1570                                             app_announce_time),
1571                    app_announce_time,
1572                    NULL, NULL);
1573     GNUNET_free (block);
1574 }
1575
1576
1577 /**
1578  * Store the regular expression describing a local service into the DHT.
1579  *
1580  * @param regex The regular expresion.
1581  */
1582 static void
1583 regex_put (const char *regex)
1584 {
1585   struct GNUNET_REGEX_Automaton *dfa;
1586
1587   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     /* Check if buffer size is enough for the message */
4904     if (queue->size > size)
4905     {
4906         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4907                     "*********   not enough room, reissue\n");
4908         peer->core_transmit =
4909             GNUNET_CORE_notify_transmit_ready (core_handle,
4910                                                0,
4911                                                0,
4912                                                GNUNET_TIME_UNIT_FOREVER_REL,
4913                                                &dst_id,
4914                                                queue->size,
4915                                                &queue_send,
4916                                                peer);
4917         return 0;
4918     }
4919     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   size ok\n");
4920
4921     t = queue->tunnel;
4922     if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == queue->type)
4923     {
4924       t->fwd_queue_n--;
4925       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4926                   "*********   unicast: t->q (%u/%u)\n",
4927                   t->fwd_queue_n, t->fwd_queue_max);
4928     }
4929     else if (GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == queue->type)
4930     {
4931       t->bck_queue_n--;
4932       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   to origin\n");
4933     }
4934
4935     /* Fill buf */
4936     switch (queue->type)
4937     {
4938       case 0:
4939       case GNUNET_MESSAGE_TYPE_MESH_ACK:
4940       case GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN:
4941       case GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY:
4942       case GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY:
4943         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4944                     "*********   raw: %s\n",
4945                     GNUNET_MESH_DEBUG_M2S (queue->type));
4946         /* Fall through */
4947       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4948       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4949         data_size = send_core_data_raw (queue->cls, size, buf);
4950         msg = (struct GNUNET_MessageHeader *) buf;
4951         switch (ntohs (msg->type)) // Type of preconstructed message
4952         {
4953           case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4954             tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_UNICAST);
4955             break;
4956           case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4957             tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
4958             break;
4959           default:
4960               break;
4961         }
4962         break;
4963       case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
4964         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   multicast\n");
4965         {
4966           struct MeshTransmissionDescriptor *info = queue->cls;
4967
4968           if ((1 == info->mesh_data->reference_counter
4969               && GNUNET_YES == t->speed_min)
4970               ||
4971               (info->mesh_data->total_out == info->mesh_data->reference_counter
4972               && GNUNET_NO == t->speed_min))
4973           {
4974             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4975                         "*********   considered sent\n");
4976             t->fwd_queue_n--;
4977           }
4978         }
4979         data_size = send_core_data_multicast(queue->cls, size, buf);
4980         tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
4981         break;
4982       case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
4983         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path create\n");
4984         data_size = send_core_path_create (queue->cls, size, buf);
4985         break;
4986       case GNUNET_MESSAGE_TYPE_MESH_PATH_ACK:
4987         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path ack\n");
4988         data_size = send_core_path_ack (queue->cls, size, buf);
4989         break;
4990       case GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE:
4991         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path keepalive\n");
4992         data_size = send_core_data_multicast (queue->cls, size, buf);
4993         break;
4994       default:
4995         GNUNET_break (0);
4996         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4997                     "*********   type unknown: %u\n",
4998                     queue->type);
4999         data_size = 0;
5000     }
5001     switch (queue->type)
5002     {
5003       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
5004       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
5005       case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
5006         cinfo = tunnel_get_neighbor_fc (t, &dst_id);
5007         if (cinfo->send_buffer[cinfo->send_buffer_start] != queue)
5008         {
5009           GNUNET_break (0);
5010           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5011                       "at pos %u (%p) != %p\n",
5012                       cinfo->send_buffer_start,
5013                       cinfo->send_buffer[cinfo->send_buffer_start],
5014                       queue);
5015         }
5016         if (cinfo->send_buffer_n > 0)
5017         {
5018           cinfo->send_buffer[cinfo->send_buffer_start] = NULL;
5019           cinfo->send_buffer_n--;
5020           cinfo->send_buffer_start++;
5021           cinfo->send_buffer_start %= t->fwd_queue_max;
5022         }
5023         else
5024         {
5025           GNUNET_break (0);
5026         }
5027         break;
5028       default:
5029         break;
5030     }
5031
5032     /* Free queue, but cls was freed by send_core_* */
5033     queue_destroy (queue, GNUNET_NO);
5034
5035     if (GNUNET_YES == t->destroy)
5036     {
5037       // FIXME fc tunnel destroy all pending traffic? wait for it?
5038       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********  destroying tunnel!\n");
5039       tunnel_destroy (t);
5040     }
5041
5042     /* If more data in queue, send next */
5043     queue = queue_get_next(peer);
5044     if (NULL != queue)
5045     {
5046         struct GNUNET_PeerIdentity id;
5047
5048         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   more data!\n");
5049         GNUNET_PEER_resolve (peer->id, &id);
5050         peer->core_transmit =
5051             GNUNET_CORE_notify_transmit_ready(core_handle,
5052                                               0,
5053                                               0,
5054                                               GNUNET_TIME_UNIT_FOREVER_REL,
5055                                               &id,
5056                                               queue->size,
5057                                               &queue_send,
5058                                               peer);
5059     }
5060     else
5061     {
5062       if (NULL != peer->queue_head)
5063       {
5064         GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5065                     "*********   %s stalled\n",
5066                     GNUNET_i2s(&my_full_id));
5067         if (NULL == cinfo)
5068           cinfo = tunnel_get_neighbor_fc (t, &dst_id);
5069         cinfo->fc_poll = GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_SECONDS,
5070                                                      &tunnel_poll, cinfo);
5071       }
5072     }
5073     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   return %d\n", data_size);
5074     return data_size;
5075 }
5076
5077
5078 /**
5079  * @brief Queue and pass message to core when possible.
5080  * 
5081  * If type is payload (UNICAST, TO_ORIGIN, MULTICAST) checks for queue status
5082  * and accounts for it. In case the queue is full, the message is dropped and
5083  * a break issued.
5084  * 
5085  * Otherwise, message is treated as internal and allowed to go regardless of 
5086  * queue status.
5087  *
5088  * @param cls Closure (@c type dependant). It will be used by queue_send to
5089  *            build the message to be sent if not already prebuilt.
5090  * @param type Type of the message, 0 for a raw message.
5091  * @param size Size of the message.
5092  * @param dst Neighbor to send message to.
5093  * @param t Tunnel this message belongs to.
5094  */
5095 static void
5096 queue_add (void *cls, uint16_t type, size_t size,
5097            struct MeshPeerInfo *dst, struct MeshTunnel *t)
5098 {
5099   struct MeshPeerQueue *queue;
5100   struct MeshTunnelChildInfo *cinfo;
5101   struct GNUNET_PeerIdentity id;
5102   unsigned int *max;
5103   unsigned int *n;
5104   unsigned int i;
5105
5106   n = NULL;
5107   if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == type ||
5108       GNUNET_MESSAGE_TYPE_MESH_MULTICAST == type)
5109   {
5110     n = &t->fwd_queue_n;
5111     max = &t->fwd_queue_max;
5112   }
5113   else if (GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == type)
5114   {
5115     n = &t->bck_queue_n;
5116     max = &t->bck_queue_max;
5117   }
5118   if (NULL != n)
5119   {
5120     if (*n >= *max)
5121     {
5122       struct MeshTransmissionDescriptor *td = cls;
5123       struct GNUNET_MESH_ToOrigin *to;
5124
5125       to = td->mesh_data->data;
5126       GNUNET_break(0);
5127       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5128                   "bck pid %u, bck ack %u, msg pid %u\n",
5129                   t->bck_pid, t->bck_ack, ntohl(to->pid));
5130       GNUNET_STATISTICS_update(stats, "# messages dropped (buffer full)",
5131                                1, GNUNET_NO);
5132       return;                       // Drop message
5133     }
5134     (*n)++;
5135   }
5136   queue = GNUNET_malloc (sizeof (struct MeshPeerQueue));
5137   queue->cls = cls;
5138   queue->type = type;
5139   queue->size = size;
5140   queue->peer = dst;
5141   queue->tunnel = t;
5142   GNUNET_CONTAINER_DLL_insert_tail (dst->queue_head, dst->queue_tail, queue);
5143   GNUNET_PEER_resolve (dst->id, &id);
5144   if (NULL == dst->core_transmit)
5145   {
5146       dst->core_transmit =
5147           GNUNET_CORE_notify_transmit_ready (core_handle,
5148                                              0,
5149                                              0,
5150                                              GNUNET_TIME_UNIT_FOREVER_REL,
5151                                              &id,
5152                                              size,
5153                                              &queue_send,
5154                                              dst);
5155   }
5156   if (NULL == n) // Is this internal mesh traffic?
5157     return;
5158
5159   // It's payload, keep track of buffer per peer.
5160   cinfo = tunnel_get_neighbor_fc(t, &id);
5161   i = (cinfo->send_buffer_start + cinfo->send_buffer_n) % t->fwd_queue_max;
5162   if (NULL != cinfo->send_buffer[i])
5163   {
5164     GNUNET_break (cinfo->send_buffer_n == t->fwd_queue_max); // aka i == start
5165     queue_destroy (cinfo->send_buffer[cinfo->send_buffer_start], GNUNET_YES);
5166     cinfo->send_buffer_start++;
5167     cinfo->send_buffer_start %= t->fwd_queue_max;
5168   }
5169   else
5170   {
5171     cinfo->send_buffer_n++;
5172   }
5173   cinfo->send_buffer[i] = queue;
5174   if (cinfo->send_buffer_n > t->fwd_queue_max)
5175   {
5176     GNUNET_break (0);
5177     cinfo->send_buffer_n = t->fwd_queue_max;
5178   }
5179 }
5180
5181
5182 /******************************************************************************/
5183 /********************      MESH NETWORK HANDLERS     **************************/
5184 /******************************************************************************/
5185
5186
5187 /**
5188  * Core handler for path creation
5189  *
5190  * @param cls closure
5191  * @param message message
5192  * @param peer peer identity this notification is about
5193  * @param atsi performance data
5194  * @param atsi_count number of records in 'atsi'
5195  *
5196  * @return GNUNET_OK to keep the connection open,
5197  *         GNUNET_SYSERR to close it (signal serious error)
5198  */
5199 static int
5200 handle_mesh_path_create (void *cls, const struct GNUNET_PeerIdentity *peer,
5201                          const struct GNUNET_MessageHeader *message,
5202                          const struct GNUNET_ATS_Information *atsi,
5203                          unsigned int atsi_count)
5204 {
5205   unsigned int own_pos;
5206   uint16_t size;
5207   uint16_t i;
5208   MESH_TunnelNumber tid;
5209   struct GNUNET_MESH_ManipulatePath *msg;
5210   struct GNUNET_PeerIdentity *pi;
5211   struct GNUNET_HashCode hash;
5212   struct MeshPeerPath *path;
5213   struct MeshPeerInfo *dest_peer_info;
5214   struct MeshPeerInfo *orig_peer_info;
5215   struct MeshTunnel *t;
5216
5217   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5218               "Received a path create msg [%s]\n",
5219               GNUNET_i2s (&my_full_id));
5220   size = ntohs (message->size);
5221   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
5222   {
5223     GNUNET_break_op (0);
5224     return GNUNET_OK;
5225   }
5226
5227   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
5228   if (size % sizeof (struct GNUNET_PeerIdentity))
5229   {
5230     GNUNET_break_op (0);
5231     return GNUNET_OK;
5232   }
5233   size /= sizeof (struct GNUNET_PeerIdentity);
5234   if (size < 2)
5235   {
5236     GNUNET_break_op (0);
5237     return GNUNET_OK;
5238   }
5239   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
5240   msg = (struct GNUNET_MESH_ManipulatePath *) message;
5241
5242   tid = ntohl (msg->tid);
5243   pi = (struct GNUNET_PeerIdentity *) &msg[1];
5244   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5245               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi), tid);
5246   t = tunnel_get (pi, tid);
5247   if (NULL == t) // FIXME only for INCOMING tunnels?
5248   {
5249     uint32_t opt;
5250
5251     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating tunnel\n");
5252     t = tunnel_new (GNUNET_PEER_intern (pi), tid, NULL, 0);
5253     if (NULL == t)
5254     {
5255       // FIXME notify failure
5256       return GNUNET_OK;
5257     }
5258     opt = ntohl (msg->opt);
5259     t->speed_min = (0 != (opt & MESH_TUNNEL_OPT_SPEED_MIN)) ?
5260                    GNUNET_YES : GNUNET_NO;
5261     if (0 != (opt & MESH_TUNNEL_OPT_NOBUFFER))
5262     {
5263       t->nobuffer = GNUNET_YES;
5264       t->last_fwd_ack = t->fwd_pid + 1;
5265     }
5266     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5267                 "  speed_min: %d, nobuffer:%d\n",
5268                 t->speed_min, t->nobuffer);
5269
5270     if (GNUNET_YES == t->nobuffer)
5271     {
5272       t->bck_queue_max = 1;
5273       t->fwd_queue_max = 1;
5274     }
5275
5276     // FIXME only assign a local tid if a local client is interested (on demand)
5277     while (NULL != tunnel_get_incoming (next_local_tid))
5278       next_local_tid = (next_local_tid + 1) | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
5279     t->local_tid_dest = next_local_tid++;
5280     next_local_tid = next_local_tid | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
5281     // FIXME end
5282
5283     tunnel_reset_timeout (t);
5284     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
5285     if (GNUNET_OK !=
5286         GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
5287                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
5288     {
5289       tunnel_destroy (t);
5290       GNUNET_break (0);
5291       return GNUNET_OK;
5292     }
5293   }
5294   dest_peer_info =
5295       GNUNET_CONTAINER_multihashmap_get (peers, &pi[size - 1].hashPubKey);
5296   if (NULL == dest_peer_info)
5297   {
5298     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5299                 "  Creating PeerInfo for destination.\n");
5300     dest_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
5301     dest_peer_info->id = GNUNET_PEER_intern (&pi[size - 1]);
5302     GNUNET_CONTAINER_multihashmap_put (peers, &pi[size - 1].hashPubKey,
5303                                        dest_peer_info,
5304                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
5305   }
5306   orig_peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &pi->hashPubKey);
5307   if (NULL == orig_peer_info)
5308   {
5309     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5310                 "  Creating PeerInfo for origin.\n");
5311     orig_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
5312     orig_peer_info->id = GNUNET_PEER_intern (pi);
5313     GNUNET_CONTAINER_multihashmap_put (peers, &pi->hashPubKey, orig_peer_info,
5314                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
5315   }
5316   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
5317   path = path_new (size);
5318   own_pos = 0;
5319   for (i = 0; i < size; i++)
5320   {
5321     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
5322                 GNUNET_i2s (&pi[i]));
5323     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
5324     if (path->peers[i] == myid)
5325       own_pos = i;
5326   }
5327   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
5328   if (own_pos == 0)
5329   {
5330     /* cannot be self, must be 'not found' */
5331     /* create path: self not found in path through self */
5332     GNUNET_break_op (0);
5333     path_destroy (path);
5334     tunnel_destroy (t);
5335     return GNUNET_OK;
5336   }
5337   path_add_to_peers (path, GNUNET_NO);
5338   tunnel_add_path (t, path, own_pos);
5339   if (own_pos == size - 1)
5340   {
5341     /* It is for us! Send ack. */
5342     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
5343     peer_info_add_path_to_origin (orig_peer_info, path, GNUNET_NO);
5344     if (NULL == t->peers)
5345     {
5346       /* New tunnel! Notify clients on first payload message. */
5347       t->peers = GNUNET_CONTAINER_multihashmap_create (4, GNUNET_NO);
5348     }
5349     GNUNET_break (GNUNET_SYSERR !=
5350                   GNUNET_CONTAINER_multihashmap_put (t->peers,
5351                                                      &my_full_id.hashPubKey,
5352                                                      peer_info_get
5353                                                      (&my_full_id),
5354                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE));
5355     send_path_ack (t);
5356   }
5357   else
5358   {
5359     struct MeshPeerPath *path2;
5360
5361     /* It's for somebody else! Retransmit. */
5362     path2 = path_duplicate (path);
5363     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Retransmitting.\n");
5364     peer_info_add_path (dest_peer_info, path2, GNUNET_NO);
5365     path2 = path_duplicate (path);
5366     peer_info_add_path_to_origin (orig_peer_info, path2, GNUNET_NO);
5367     send_create_path (dest_peer_info, path, t);
5368   }
5369   return GNUNET_OK;
5370 }
5371
5372
5373 /**
5374  * Core handler for path destruction
5375  *
5376  * @param cls closure
5377  * @param message message
5378  * @param peer peer identity this notification is about
5379  * @param atsi performance data
5380  * @param atsi_count number of records in 'atsi'
5381  *
5382  * @return GNUNET_OK to keep the connection open,
5383  *         GNUNET_SYSERR to close it (signal serious error)
5384  */
5385 static int
5386 handle_mesh_path_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
5387                           const struct GNUNET_MessageHeader *message,
5388                           const struct GNUNET_ATS_Information *atsi,
5389                           unsigned int atsi_count)
5390 {
5391   struct GNUNET_MESH_ManipulatePath *msg;
5392   struct GNUNET_PeerIdentity *pi;
5393   struct MeshPeerPath *path;
5394   struct MeshTunnel *t;
5395   unsigned int own_pos;
5396   unsigned int i;
5397   size_t size;
5398
5399   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5400               "Received a PATH DESTROY msg from %s\n", GNUNET_i2s (peer));
5401   size = ntohs (message->size);
5402   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
5403   {
5404     GNUNET_break_op (0);
5405     return GNUNET_OK;
5406   }
5407
5408   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
5409   if (size % sizeof (struct GNUNET_PeerIdentity))
5410   {
5411     GNUNET_break_op (0);
5412     return GNUNET_OK;
5413   }
5414   size /= sizeof (struct GNUNET_PeerIdentity);
5415   if (size < 2)
5416   {
5417     GNUNET_break_op (0);
5418     return GNUNET_OK;
5419   }
5420   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
5421
5422   msg = (struct GNUNET_MESH_ManipulatePath *) message;
5423   pi = (struct GNUNET_PeerIdentity *) &msg[1];
5424   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5425               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi),
5426               msg->tid);
5427   t = tunnel_get (pi, ntohl (msg->tid));
5428   if (NULL == t)
5429   {
5430     /* TODO notify back: we don't know this tunnel */
5431     GNUNET_break_op (0);
5432     return GNUNET_OK;
5433   }
5434   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
5435   path = path_new (size);
5436   own_pos = 0;
5437   for (i = 0; i < size; i++)
5438   {
5439     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
5440                 GNUNET_i2s (&pi[i]));
5441     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
5442     if (path->peers[i] == myid)
5443       own_pos = i;
5444   }
5445   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
5446   if (own_pos < path->length - 1)
5447     send_prebuilt_message (message, &pi[own_pos + 1], t);
5448   else
5449     send_client_tunnel_disconnect(t, NULL);
5450
5451   tunnel_delete_peer (t, path->peers[path->length - 1]);
5452   path_destroy (path);
5453   return GNUNET_OK;
5454 }
5455
5456
5457 /**
5458  * Core handler for notifications of broken paths
5459  *
5460  * @param cls closure
5461  * @param message message
5462  * @param peer peer identity this notification is about
5463  * @param atsi performance data
5464  * @param atsi_count number of records in 'atsi'
5465  *
5466  * @return GNUNET_OK to keep the connection open,
5467  *         GNUNET_SYSERR to close it (signal serious error)
5468  */
5469 static int
5470 handle_mesh_path_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
5471                          const struct GNUNET_MessageHeader *message,
5472                          const struct GNUNET_ATS_Information *atsi,
5473                          unsigned int atsi_count)
5474 {
5475   struct GNUNET_MESH_PathBroken *msg;
5476   struct MeshTunnel *t;
5477
5478   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5479               "Received a PATH BROKEN msg from %s\n", GNUNET_i2s (peer));
5480   msg = (struct GNUNET_MESH_PathBroken *) message;
5481   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
5482               GNUNET_i2s (&msg->peer1));
5483   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
5484               GNUNET_i2s (&msg->peer2));
5485   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5486   if (NULL == t)
5487   {
5488     GNUNET_break_op (0);
5489     return GNUNET_OK;
5490   }
5491   tunnel_notify_connection_broken (t, GNUNET_PEER_search (&msg->peer1),
5492                                    GNUNET_PEER_search (&msg->peer2));
5493   return GNUNET_OK;
5494
5495 }
5496
5497
5498 /**
5499  * Core handler for tunnel destruction
5500  *
5501  * @param cls closure
5502  * @param message message
5503  * @param peer peer identity this notification is about
5504  * @param atsi performance data
5505  * @param atsi_count number of records in 'atsi'
5506  *
5507  * @return GNUNET_OK to keep the connection open,
5508  *         GNUNET_SYSERR to close it (signal serious error)
5509  */
5510 static int
5511 handle_mesh_tunnel_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
5512                             const struct GNUNET_MessageHeader *message,
5513                             const struct GNUNET_ATS_Information *atsi,
5514                             unsigned int atsi_count)
5515 {
5516   struct GNUNET_MESH_TunnelDestroy *msg;
5517   struct MeshTunnel *t;
5518
5519   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5520               "Got a TUNNEL DESTROY packet from %s\n", GNUNET_i2s (peer));
5521   msg = (struct GNUNET_MESH_TunnelDestroy *) message;
5522   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for tunnel %s [%u]\n",
5523               GNUNET_i2s (&msg->oid), ntohl (msg->tid));
5524   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5525   if (NULL == t)
5526   {
5527     /* Probably already got the message from another path,
5528      * destroyed the tunnel and retransmitted to children.
5529      * Safe to ignore.
5530      */
5531     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel", 1, GNUNET_NO);
5532     return GNUNET_OK;
5533   }
5534   if (t->id.oid == myid)
5535   {
5536     GNUNET_break_op (0);
5537     return GNUNET_OK;
5538   }
5539   if (t->local_tid_dest >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
5540   {
5541     /* Tunnel was incoming, notify clients */
5542     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "INCOMING TUNNEL %X %X\n",
5543                 t->local_tid, t->local_tid_dest);
5544     send_clients_tunnel_destroy (t);
5545   }
5546   tunnel_send_destroy (t);
5547   t->destroy = GNUNET_YES;
5548   // TODO: add timeout to destroy the tunnel anyway
5549   return GNUNET_OK;
5550 }
5551
5552
5553 /**
5554  * Core handler for mesh network traffic going from the origin to a peer
5555  *
5556  * @param cls closure
5557  * @param peer peer identity this notification is about
5558  * @param message message
5559  * @param atsi performance data
5560  * @param atsi_count number of records in 'atsi'
5561  * @return GNUNET_OK to keep the connection open,
5562  *         GNUNET_SYSERR to close it (signal serious error)
5563  */
5564 static int
5565 handle_mesh_data_unicast (void *cls, const struct GNUNET_PeerIdentity *peer,
5566                           const struct GNUNET_MessageHeader *message,
5567                           const struct GNUNET_ATS_Information *atsi,
5568                           unsigned int atsi_count)
5569 {
5570   struct GNUNET_MESH_Unicast *msg;
5571   struct GNUNET_PeerIdentity *neighbor;
5572   struct MeshTunnelChildInfo *cinfo;
5573   struct MeshTunnel *t;
5574   GNUNET_PEER_Id dest_id;
5575   uint32_t pid;
5576   uint32_t ttl;
5577   size_t size;
5578
5579   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a unicast packet from %s\n",
5580               GNUNET_i2s (peer));
5581   /* Check size */
5582   size = ntohs (message->size);
5583   if (size <
5584       sizeof (struct GNUNET_MESH_Unicast) +
5585       sizeof (struct GNUNET_MessageHeader))
5586   {
5587     GNUNET_break (0);
5588     return GNUNET_OK;
5589   }
5590   msg = (struct GNUNET_MESH_Unicast *) message;
5591   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %s\n",
5592               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
5593   /* Check tunnel */
5594   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5595   if (NULL == t)
5596   {
5597     /* TODO notify back: we don't know this tunnel */
5598     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
5599     GNUNET_break_op (0);
5600     return GNUNET_OK;
5601   }
5602   pid = ntohl (msg->pid);
5603   if (t->fwd_pid == pid)
5604   {
5605     GNUNET_STATISTICS_update (stats, "# duplicate PID drops", 1, GNUNET_NO);
5606     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5607                 " Already seen pid %u, DROPPING!\n", pid);
5608     return GNUNET_OK;
5609   }
5610   else
5611   {
5612     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5613                 " pid %u not seen yet, forwarding\n", pid);
5614   }
5615
5616   t->skip += (pid - t->fwd_pid) - 1;
5617   t->fwd_pid = pid;
5618
5619   if (GMC_is_pid_bigger (pid, t->last_fwd_ack))
5620   {
5621     GNUNET_STATISTICS_update (stats, "# unsolicited unicast", 1, GNUNET_NO);
5622     GNUNET_break_op (0);
5623     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5624                 "Received PID %u, ACK %u\n",
5625                 pid, t->last_fwd_ack);
5626     return GNUNET_OK;
5627   }
5628
5629   tunnel_reset_timeout (t);
5630   dest_id = GNUNET_PEER_search (&msg->destination);
5631   if (dest_id == myid)
5632   {
5633     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5634                 "  it's for us! sending to clients...\n");
5635     GNUNET_STATISTICS_update (stats, "# unicast received", 1, GNUNET_NO);
5636     send_subscribed_clients (message, &msg[1].header, t);
5637     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_UNICAST);
5638     return GNUNET_OK;
5639   }
5640   ttl = ntohl (msg->ttl);
5641   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ttl);
5642   if (ttl == 0)
5643   {
5644     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
5645     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
5646     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5647     return GNUNET_OK;
5648   }
5649   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5650               "  not for us, retransmitting...\n");
5651
5652   neighbor = tree_get_first_hop (t->tree, dest_id);
5653   cinfo = tunnel_get_neighbor_fc (t, neighbor);
5654   cinfo->fwd_pid = pid;
5655   GNUNET_CONTAINER_multihashmap_iterate (t->children_fc,
5656                                          &tunnel_add_skip,
5657                                          &neighbor);
5658   if (GNUNET_YES == t->nobuffer &&
5659       GNUNET_YES == GMC_is_pid_bigger (pid, cinfo->fwd_ack))
5660   {
5661     GNUNET_STATISTICS_update (stats, "# unsolicited unicast", 1, GNUNET_NO);
5662     GNUNET_log (GNUNET_ERROR_TYPE_INFO, "  %u > %u\n", pid, cinfo->fwd_ack);
5663     GNUNET_break_op (0);
5664     return GNUNET_OK;
5665   }
5666   send_prebuilt_message (message, neighbor, t);
5667   GNUNET_STATISTICS_update (stats, "# unicast forwarded", 1, GNUNET_NO);
5668   return GNUNET_OK;
5669 }
5670
5671
5672 /**
5673  * Core handler for mesh network traffic going from the origin to all peers
5674  *
5675  * @param cls closure
5676  * @param message message
5677  * @param peer peer identity this notification is about
5678  * @param atsi performance data
5679  * @param atsi_count number of records in 'atsi'
5680  * @return GNUNET_OK to keep the connection open,
5681  *         GNUNET_SYSERR to close it (signal serious error)
5682  *
5683  * TODO: Check who we got this from, to validate route.
5684  */
5685 static int
5686 handle_mesh_data_multicast (void *cls, const struct GNUNET_PeerIdentity *peer,
5687                             const struct GNUNET_MessageHeader *message,
5688                             const struct GNUNET_ATS_Information *atsi,
5689                             unsigned int atsi_count)
5690 {
5691   struct GNUNET_MESH_Multicast *msg;
5692   struct MeshTunnel *t;
5693   size_t size;
5694   uint32_t pid;
5695
5696   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a multicast packet from %s\n",
5697               GNUNET_i2s (peer));
5698   size = ntohs (message->size);
5699   if (sizeof (struct GNUNET_MESH_Multicast) +
5700       sizeof (struct GNUNET_MessageHeader) > size)
5701   {
5702     GNUNET_break_op (0);
5703     return GNUNET_OK;
5704   }
5705   msg = (struct GNUNET_MESH_Multicast *) message;
5706   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5707
5708   if (NULL == t)
5709   {
5710     /* TODO notify that we dont know that tunnel */
5711     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
5712     GNUNET_break_op (0);
5713     return GNUNET_OK;
5714   }
5715   pid = ntohl (msg->pid);
5716   if (t->fwd_pid == pid)
5717   {
5718     /* already seen this packet, drop */
5719     GNUNET_STATISTICS_update (stats, "# duplicate PID drops", 1, GNUNET_NO);
5720     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5721                 " Already seen pid %u, DROPPING!\n", pid);
5722     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5723     return GNUNET_OK;
5724   }
5725   else
5726   {
5727     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5728                 " pid %u not seen yet, forwarding\n", pid);
5729   }
5730   t->skip += (pid - t->fwd_pid) - 1;
5731   t->fwd_pid = pid;
5732   tunnel_reset_timeout (t);
5733
5734   /* Transmit to locally interested clients */
5735   if (NULL != t->peers &&
5736       GNUNET_CONTAINER_multihashmap_contains (t->peers, &my_full_id.hashPubKey))
5737   {
5738     GNUNET_STATISTICS_update (stats, "# multicast received", 1, GNUNET_NO);
5739     send_subscribed_clients (message, &msg[1].header, t);
5740     tunnel_send_fwd_ack(t, GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
5741   }
5742   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ntohl (msg->ttl));
5743   if (ntohl (msg->ttl) == 0)
5744   {
5745     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
5746     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
5747     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5748     return GNUNET_OK;
5749   }
5750   GNUNET_STATISTICS_update (stats, "# multicast forwarded", 1, GNUNET_NO);
5751   tunnel_send_multicast (t, message);
5752   return GNUNET_OK;
5753 }
5754
5755
5756 /**
5757  * Core handler for mesh network traffic toward the owner of a tunnel
5758  *
5759  * @param cls closure
5760  * @param message message
5761  * @param peer peer identity this notification is about
5762  * @param atsi performance data
5763  * @param atsi_count number of records in 'atsi'
5764  *
5765  * @return GNUNET_OK to keep the connection open,
5766  *         GNUNET_SYSERR to close it (signal serious error)
5767  */
5768 static int
5769 handle_mesh_data_to_orig (void *cls, const struct GNUNET_PeerIdentity *peer,
5770                           const struct GNUNET_MessageHeader *message,
5771                           const struct GNUNET_ATS_Information *atsi,
5772                           unsigned int atsi_count)
5773 {
5774   struct GNUNET_MESH_ToOrigin *msg;
5775   struct GNUNET_PeerIdentity id;
5776   struct MeshPeerInfo *peer_info;
5777   struct MeshTunnel *t;
5778   struct MeshTunnelChildInfo *cinfo;
5779   size_t size;
5780   uint32_t pid;
5781
5782   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a ToOrigin packet from %s\n",
5783               GNUNET_i2s (peer));
5784   size = ntohs (message->size);
5785   if (size < sizeof (struct GNUNET_MESH_ToOrigin) +     /* Payload must be */
5786       sizeof (struct GNUNET_MessageHeader))     /* at least a header */
5787   {
5788     GNUNET_break_op (0);
5789     return GNUNET_OK;
5790   }
5791   msg = (struct GNUNET_MESH_ToOrigin *) message;
5792   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %s\n",
5793               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
5794   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5795   pid = ntohl (msg->pid);
5796
5797   if (NULL == t)
5798   {
5799     /* TODO notify that we dont know this tunnel (whom)? */
5800     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
5801     GNUNET_break_op (0);
5802     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5803                 "Received to_origin with PID %u on unknown tunnel\n",
5804                 pid);
5805     return GNUNET_OK;
5806   }
5807
5808   cinfo = tunnel_get_neighbor_fc(t, peer);
5809   if (NULL == cinfo)
5810   {
5811     GNUNET_break (0);
5812     return GNUNET_OK;
5813   }
5814
5815   if (cinfo->bck_pid == pid)
5816   {
5817     /* already seen this packet, drop */
5818     GNUNET_STATISTICS_update (stats, "# duplicate PID drops BCK", 1, GNUNET_NO);
5819     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5820                 " Already seen pid %u, DROPPING!\n", pid);
5821     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5822     return GNUNET_OK;
5823   }
5824
5825   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5826               " pid %u not seen yet, forwarding\n", pid);
5827   cinfo->bck_pid = pid;
5828
5829   if (NULL != t->owner)
5830   {
5831     char cbuf[size];
5832     struct GNUNET_MESH_ToOrigin *copy;
5833
5834     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5835                 "  it's for us! sending to clients...\n");
5836     /* TODO signature verification */
5837     memcpy (cbuf, message, size);
5838     copy = (struct GNUNET_MESH_ToOrigin *) cbuf;
5839     copy->tid = htonl (t->local_tid);
5840     t->bck_pid++;
5841     copy->pid = htonl (t->bck_pid);
5842     GNUNET_STATISTICS_update (stats, "# to origin received", 1, GNUNET_NO);
5843     GNUNET_SERVER_notification_context_unicast (nc, t->owner->handle,
5844                                                 &copy->header, GNUNET_NO);
5845     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
5846     return GNUNET_OK;
5847   }
5848   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5849               "  not for us, retransmitting...\n");
5850
5851   peer_info = peer_info_get (&msg->oid);
5852   if (NULL == peer_info)
5853   {
5854     /* unknown origin of tunnel */
5855     GNUNET_break (0);
5856     return GNUNET_OK;
5857   }
5858   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
5859   send_prebuilt_message (message, &id, t);
5860   GNUNET_STATISTICS_update (stats, "# to origin forwarded", 1, GNUNET_NO);
5861
5862   return GNUNET_OK;
5863 }
5864
5865
5866 /**
5867  * Core handler for mesh network traffic point-to-point acks.
5868  *
5869  * @param cls closure
5870  * @param message message
5871  * @param peer peer identity this notification is about
5872  * @param atsi performance data
5873  * @param atsi_count number of records in 'atsi'
5874  *
5875  * @return GNUNET_OK to keep the connection open,
5876  *         GNUNET_SYSERR to close it (signal serious error)
5877  */
5878 static int
5879 handle_mesh_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5880                  const struct GNUNET_MessageHeader *message,
5881                  const struct GNUNET_ATS_Information *atsi,
5882                  unsigned int atsi_count)
5883 {
5884   struct GNUNET_MESH_ACK *msg;
5885   struct MeshTunnel *t;
5886   uint32_t ack;
5887
5888   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK packet from %s!\n",
5889               GNUNET_i2s (peer));
5890   msg = (struct GNUNET_MESH_ACK *) message;
5891
5892   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5893
5894   if (NULL == t)
5895   {
5896     /* TODO notify that we dont know this tunnel (whom)? */
5897     GNUNET_STATISTICS_update (stats, "# ack on unknown tunnel", 1, GNUNET_NO);
5898     GNUNET_break_op (0);
5899     return GNUNET_OK;
5900   }
5901   ack = ntohl (msg->pid);
5902   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ACK %u\n", ack);
5903
5904   /* Is this a forward or backward ACK? */
5905   if (tree_get_predecessor(t->tree) != GNUNET_PEER_search(peer))
5906   {
5907     struct MeshTunnelChildInfo *cinfo;
5908
5909     debug_bck_ack++;
5910     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
5911     cinfo = tunnel_get_neighbor_fc (t, peer);
5912     cinfo->fwd_ack = ack;
5913     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5914     tunnel_unlock_fwd_queues (t);
5915   }
5916   else
5917   {
5918     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
5919     t->bck_ack = ack;
5920     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5921     tunnel_unlock_bck_queue (t);
5922   }
5923   return GNUNET_OK;
5924 }
5925
5926
5927 /**
5928  * Core handler for mesh network traffic point-to-point ack polls.
5929  *
5930  * @param cls closure
5931  * @param message message
5932  * @param peer peer identity this notification is about
5933  * @param atsi performance data
5934  * @param atsi_count number of records in 'atsi'
5935  *
5936  * @return GNUNET_OK to keep the connection open,
5937  *         GNUNET_SYSERR to close it (signal serious error)
5938  */
5939 static int
5940 handle_mesh_poll (void *cls, const struct GNUNET_PeerIdentity *peer,
5941                   const struct GNUNET_MessageHeader *message,
5942                   const struct GNUNET_ATS_Information *atsi,
5943                   unsigned int atsi_count)
5944 {
5945   struct GNUNET_MESH_Poll *msg;
5946   struct MeshTunnel *t;
5947
5948   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an POLL packet from %s!\n",
5949               GNUNET_i2s (peer));
5950
5951   msg = (struct GNUNET_MESH_Poll *) message;
5952
5953   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5954
5955   if (NULL == t)
5956   {
5957     /* TODO notify that we dont know this tunnel (whom)? */
5958     GNUNET_STATISTICS_update (stats, "# poll on unknown tunnel", 1, GNUNET_NO);
5959     GNUNET_break_op (0);
5960     return GNUNET_OK;
5961   }
5962
5963   /* Is this a forward or backward ACK? */
5964   if (tree_get_predecessor(t->tree) != GNUNET_PEER_search(peer))
5965   {
5966     struct MeshTunnelChildInfo *cinfo;
5967
5968     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  from FWD\n");
5969     cinfo = tunnel_get_neighbor_fc (t, peer);
5970     cinfo->bck_ack = cinfo->fwd_pid; // mark as ready to send
5971     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_POLL);
5972   }
5973   else
5974   {
5975     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  from BCK\n");
5976     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_POLL);
5977   }
5978
5979   return GNUNET_OK;
5980 }
5981
5982
5983 /**
5984  * Core handler for path ACKs
5985  *
5986  * @param cls closure
5987  * @param message message
5988  * @param peer peer identity this notification is about
5989  * @param atsi performance data
5990  * @param atsi_count number of records in 'atsi'
5991  *
5992  * @return GNUNET_OK to keep the connection open,
5993  *         GNUNET_SYSERR to close it (signal serious error)
5994  */
5995 static int
5996 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5997                       const struct GNUNET_MessageHeader *message,
5998                       const struct GNUNET_ATS_Information *atsi,
5999                       unsigned int atsi_count)
6000 {
6001   struct GNUNET_MESH_PathACK *msg;
6002   struct GNUNET_PeerIdentity id;
6003   struct MeshPeerInfo *peer_info;
6004   struct MeshPeerPath *p;
6005   struct MeshTunnel *t;
6006
6007   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a path ACK msg [%s]\n",
6008               GNUNET_i2s (&my_full_id));
6009   msg = (struct GNUNET_MESH_PathACK *) message;
6010   t = tunnel_get (&msg->oid, ntohl(msg->tid));
6011   if (NULL == t)
6012   {
6013     /* TODO notify that we don't know the tunnel */
6014     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel", 1, GNUNET_NO);
6015     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  don't know the tunnel %s [%X]!\n",
6016                 GNUNET_i2s (&msg->oid), ntohl(msg->tid));
6017     return GNUNET_OK;
6018   }
6019   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %s [%X]\n",
6020               GNUNET_i2s (&msg->oid), ntohl(msg->tid));
6021
6022   peer_info = peer_info_get (&msg->peer_id);
6023   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by peer %s\n",
6024               GNUNET_i2s (&msg->peer_id));
6025   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  via peer %s\n",
6026               GNUNET_i2s (peer));
6027
6028   if (NULL != t->regex_ctx && t->regex_ctx->info->peer == peer_info->id)
6029   {
6030     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6031                 "connect_by_string completed, stopping search\n");
6032     regex_cancel_search (t->regex_ctx);
6033     t->regex_ctx = NULL;
6034   }
6035
6036   /* Add paths to peers? */
6037   p = tree_get_path_to_peer (t->tree, peer_info->id);
6038   if (NULL != p)
6039   {
6040     path_add_to_peers (p, GNUNET_YES);
6041     path_destroy (p);
6042   }
6043   else
6044   {
6045     GNUNET_break (0);
6046   }
6047
6048   /* Message for us? */
6049   if (0 == memcmp (&msg->oid, &my_full_id, sizeof (struct GNUNET_PeerIdentity)))
6050   {
6051     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
6052     if (NULL == t->owner)
6053     {
6054       GNUNET_break_op (0);
6055       return GNUNET_OK;
6056     }
6057     if (NULL != t->dht_get_type)
6058     {
6059       GNUNET_DHT_get_stop (t->dht_get_type);
6060       t->dht_get_type = NULL;
6061     }
6062     if (tree_get_status (t->tree, peer_info->id) != MESH_PEER_READY)
6063     {
6064       tree_set_status (t->tree, peer_info->id, MESH_PEER_READY);
6065       send_client_peer_connected (t, peer_info->id);
6066     }
6067     return GNUNET_OK;
6068   }
6069
6070   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6071               "  not for us, retransmitting...\n");
6072   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
6073   peer_info = peer_info_get (&msg->oid);
6074   if (NULL == peer_info)
6075   {
6076     /* If we know the tunnel, we should DEFINITELY know the peer */
6077     GNUNET_break (0);
6078     return GNUNET_OK;
6079   }
6080   send_prebuilt_message (message, &id, t);
6081   return GNUNET_OK;
6082 }
6083
6084
6085 /**
6086  * Core handler for mesh keepalives.
6087  *
6088  * @param cls closure
6089  * @param message message
6090  * @param peer peer identity this notification is about
6091  * @param atsi performance data
6092  * @param atsi_count number of records in 'atsi'
6093  * @return GNUNET_OK to keep the connection open,
6094  *         GNUNET_SYSERR to close it (signal serious error)
6095  *
6096  * TODO: Check who we got this from, to validate route.
6097  */
6098 static int
6099 handle_mesh_keepalive (void *cls, const struct GNUNET_PeerIdentity *peer,
6100                        const struct GNUNET_MessageHeader *message,
6101                        const struct GNUNET_ATS_Information *atsi,
6102                        unsigned int atsi_count)
6103 {
6104   struct GNUNET_MESH_TunnelKeepAlive *msg;
6105   struct MeshTunnel *t;
6106
6107   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a keepalive packet from %s\n",
6108               GNUNET_i2s (peer));
6109
6110   msg = (struct GNUNET_MESH_TunnelKeepAlive *) message;
6111   t = tunnel_get (&msg->oid, ntohl (msg->tid));
6112
6113   if (NULL == t)
6114   {
6115     /* TODO notify that we dont know that tunnel */
6116     GNUNET_STATISTICS_update (stats, "# keepalive on unknown tunnel", 1, GNUNET_NO);
6117     GNUNET_break_op (0);
6118     return GNUNET_OK;
6119   }
6120
6121   tunnel_reset_timeout (t);
6122
6123   GNUNET_STATISTICS_update (stats, "# keepalives forwarded", 1, GNUNET_NO);
6124   tunnel_send_multicast (t, message);
6125   return GNUNET_OK;
6126   }
6127
6128
6129
6130 /**
6131  * Functions to handle messages from core
6132  */
6133 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
6134   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
6135   {&handle_mesh_path_destroy, GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY, 0},
6136   {&handle_mesh_path_broken, GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN,
6137    sizeof (struct GNUNET_MESH_PathBroken)},
6138   {&handle_mesh_tunnel_destroy, GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY,
6139    sizeof (struct GNUNET_MESH_TunnelDestroy)},
6140   {&handle_mesh_data_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
6141   {&handle_mesh_data_multicast, GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
6142   {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE,
6143     sizeof (struct GNUNET_MESH_TunnelKeepAlive)},
6144   {&handle_mesh_data_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
6145   {&handle_mesh_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
6146     sizeof (struct GNUNET_MESH_ACK)},
6147   {&handle_mesh_poll, GNUNET_MESSAGE_TYPE_MESH_POLL,
6148     sizeof (struct GNUNET_MESH_Poll)},
6149   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
6150    sizeof (struct GNUNET_MESH_PathACK)},
6151   {NULL, 0, 0}
6152 };
6153
6154
6155
6156 /******************************************************************************/
6157 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
6158 /******************************************************************************/
6159
6160 /**
6161  * deregister_app: iterator for removing each application registered by a client
6162  *
6163  * @param cls closure
6164  * @param key the hash of the application id (used to access the hashmap)
6165  * @param value the value stored at the key (client)
6166  *
6167  * @return GNUNET_OK on success
6168  */
6169 static int
6170 deregister_app (void *cls, const struct GNUNET_HashCode * key, void *value)
6171 {
6172   struct GNUNET_CONTAINER_MultiHashMap *h = cls;
6173   GNUNET_break (GNUNET_YES ==
6174                 GNUNET_CONTAINER_multihashmap_remove (h, key, value));
6175   return GNUNET_OK;
6176 }
6177
6178 #if LATER
6179 /**
6180  * notify_client_connection_failure: notify a client that the connection to the
6181  * requested remote peer is not possible (for instance, no route found)
6182  * Function called when the socket is ready to queue more data. "buf" will be
6183  * NULL and "size" zero if the socket was closed for writing in the meantime.
6184  *
6185  * @param cls closure
6186  * @param size number of bytes available in buf
6187  * @param buf where the callee should write the message
6188  * @return number of bytes written to buf
6189  */
6190 static size_t
6191 notify_client_connection_failure (void *cls, size_t size, void *buf)
6192 {
6193   int size_needed;
6194   struct MeshPeerInfo *peer_info;
6195   struct GNUNET_MESH_PeerControl *msg;
6196   struct GNUNET_PeerIdentity id;
6197
6198   if (0 == size && NULL == buf)
6199   {
6200     // TODO retry? cancel?
6201     return 0;
6202   }
6203
6204   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
6205   peer_info = (struct MeshPeerInfo *) cls;
6206   msg = (struct GNUNET_MESH_PeerControl *) buf;
6207   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
6208   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
6209 //     msg->tunnel_id = htonl(peer_info->t->tid);
6210   GNUNET_PEER_resolve (peer_info->id, &id);
6211   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
6212
6213   return size_needed;
6214 }
6215 #endif
6216
6217
6218 /**
6219  * Send keepalive packets for a peer
6220  *
6221  * @param cls Closure (tunnel for which to send the keepalive).
6222  * @param tc Notification context.
6223  */
6224 static void
6225 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
6226 {
6227   struct MeshTunnel *t = cls;
6228   struct GNUNET_MESH_TunnelKeepAlive *msg;
6229   size_t size = sizeof (struct GNUNET_MESH_TunnelKeepAlive);
6230   char cbuf[size];
6231
6232   t->path_refresh_task = GNUNET_SCHEDULER_NO_TASK;
6233   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
6234   {
6235     return;
6236   }
6237
6238   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6239               "sending keepalive for tunnel %d\n", t->id.tid);
6240
6241   msg = (struct GNUNET_MESH_TunnelKeepAlive *) cbuf;
6242   msg->header.size = htons (size);
6243   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE);
6244   msg->oid = my_full_id;
6245   msg->tid = htonl (t->id.tid);
6246   tunnel_send_multicast (t, &msg->header);
6247
6248   t->path_refresh_task =
6249       GNUNET_SCHEDULER_add_delayed (refresh_path_time, &path_refresh, t);
6250   tunnel_reset_timeout(t);
6251 }
6252
6253
6254 /**
6255  * Function to process paths received for a new peer addition. The recorded
6256  * paths form the initial tunnel, which can be optimized later.
6257  * Called on each result obtained for the DHT search.
6258  *
6259  * @param cls closure
6260  * @param exp when will this value expire
6261  * @param key key of the result
6262  * @param get_path path of the get request
6263  * @param get_path_length lenght of get_path
6264  * @param put_path path of the put request
6265  * @param put_path_length length of the put_path
6266  * @param type type of the result
6267  * @param size number of bytes in data
6268  * @param data pointer to the result data
6269  *
6270  * TODO: re-issue the request after certain time? cancel after X results?
6271  */
6272 static void
6273 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
6274                     const struct GNUNET_HashCode * key,
6275                     const struct GNUNET_PeerIdentity *get_path,
6276                     unsigned int get_path_length,
6277                     const struct GNUNET_PeerIdentity *put_path,
6278                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
6279                     size_t size, const void *data)
6280 {
6281   struct MeshPathInfo *path_info = cls;
6282   struct MeshPeerPath *p;
6283   struct GNUNET_PeerIdentity pi;
6284   int i;
6285
6286   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
6287   GNUNET_PEER_resolve (path_info->peer->id, &pi);
6288   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", GNUNET_i2s (&pi));
6289
6290   p = path_build_from_dht (get_path, get_path_length, put_path,
6291                            put_path_length);
6292   path_add_to_peers (p, GNUNET_NO);
6293   path_destroy(p);
6294   for (i = 0; i < path_info->peer->ntunnels; i++)
6295   {
6296     tunnel_add_peer (path_info->peer->tunnels[i], path_info->peer);
6297     peer_info_connect (path_info->peer, path_info->t);
6298   }
6299
6300   return;
6301 }
6302
6303
6304 /**
6305  * Function to process paths received for a new peer addition. The recorded
6306  * paths form the initial tunnel, which can be optimized later.
6307  * Called on each result obtained for the DHT search.
6308  *
6309  * @param cls closure
6310  * @param exp when will this value expire
6311  * @param key key of the result
6312  * @param get_path path of the get request
6313  * @param get_path_length lenght of get_path
6314  * @param put_path path of the put request
6315  * @param put_path_length length of the put_path
6316  * @param type type of the result
6317  * @param size number of bytes in data
6318  * @param data pointer to the result data
6319  */
6320 static void
6321 dht_get_type_handler (void *cls, struct GNUNET_TIME_Absolute exp,
6322                       const struct GNUNET_HashCode * key,
6323                       const struct GNUNET_PeerIdentity *get_path,
6324                       unsigned int get_path_length,
6325                       const struct GNUNET_PeerIdentity *put_path,
6326                       unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
6327                       size_t size, const void *data)
6328 {
6329   const struct PBlock *pb = data;
6330   const struct GNUNET_PeerIdentity *pi = &pb->id;
6331   struct MeshTunnel *t = cls;
6332   struct MeshPeerInfo *peer_info;
6333   struct MeshPeerPath *p;
6334
6335   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got type DHT result!\n");
6336   if (size != sizeof (struct PBlock))
6337   {
6338     GNUNET_break_op (0);
6339     return;
6340   }
6341   if (ntohl(pb->type) != t->type)
6342   {
6343     GNUNET_break_op (0);
6344     return;
6345   }
6346   GNUNET_assert (NULL != t->owner);
6347   peer_info = peer_info_get (pi);
6348   (void) GNUNET_CONTAINER_multihashmap_put (t->peers, &pi->hashPubKey,
6349                                             peer_info,
6350                                             GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
6351
6352   p = path_build_from_dht (get_path, get_path_length, put_path,
6353                            put_path_length);
6354   path_add_to_peers (p, GNUNET_NO);
6355   path_destroy(p);
6356   tunnel_add_peer (t, peer_info);
6357   peer_info_connect (peer_info, t);
6358 }
6359
6360
6361 /**
6362  * Function to process DHT string to regex matching.
6363  * Called on each result obtained for the DHT search.
6364  *
6365  * @param cls closure (search context)
6366  * @param exp when will this value expire
6367  * @param key key of the result
6368  * @param get_path path of the get request (not used)
6369  * @param get_path_length lenght of get_path (not used)
6370  * @param put_path path of the put request (not used)
6371  * @param put_path_length length of the put_path (not used)
6372  * @param type type of the result
6373  * @param size number of bytes in data
6374  * @param data pointer to the result data
6375  */
6376 static void
6377 dht_get_string_accept_handler (void *cls, struct GNUNET_TIME_Absolute exp,
6378                                const struct GNUNET_HashCode * key,
6379                                const struct GNUNET_PeerIdentity *get_path,
6380                                unsigned int get_path_length,
6381                                const struct GNUNET_PeerIdentity *put_path,
6382                                unsigned int put_path_length,
6383                                enum GNUNET_BLOCK_Type type,
6384                                size_t size, const void *data)
6385 {
6386   const struct MeshRegexAccept *block = data;
6387   struct MeshRegexSearchContext *ctx = cls;
6388   struct MeshRegexSearchInfo *info = ctx->info;
6389   struct MeshPeerPath *p;
6390   struct MeshPeerInfo *peer_info;
6391
6392   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got regex results from DHT!\n");
6393   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", info->description);
6394
6395   peer_info = peer_info_get(&block->id);
6396   p = path_build_from_dht (get_path, get_path_length, put_path,
6397                            put_path_length);
6398   path_add_to_peers (p, GNUNET_NO);
6399   path_destroy(p);
6400
6401   tunnel_add_peer (info->t, peer_info);
6402   peer_info_connect (peer_info, info->t);
6403   if (0 == info->peer)
6404   {
6405     info->peer = peer_info->id;
6406   }
6407   else
6408   {
6409     GNUNET_array_append (info->peers, info->n_peers, peer_info->id);
6410   }
6411
6412   info->timeout = GNUNET_SCHEDULER_add_delayed (connect_timeout,
6413                                                 &regex_connect_timeout,
6414                                                 info);
6415
6416   return;
6417 }
6418
6419
6420 /**
6421  * Function to process DHT string to regex matching.
6422  * Called on each result obtained for the DHT search.
6423  *
6424  * @param cls closure (search context)
6425  * @param exp when will this value expire
6426  * @param key key of the result
6427  * @param get_path path of the get request (not used)
6428  * @param get_path_length lenght of get_path (not used)
6429  * @param put_path path of the put request (not used)
6430  * @param put_path_length length of the put_path (not used)
6431  * @param type type of the result
6432  * @param size number of bytes in data
6433  * @param data pointer to the result data
6434  *
6435  * TODO: re-issue the request after certain time? cancel after X results?
6436  */
6437 static void
6438 dht_get_string_handler (void *cls, struct GNUNET_TIME_Absolute exp,
6439                         const struct GNUNET_HashCode * key,
6440                         const struct GNUNET_PeerIdentity *get_path,
6441                         unsigned int get_path_length,
6442                         const struct GNUNET_PeerIdentity *put_path,
6443                         unsigned int put_path_length,
6444                         enum GNUNET_BLOCK_Type type,
6445                         size_t size, const void *data)
6446 {
6447   const struct MeshRegexBlock *block = data;
6448   struct MeshRegexSearchContext *ctx = cls;
6449   struct MeshRegexSearchInfo *info = ctx->info;
6450   void *copy;
6451   size_t len;
6452
6453   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6454               "DHT GET STRING RETURNED RESULTS\n");
6455   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6456               "  key: %s\n", GNUNET_h2s (key));
6457
6458   copy = GNUNET_malloc (size);
6459   memcpy (copy, data, size);
6460   GNUNET_break (GNUNET_OK ==
6461                 GNUNET_CONTAINER_multihashmap_put(info->dht_get_results, key, copy,
6462                                                   GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
6463   len = ntohl (block->n_proof);
6464   {
6465     char proof[len + 1];
6466
6467     memcpy (proof, &block[1], len);
6468     proof[len] = '\0';
6469     if (GNUNET_OK != GNUNET_REGEX_check_proof (proof, key))
6470     {
6471       GNUNET_break_op (0);
6472       return;
6473     }
6474   }
6475   len = strlen (info->description);
6476   if (len == ctx->position) // String processed
6477   {
6478     if (GNUNET_YES == ntohl (block->accepting))
6479     {
6480       regex_find_path(key, ctx);
6481     }
6482     else
6483     {
6484       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  block not accepting!\n");
6485       // FIXME REGEX this block not successful, wait for more? start timeout?
6486     }
6487     return;
6488   }
6489
6490   regex_next_edge (block, size, ctx);
6491
6492   return;
6493 }
6494
6495 /******************************************************************************/
6496 /*********************       MESH LOCAL HANDLES      **************************/
6497 /******************************************************************************/
6498
6499
6500 /**
6501  * Handler for client disconnection
6502  *
6503  * @param cls closure
6504  * @param client identification of the client; NULL
6505  *        for the last call when the server is destroyed
6506  */
6507 static void
6508 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
6509 {
6510   struct MeshClient *c;
6511   struct MeshClient *next;
6512   unsigned int i;
6513
6514   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected\n");
6515   if (client == NULL)
6516   {
6517     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (SERVER DOWN)\n");
6518     return;
6519   }
6520   c = clients;
6521   while (NULL != c)
6522   {
6523     if (c->handle != client)
6524     {
6525       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ... searching\n");
6526       c = c->next;
6527       continue;
6528     }
6529     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u)\n",
6530                 c->id);
6531     GNUNET_SERVER_client_drop (c->handle);
6532     c->shutting_down = GNUNET_YES;
6533     GNUNET_assert (NULL != c->own_tunnels);
6534     GNUNET_assert (NULL != c->incoming_tunnels);
6535     GNUNET_CONTAINER_multihashmap_iterate (c->own_tunnels,
6536                                            &tunnel_destroy_iterator, c);
6537     GNUNET_CONTAINER_multihashmap_iterate (c->incoming_tunnels,
6538                                            &tunnel_destroy_iterator, c);
6539     GNUNET_CONTAINER_multihashmap_iterate (c->ignore_tunnels,
6540                                            &tunnel_destroy_iterator, c);
6541     GNUNET_CONTAINER_multihashmap_destroy (c->own_tunnels);
6542     GNUNET_CONTAINER_multihashmap_destroy (c->incoming_tunnels);
6543     GNUNET_CONTAINER_multihashmap_destroy (c->ignore_tunnels);
6544
6545     /* deregister clients applications */
6546     if (NULL != c->apps)
6547     {
6548       GNUNET_CONTAINER_multihashmap_iterate (c->apps, &deregister_app, c->apps);
6549       GNUNET_CONTAINER_multihashmap_destroy (c->apps);
6550     }
6551     if (0 == GNUNET_CONTAINER_multihashmap_size (applications) &&
6552         GNUNET_SCHEDULER_NO_TASK != announce_applications_task)
6553     {
6554       GNUNET_SCHEDULER_cancel (announce_applications_task);
6555       announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
6556     }
6557     if (NULL != c->types)
6558       GNUNET_CONTAINER_multihashmap_destroy (c->types);
6559     for (i = 0; i < c->n_regex; i++)
6560     {
6561       GNUNET_free (c->regexes[i]);
6562     }
6563     GNUNET_free_non_null (c->regexes);
6564     if (GNUNET_SCHEDULER_NO_TASK != c->regex_announce_task)
6565       GNUNET_SCHEDULER_cancel (c->regex_announce_task);
6566     next = c->next;
6567     GNUNET_CONTAINER_DLL_remove (clients, clients_tail, c);
6568     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT FREE at %p\n", c);
6569     GNUNET_free (c);
6570     GNUNET_STATISTICS_update (stats, "# clients", -1, GNUNET_NO);
6571     c = next;
6572   }
6573   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   done!\n");
6574   return;
6575 }
6576
6577
6578 /**
6579  * Handler for new clients
6580  *
6581  * @param cls closure
6582  * @param client identification of the client
6583  * @param message the actual message, which includes messages the client wants
6584  */
6585 static void
6586 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
6587                          const struct GNUNET_MessageHeader *message)
6588 {
6589   struct GNUNET_MESH_ClientConnect *cc_msg;
6590   struct MeshClient *c;
6591   GNUNET_MESH_ApplicationType *a;
6592   unsigned int size;
6593   uint16_t ntypes;
6594   uint16_t *t;
6595   uint16_t napps;
6596   uint16_t i;
6597
6598   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected\n");
6599   /* Check data sanity */
6600   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
6601   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
6602   ntypes = ntohs (cc_msg->types);
6603   napps = ntohs (cc_msg->applications);
6604   if (size !=
6605       ntypes * sizeof (uint16_t) + napps * sizeof (GNUNET_MESH_ApplicationType))
6606   {
6607     GNUNET_break (0);
6608     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6609     return;
6610   }
6611
6612   /* Create new client structure */
6613   c = GNUNET_malloc (sizeof (struct MeshClient));
6614   c->id = next_client_id++;
6615   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT NEW %u\n", c->id);
6616   c->handle = client;
6617   GNUNET_SERVER_client_keep (client);
6618   a = (GNUNET_MESH_ApplicationType *) &cc_msg[1];
6619   if (napps > 0)
6620   {
6621     GNUNET_MESH_ApplicationType at;
6622     struct GNUNET_HashCode hc;
6623
6624     c->apps = GNUNET_CONTAINER_multihashmap_create (napps, GNUNET_NO);
6625     for (i = 0; i < napps; i++)
6626     {
6627       at = ntohl (a[i]);
6628       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  app type: %u\n", at);
6629       GNUNET_CRYPTO_hash (&at, sizeof (at), &hc);
6630       /* store in clients hashmap */
6631       GNUNET_CONTAINER_multihashmap_put (c->apps, &hc, (void *) (long) at,
6632                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6633       /* store in global hashmap, for announcements */
6634       GNUNET_CONTAINER_multihashmap_put (applications, &hc, c,
6635                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6636     }
6637     if (GNUNET_SCHEDULER_NO_TASK == announce_applications_task)
6638       announce_applications_task =
6639           GNUNET_SCHEDULER_add_now (&announce_applications, NULL);
6640
6641   }
6642   if (ntypes > 0)
6643   {
6644     uint16_t u16;
6645     struct GNUNET_HashCode hc;
6646
6647     t = (uint16_t *) & a[napps];
6648     c->types = GNUNET_CONTAINER_multihashmap_create (ntypes, GNUNET_NO);
6649     for (i = 0; i < ntypes; i++)
6650     {
6651       u16 = ntohs (t[i]);
6652       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  msg type: %u\n", u16);
6653       GNUNET_CRYPTO_hash (&u16, sizeof (u16), &hc);
6654
6655       /* store in clients hashmap */
6656       GNUNET_CONTAINER_multihashmap_put (c->types, &hc, c,
6657                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6658       /* store in global hashmap */
6659       GNUNET_CONTAINER_multihashmap_put (types, &hc, c,
6660                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6661     }
6662   }
6663   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6664               " client has %u+%u subscriptions\n", napps, ntypes);
6665
6666   GNUNET_CONTAINER_DLL_insert (clients, clients_tail, c);
6667   c->own_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6668   c->incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6669   c->ignore_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6670   GNUNET_SERVER_notification_context_add (nc, client);
6671   GNUNET_STATISTICS_update (stats, "# clients", 1, GNUNET_NO);
6672
6673   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6674   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
6675 }
6676
6677
6678 /**
6679  * Handler for clients announcing available services by a regular expression.
6680  *
6681  * @param cls closure
6682  * @param client identification of the client
6683  * @param message the actual message, which includes messages the client wants
6684  */
6685 static void
6686 handle_local_announce_regex (void *cls, struct GNUNET_SERVER_Client *client,
6687                              const struct GNUNET_MessageHeader *message)
6688 {
6689   struct MeshClient *c;
6690   char *regex;
6691   size_t len;
6692
6693   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "announce regex started\n");
6694
6695   /* Sanity check for client registration */
6696   if (NULL == (c = client_get (client)))
6697   {
6698     GNUNET_break (0);
6699     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6700     return;
6701   }
6702   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6703
6704   len = ntohs (message->size) - sizeof(struct GNUNET_MessageHeader);
6705   regex = GNUNET_malloc (len + 1);
6706   memcpy (regex, &message[1], len);
6707   regex[len] = '\0';
6708   GNUNET_array_append (c->regexes, c->n_regex, regex);
6709   if (GNUNET_SCHEDULER_NO_TASK == c->regex_announce_task)
6710   {
6711     c->regex_announce_task = GNUNET_SCHEDULER_add_now(&announce_regex, c);
6712   }
6713   else
6714   {
6715     regex_put(regex);
6716   }
6717   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6718   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "announce regex processed\n");
6719 }
6720
6721
6722 /**
6723  * Handler for requests of new tunnels
6724  *
6725  * @param cls closure
6726  * @param client identification of the client
6727  * @param message the actual message
6728  */
6729 static void
6730 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
6731                             const struct GNUNET_MessageHeader *message)
6732 {
6733   struct GNUNET_MESH_TunnelMessage *t_msg;
6734   struct MeshTunnel *t;
6735   struct MeshClient *c;
6736   MESH_TunnelNumber tid;
6737
6738   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel requested\n");
6739
6740   /* Sanity check for client registration */
6741   if (NULL == (c = client_get (client)))
6742   {
6743     GNUNET_break (0);
6744     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6745     return;
6746   }
6747   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6748
6749   /* Message sanity check */
6750   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
6751   {
6752     GNUNET_break (0);
6753     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6754     return;
6755   }
6756
6757   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6758   /* Sanity check for tunnel numbering */
6759   tid = ntohl (t_msg->tunnel_id);
6760   if (0 == (tid & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
6761   {
6762     GNUNET_break (0);
6763     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6764     return;
6765   }
6766   /* Sanity check for duplicate tunnel IDs */
6767   if (NULL != tunnel_get_by_local_id (c, tid))
6768   {
6769     GNUNET_break (0);
6770     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6771     return;
6772   }
6773
6774   while (NULL != tunnel_get_by_pi (myid, next_tid))
6775     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
6776   t = tunnel_new (myid, next_tid++, c, tid);
6777   if (NULL == t)
6778   {
6779     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Tunnel creation failed.\n");
6780     GNUNET_break (0);
6781     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6782     return;
6783   }
6784   next_tid = next_tid & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
6785   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED TUNNEL %s [%x] (%x)\n",
6786               GNUNET_i2s (&my_full_id), t->id.tid, t->local_tid);
6787   t->peers = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6788
6789   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel created\n");
6790   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6791   return;
6792 }
6793
6794
6795 /**
6796  * Handler for requests of deleting tunnels
6797  *
6798  * @param cls closure
6799  * @param client identification of the client
6800  * @param message the actual message
6801  */
6802 static void
6803 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
6804                              const struct GNUNET_MessageHeader *message)
6805 {
6806   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
6807   struct MeshClient *c;
6808   struct MeshTunnel *t;
6809   MESH_TunnelNumber tid;
6810
6811   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6812               "Got a DESTROY TUNNEL from client!\n");
6813
6814   /* Sanity check for client registration */
6815   if (NULL == (c = client_get (client)))
6816   {
6817     GNUNET_break (0);
6818     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6819     return;
6820   }
6821   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6822
6823   /* Message sanity check */
6824   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
6825   {
6826     GNUNET_break (0);
6827     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6828     return;
6829   }
6830
6831   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6832
6833   /* Retrieve tunnel */
6834   tid = ntohl (tunnel_msg->tunnel_id);
6835   t = tunnel_get_by_local_id(c, tid);
6836   if (NULL == t)
6837   {
6838     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
6839     GNUNET_break (0);
6840     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6841     return;
6842   }
6843   if (c != t->owner || tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
6844   {
6845     client_ignore_tunnel (c, t);
6846 #if 0
6847     // TODO: when to destroy incoming tunnel?
6848     if (t->nclients == 0)
6849     {
6850       GNUNET_assert (GNUNET_YES ==
6851                      GNUNET_CONTAINER_multihashmap_remove (incoming_tunnels,
6852                                                            &hash, t));
6853       GNUNET_assert (GNUNET_YES ==
6854                      GNUNET_CONTAINER_multihashmap_remove (t->peers,
6855                                                            &my_full_id.hashPubKey,
6856                                                            t));
6857     }
6858 #endif
6859     GNUNET_SERVER_receive_done (client, GNUNET_OK);
6860     return;
6861   }
6862   send_client_tunnel_disconnect(t, c);
6863   client_delete_tunnel(c, t);
6864
6865   /* Don't try to ACK the client about the tunnel_destroy multicast packet */
6866   t->owner = NULL;
6867   tunnel_send_destroy (t);
6868   t->destroy = GNUNET_YES;
6869   // The tunnel will be destroyed when the last message is transmitted.
6870   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6871   return;
6872 }
6873
6874
6875 /**
6876  * Handler for requests of seeting tunnel's speed.
6877  *
6878  * @param cls Closure (unused).
6879  * @param client Identification of the client.
6880  * @param message The actual message.
6881  */
6882 static void
6883 handle_local_tunnel_speed (void *cls, struct GNUNET_SERVER_Client *client,
6884                            const struct GNUNET_MessageHeader *message)
6885 {
6886   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
6887   struct MeshClient *c;
6888   struct MeshTunnel *t;
6889   MESH_TunnelNumber tid;
6890
6891   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6892               "Got a SPEED request from client!\n");
6893
6894   /* Sanity check for client registration */
6895   if (NULL == (c = client_get (client)))
6896   {
6897     GNUNET_break (0);
6898     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6899     return;
6900   }
6901
6902   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6903
6904   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6905
6906   /* Retrieve tunnel */
6907   tid = ntohl (tunnel_msg->tunnel_id);
6908   t = tunnel_get_by_local_id(c, tid);
6909   if (NULL == t)
6910   {
6911     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  tunnel %X not found\n", tid);
6912     GNUNET_break (0);
6913     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6914     return;
6915   }
6916
6917   switch (ntohs(message->type))
6918   {
6919       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MIN:
6920           t->speed_min = GNUNET_YES;
6921           break;
6922       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MAX:
6923           t->speed_min = GNUNET_NO;
6924           break;
6925       default:
6926           GNUNET_break (0);
6927   }
6928   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6929 }
6930
6931
6932 /**
6933  * Handler for requests of seeting tunnel's buffering policy.
6934  *
6935  * @param cls Closure (unused).
6936  * @param client Identification of the client.
6937  * @param message The actual message.
6938  */
6939 static void
6940 handle_local_tunnel_buffer (void *cls, struct GNUNET_SERVER_Client *client,
6941                             const struct GNUNET_MessageHeader *message)
6942 {
6943   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
6944   struct MeshClient *c;
6945   struct MeshTunnel *t;
6946   MESH_TunnelNumber tid;
6947
6948   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6949               "Got a BUFFER request from client!\n");
6950
6951   /* Sanity check for client registration */
6952   if (NULL == (c = client_get (client)))
6953   {
6954     GNUNET_break (0);
6955     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6956     return;
6957   }
6958   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6959
6960   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6961
6962   /* Retrieve tunnel */
6963   tid = ntohl (tunnel_msg->tunnel_id);
6964   t = tunnel_get_by_local_id(c, tid);
6965   if (NULL == t)
6966   {
6967     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
6968     GNUNET_break (0);
6969     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6970     return;
6971   }
6972
6973   switch (ntohs(message->type))
6974   {
6975       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER:
6976           t->nobuffer = GNUNET_NO;
6977           break;
6978       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER:
6979           t->nobuffer = GNUNET_YES;
6980           break;
6981       default:
6982           GNUNET_break (0);
6983   }
6984
6985   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6986 }
6987
6988
6989 /**
6990  * Handler for connection requests to new peers
6991  *
6992  * @param cls closure
6993  * @param client identification of the client
6994  * @param message the actual message (PeerControl)
6995  */
6996 static void
6997 handle_local_connect_add (void *cls, struct GNUNET_SERVER_Client *client,
6998                           const struct GNUNET_MessageHeader *message)
6999 {
7000   struct GNUNET_MESH_PeerControl *peer_msg;
7001   struct MeshPeerInfo *peer_info;
7002   struct MeshClient *c;
7003   struct MeshTunnel *t;
7004   MESH_TunnelNumber tid;
7005
7006   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got connection request\n");
7007   /* Sanity check for client registration */
7008   if (NULL == (c = client_get (client)))
7009   {
7010     GNUNET_break (0);
7011     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7012     return;
7013   }
7014   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7015
7016   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
7017
7018   /* Sanity check for message size */
7019   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
7020   {
7021     GNUNET_break (0);
7022     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7023     return;
7024   }
7025
7026   /* Tunnel exists? */
7027   tid = ntohl (peer_msg->tunnel_id);
7028   t = tunnel_get_by_local_id (c, tid);
7029   if (NULL == t)
7030   {
7031     GNUNET_break (0);
7032     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7033     return;
7034   }
7035
7036   /* Does client own tunnel? */
7037   if (t->owner->handle != client)
7038   {
7039     GNUNET_break (0);
7040     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7041     return;
7042   }
7043   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "     for %s\n",
7044               GNUNET_i2s (&peer_msg->peer));
7045   peer_info = peer_info_get (&peer_msg->peer);
7046
7047   tunnel_add_peer (t, peer_info);
7048   peer_info_connect (peer_info, t);
7049
7050   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7051   return;
7052 }
7053
7054
7055 /**
7056  * Handler for disconnection requests of peers in a tunnel
7057  *
7058  * @param cls closure
7059  * @param client identification of the client
7060  * @param message the actual message (PeerControl)
7061  */
7062 static void
7063 handle_local_connect_del (void *cls, struct GNUNET_SERVER_Client *client,
7064                           const struct GNUNET_MessageHeader *message)
7065 {
7066   struct GNUNET_MESH_PeerControl *peer_msg;
7067   struct MeshPeerInfo *peer_info;
7068   struct MeshClient *c;
7069   struct MeshTunnel *t;
7070   MESH_TunnelNumber tid;
7071
7072   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER DEL request\n");
7073   /* Sanity check for client registration */
7074   if (NULL == (c = client_get (client)))
7075   {
7076     GNUNET_break (0);
7077     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7078     return;
7079   }
7080   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7081
7082   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
7083
7084   /* Sanity check for message size */
7085   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
7086   {
7087     GNUNET_break (0);
7088     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7089     return;
7090   }
7091
7092   /* Tunnel exists? */
7093   tid = ntohl (peer_msg->tunnel_id);
7094   t = tunnel_get_by_local_id (c, tid);
7095   if (NULL == t)
7096   {
7097     GNUNET_break (0);
7098     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7099     return;
7100   }
7101   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
7102
7103   /* Does client own tunnel? */
7104   if (t->owner->handle != client)
7105   {
7106     GNUNET_break (0);
7107     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7108     return;
7109   }
7110
7111   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for peer %s\n",
7112               GNUNET_i2s (&peer_msg->peer));
7113   /* Is the peer in the tunnel? */
7114   peer_info =
7115       GNUNET_CONTAINER_multihashmap_get (t->peers, &peer_msg->peer.hashPubKey);
7116   if (NULL == peer_info)
7117   {
7118     GNUNET_break (0);
7119     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7120     return;
7121   }
7122
7123   /* Ok, delete peer from tunnel */
7124   GNUNET_CONTAINER_multihashmap_remove_all (t->peers,
7125                                             &peer_msg->peer.hashPubKey);
7126
7127   send_destroy_path (t, peer_info->id);
7128   tunnel_delete_peer (t, peer_info->id);
7129   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7130   return;
7131 }
7132
7133 /**
7134  * Handler for blacklist requests of peers in a tunnel
7135  *
7136  * @param cls closure
7137  * @param client identification of the client
7138  * @param message the actual message (PeerControl)
7139  * 
7140  * FIXME implement DHT block bloomfilter
7141  */
7142 static void
7143 handle_local_blacklist (void *cls, struct GNUNET_SERVER_Client *client,
7144                           const struct GNUNET_MessageHeader *message)
7145 {
7146   struct GNUNET_MESH_PeerControl *peer_msg;
7147   struct MeshClient *c;
7148   struct MeshTunnel *t;
7149   MESH_TunnelNumber tid;
7150
7151   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER BLACKLIST request\n");
7152   /* Sanity check for client registration */
7153   if (NULL == (c = client_get (client)))
7154   {
7155     GNUNET_break (0);
7156     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7157     return;
7158   }
7159   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7160
7161   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
7162
7163   /* Sanity check for message size */
7164   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
7165   {
7166     GNUNET_break (0);
7167     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7168     return;
7169   }
7170
7171   /* Tunnel exists? */
7172   tid = ntohl (peer_msg->tunnel_id);
7173   t = tunnel_get_by_local_id (c, tid);
7174   if (NULL == t)
7175   {
7176     GNUNET_break (0);
7177     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7178     return;
7179   }
7180   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
7181
7182   GNUNET_array_append(t->blacklisted, t->nblacklisted,
7183                       GNUNET_PEER_intern(&peer_msg->peer));
7184 }
7185
7186
7187 /**
7188  * Handler for unblacklist requests of peers in a tunnel
7189  *
7190  * @param cls closure
7191  * @param client identification of the client
7192  * @param message the actual message (PeerControl)
7193  */
7194 static void
7195 handle_local_unblacklist (void *cls, struct GNUNET_SERVER_Client *client,
7196                           const struct GNUNET_MessageHeader *message)
7197 {
7198   struct GNUNET_MESH_PeerControl *peer_msg;
7199   struct MeshClient *c;
7200   struct MeshTunnel *t;
7201   MESH_TunnelNumber tid;
7202   GNUNET_PEER_Id pid;
7203   unsigned int i;
7204
7205   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER UNBLACKLIST request\n");
7206   /* Sanity check for client registration */
7207   if (NULL == (c = client_get (client)))
7208   {
7209     GNUNET_break (0);
7210     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7211     return;
7212   }
7213   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7214
7215   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
7216
7217   /* Sanity check for message size */
7218   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
7219   {
7220     GNUNET_break (0);
7221     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7222     return;
7223   }
7224
7225   /* Tunnel exists? */
7226   tid = ntohl (peer_msg->tunnel_id);
7227   t = tunnel_get_by_local_id (c, tid);
7228   if (NULL == t)
7229   {
7230     GNUNET_break (0);
7231     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7232     return;
7233   }
7234   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
7235
7236   /* if peer is not known, complain */
7237   pid = GNUNET_PEER_search (&peer_msg->peer);
7238   if (0 == pid)
7239   {
7240     GNUNET_break (0);
7241     return;
7242   }
7243
7244   /* search and remove from list */
7245   for (i = 0; i < t->nblacklisted; i++)
7246   {
7247     if (t->blacklisted[i] == pid)
7248     {
7249       t->blacklisted[i] = t->blacklisted[t->nblacklisted - 1];
7250       GNUNET_array_grow (t->blacklisted, t->nblacklisted, t->nblacklisted - 1);
7251       return;
7252     }
7253   }
7254
7255   /* if peer hasn't been blacklisted, complain */
7256   GNUNET_break (0);
7257 }
7258
7259
7260 /**
7261  * Handler for connection requests to new peers by type
7262  *
7263  * @param cls closure
7264  * @param client identification of the client
7265  * @param message the actual message (ConnectPeerByType)
7266  */
7267 static void
7268 handle_local_connect_by_type (void *cls, struct GNUNET_SERVER_Client *client,
7269                               const struct GNUNET_MessageHeader *message)
7270 {
7271   struct GNUNET_MESH_ConnectPeerByType *connect_msg;
7272   struct MeshClient *c;
7273   struct MeshTunnel *t;
7274   struct GNUNET_HashCode hash;
7275   MESH_TunnelNumber tid;
7276
7277   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got connect by type request\n");
7278   /* Sanity check for client registration */
7279   if (NULL == (c = client_get (client)))
7280   {
7281     GNUNET_break (0);
7282     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7283     return;
7284   }
7285   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7286
7287   connect_msg = (struct GNUNET_MESH_ConnectPeerByType *) message;
7288
7289   /* Sanity check for message size */
7290   if (sizeof (struct GNUNET_MESH_ConnectPeerByType) !=
7291       ntohs (connect_msg->header.size))
7292   {
7293     GNUNET_break (0);
7294     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7295     return;
7296   }
7297
7298   /* Tunnel exists? */
7299   tid = ntohl (connect_msg->tunnel_id);
7300   t = tunnel_get_by_local_id (c, tid);
7301   if (NULL == t)
7302   {
7303     GNUNET_break (0);
7304     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7305     return;
7306   }
7307
7308   /* Does client own tunnel? */
7309   if (t->owner->handle != client)
7310   {
7311     GNUNET_break (0);
7312     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7313     return;
7314   }
7315
7316   /* Do WE have the service? */
7317   t->type = ntohl (connect_msg->type);
7318   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " type requested: %u\n", t->type);
7319   GNUNET_CRYPTO_hash (&t->type, sizeof (GNUNET_MESH_ApplicationType), &hash);
7320   if (GNUNET_CONTAINER_multihashmap_contains (applications, &hash) ==
7321       GNUNET_YES)
7322   {
7323     /* Yes! Fast forward, add ourselves to the tunnel and send the
7324      * good news to the client, and alert the destination client of
7325      * an incoming tunnel.
7326      *
7327      * FIXME send a path create to self, avoid code duplication
7328      */
7329     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " available locally\n");
7330     GNUNET_CONTAINER_multihashmap_put (t->peers, &my_full_id.hashPubKey,
7331                                        peer_info_get (&my_full_id),
7332                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
7333
7334     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " notifying client\n");
7335     send_client_peer_connected (t, myid);
7336     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Done\n");
7337     GNUNET_SERVER_receive_done (client, GNUNET_OK);
7338
7339     t->local_tid_dest = next_local_tid++;
7340     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
7341     GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
7342                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
7343
7344     return;
7345   }
7346   /* Ok, lets find a peer offering the service */
7347   if (NULL != t->dht_get_type)
7348   {
7349     GNUNET_DHT_get_stop (t->dht_get_type);
7350   }
7351   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " looking in DHT for %s\n",
7352               GNUNET_h2s (&hash));
7353   t->dht_get_type =
7354       GNUNET_DHT_get_start (dht_handle, 
7355                             GNUNET_BLOCK_TYPE_MESH_PEER_BY_TYPE,
7356                             &hash,
7357                             dht_replication_level,
7358                             GNUNET_DHT_RO_RECORD_ROUTE |
7359                             GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
7360                             NULL, 0,
7361                             &dht_get_type_handler, t);
7362
7363   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7364   return;
7365 }
7366
7367
7368 /**
7369  * Handler for connection requests to new peers by a string service description.
7370  *
7371  * @param cls closure
7372  * @param client identification of the client
7373  * @param message the actual message, which includes messages the client wants
7374  */
7375 static void
7376 handle_local_connect_by_string (void *cls, struct GNUNET_SERVER_Client *client,
7377                                 const struct GNUNET_MessageHeader *message)
7378 {
7379   struct GNUNET_MESH_ConnectPeerByString *msg;
7380   struct MeshRegexSearchContext *ctx;
7381   struct MeshRegexSearchInfo *info;
7382   struct GNUNET_DHT_GetHandle *get_h;
7383   struct GNUNET_HashCode key;
7384   struct MeshTunnel *t;
7385   struct MeshClient *c;
7386   MESH_TunnelNumber tid;
7387   const char *string;
7388   size_t size;
7389   size_t len;
7390   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7391               "Connect by string started\n");
7392   msg = (struct GNUNET_MESH_ConnectPeerByString *) message;
7393   size = htons (message->size);
7394
7395   /* Sanity check for client registration */
7396   if (NULL == (c = client_get (client)))
7397   {
7398     GNUNET_break (0);
7399     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7400     return;
7401   }
7402   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7403
7404   /* Message size sanity check */
7405   if (sizeof(struct GNUNET_MESH_ConnectPeerByString) >= size)
7406   {
7407     GNUNET_break (0);
7408     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7409     return;
7410   }
7411
7412   /* Tunnel exists? */
7413   tid = ntohl (msg->tunnel_id);
7414   t = tunnel_get_by_local_id (c, tid);
7415   if (NULL == t)
7416   {
7417     GNUNET_break (0);
7418     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7419     return;
7420   }
7421
7422   /* Does client own tunnel? */
7423   if (t->owner->handle != client)
7424   {
7425     GNUNET_break (0);
7426     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7427     return;
7428   }
7429
7430   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7431               "  on tunnel %s [%u]\n",
7432               GNUNET_i2s(&my_full_id),
7433               t->id.tid);
7434
7435   /* Only one connect_by_string allowed at the same time! */
7436   /* FIXME: allow more, return handle at api level to cancel, document */
7437   if (NULL != t->regex_ctx)
7438   {
7439     GNUNET_break (0);
7440     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7441     return;
7442   }
7443
7444   /* Find string itself */
7445   len = size - sizeof(struct GNUNET_MESH_ConnectPeerByString);
7446   string = (const char *) &msg[1];
7447
7448   /* Initialize context */
7449   size = GNUNET_REGEX_get_first_key(string, len, &key);
7450   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7451               "  consumed %u bits out of %u\n", size, len);
7452   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7453               "  looking for %s\n", GNUNET_h2s (&key));
7454
7455   info = GNUNET_malloc (sizeof (struct MeshRegexSearchInfo));
7456   info->t = t;
7457   info->description = GNUNET_malloc (len + 1);
7458   memcpy (info->description, string, len);
7459   info->description[len] = '\0';
7460   info->dht_get_handles = GNUNET_CONTAINER_multihashmap_create(32, GNUNET_NO);
7461   info->dht_get_results = GNUNET_CONTAINER_multihashmap_create(32, GNUNET_NO);
7462   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   string: %s\n", info->description);
7463
7464   ctx = GNUNET_malloc (sizeof (struct MeshRegexSearchContext));
7465   ctx->position = size;
7466   ctx->info = info;
7467   t->regex_ctx = ctx;
7468
7469   GNUNET_array_append (info->contexts, info->n_contexts, ctx);
7470
7471   /* Start search in DHT */
7472   get_h = GNUNET_DHT_get_start (dht_handle,    /* handle */
7473                                 GNUNET_BLOCK_TYPE_MESH_REGEX, /* type */
7474                                 &key,     /* key to search */
7475                                 dht_replication_level, /* replication level */
7476                                 GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
7477                                 NULL,       /* xquery */ // FIXME BLOOMFILTER
7478                                 0,     /* xquery bits */ // FIXME BLOOMFILTER SIZE
7479                                 &dht_get_string_handler, ctx);
7480
7481   GNUNET_break (GNUNET_OK ==
7482                 GNUNET_CONTAINER_multihashmap_put(info->dht_get_handles,
7483                                                   &key,
7484                                                   get_h,
7485                                                   GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
7486
7487   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7488   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "connect by string processed\n");
7489 }
7490
7491
7492 /**
7493  * Handler for client traffic directed to one peer
7494  *
7495  * @param cls closure
7496  * @param client identification of the client
7497  * @param message the actual message
7498  */
7499 static void
7500 handle_local_unicast (void *cls, struct GNUNET_SERVER_Client *client,
7501                       const struct GNUNET_MessageHeader *message)
7502 {
7503   struct MeshClient *c;
7504   struct MeshTunnel *t;
7505   struct MeshPeerInfo *pi;
7506   struct GNUNET_MESH_Unicast *data_msg;
7507   MESH_TunnelNumber tid;
7508   size_t size;
7509
7510   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7511               "Got a unicast request from a client!\n");
7512
7513   /* Sanity check for client registration */
7514   if (NULL == (c = client_get (client)))
7515   {
7516     GNUNET_break (0);
7517     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7518     return;
7519   }
7520   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7521
7522   data_msg = (struct GNUNET_MESH_Unicast *) message;
7523
7524   /* Sanity check for message size */
7525   size = ntohs (message->size);
7526   if (sizeof (struct GNUNET_MESH_Unicast) +
7527       sizeof (struct GNUNET_MessageHeader) > size)
7528   {
7529     GNUNET_break (0);
7530     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7531     return;
7532   }
7533
7534   /* Tunnel exists? */
7535   tid = ntohl (data_msg->tid);
7536   t = tunnel_get_by_local_id (c, tid);
7537   if (NULL == t)
7538   {
7539     GNUNET_break (0);
7540     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7541     return;
7542   }
7543
7544   /*  Is it a local tunnel? Then, does client own the tunnel? */
7545   if (t->owner->handle != client)
7546   {
7547     GNUNET_break (0);
7548     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7549     return;
7550   }
7551
7552   pi = GNUNET_CONTAINER_multihashmap_get (t->peers,
7553                                           &data_msg->destination.hashPubKey);
7554   /* Is the selected peer in the tunnel? */
7555   if (NULL == pi)
7556   {
7557     GNUNET_break (0);
7558     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7559     return;
7560   }
7561
7562   /* PID should be as expected */
7563   if (ntohl (data_msg->pid) != t->fwd_pid + 1)
7564   {
7565     GNUNET_break (0);
7566     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7567               "Unicast PID, expected %u, got %u\n",
7568               t->fwd_pid + 1, ntohl (data_msg->pid));
7569     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7570     return;
7571   }
7572
7573   /* Ok, everything is correct, send the message
7574    * (pretend we got it from a mesh peer)
7575    */
7576   {
7577     /* Work around const limitation */
7578     char buf[ntohs (message->size)] GNUNET_ALIGN;
7579     struct GNUNET_MESH_Unicast *copy;
7580
7581     copy = (struct GNUNET_MESH_Unicast *) buf;
7582     memcpy (buf, data_msg, size);
7583     copy->oid = my_full_id;
7584     copy->tid = htonl (t->id.tid);
7585     copy->ttl = htonl (default_ttl);
7586     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7587                 "  calling generic handler...\n");
7588     handle_mesh_data_unicast (NULL, &my_full_id, &copy->header, NULL, 0);
7589   }
7590   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "receive done OK\n");
7591   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7592
7593   return;
7594 }
7595
7596
7597 /**
7598  * Handler for client traffic directed to the origin
7599  *
7600  * @param cls closure
7601  * @param client identification of the client
7602  * @param message the actual message
7603  */
7604 static void
7605 handle_local_to_origin (void *cls, struct GNUNET_SERVER_Client *client,
7606                         const struct GNUNET_MessageHeader *message)
7607 {
7608   struct GNUNET_MESH_ToOrigin *data_msg;
7609   struct MeshTunnelClientInfo *clinfo;
7610   struct MeshClient *c;
7611   struct MeshTunnel *t;
7612   MESH_TunnelNumber tid;
7613   size_t size;
7614
7615   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7616               "Got a ToOrigin request from a client!\n");
7617   /* Sanity check for client registration */
7618   if (NULL == (c = client_get (client)))
7619   {
7620     GNUNET_break (0);
7621     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7622     return;
7623   }
7624   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7625
7626   data_msg = (struct GNUNET_MESH_ToOrigin *) message;
7627
7628   /* Sanity check for message size */
7629   size = ntohs (message->size);
7630   if (sizeof (struct GNUNET_MESH_ToOrigin) +
7631       sizeof (struct GNUNET_MessageHeader) > size)
7632   {
7633     GNUNET_break (0);
7634     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7635     return;
7636   }
7637
7638   /* Tunnel exists? */
7639   tid = ntohl (data_msg->tid);
7640   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
7641   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
7642   {
7643     GNUNET_break (0);
7644     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7645     return;
7646   }
7647   t = tunnel_get_by_local_id (c, tid);
7648   if (NULL == t)
7649   {
7650     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
7651     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
7652     GNUNET_break (0);
7653     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7654     return;
7655   }
7656
7657   /*  It should be sent by someone who has this as incoming tunnel. */
7658   if (GNUNET_NO == client_knows_tunnel (c, t))
7659   {
7660     GNUNET_break (0);
7661     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7662     return;
7663   }
7664
7665   /* PID should be as expected */
7666   clinfo = tunnel_get_client_fc (t, c);
7667   if (ntohl (data_msg->pid) != clinfo->bck_pid + 1)
7668   {
7669     GNUNET_break (0);
7670     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7671                 "To Origin PID, expected %u, got %u\n",
7672                 clinfo->bck_pid + 1,
7673                 ntohl (data_msg->pid));
7674     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7675     return;
7676   }
7677
7678   /* Ok, everything is correct, send the message
7679    * (pretend we got it from a mesh peer)
7680    */
7681   clinfo->bck_pid++;
7682   {
7683     char buf[ntohs (message->size)] GNUNET_ALIGN;
7684     struct GNUNET_MESH_ToOrigin *copy;
7685
7686     /* Work around const limitation */
7687     copy = (struct GNUNET_MESH_ToOrigin *) buf;
7688     memcpy (buf, data_msg, size);
7689     GNUNET_PEER_resolve (t->id.oid, &copy->oid);
7690     copy->tid = htonl (t->id.tid);
7691     copy->ttl = htonl (default_ttl);
7692     if (ntohl (copy->pid) != (t->bck_pid + 1))
7693     {
7694       GNUNET_break (0);
7695       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7696                   "To Origin PID, expected %u, got %u\n",
7697                   t->bck_pid + 1,
7698                   ntohl (copy->pid));
7699       return;
7700     }
7701     copy->sender = my_full_id;
7702     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7703                 "  calling generic handler...\n");
7704     handle_mesh_data_to_orig (NULL, &my_full_id, &copy->header, NULL, 0);
7705   }
7706   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7707
7708   return;
7709 }
7710
7711
7712 /**
7713  * Handler for client traffic directed to all peers in a tunnel
7714  *
7715  * @param cls closure
7716  * @param client identification of the client
7717  * @param message the actual message
7718  */
7719 static void
7720 handle_local_multicast (void *cls, struct GNUNET_SERVER_Client *client,
7721                         const struct GNUNET_MessageHeader *message)
7722 {
7723   struct MeshClient *c;
7724   struct MeshTunnel *t;
7725   struct GNUNET_MESH_Multicast *data_msg;
7726   MESH_TunnelNumber tid;
7727
7728   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7729               "Got a multicast request from a client!\n");
7730
7731   /* Sanity check for client registration */
7732   if (NULL == (c = client_get (client)))
7733   {
7734     GNUNET_break (0);
7735     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7736     return;
7737   }
7738   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7739
7740   data_msg = (struct GNUNET_MESH_Multicast *) message;
7741
7742   /* Sanity check for message size */
7743   if (sizeof (struct GNUNET_MESH_Multicast) +
7744       sizeof (struct GNUNET_MessageHeader) > ntohs (data_msg->header.size))
7745   {
7746     GNUNET_break (0);
7747     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7748     return;
7749   }
7750
7751   /* Tunnel exists? */
7752   tid = ntohl (data_msg->tid);
7753   t = tunnel_get_by_local_id (c, tid);
7754   if (NULL == t)
7755   {
7756     GNUNET_break (0);
7757     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
7758     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
7759     GNUNET_break (0);
7760     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7761     return;
7762   }
7763
7764   /* Does client own tunnel? */
7765   if (t->owner->handle != client)
7766   {
7767     GNUNET_break (0);
7768     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7769     return;
7770   }
7771
7772   /* PID should be as expected */
7773   if (ntohl (data_msg->pid) != t->fwd_pid + 1)
7774   {
7775     GNUNET_break (0);
7776     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7777               "Multicast PID, expected %u, got %u\n",
7778               t->fwd_pid + 1, ntohl (data_msg->pid));
7779     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7780     return;
7781   }
7782
7783   {
7784     char buf[ntohs (message->size)] GNUNET_ALIGN;
7785     struct GNUNET_MESH_Multicast *copy;
7786
7787     copy = (struct GNUNET_MESH_Multicast *) buf;
7788     memcpy (buf, message, ntohs (message->size));
7789     copy->oid = my_full_id;
7790     copy->tid = htonl (t->id.tid);
7791     copy->ttl = htonl (default_ttl);
7792     GNUNET_assert (ntohl (copy->pid) == (t->fwd_pid + 1));
7793     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7794                 "  calling generic handler...\n");
7795     handle_mesh_data_multicast (client, &my_full_id, &copy->header, NULL, 0);
7796   }
7797
7798   GNUNET_SERVER_receive_done (t->owner->handle, GNUNET_OK);
7799   return;
7800 }
7801
7802
7803 /**
7804  * Handler for client's ACKs for payload traffic.
7805  *
7806  * @param cls Closure (unused).
7807  * @param client Identification of the client.
7808  * @param message The actual message.
7809  */
7810 static void
7811 handle_local_ack (void *cls, struct GNUNET_SERVER_Client *client,
7812                   const struct GNUNET_MessageHeader *message)
7813 {
7814   struct GNUNET_MESH_LocalAck *msg;
7815   struct MeshTunnel *t;
7816   struct MeshClient *c;
7817   MESH_TunnelNumber tid;
7818   uint32_t ack;
7819
7820   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a local ACK\n");
7821   /* Sanity check for client registration */
7822   if (NULL == (c = client_get (client)))
7823   {
7824     GNUNET_break (0);
7825     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7826     return;
7827   }
7828   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7829
7830   msg = (struct GNUNET_MESH_LocalAck *) message;
7831
7832   /* Tunnel exists? */
7833   tid = ntohl (msg->tunnel_id);
7834   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
7835   t = tunnel_get_by_local_id (c, tid);
7836   if (NULL == t)
7837   {
7838     GNUNET_break (0);
7839     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
7840     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
7841     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7842     return;
7843   }
7844
7845   ack = ntohl (msg->max_pid);
7846   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ack %u\n", ack);
7847
7848   /* Does client own tunnel? I.E: Is this and ACK for BCK traffic? */
7849   if (NULL != t->owner && t->owner->handle == client)
7850   {
7851     /* The client owns the tunnel, ACK is for data to_origin, send BCK ACK. */
7852     t->bck_ack = ack;
7853     tunnel_send_bck_ack(t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
7854   }
7855   else
7856   {
7857     /* The client doesn't own the tunnel, this ACK is for FWD traffic. */
7858     tunnel_set_client_fwd_ack (t, c, ack);
7859     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
7860   }
7861
7862   GNUNET_SERVER_receive_done (client, GNUNET_OK);  
7863
7864   return;
7865 }
7866
7867
7868 /**
7869  * Functions to handle messages from clients
7870  */
7871 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
7872   {&handle_local_new_client, NULL,
7873    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
7874   {&handle_local_announce_regex, NULL,
7875    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ANNOUNCE_REGEX, 0},
7876   {&handle_local_tunnel_create, NULL,
7877    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
7878    sizeof (struct GNUNET_MESH_TunnelMessage)},
7879   {&handle_local_tunnel_destroy, NULL,
7880    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
7881    sizeof (struct GNUNET_MESH_TunnelMessage)},
7882   {&handle_local_tunnel_speed, NULL,
7883    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MIN,
7884    sizeof (struct GNUNET_MESH_TunnelMessage)},
7885   {&handle_local_tunnel_speed, NULL,
7886    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MAX,
7887    sizeof (struct GNUNET_MESH_TunnelMessage)},
7888   {&handle_local_tunnel_buffer, NULL,
7889    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER,
7890    sizeof (struct GNUNET_MESH_TunnelMessage)},
7891   {&handle_local_tunnel_buffer, NULL,
7892    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER,
7893    sizeof (struct GNUNET_MESH_TunnelMessage)},
7894   {&handle_local_connect_add, NULL,
7895    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD,
7896    sizeof (struct GNUNET_MESH_PeerControl)},
7897   {&handle_local_connect_del, NULL,
7898    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL,
7899    sizeof (struct GNUNET_MESH_PeerControl)},
7900   {&handle_local_blacklist, NULL,
7901    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_BLACKLIST,
7902    sizeof (struct GNUNET_MESH_PeerControl)},
7903   {&handle_local_unblacklist, NULL,
7904    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_UNBLACKLIST,
7905    sizeof (struct GNUNET_MESH_PeerControl)},
7906   {&handle_local_connect_by_type, NULL,
7907    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE,
7908    sizeof (struct GNUNET_MESH_ConnectPeerByType)},
7909   {&handle_local_connect_by_string, NULL,
7910    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_STRING, 0},
7911   {&handle_local_unicast, NULL,
7912    GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
7913   {&handle_local_to_origin, NULL,
7914    GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
7915   {&handle_local_multicast, NULL,
7916    GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
7917   {&handle_local_ack, NULL,
7918    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK,
7919    sizeof (struct GNUNET_MESH_LocalAck)},
7920   {NULL, NULL, 0, 0}
7921 };
7922
7923
7924 /**
7925  * To be called on core init/fail.
7926  *
7927  * @param cls service closure
7928  * @param server handle to the server for this service
7929  * @param identity the public identity of this peer
7930  */
7931 static void
7932 core_init (void *cls, struct GNUNET_CORE_Handle *server,
7933            const struct GNUNET_PeerIdentity *identity)
7934 {
7935   static int i = 0;
7936   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
7937   core_handle = server;
7938   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)) ||
7939       NULL == server)
7940   {
7941     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
7942     GNUNET_SCHEDULER_shutdown (); // Try gracefully
7943     if (10 < i++)
7944       GNUNET_abort(); // Try harder
7945   }
7946   return;
7947 }
7948
7949
7950 /**
7951  * Method called whenever a given peer connects.
7952  *
7953  * @param cls closure
7954  * @param peer peer identity this notification is about
7955  * @param atsi performance data for the connection
7956  * @param atsi_count number of records in 'atsi'
7957  */
7958 static void
7959 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
7960               const struct GNUNET_ATS_Information *atsi,
7961               unsigned int atsi_count)
7962 {
7963   struct MeshPeerInfo *peer_info;
7964   struct MeshPeerPath *path;
7965
7966   DEBUG_CONN ("Peer connected\n");
7967   DEBUG_CONN ("     %s\n", GNUNET_i2s (&my_full_id));
7968   peer_info = peer_info_get (peer);
7969   if (myid == peer_info->id)
7970   {
7971     DEBUG_CONN ("     (self)\n");
7972     return;
7973   }
7974   else
7975   {
7976     DEBUG_CONN ("     %s\n", GNUNET_i2s (peer));
7977   }
7978   path = path_new (2);
7979   path->peers[0] = myid;
7980   path->peers[1] = peer_info->id;
7981   GNUNET_PEER_change_rc (myid, 1);
7982   GNUNET_PEER_change_rc (peer_info->id, 1);
7983   peer_info_add_path (peer_info, path, GNUNET_YES);
7984   GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
7985   return;
7986 }
7987
7988
7989 /**
7990  * Method called whenever a peer disconnects.
7991  *
7992  * @param cls closure
7993  * @param peer peer identity this notification is about
7994  */
7995 static void
7996 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
7997 {
7998   struct MeshPeerInfo *pi;
7999   struct MeshPeerQueue *q;
8000   struct MeshPeerQueue *n;
8001
8002   DEBUG_CONN ("Peer disconnected\n");
8003   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
8004   if (NULL == pi)
8005   {
8006     GNUNET_break (0);
8007     return;
8008   }
8009   q = pi->queue_head;
8010   while (NULL != q)
8011   {
8012       n = q->next;
8013       /* TODO try to reroute this traffic instead */
8014       queue_destroy(q, GNUNET_YES);
8015       q = n;
8016   }
8017   if (NULL != pi->core_transmit)
8018   {
8019     GNUNET_CORE_notify_transmit_ready_cancel(pi->core_transmit);
8020     pi->core_transmit = NULL;
8021   }
8022   peer_info_remove_path (pi, pi->id, myid);
8023   if (myid == pi->id)
8024   {
8025     DEBUG_CONN ("     (self)\n");
8026   }
8027   GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
8028   return;
8029 }
8030
8031
8032 /******************************************************************************/
8033 /************************      MAIN FUNCTIONS      ****************************/
8034 /******************************************************************************/
8035
8036 /**
8037  * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
8038  *
8039  * @param cls closure
8040  * @param key current key code
8041  * @param value value in the hash map
8042  * @return GNUNET_YES if we should continue to iterate,
8043  *         GNUNET_NO if not.
8044  */
8045 static int
8046 shutdown_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
8047 {
8048   struct MeshTunnel *t = value;
8049
8050   tunnel_destroy (t);
8051   return GNUNET_YES;
8052 }
8053
8054 /**
8055  * Iterator over peer hash map entries to destroy the tunnel during shutdown.
8056  *
8057  * @param cls closure
8058  * @param key current key code
8059  * @param value value in the hash map
8060  * @return GNUNET_YES if we should continue to iterate,
8061  *         GNUNET_NO if not.
8062  */
8063 static int
8064 shutdown_peer (void *cls, const struct GNUNET_HashCode * key, void *value)
8065 {
8066   struct MeshPeerInfo *p = value;
8067   struct MeshPeerQueue *q;
8068   struct MeshPeerQueue *n;
8069
8070   q = p->queue_head;
8071   while (NULL != q)
8072   {
8073       n = q->next;
8074       if (q->peer == p)
8075       {
8076         queue_destroy(q, GNUNET_YES);
8077       }
8078       q = n;
8079   }
8080   peer_info_destroy (p);
8081   return GNUNET_YES;
8082 }
8083
8084
8085 /**
8086  * Task run during shutdown.
8087  *
8088  * @param cls unused
8089  * @param tc unused
8090  */
8091 static void
8092 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
8093 {
8094   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
8095
8096   if (core_handle != NULL)
8097   {
8098     GNUNET_CORE_disconnect (core_handle);
8099     core_handle = NULL;
8100   }
8101  if (NULL != keygen)
8102   {
8103     GNUNET_CRYPTO_rsa_key_create_stop (keygen);
8104     keygen = NULL;
8105   }
8106   GNUNET_CONTAINER_multihashmap_iterate (tunnels, &shutdown_tunnel, NULL);
8107   GNUNET_CONTAINER_multihashmap_iterate (peers, &shutdown_peer, NULL);
8108   if (dht_handle != NULL)
8109   {
8110     GNUNET_DHT_disconnect (dht_handle);
8111     dht_handle = NULL;
8112   }
8113   if (nc != NULL)
8114   {
8115     GNUNET_SERVER_notification_context_destroy (nc);
8116     nc = NULL;
8117   }
8118   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
8119   {
8120     GNUNET_SCHEDULER_cancel (announce_id_task);
8121     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
8122   }
8123   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
8124 }
8125
8126
8127 /**
8128  * Callback for hostkey read/generation
8129  *
8130  * @param cls NULL
8131  * @param pk the private key
8132  * @param emsg error message
8133  */
8134 static void
8135 key_generation_cb (void *cls,
8136                    struct GNUNET_CRYPTO_RsaPrivateKey *pk,
8137                    const char *emsg)
8138 {
8139   struct MeshPeerInfo *peer;
8140   struct MeshPeerPath *p;
8141
8142   keygen = NULL;  
8143   if (NULL == pk)
8144   {
8145     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8146                 _("Mesh service could not access hostkey.  Exiting.\n"));
8147     GNUNET_SCHEDULER_shutdown ();
8148     return;
8149   }
8150   my_private_key = pk;
8151   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
8152   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
8153                       &my_full_id.hashPubKey);
8154   myid = GNUNET_PEER_intern (&my_full_id);
8155   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
8156               "Mesh for peer [%s] starting\n",
8157               GNUNET_i2s(&my_full_id));
8158
8159 //   transport_handle = GNUNET_TRANSPORT_connect(c,
8160 //                                               &my_full_id,
8161 //                                               NULL,
8162 //                                               NULL,
8163 //                                               NULL,
8164 //                                               NULL);
8165
8166
8167
8168   next_tid = 0;
8169   next_local_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
8170
8171
8172   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
8173   nc = GNUNET_SERVER_notification_context_create (server_handle, 1);
8174   GNUNET_SERVER_disconnect_notify (server_handle,
8175                                    &handle_local_client_disconnect, NULL);
8176
8177
8178   clients = NULL;
8179   clients_tail = NULL;
8180   next_client_id = 0;
8181
8182   announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
8183   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
8184
8185   /* Create a peer_info for the local peer */
8186   peer = peer_info_get (&my_full_id);
8187   p = path_new (1);
8188   p->peers[0] = myid;
8189   GNUNET_PEER_change_rc (myid, 1);
8190   peer_info_add_path (peer, p, GNUNET_YES);
8191   GNUNET_SERVER_resume (server_handle);
8192   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Mesh service running\n");
8193 }
8194
8195
8196 /**
8197  * Process mesh requests.
8198  *
8199  * @param cls closure
8200  * @param server the initialized server
8201  * @param c configuration to use
8202  */
8203 static void
8204 run (void *cls, struct GNUNET_SERVER_Handle *server,
8205      const struct GNUNET_CONFIGURATION_Handle *c)
8206 {
8207   char *keyfile;
8208
8209   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
8210   server_handle = server;
8211   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
8212                                      NULL,      /* Closure passed to MESH functions */
8213                                      &core_init,        /* Call core_init once connected */
8214                                      &core_connect,     /* Handle connects */
8215                                      &core_disconnect,  /* remove peers on disconnects */
8216                                      NULL,      /* Don't notify about all incoming messages */
8217                                      GNUNET_NO, /* For header only in notification */
8218                                      NULL,      /* Don't notify about all outbound messages */
8219                                      GNUNET_NO, /* For header-only out notification */
8220                                      core_handlers);    /* Register these handlers */
8221
8222   if (core_handle == NULL)
8223   {
8224     GNUNET_break (0);
8225     GNUNET_SCHEDULER_shutdown ();
8226     return;
8227   }
8228
8229   if (GNUNET_OK !=
8230       GNUNET_CONFIGURATION_get_value_filename (c, "GNUNETD", "HOSTKEY",
8231                                                &keyfile))
8232   {
8233     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8234                 _
8235                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8236                 "mesh", "hostkey");
8237     GNUNET_SCHEDULER_shutdown ();
8238     return;
8239   }
8240
8241   if (GNUNET_OK !=
8242       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_PATH_TIME",
8243                                            &refresh_path_time))
8244   {
8245     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8246                 _
8247                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8248                 "mesh", "refresh path time");
8249     GNUNET_SCHEDULER_shutdown ();
8250     return;
8251   }
8252
8253   if (GNUNET_OK !=
8254       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "APP_ANNOUNCE_TIME",
8255                                            &app_announce_time))
8256   {
8257     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8258                 _
8259                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8260                 "mesh", "app announce time");
8261     GNUNET_SCHEDULER_shutdown ();
8262     return;
8263   }
8264   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "APP_ANNOUNCE_TIME %llu ms\n", app_announce_time.rel_value);
8265
8266   if (GNUNET_OK !=
8267       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "ID_ANNOUNCE_TIME",
8268                                            &id_announce_time))
8269   {
8270     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8271                 _
8272                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8273                 "mesh", "id announce time");
8274     GNUNET_SCHEDULER_shutdown ();
8275     return;
8276   }
8277   else
8278   {
8279   }
8280
8281   if (GNUNET_OK !=
8282       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "UNACKNOWLEDGED_WAIT",
8283                                            &unacknowledged_wait_time))
8284   {
8285     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8286                 _
8287                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8288                 "mesh", "unacknowledged wait time");
8289     GNUNET_SCHEDULER_shutdown ();
8290     return;
8291   }
8292
8293   if (GNUNET_OK !=
8294       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "CONNECT_TIMEOUT",
8295                                            &connect_timeout))
8296   {
8297     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8298                 _
8299                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8300                 "mesh", "connect timeout");
8301     GNUNET_SCHEDULER_shutdown ();
8302     return;
8303   }
8304
8305   if (GNUNET_OK !=
8306       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
8307                                              &max_msgs_queue))
8308   {
8309     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8310                 _
8311                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8312                 "mesh", "max msgs queue");
8313     GNUNET_SCHEDULER_shutdown ();
8314     return;
8315   }
8316
8317   if (GNUNET_OK !=
8318       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_TUNNELS",
8319                                              &max_tunnels))
8320   {
8321     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8322                 _
8323                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8324                 "mesh", "max tunnels");
8325     GNUNET_SCHEDULER_shutdown ();
8326     return;
8327   }
8328
8329   if (GNUNET_OK !=
8330       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
8331                                              &default_ttl))
8332   {
8333     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
8334                 _
8335                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
8336                 "mesh", "default ttl", 64);
8337     default_ttl = 64;
8338   }
8339
8340   if (GNUNET_OK !=
8341       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DHT_REPLICATION_LEVEL",
8342                                              &dht_replication_level))
8343   {
8344     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
8345                 _
8346                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
8347                 "mesh", "dht replication level", 10);
8348     dht_replication_level = 10;
8349   }
8350
8351   tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
8352   incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
8353   peers = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
8354   applications = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
8355   types = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
8356
8357   dht_handle = GNUNET_DHT_connect (c, 64);
8358   if (NULL == dht_handle)
8359   {
8360     GNUNET_break (0);
8361   }
8362   stats = GNUNET_STATISTICS_create ("mesh", c);
8363
8364   GNUNET_SERVER_suspend (server_handle);
8365   /* Scheduled the task to clean up when shutdown is called */
8366   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
8367                                 NULL);
8368   keygen = GNUNET_CRYPTO_rsa_key_create_start (keyfile, &key_generation_cb, NULL);
8369   GNUNET_free (keyfile);
8370 }
8371
8372
8373 /**
8374  * The main function for the mesh service.
8375  *
8376  * @param argc number of arguments from the command line
8377  * @param argv command line arguments
8378  * @return 0 ok, 1 on error
8379  */
8380 int
8381 main (int argc, char *const *argv)
8382 {
8383   int ret;
8384   int r;
8385
8386   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
8387   r = GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
8388                           NULL);
8389   ret = (GNUNET_OK == r) ? 0 : 1;
8390   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");
8391
8392   INTERVAL_SHOW;
8393
8394   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
8395               "Mesh for peer [%s] FWD ACKs %u, BCK ACKs %u\n",
8396               GNUNET_i2s(&my_full_id), debug_fwd_ack, debug_bck_ack);
8397
8398   return ret;
8399 }