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