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