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