- disable debug by default
[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           GNUNET_SERVER_notification_context_unicast (nc, c->handle,
2089                                                       &tmsg.header, GNUNET_NO);
2090           tunnel_add_client (t, c);
2091           GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber),
2092                               &hash);
2093           GNUNET_break (GNUNET_OK == GNUNET_CONTAINER_multihashmap_put (
2094                                        c->incoming_tunnels, &hash, t,
2095                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
2096         }
2097         *tid = htonl (t->local_tid_dest);
2098       }
2099
2100       /* Check if the client wants to get traffic from the tunnel */
2101       if (GNUNET_NO == client_wants_tunnel(c, t))
2102         continue;
2103       count++;
2104       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "     sending\n");
2105       GNUNET_SERVER_notification_context_unicast (nc, c->handle,
2106                                                   (struct GNUNET_MessageHeader
2107                                                    *) cbuf, GNUNET_NO);
2108     }
2109   }
2110
2111   return count;
2112 }
2113
2114
2115 /**
2116  * Notify the client that owns the tunnel that a peer has connected to it
2117  * (the requested path to it has been confirmed).
2118  *
2119  * @param t Tunnel whose owner to notify
2120  * @param id Short id of the peer that has connected
2121  */
2122 static void
2123 send_client_peer_connected (const struct MeshTunnel *t, const GNUNET_PEER_Id id)
2124 {
2125   struct GNUNET_MESH_PeerControl pc;
2126
2127   pc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD);
2128   pc.header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
2129   pc.tunnel_id = htonl (t->local_tid);
2130   GNUNET_PEER_resolve (id, &pc.peer);
2131   GNUNET_SERVER_notification_context_unicast (nc, t->owner->handle, &pc.header,
2132                                               GNUNET_NO);
2133 }
2134
2135
2136 /**
2137  * Notify all clients (not depending on registration status) that the incoming
2138  * tunnel is no longer valid.
2139  *
2140  * @param t Tunnel that was destroyed.
2141  */
2142 static void
2143 send_clients_tunnel_destroy (struct MeshTunnel *t)
2144 {
2145   struct GNUNET_MESH_TunnelMessage msg;
2146
2147   msg.header.size = htons (sizeof (msg));
2148   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
2149   msg.tunnel_id = htonl (t->local_tid_dest);
2150   GNUNET_SERVER_notification_context_broadcast (nc, &msg.header, GNUNET_NO);
2151 }
2152
2153
2154 /**
2155  * Notify clients of tunnel disconnections, if needed.
2156  * In case the origin disconnects, the destination clients get a tunnel destroy
2157  * notification. If the last destination disconnects (only one remaining client
2158  * in tunnel), the origin gets a (local ID) peer disconnected.
2159  * Note that the function must be called BEFORE removing the client from
2160  * the tunnel.
2161  *
2162  * @param t Tunnel that was destroyed.
2163  * @param c Client that disconnected.
2164  */
2165 static void
2166 send_client_tunnel_disconnect (struct MeshTunnel *t, struct MeshClient *c)
2167 {
2168   unsigned int i;
2169
2170   if (c == t->owner)
2171   {
2172     struct GNUNET_MESH_TunnelMessage msg;
2173
2174     msg.header.size = htons (sizeof (msg));
2175     msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
2176     msg.tunnel_id = htonl (t->local_tid_dest);
2177     for (i = 0; i < t->nclients; i++)
2178       GNUNET_SERVER_notification_context_unicast (nc, t->clients[i]->handle,
2179                                                   &msg.header, GNUNET_NO);
2180   }
2181   // FIXME when to disconnect an incoming tunnel?
2182   else if (1 == t->nclients && NULL != t->owner)
2183   {
2184     struct GNUNET_MESH_PeerControl msg;
2185
2186     msg.header.size = htons (sizeof (msg));
2187     msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL);
2188     msg.tunnel_id = htonl (t->local_tid);
2189     msg.peer = my_full_id;
2190     GNUNET_SERVER_notification_context_unicast (nc, t->owner->handle,
2191                                                 &msg.header, GNUNET_NO);
2192   }
2193 }
2194
2195
2196 /**
2197  * Retrieve the MeshPeerInfo stucture associated with the peer, create one
2198  * and insert it in the appropiate structures if the peer is not known yet.
2199  *
2200  * @param peer Full identity of the peer.
2201  *
2202  * @return Existing or newly created peer info.
2203  */
2204 static struct MeshPeerInfo *
2205 peer_info_get (const struct GNUNET_PeerIdentity *peer)
2206 {
2207   struct MeshPeerInfo *peer_info;
2208
2209   peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
2210   if (NULL == peer_info)
2211   {
2212     peer_info =
2213         (struct MeshPeerInfo *) GNUNET_malloc (sizeof (struct MeshPeerInfo));
2214     GNUNET_CONTAINER_multihashmap_put (peers, &peer->hashPubKey, peer_info,
2215                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2216     peer_info->id = GNUNET_PEER_intern (peer);
2217   }
2218
2219   return peer_info;
2220 }
2221
2222
2223 /**
2224  * Retrieve the MeshPeerInfo stucture associated with the peer, create one
2225  * and insert it in the appropiate structures if the peer is not known yet.
2226  *
2227  * @param peer Short identity of the peer.
2228  *
2229  * @return Existing or newly created peer info.
2230  */
2231 static struct MeshPeerInfo *
2232 peer_info_get_short (const GNUNET_PEER_Id peer)
2233 {
2234   struct GNUNET_PeerIdentity id;
2235
2236   GNUNET_PEER_resolve (peer, &id);
2237   return peer_info_get (&id);
2238 }
2239
2240
2241 /**
2242  * Iterator to remove the tunnel from the list of tunnels a peer participates
2243  * in.
2244  *
2245  * @param cls Closure (tunnel info)
2246  * @param key GNUNET_PeerIdentity of the peer (unused)
2247  * @param value PeerInfo of the peer
2248  *
2249  * @return always GNUNET_YES, to keep iterating
2250  */
2251 static int
2252 peer_info_delete_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
2253 {
2254   struct MeshTunnel *t = cls;
2255   struct MeshPeerInfo *peer = value;
2256   unsigned int i;
2257
2258   for (i = 0; i < peer->ntunnels; i++)
2259   {
2260     if (0 ==
2261         memcmp (&peer->tunnels[i]->id, &t->id, sizeof (struct MESH_TunnelID)))
2262     {
2263       peer->ntunnels--;
2264       peer->tunnels[i] = peer->tunnels[peer->ntunnels];
2265       peer->tunnels = GNUNET_realloc (peer->tunnels, peer->ntunnels);
2266       return GNUNET_YES;
2267     }
2268   }
2269   return GNUNET_YES;
2270 }
2271
2272
2273 /**
2274   * Core callback to write a pre-constructed data packet to core buffer
2275   *
2276   * @param cls Closure (MeshTransmissionDescriptor with data in "data" member).
2277   * @param size Number of bytes available in buf.
2278   * @param buf Where the to write the message.
2279   *
2280   * @return number of bytes written to buf
2281   */
2282 static size_t
2283 send_core_data_raw (void *cls, size_t size, void *buf)
2284 {
2285   struct MeshTransmissionDescriptor *info = cls;
2286   struct GNUNET_MessageHeader *msg;
2287   size_t total_size;
2288
2289   GNUNET_assert (NULL != info);
2290   GNUNET_assert (NULL != info->mesh_data);
2291   msg = (struct GNUNET_MessageHeader *) info->mesh_data->data;
2292   total_size = ntohs (msg->size);
2293
2294   if (total_size > size)
2295   {
2296     GNUNET_break (0);
2297     return 0;
2298   }
2299   memcpy (buf, msg, total_size);
2300   data_descriptor_decrement_rc (info->mesh_data);
2301   GNUNET_free (info);
2302   return total_size;
2303 }
2304
2305
2306 /**
2307  * Sends an already built non-multicast message to a peer,
2308  * properly registrating all used resources.
2309  *
2310  * @param message Message to send. Function makes a copy of it.
2311  * @param peer Short ID of the neighbor whom to send the message.
2312  * @param t Tunnel on which this message is transmitted.
2313  */
2314 static void
2315 send_prebuilt_message (const struct GNUNET_MessageHeader *message,
2316                        const struct GNUNET_PeerIdentity *peer,
2317                        struct MeshTunnel *t)
2318 {
2319   struct MeshTransmissionDescriptor *info;
2320   struct MeshPeerInfo *neighbor;
2321   struct MeshPeerPath *p;
2322   size_t size;
2323   uint16_t type;
2324
2325 //   GNUNET_TRANSPORT_try_connect(); FIXME use?
2326
2327   size = ntohs (message->size);
2328   info = GNUNET_malloc (sizeof (struct MeshTransmissionDescriptor));
2329   info->mesh_data = GNUNET_malloc (sizeof (struct MeshData));
2330   info->mesh_data->data = GNUNET_malloc (size);
2331   memcpy (info->mesh_data->data, message, size);
2332   type = ntohs(message->type);
2333   if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == type)
2334   {
2335     struct GNUNET_MESH_Unicast *m;
2336
2337     m = (struct GNUNET_MESH_Unicast *) info->mesh_data->data;
2338     m->ttl = htonl (ntohl (m->ttl) - 1);
2339   }
2340   info->mesh_data->data_len = size;
2341   info->mesh_data->reference_counter = 1;
2342   info->mesh_data->total_out = 1;
2343   neighbor = peer_info_get (peer);
2344   for (p = neighbor->path_head; NULL != p; p = p->next)
2345   {
2346     if (2 >= p->length)
2347     {
2348       break;
2349     }
2350   }
2351   if (NULL == p)
2352   {
2353 #if MESH_DEBUG
2354     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2355                 "  %s IS NOT DIRECTLY CONNECTED\n",
2356                 GNUNET_i2s(peer));
2357     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2358                 "  PATHS TO %s:\n",
2359                 GNUNET_i2s(peer));
2360     for (p = neighbor->path_head; NULL != p; p = p->next)
2361     {
2362       struct GNUNET_PeerIdentity debug_id;
2363       unsigned int i;
2364
2365       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2366                   "    path with %u hops through:\n",
2367                   p->length);
2368       for (i = 0; i < p->length; i++)
2369       {
2370         GNUNET_PEER_resolve(p->peers[i], &debug_id);
2371         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2372                     "      hop %u: %s\n",
2373                     i, GNUNET_i2s(&debug_id));
2374       }
2375     }
2376 #endif
2377     GNUNET_break (0); // FIXME sometimes fails (testing disconnect?)
2378     GNUNET_free (info->mesh_data->data);
2379     GNUNET_free (info->mesh_data);
2380     GNUNET_free (info);
2381     return;
2382   }
2383   info->peer = neighbor;
2384   if (GNUNET_MESSAGE_TYPE_MESH_PATH_ACK == type)
2385     type = 0;
2386   queue_add (info,
2387              type,
2388              size,
2389              neighbor,
2390              t);
2391 }
2392
2393
2394 /**
2395  * Sends a CREATE PATH message for a path to a peer, properly registrating
2396  * all used resources.
2397  *
2398  * @param peer PeerInfo of the final peer for whom this path is being created.
2399  * @param p Path itself.
2400  * @param t Tunnel for which the path is created.
2401  */
2402 static void
2403 send_create_path (struct MeshPeerInfo *peer, struct MeshPeerPath *p,
2404                   struct MeshTunnel *t)
2405 {
2406   struct GNUNET_PeerIdentity id;
2407   struct MeshPathInfo *path_info;
2408   struct MeshPeerInfo *neighbor;
2409
2410   unsigned int i;
2411
2412   if (NULL == p)
2413   {
2414     p = tree_get_path_to_peer (t->tree, peer->id);
2415     if (NULL == p)
2416     {
2417       GNUNET_break (0);
2418       return;
2419     }
2420   }
2421   for (i = 0; i < p->length; i++)
2422   {
2423     if (p->peers[i] == myid)
2424       break;
2425   }
2426   if (i >= p->length - 1)
2427   {
2428     path_destroy (p);
2429     GNUNET_break (0);
2430     return;
2431   }
2432   GNUNET_PEER_resolve (p->peers[i + 1], &id);
2433
2434   path_info = GNUNET_malloc (sizeof (struct MeshPathInfo));
2435   path_info->path = p;
2436   path_info->t = t;
2437   neighbor = peer_info_get (&id);
2438   path_info->peer = neighbor;
2439   queue_add (path_info,
2440              GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE,
2441              sizeof (struct GNUNET_MESH_ManipulatePath) +
2442                 (p->length * sizeof (struct GNUNET_PeerIdentity)),
2443              neighbor,
2444              t);
2445 }
2446
2447
2448 /**
2449  * Sends a DESTROY PATH message to free resources for a path in a tunnel
2450  *
2451  * @param t Tunnel whose path to destroy.
2452  * @param destination Short ID of the peer to whom the path to destroy.
2453  */
2454 static void
2455 send_destroy_path (struct MeshTunnel *t, GNUNET_PEER_Id destination)
2456 {
2457   struct MeshPeerPath *p;
2458   size_t size;
2459
2460   p = tree_get_path_to_peer (t->tree, destination);
2461   if (NULL == p)
2462   {
2463     GNUNET_break (0);
2464     return;
2465   }
2466   size = sizeof (struct GNUNET_MESH_ManipulatePath);
2467   size += p->length * sizeof (struct GNUNET_PeerIdentity);
2468   {
2469     struct GNUNET_MESH_ManipulatePath *msg;
2470     struct GNUNET_PeerIdentity *pi;
2471     char cbuf[size];
2472     unsigned int i;
2473
2474     msg = (struct GNUNET_MESH_ManipulatePath *) cbuf;
2475     msg->header.size = htons (size);
2476     msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY);
2477     msg->tid = htonl (t->id.tid);
2478     pi = (struct GNUNET_PeerIdentity *) &msg[1];
2479     for (i = 0; i < p->length; i++)
2480     {
2481       GNUNET_PEER_resolve (p->peers[i], &pi[i]);
2482     }
2483     send_prebuilt_message (&msg->header, tree_get_first_hop (t->tree, destination), t);
2484   }
2485   path_destroy (p);
2486 }
2487
2488
2489 /**
2490  * Sends a PATH ACK message in reponse to a received PATH_CREATE directed to us.
2491  *
2492  * @param t Tunnel which to confirm.
2493  */
2494 static void
2495 send_path_ack (struct MeshTunnel *t) 
2496 {
2497   struct MeshTransmissionDescriptor *info;
2498   struct GNUNET_PeerIdentity id;
2499   GNUNET_PEER_Id peer;
2500
2501   peer = tree_get_predecessor (t->tree);
2502   GNUNET_PEER_resolve (peer, &id);
2503   info = GNUNET_malloc (sizeof (struct MeshTransmissionDescriptor));
2504   info->origin = &t->id;
2505   info->peer = GNUNET_CONTAINER_multihashmap_get (peers, &id.hashPubKey);
2506   GNUNET_assert (NULL != info->peer);
2507
2508   queue_add (info,
2509              GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
2510              sizeof (struct GNUNET_MESH_PathACK),
2511              info->peer,
2512              t);
2513 }
2514
2515
2516 /**
2517  * Try to establish a new connection to this peer.
2518  * Use the best path for the given tunnel.
2519  * If the peer doesn't have any path to it yet, try to get one.
2520  * If the peer already has some path, send a CREATE PATH towards it.
2521  *
2522  * @param peer PeerInfo of the peer.
2523  * @param t Tunnel for which to create the path, if possible.
2524  */
2525 static void
2526 peer_info_connect (struct MeshPeerInfo *peer, struct MeshTunnel *t)
2527 {
2528   struct MeshPeerPath *p;
2529   struct MeshPathInfo *path_info;
2530
2531   if (NULL != peer->path_head)
2532   {
2533     p = tree_get_path_to_peer (t->tree, peer->id);
2534     if (NULL == p)
2535     {
2536       GNUNET_break (0);
2537       return;
2538     }
2539
2540     // FIXME always send create path to self
2541     if (p->length > 1)
2542     {
2543       send_create_path (peer, p, t);
2544     }
2545     else
2546     {
2547       struct GNUNET_HashCode hash;
2548
2549       path_destroy (p);
2550       send_client_peer_connected (t, myid);
2551       t->local_tid_dest = next_local_tid++;
2552       GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber),
2553                           &hash);
2554       if (GNUNET_OK !=
2555           GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
2556                                              GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2557       {
2558         GNUNET_break (0);
2559         return;
2560       }
2561     }
2562   }
2563   else if (NULL == peer->dhtget)
2564   {
2565     struct GNUNET_PeerIdentity id;
2566
2567     GNUNET_PEER_resolve (peer->id, &id);
2568     path_info = GNUNET_malloc (sizeof (struct MeshPathInfo));
2569     path_info->peer = peer;
2570     path_info->t = t;
2571     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2572                 "  Starting DHT GET for peer %s\n", GNUNET_i2s (&id));
2573     peer->dhtgetcls = path_info;
2574     peer->dhtget = GNUNET_DHT_get_start (dht_handle,    /* handle */
2575                                          GNUNET_BLOCK_TYPE_MESH_PEER, /* type */
2576                                          &id.hashPubKey,     /* key to search */
2577                                          dht_replication_level, /* replication level */
2578                                          GNUNET_DHT_RO_RECORD_ROUTE |
2579                                          GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
2580                                          NULL,       /* xquery */ // FIXME BLOOMFILTER
2581                                          0,     /* xquery bits */ // FIXME BLOOMFILTER SIZE
2582                                          &dht_get_id_handler, path_info);
2583   }
2584   /* Otherwise, there is no path but the DHT get is already started. */
2585 }
2586
2587
2588 /**
2589  * Task to delay the connection of a peer
2590  *
2591  * @param cls Closure (path info with tunnel and peer to connect).
2592  *            Will be free'd on exection.
2593  * @param tc TaskContext
2594  */
2595 static void
2596 peer_info_connect_task (void *cls,
2597                         const struct GNUNET_SCHEDULER_TaskContext *tc)
2598 {
2599   struct MeshPathInfo *path_info = cls;
2600
2601   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2602   {
2603     GNUNET_free (cls);
2604     return;
2605   }
2606   peer_info_connect (path_info->peer, path_info->t);
2607   GNUNET_free (cls);
2608 }
2609
2610
2611 /**
2612  * Destroy the peer_info and free any allocated resources linked to it
2613  *
2614  * @param pi The peer_info to destroy.
2615  *
2616  * @return GNUNET_OK on success
2617  */
2618 static int
2619 peer_info_destroy (struct MeshPeerInfo *pi)
2620 {
2621   struct GNUNET_PeerIdentity id;
2622   struct MeshPeerPath *p;
2623   struct MeshPeerPath *nextp;
2624
2625   GNUNET_PEER_resolve (pi->id, &id);
2626   GNUNET_PEER_change_rc (pi->id, -1);
2627
2628   if (GNUNET_YES !=
2629       GNUNET_CONTAINER_multihashmap_remove (peers, &id.hashPubKey, pi))
2630   {
2631     GNUNET_break (0);
2632     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2633                 "removing peer %s, not in hashmap\n", GNUNET_i2s (&id));
2634   }
2635   if (NULL != pi->dhtget)
2636   {
2637     GNUNET_DHT_get_stop (pi->dhtget);
2638     GNUNET_free (pi->dhtgetcls);
2639   }
2640   p = pi->path_head;
2641   while (NULL != p)
2642   {
2643     nextp = p->next;
2644     GNUNET_CONTAINER_DLL_remove (pi->path_head, pi->path_tail, p);
2645     path_destroy (p);
2646     p = nextp;
2647   }
2648   GNUNET_free (pi);
2649   return GNUNET_OK;
2650 }
2651
2652
2653 /**
2654  * Remove all paths that rely on a direct connection between p1 and p2
2655  * from the peer itself and notify all tunnels about it.
2656  *
2657  * @param peer PeerInfo of affected peer.
2658  * @param p1 GNUNET_PEER_Id of one peer.
2659  * @param p2 GNUNET_PEER_Id of another peer that was connected to the first and
2660  *           no longer is.
2661  *
2662  * TODO: optimize (see below)
2663  */
2664 static void
2665 peer_info_remove_path (struct MeshPeerInfo *peer, GNUNET_PEER_Id p1,
2666                        GNUNET_PEER_Id p2)
2667 {
2668   struct MeshPeerPath *p;
2669   struct MeshPeerPath *aux;
2670   struct MeshPeerInfo *peer_d;
2671   GNUNET_PEER_Id d;
2672   unsigned int destroyed;
2673   unsigned int best;
2674   unsigned int cost;
2675   unsigned int i;
2676
2677   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "peer_info_remove_path\n");
2678   destroyed = 0;
2679   p = peer->path_head;
2680   while (NULL != p)
2681   {
2682     aux = p->next;
2683     for (i = 0; i < (p->length - 1); i++)
2684     {
2685       if ((p->peers[i] == p1 && p->peers[i + 1] == p2) ||
2686           (p->peers[i] == p2 && p->peers[i + 1] == p1))
2687       {
2688         GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, p);
2689         path_destroy (p);
2690         destroyed++;
2691         break;
2692       }
2693     }
2694     p = aux;
2695   }
2696   if (0 == destroyed)
2697     return;
2698
2699   for (i = 0; i < peer->ntunnels; i++)
2700   {
2701     d = tunnel_notify_connection_broken (peer->tunnels[i], p1, p2);
2702     if (0 == d)
2703       continue;
2704     /* TODO
2705      * Problem: one or more peers have been deleted from the tunnel tree.
2706      * We don't know who they are to try to add them again.
2707      * We need to try to find a new path for each of the disconnected peers.
2708      * Some of them might already have a path to reach them that does not
2709      * involve p1 and p2. Adding all anew might render in a better tree than
2710      * the trivial immediate fix.
2711      *
2712      * Trivial immiediate fix: try to reconnect to the disconnected node. All
2713      * its children will be reachable trough him.
2714      */
2715     peer_d = peer_info_get_short (d);
2716     best = UINT_MAX;
2717     aux = NULL;
2718     for (p = peer_d->path_head; NULL != p; p = p->next)
2719     {
2720       if ((cost = tree_get_path_cost (peer->tunnels[i]->tree, p)) < best)
2721       {
2722         best = cost;
2723         aux = p;
2724       }
2725     }
2726     if (NULL != aux)
2727     {
2728       /* No callback, as peer will be already disconnected and a connection
2729        * scheduled by tunnel_notify_connection_broken.
2730        */
2731       tree_add_path (peer->tunnels[i]->tree, aux, NULL, NULL);
2732     }
2733     else
2734     {
2735       peer_info_connect (peer_d, peer->tunnels[i]);
2736     }
2737   }
2738   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "peer_info_remove_path END\n");
2739 }
2740
2741
2742 /**
2743  * Add the path to the peer and update the path used to reach it in case this
2744  * is the shortest.
2745  *
2746  * @param peer_info Destination peer to add the path to.
2747  * @param path New path to add. Last peer must be the peer in arg 1.
2748  *             Path will be either used of freed if already known.
2749  * @param trusted Do we trust that this path is real?
2750  */
2751 void
2752 peer_info_add_path (struct MeshPeerInfo *peer_info, struct MeshPeerPath *path,
2753                     int trusted)
2754 {
2755   struct MeshPeerPath *aux;
2756   unsigned int l;
2757   unsigned int l2;
2758
2759   if ((NULL == peer_info) || (NULL == path))
2760   {
2761     GNUNET_break (0);
2762     path_destroy (path);
2763     return;
2764   }
2765   if (path->peers[path->length - 1] != peer_info->id)
2766   {
2767     GNUNET_break (0);
2768     path_destroy (path);
2769     return;
2770   }
2771   if (path->length <= 2 && GNUNET_NO == trusted)
2772   {
2773     /* Only allow CORE to tell us about direct paths */
2774     path_destroy (path);
2775     return;
2776   }
2777   GNUNET_assert (peer_info->id == path->peers[path->length - 1]);
2778   for (l = 1; l < path->length; l++)
2779   {
2780     if (path->peers[l] == myid)
2781     {
2782       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shortening path by %u\n", l);
2783       for (l2 = 0; l2 < path->length - l; l2++)
2784       {
2785         path->peers[l2] = path->peers[l + l2];
2786       }
2787       path->length -= l;
2788       l = 1;
2789       path->peers =
2790           GNUNET_realloc (path->peers, path->length * sizeof (GNUNET_PEER_Id));
2791     }
2792   }
2793 #if MESH_DEBUG
2794   {
2795     struct GNUNET_PeerIdentity id;
2796
2797     GNUNET_PEER_resolve (peer_info->id, &id);
2798     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "adding path [%u] to peer %s\n",
2799                 path->length, GNUNET_i2s (&id));
2800   }
2801 #endif
2802   l = path_get_length (path);
2803   if (0 == l)
2804   {
2805     GNUNET_free (path);
2806     return;
2807   }
2808
2809   GNUNET_assert (peer_info->id == path->peers[path->length - 1]);
2810   for (aux = peer_info->path_head; aux != NULL; aux = aux->next)
2811   {
2812     l2 = path_get_length (aux);
2813     if (l2 > l)
2814     {
2815       GNUNET_CONTAINER_DLL_insert_before (peer_info->path_head,
2816                                           peer_info->path_tail, aux, path);
2817       return;
2818     }
2819     else
2820     {
2821       if (l2 == l && memcmp (path->peers, aux->peers, l) == 0)
2822       {
2823         path_destroy (path);
2824         return;
2825       }
2826     }
2827   }
2828   GNUNET_CONTAINER_DLL_insert_tail (peer_info->path_head, peer_info->path_tail,
2829                                     path);
2830   return;
2831 }
2832
2833
2834 /**
2835  * Add the path to the origin peer and update the path used to reach it in case
2836  * this is the shortest.
2837  * The path is given in peer_info -> destination, therefore we turn the path
2838  * upside down first.
2839  *
2840  * @param peer_info Peer to add the path to, being the origin of the path.
2841  * @param path New path to add after being inversed.
2842  * @param trusted Do we trust that this path is real?
2843  */
2844 static void
2845 peer_info_add_path_to_origin (struct MeshPeerInfo *peer_info,
2846                               struct MeshPeerPath *path, int trusted)
2847 {
2848   path_invert (path);
2849   peer_info_add_path (peer_info, path, trusted);
2850 }
2851
2852
2853 /**
2854  * Build a PeerPath from the paths returned from the DHT, reversing the paths
2855  * to obtain a local peer -> destination path and interning the peer ids.
2856  *
2857  * @return Newly allocated and created path
2858  */
2859 static struct MeshPeerPath *
2860 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
2861                      unsigned int get_path_length,
2862                      const struct GNUNET_PeerIdentity *put_path,
2863                      unsigned int put_path_length)
2864 {
2865   struct MeshPeerPath *p;
2866   GNUNET_PEER_Id id;
2867   int i;
2868
2869   p = path_new (1);
2870   p->peers[0] = myid;
2871   GNUNET_PEER_change_rc (myid, 1);
2872   i = get_path_length;
2873   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   GET has %d hops.\n", i);
2874   for (i--; i >= 0; i--)
2875   {
2876     id = GNUNET_PEER_intern (&get_path[i]);
2877     if (p->length > 0 && id == p->peers[p->length - 1])
2878     {
2879       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Optimizing 1 hop out.\n");
2880       GNUNET_PEER_change_rc (id, -1);
2881     }
2882     else
2883     {
2884       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Adding from GET: %s.\n",
2885                   GNUNET_i2s (&get_path[i]));
2886       p->length++;
2887       p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
2888       p->peers[p->length - 1] = id;
2889     }
2890   }
2891   i = put_path_length;
2892   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   PUT has %d hops.\n", i);
2893   for (i--; i >= 0; i--)
2894   {
2895     id = GNUNET_PEER_intern (&put_path[i]);
2896     if (id == myid)
2897     {
2898       /* PUT path went through us, so discard the path up until now and start
2899        * from here to get a much shorter (and loop-free) path.
2900        */
2901       path_destroy (p);
2902       p = path_new (0);
2903     }
2904     if (p->length > 0 && id == p->peers[p->length - 1])
2905     {
2906       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Optimizing 1 hop out.\n");
2907       GNUNET_PEER_change_rc (id, -1);
2908     }
2909     else
2910     {
2911       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Adding from PUT: %s.\n",
2912                   GNUNET_i2s (&put_path[i]));
2913       p->length++;
2914       p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
2915       p->peers[p->length - 1] = id;
2916     }
2917   }
2918 #if MESH_DEBUG
2919   if (get_path_length > 0)
2920     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (first of GET: %s)\n",
2921                 GNUNET_i2s (&get_path[0]));
2922   if (put_path_length > 0)
2923     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (first of PUT: %s)\n",
2924                 GNUNET_i2s (&put_path[0]));
2925   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   In total: %d hops\n",
2926               p->length);
2927   for (i = 0; i < p->length; i++)
2928   {
2929     struct GNUNET_PeerIdentity peer_id;
2930
2931     GNUNET_PEER_resolve (p->peers[i], &peer_id);
2932     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "       %u: %s\n", p->peers[i],
2933                 GNUNET_i2s (&peer_id));
2934   }
2935 #endif
2936   return p;
2937 }
2938
2939
2940 /**
2941  * Adds a path to the peer_infos of all the peers in the path
2942  *
2943  * @param p Path to process.
2944  * @param confirmed Whether we know if the path works or not.
2945  */
2946 static void
2947 path_add_to_peers (struct MeshPeerPath *p, int confirmed)
2948 {
2949   unsigned int i;
2950
2951   /* TODO: invert and add */
2952   for (i = 0; i < p->length && p->peers[i] != myid; i++) /* skip'em */ ;
2953   for (i++; i < p->length; i++)
2954   {
2955     struct MeshPeerInfo *aux;
2956     struct MeshPeerPath *copy;
2957
2958     aux = peer_info_get_short (p->peers[i]);
2959     copy = path_duplicate (p);
2960     copy->length = i + 1;
2961     peer_info_add_path (aux, copy, GNUNET_NO);
2962   }
2963 }
2964
2965
2966 /**
2967  * Send keepalive packets for a peer
2968  *
2969  * @param cls Closure (tunnel for which to send the keepalive).
2970  * @param tc Notification context.
2971  *
2972  * TODO: implement explicit multicast keepalive?
2973  */
2974 static void
2975 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
2976
2977
2978 /**
2979  * Search for a tunnel among the incoming tunnels
2980  *
2981  * @param tid the local id of the tunnel
2982  *
2983  * @return tunnel handler, NULL if doesn't exist
2984  */
2985 static struct MeshTunnel *
2986 tunnel_get_incoming (MESH_TunnelNumber tid)
2987 {
2988   struct GNUNET_HashCode hash;
2989
2990   GNUNET_assert (tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV);
2991   GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
2992   return GNUNET_CONTAINER_multihashmap_get (incoming_tunnels, &hash);
2993 }
2994
2995
2996 /**
2997  * Search for a tunnel among the tunnels for a client
2998  *
2999  * @param c the client whose tunnels to search in
3000  * @param tid the local id of the tunnel
3001  *
3002  * @return tunnel handler, NULL if doesn't exist
3003  */
3004 static struct MeshTunnel *
3005 tunnel_get_by_local_id (struct MeshClient *c, MESH_TunnelNumber tid)
3006 {
3007   if (tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
3008   {
3009     return tunnel_get_incoming (tid);
3010   }
3011   else
3012   {
3013     struct GNUNET_HashCode hash;
3014
3015     GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
3016     return GNUNET_CONTAINER_multihashmap_get (c->own_tunnels, &hash);
3017   }
3018 }
3019
3020
3021 /**
3022  * Search for a tunnel by global ID using PEER_ID
3023  *
3024  * @param pi owner of the tunnel
3025  * @param tid global tunnel number
3026  *
3027  * @return tunnel handler, NULL if doesn't exist
3028  */
3029 static struct MeshTunnel *
3030 tunnel_get_by_pi (GNUNET_PEER_Id pi, MESH_TunnelNumber tid)
3031 {
3032   struct MESH_TunnelID id;
3033   struct GNUNET_HashCode hash;
3034
3035   id.oid = pi;
3036   id.tid = tid;
3037
3038   GNUNET_CRYPTO_hash (&id, sizeof (struct MESH_TunnelID), &hash);
3039   return GNUNET_CONTAINER_multihashmap_get (tunnels, &hash);
3040 }
3041
3042
3043 /**
3044  * Search for a tunnel by global ID using full PeerIdentities
3045  *
3046  * @param oid owner of the tunnel
3047  * @param tid global tunnel number
3048  *
3049  * @return tunnel handler, NULL if doesn't exist
3050  */
3051 static struct MeshTunnel *
3052 tunnel_get (struct GNUNET_PeerIdentity *oid, MESH_TunnelNumber tid)
3053 {
3054   return tunnel_get_by_pi (GNUNET_PEER_search (oid), tid);
3055 }
3056
3057
3058 /**
3059  * Delete an active client from the tunnel.
3060  * 
3061  * @param t Tunnel.
3062  * @param c Client.
3063  */
3064 static void
3065 tunnel_delete_active_client (struct MeshTunnel *t, const struct MeshClient *c)
3066 {
3067   unsigned int i;
3068
3069   for (i = 0; i < t->nclients; i++)
3070   {
3071     if (t->clients[i] == c)
3072     {
3073       t->clients[i] = t->clients[t->nclients - 1];
3074       t->clients_fc[i] = t->clients_fc[t->nclients - 1];
3075       GNUNET_array_grow (t->clients, t->nclients, t->nclients - 1);
3076       t->nclients++;
3077       GNUNET_array_grow (t->clients_fc, t->nclients, t->nclients - 1);
3078       break;
3079     }
3080   }
3081 }
3082
3083
3084 /**
3085  * Delete an ignored client from the tunnel.
3086  * 
3087  * @param t Tunnel.
3088  * @param c Client.
3089  */
3090 static void
3091 tunnel_delete_ignored_client (struct MeshTunnel *t, const struct MeshClient *c)
3092 {
3093   unsigned int i;
3094
3095   for (i = 0; i < t->nignore; i++)
3096   {
3097     if (t->ignore[i] == c)
3098     {
3099       t->ignore[i] = t->ignore[t->nignore - 1];
3100       GNUNET_array_grow (t->ignore, t->nignore, t->nignore - 1);
3101       break;
3102     }
3103   }
3104 }
3105
3106
3107 /**
3108  * Delete a client from the tunnel. It should be only done on
3109  * client disconnection, otherwise use client_ignore_tunnel.
3110  * 
3111  * @param t Tunnel.
3112  * @param c Client.
3113  */
3114 static void
3115 tunnel_delete_client (struct MeshTunnel *t, const struct MeshClient *c)
3116 {
3117   tunnel_delete_ignored_client (t, c);
3118   tunnel_delete_active_client (t, c);
3119 }
3120
3121
3122 /**
3123  * @brief Iterator to destroy MeshTunnelChildInfo of tunnel children.
3124  * 
3125  * Destroys queue elements of all waiting transmissions and frees all memory
3126  * used by the struct and its elements.
3127  *
3128  * @param cls Closure (tunnel info).
3129  * @param key Hash of GNUNET_PEER_Id (unused).
3130  * @param value MeshTunnelChildInfo of the child.
3131  *
3132  * @return always GNUNET_YES, to keep iterating
3133  */
3134 static int
3135 tunnel_destroy_child (void *cls,
3136                       const struct GNUNET_HashCode * key,
3137                       void *value)
3138 {
3139   struct MeshTunnelChildInfo *cinfo = value;
3140   struct MeshTunnel *t = cls;
3141   unsigned int c;
3142   unsigned int i;
3143
3144   for (c = 0; c < cinfo->send_buffer_n; c++)
3145   {
3146     i = (cinfo->send_buffer_start + c) % t->fwd_queue_max;
3147     if (NULL != cinfo->send_buffer[i])
3148       queue_destroy (cinfo->send_buffer[i], GNUNET_YES);
3149     else
3150       GNUNET_break (0);
3151     GNUNET_log (GNUNET_ERROR_TYPE_INFO, "%u %u\n", c, cinfo->send_buffer_n);
3152   }
3153   GNUNET_free_non_null (cinfo->send_buffer);
3154   GNUNET_free (cinfo);
3155   return GNUNET_YES;
3156 }
3157
3158
3159 /**
3160  * Callback used to notify a client owner of a tunnel that a peer has
3161  * disconnected, most likely because of a path change.
3162  *
3163  * @param cls Closure (tunnel this notification is about).
3164  * @param peer_id Short ID of disconnected peer.
3165  */
3166 void
3167 tunnel_notify_client_peer_disconnected (void *cls, GNUNET_PEER_Id peer_id)
3168 {
3169   struct MeshTunnel *t = cls;
3170   struct MeshPeerInfo *peer;
3171   struct MeshPathInfo *path_info;
3172
3173   if (NULL != t->owner && NULL != nc)
3174   {
3175     struct GNUNET_MESH_PeerControl msg;
3176
3177     msg.header.size = htons (sizeof (msg));
3178     msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL);
3179     msg.tunnel_id = htonl (t->local_tid);
3180     GNUNET_PEER_resolve (peer_id, &msg.peer);
3181     GNUNET_SERVER_notification_context_unicast (nc, t->owner->handle,
3182                                                 &msg.header, GNUNET_NO);
3183   }
3184   peer = peer_info_get_short (peer_id);
3185   path_info = GNUNET_malloc (sizeof (struct MeshPathInfo));
3186   path_info->peer = peer;
3187   path_info->t = t;
3188   GNUNET_SCHEDULER_add_now (&peer_info_connect_task, path_info);
3189 }
3190
3191
3192 /**
3193  * Add a peer to a tunnel, accomodating paths accordingly and initializing all
3194  * needed rescources.
3195  * If peer already exists, reevaluate shortest path and change if different.
3196  *
3197  * @param t Tunnel we want to add a new peer to
3198  * @param peer PeerInfo of the peer being added
3199  *
3200  */
3201 static void
3202 tunnel_add_peer (struct MeshTunnel *t, struct MeshPeerInfo *peer)
3203 {
3204   struct GNUNET_PeerIdentity id;
3205   struct MeshPeerPath *best_p;
3206   struct MeshPeerPath *p;
3207   unsigned int best_cost;
3208   unsigned int cost;
3209
3210   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "tunnel_add_peer\n");
3211   GNUNET_PEER_resolve (peer->id, &id);
3212   if (GNUNET_NO ==
3213       GNUNET_CONTAINER_multihashmap_contains (t->peers, &id.hashPubKey))
3214   {
3215     t->peers_total++;
3216     GNUNET_array_append (peer->tunnels, peer->ntunnels, t);
3217     GNUNET_assert (GNUNET_OK ==
3218                    GNUNET_CONTAINER_multihashmap_put (t->peers, &id.hashPubKey,
3219                                                       peer,
3220                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
3221   }
3222
3223   if (NULL != (p = peer->path_head))
3224   {
3225     best_p = p;
3226     best_cost = tree_get_path_cost (t->tree, p);
3227     while (NULL != p)
3228     {
3229       if ((cost = tree_get_path_cost (t->tree, p)) < best_cost)
3230       {
3231         best_cost = cost;
3232         best_p = p;
3233       }
3234       p = p->next;
3235     }
3236     tree_add_path (t->tree, best_p, &tunnel_notify_client_peer_disconnected, t);
3237     if (GNUNET_SCHEDULER_NO_TASK == t->path_refresh_task)
3238       t->path_refresh_task =
3239           GNUNET_SCHEDULER_add_delayed (refresh_path_time, &path_refresh, t);
3240   }
3241   else
3242   {
3243     /* Start a DHT get */
3244     peer_info_connect (peer, t);
3245   }
3246   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "tunnel_add_peer END\n");
3247 }
3248
3249 /**
3250  * Add a path to a tunnel which we don't own, just to remember the next hop.
3251  * If destination node was already in the tunnel, the first hop information
3252  * will be replaced with the new path.
3253  *
3254  * @param t Tunnel we want to add a new peer to
3255  * @param p Path to add
3256  * @param own_pos Position of local node in path.
3257  *
3258  */
3259 static void
3260 tunnel_add_path (struct MeshTunnel *t, struct MeshPeerPath *p,
3261                  unsigned int own_pos)
3262 {
3263   struct GNUNET_PeerIdentity id;
3264
3265   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "tunnel_add_path\n");
3266   GNUNET_assert (0 != own_pos);
3267   tree_add_path (t->tree, p, NULL, NULL);
3268   if (own_pos < p->length - 1)
3269   {
3270     GNUNET_PEER_resolve (p->peers[own_pos + 1], &id);
3271     tree_update_first_hops (t->tree, myid, &id);
3272   }
3273   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "tunnel_add_path END\n");
3274 }
3275
3276 /**
3277  * Add a client to a tunnel, initializing all needed data structures.
3278  * 
3279  * @param t Tunnel to which add the client.
3280  * @param c Client which to add to the tunnel.
3281  */
3282 static void
3283 tunnel_add_client (struct MeshTunnel *t, struct MeshClient *c)
3284 {
3285   struct MeshTunnelClientInfo clinfo;
3286
3287   GNUNET_array_append (t->clients, t->nclients, c);
3288   clinfo.fwd_ack = t->fwd_pid + 1;
3289   clinfo.bck_ack = t->nobuffer ? 1 : INITIAL_WINDOW_SIZE - 1;
3290   clinfo.fwd_pid = t->fwd_pid;
3291   clinfo.bck_pid = (uint32_t) -1; // Expected next: 0
3292   t->nclients--;
3293   GNUNET_array_append (t->clients_fc, t->nclients, clinfo);
3294 }
3295
3296
3297 /**
3298  * Notifies a tunnel that a connection has broken that affects at least
3299  * some of its peers. Sends a notification towards the root of the tree.
3300  * In case the peer is the owner of the tree, notifies the client that owns
3301  * the tunnel and tries to reconnect.
3302  *
3303  * @param t Tunnel affected.
3304  * @param p1 Peer that got disconnected from p2.
3305  * @param p2 Peer that got disconnected from p1.
3306  *
3307  * @return Short ID of the peer disconnected (either p1 or p2).
3308  *         0 if the tunnel remained unaffected.
3309  */
3310 static GNUNET_PEER_Id
3311 tunnel_notify_connection_broken (struct MeshTunnel *t, GNUNET_PEER_Id p1,
3312                                  GNUNET_PEER_Id p2)
3313 {
3314   GNUNET_PEER_Id pid;
3315
3316   pid =
3317       tree_notify_connection_broken (t->tree, p1, p2,
3318                                      &tunnel_notify_client_peer_disconnected,
3319                                      t);
3320   if (myid != p1 && myid != p2)
3321   {
3322     return pid;
3323   }
3324   if (pid != myid)
3325   {
3326     if (tree_get_predecessor (t->tree) != 0)
3327     {
3328       /* We are the peer still connected, notify owner of the disconnection. */
3329       struct GNUNET_MESH_PathBroken msg;
3330       struct GNUNET_PeerIdentity neighbor;
3331
3332       msg.header.size = htons (sizeof (msg));
3333       msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN);
3334       GNUNET_PEER_resolve (t->id.oid, &msg.oid);
3335       msg.tid = htonl (t->id.tid);
3336       msg.peer1 = my_full_id;
3337       GNUNET_PEER_resolve (pid, &msg.peer2);
3338       GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &neighbor);
3339       send_prebuilt_message (&msg.header, &neighbor, t);
3340     }
3341   }
3342   return pid;
3343 }
3344
3345
3346 /**
3347  * Send a multicast packet to a neighbor.
3348  *
3349  * @param cls Closure (Info about the multicast packet)
3350  * @param neighbor_id Short ID of the neighbor to send the packet to.
3351  */
3352 static void
3353 tunnel_send_multicast_iterator (void *cls, GNUNET_PEER_Id neighbor_id)
3354 {
3355   struct MeshData *mdata = cls;
3356   struct MeshTransmissionDescriptor *info;
3357   struct GNUNET_PeerIdentity neighbor;
3358   struct GNUNET_MessageHeader *msg;
3359
3360   info = GNUNET_malloc (sizeof (struct MeshTransmissionDescriptor));
3361
3362   info->mesh_data = mdata;
3363   (mdata->reference_counter) ++;
3364   info->destination = neighbor_id;
3365   GNUNET_PEER_resolve (neighbor_id, &neighbor);
3366   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   sending to %s...\n",
3367               GNUNET_i2s (&neighbor));
3368   info->peer = peer_info_get (&neighbor);
3369   GNUNET_assert (NULL != info->peer);
3370   msg = (struct GNUNET_MessageHeader *) mdata->data;
3371   queue_add(info,
3372             ntohs (msg->type),
3373             info->mesh_data->data_len,
3374             info->peer,
3375             mdata->t);
3376 }
3377
3378
3379 /**
3380  * Queue a message in a tunnel in multicast, sending a copy to each child node
3381  * down the local one in the tunnel tree.
3382  *
3383  * @param t Tunnel in which to send the data.
3384  * @param msg Message to be sent.
3385  */
3386 static void
3387 tunnel_send_multicast (struct MeshTunnel *t,
3388                        const struct GNUNET_MessageHeader *msg)
3389 {
3390   struct MeshData *mdata;
3391
3392   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3393               " sending a multicast packet...\n");
3394
3395   mdata = GNUNET_malloc (sizeof (struct MeshData));
3396   mdata->data_len = ntohs (msg->size);
3397   mdata->t = t;
3398   mdata->data = GNUNET_malloc (mdata->data_len);
3399   memcpy (mdata->data, msg, mdata->data_len);
3400   if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_MESH_MULTICAST)
3401   {
3402     struct GNUNET_MESH_Multicast *mcast;
3403
3404     mcast = (struct GNUNET_MESH_Multicast *) mdata->data;
3405     if (t->fwd_queue_n >= t->fwd_queue_max)
3406     {
3407       GNUNET_break (0);
3408       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  queue full!\n");
3409       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3410                   "  message from %s!\n",
3411                   GNUNET_i2s(&mcast->oid));
3412       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3413                   "  message at %s!\n",
3414                   GNUNET_i2s(&my_full_id));
3415       GNUNET_free (mdata->data);
3416       GNUNET_free (mdata);
3417       return;
3418     }
3419     t->fwd_queue_n++;
3420     mcast->ttl = htonl (ntohl (mcast->ttl) - 1);
3421     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  data packet, ttl: %u\n",
3422                 ntohl (mcast->ttl));
3423   }
3424   else
3425   {
3426     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  not a data packet, no ttl\n");
3427   }
3428
3429   tree_iterate_children (t->tree, &tunnel_send_multicast_iterator, mdata);
3430   if (mdata->reference_counter == 0)
3431   {
3432     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3433               "  no one to send data to\n");
3434     GNUNET_free (mdata->data);
3435     GNUNET_free (mdata);
3436     t->fwd_queue_n--;
3437   }
3438   else
3439   {
3440     mdata->total_out = mdata->reference_counter;
3441   }
3442   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3443               " sending a multicast packet done\n");
3444   return;
3445 }
3446
3447
3448 /**
3449  * Increase the SKIP value of all peers that
3450  * have not received a unicast message.
3451  *
3452  * @param cls Closure (ID of the peer that HAS received the message).
3453  * @param key ID of the neighbor.
3454  * @param value Information about the neighbor.
3455  *
3456  * @return GNUNET_YES to keep iterating.
3457  */
3458 static int
3459 tunnel_add_skip (void *cls,
3460                  const struct GNUNET_HashCode * key,
3461                  void *value)
3462 {
3463   struct GNUNET_PeerIdentity *neighbor = cls;
3464   struct MeshTunnelChildInfo *cinfo = value;
3465
3466   /* TODO compare only pointers? key == neighbor? */
3467   if (0 == memcmp (&neighbor->hashPubKey, key, sizeof (struct GNUNET_HashCode)))
3468   {
3469     return GNUNET_YES;
3470   }
3471   cinfo->skip++;
3472   return GNUNET_YES;
3473 }
3474
3475
3476 /**
3477  * @brief Get neighbor's Flow Control information.
3478  *
3479  * Retrieves the MeshTunnelChildInfo containing Flow Control data about a direct
3480  * descendant of the local node in a certain tunnel.
3481  * If the info is not yet there (recently created path), creates the data struct
3482  * and inserts it into the tunnel info, initialized to the current tunnel ACK
3483  * values.
3484  *
3485  * @param t Tunnel related.
3486  * @param peer Neighbor whose Flow Control info is needed.
3487  *
3488  * @return Neighbor's Flow Control info.
3489  */
3490 static struct MeshTunnelChildInfo *
3491 tunnel_get_neighbor_fc (const struct MeshTunnel *t,
3492                         const struct GNUNET_PeerIdentity *peer)
3493 {
3494   struct MeshTunnelChildInfo *cinfo;
3495   cinfo = GNUNET_CONTAINER_multihashmap_get (t->children_fc,
3496                                              &peer->hashPubKey);
3497   if (NULL == cinfo)
3498   {
3499     uint32_t delta;
3500
3501     cinfo = GNUNET_malloc (sizeof (struct MeshTunnelChildInfo));
3502     cinfo->id = GNUNET_PEER_intern (peer);
3503     cinfo->skip = t->fwd_pid;
3504
3505     delta = t->nobuffer ? 1 : INITIAL_WINDOW_SIZE;
3506     cinfo->fwd_ack = t->fwd_pid + delta;
3507     cinfo->bck_ack = delta;
3508
3509     cinfo->send_buffer =
3510         GNUNET_malloc (sizeof(struct MeshPeerQueue *) * t->fwd_queue_max);
3511
3512     GNUNET_assert (GNUNET_OK ==
3513       GNUNET_CONTAINER_multihashmap_put (t->children_fc,
3514                                          &peer->hashPubKey,
3515                                          cinfo,
3516                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
3517   }
3518   return cinfo;
3519 }
3520
3521
3522 /**
3523  * Get the Flow Control info of a client.
3524  * 
3525  * @param t Tunnel on which to look.
3526  * @param c Client whose ACK to get.
3527  * 
3528  * @return ACK value.
3529  */
3530 static struct MeshTunnelClientInfo *
3531 tunnel_get_client_fc (struct MeshTunnel *t,
3532                       struct MeshClient *c)
3533 {
3534   unsigned int i;
3535
3536   for (i = 0; i < t->nclients; i++)
3537   {
3538     if (t->clients[i] != c)
3539       continue;
3540     return &t->clients_fc[i];
3541   }
3542   GNUNET_assert (0);
3543   return NULL; // avoid compiler / coverity complaints
3544 }
3545
3546
3547 /**
3548  * Iterator to get the appropiate ACK value from all children nodes.
3549  *
3550  * @param cls Closue (tunnel).
3551  * @param id Id of the child node.
3552  */
3553 static void
3554 tunnel_get_child_fwd_ack (void *cls,
3555                           GNUNET_PEER_Id id)
3556 {
3557   struct GNUNET_PeerIdentity peer_id;
3558   struct MeshTunnelChildInfo *cinfo;
3559   struct MeshTunnelChildIteratorContext *ctx = cls;
3560   struct MeshTunnel *t = ctx->t;
3561   uint32_t ack;
3562
3563   GNUNET_PEER_resolve (id, &peer_id);
3564   cinfo = tunnel_get_neighbor_fc (t, &peer_id);
3565   ack = cinfo->fwd_ack;
3566
3567   ctx->nchildren++;
3568   if (GNUNET_NO == ctx->init)
3569   {
3570     ctx->max_child_ack = ack;
3571     ctx->init = GNUNET_YES;
3572   }
3573
3574   if (GNUNET_YES == t->speed_min)
3575   {
3576     ctx->max_child_ack = ctx->max_child_ack > ack ? ack : ctx->max_child_ack;
3577   }
3578   else
3579   {
3580     ctx->max_child_ack = ctx->max_child_ack > ack ? ctx->max_child_ack : ack;
3581   }
3582
3583 }
3584
3585
3586 /**
3587  * Get the maximum PID allowed to transmit to any
3588  * tunnel child of the local peer, depending on the tunnel
3589  * buffering/speed settings.
3590  *
3591  * @param t Tunnel.
3592  *
3593  * @return Maximum PID allowed (uint32 MAX), -1LL if node has no children.
3594  */
3595 static int64_t
3596 tunnel_get_children_fwd_ack (struct MeshTunnel *t)
3597 {
3598   struct MeshTunnelChildIteratorContext ctx;
3599   ctx.t = t;
3600   ctx.max_child_ack = 0;
3601   ctx.nchildren = 0;
3602   ctx.init = GNUNET_NO;
3603   tree_iterate_children (t->tree, tunnel_get_child_fwd_ack, &ctx);
3604
3605   if (0 == ctx.nchildren)
3606   {
3607     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3608             "  tunnel has no children, no FWD ACK\n");
3609     return -1LL;
3610   }
3611
3612   if (GNUNET_YES == t->nobuffer && GMC_is_pid_bigger(ctx.max_child_ack, t->fwd_pid))
3613     ctx.max_child_ack = t->fwd_pid + 1; // Might overflow, it's ok.
3614
3615   return (int64_t) ctx.max_child_ack;
3616 }
3617
3618
3619 /**
3620  * Set the FWD ACK value of a client in a particular tunnel.
3621  * 
3622  * @param t Tunnel affected.
3623  * @param c Client whose ACK to set.
3624  * @param ack ACK value.
3625  */
3626 static void
3627 tunnel_set_client_fwd_ack (struct MeshTunnel *t,
3628                            struct MeshClient *c, 
3629                            uint32_t ack)
3630 {
3631   unsigned int i;
3632
3633   for (i = 0; i < t->nclients; i++)
3634   {
3635     if (t->clients[i] != c)
3636       continue;
3637     t->clients_fc[i].fwd_ack = ack;
3638     return;
3639   }
3640   GNUNET_break (0);
3641 }
3642
3643
3644 /**
3645  * Get the highest ACK value of all clients in a particular tunnel,
3646  * according to the buffering/speed settings.
3647  * 
3648  * @param t Tunnel on which to look.
3649  * 
3650  * @return Corresponding ACK value (max uint32_t).
3651  *         If no clients are suscribed, -1LL.
3652  */
3653 static int64_t
3654 tunnel_get_clients_fwd_ack (struct MeshTunnel *t)
3655 {
3656   unsigned int i;
3657   int64_t ack;
3658
3659   if (0 == t->nclients)
3660   {
3661     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3662                 "  tunnel has no clients, no FWD ACK\n");
3663     return -1LL;
3664   }
3665
3666   for (ack = -1LL, i = 0; i < t->nclients; i++)
3667   {
3668     if (-1LL == ack ||
3669         (GNUNET_YES == t->speed_min &&
3670          GNUNET_YES == GMC_is_pid_bigger (ack, t->clients_fc[i].fwd_ack)) ||
3671         (GNUNET_NO == t->speed_min &&
3672          GNUNET_YES == GMC_is_pid_bigger (t->clients_fc[i].fwd_ack, ack)))
3673     {
3674       ack = t->clients_fc[i].fwd_ack;
3675     }
3676   }
3677
3678   if (GNUNET_YES == t->nobuffer && GMC_is_pid_bigger(ack, t->fwd_pid))
3679     ack = (uint32_t) t->fwd_pid + 1; // Might overflow, it's ok.
3680
3681   return (uint32_t) ack;
3682 }
3683
3684
3685 /**
3686  * Get the current fwd ack value for a tunnel, taking in account the tunnel
3687  * mode and the status of all children nodes.
3688  *
3689  * @param t Tunnel.
3690  *
3691  * @return Maximum PID allowed.
3692  */
3693 static uint32_t
3694 tunnel_get_fwd_ack (struct MeshTunnel *t)
3695 {
3696   uint32_t ack;
3697   uint32_t count;
3698   uint32_t buffer_free;
3699   int64_t child_ack;
3700   int64_t client_ack;
3701
3702   count = t->fwd_pid - t->skip;
3703   buffer_free = t->fwd_queue_max - t->fwd_queue_n;
3704   ack = count + buffer_free;
3705   child_ack = tunnel_get_children_fwd_ack (t);
3706   client_ack = tunnel_get_clients_fwd_ack (t);
3707   if (-1LL == child_ack)
3708   {
3709     // Node has no children, child_ack AND core buffer are irrelevant.
3710     GNUNET_break (-1LL != client_ack); // No children AND no clients? Not good!
3711     return (uint32_t) client_ack;
3712   }
3713   if (-1LL == client_ack)
3714   {
3715     client_ack = ack; // Might overflow 32 bits, it's ok!
3716   }
3717   if (GNUNET_YES == t->speed_min)
3718   {
3719     ack = GMC_min_pid ((uint32_t) child_ack, ack); // Might overflow 32 bits, it's ok!;
3720     ack = GMC_min_pid ((uint32_t) client_ack, ack);
3721   }
3722   else
3723   {
3724     ack = GMC_max_pid ((uint32_t) child_ack, ack); // Might overflow 32 bits, it's ok!;
3725     ack = GMC_max_pid ((uint32_t) client_ack, ack);
3726   }
3727   if (GNUNET_YES == t->nobuffer && GMC_is_pid_bigger(ack, t->fwd_pid))
3728     ack = t->fwd_pid + 1; // Might overflow 32 bits, it's ok!
3729   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3730               "c %u, bf %u, ch %lld, cl %lld, ACK: %u\n",
3731               count, buffer_free, child_ack, client_ack, ack);
3732   return ack;
3733 }
3734
3735
3736 /**
3737  * Build a local ACK message and send it to a local client.
3738  * 
3739  * @param t Tunnel on which to send the ACK.
3740  * @param c Client to whom send the ACK.
3741  * @param ack Value of the ACK.
3742  */
3743 static void
3744 send_local_ack (struct MeshTunnel *t, struct MeshClient *c, uint32_t ack)
3745 {
3746   struct GNUNET_MESH_LocalAck msg;
3747
3748   msg.header.size = htons (sizeof (msg));
3749   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
3750   msg.tunnel_id = htonl (t->owner == c ? t->local_tid : t->local_tid_dest);
3751   msg.max_pid = htonl (ack); 
3752   GNUNET_SERVER_notification_context_unicast(nc,
3753                                               c->handle,
3754                                               &msg.header,
3755                                               GNUNET_NO);
3756 }
3757
3758 /**
3759  * Build an ACK message and queue it to send to the given peer.
3760  * 
3761  * @param t Tunnel on which to send the ACK.
3762  * @param peer Peer to whom send the ACK.
3763  * @param ack Value of the ACK.
3764  */
3765 static void
3766 send_ack (struct MeshTunnel *t, struct GNUNET_PeerIdentity *peer,  uint32_t ack)
3767 {
3768   struct GNUNET_MESH_ACK msg;
3769
3770   GNUNET_PEER_resolve (t->id.oid, &msg.oid);
3771   msg.header.size = htons (sizeof (msg));
3772   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_ACK);
3773   msg.pid = htonl (ack);
3774   msg.tid = htonl (t->id.tid);
3775
3776   send_prebuilt_message (&msg.header, peer, t);
3777 }
3778
3779
3780 /**
3781  * Notify a the owner of a tunnel about how many more
3782  * payload packages will we accept on a given tunnel.
3783  *
3784  * @param t Tunnel on which to send the ACK.
3785  */
3786 static void
3787 tunnel_send_client_fwd_ack (struct MeshTunnel *t)
3788 {
3789   uint32_t ack;
3790
3791   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3792               "Sending client FWD ACK on tunnel %X\n",
3793               t->local_tid);
3794
3795   ack = tunnel_get_fwd_ack (t);
3796
3797   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ack %u\n", ack);
3798   if (t->last_fwd_ack == ack)
3799     return;
3800
3801   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " sending!\n");
3802   t->last_fwd_ack = ack;
3803   send_local_ack (t, t->owner, ack);
3804 }
3805
3806
3807 /**
3808  * Send an ACK informing the predecessor about the available buffer space.
3809  * In case there is no predecessor, inform the owning client.
3810  * If buffering is off, send only on behalf of children or self if endpoint.
3811  * If buffering is on, send when sent to children and buffer space is free.
3812  * Note that although the name is fwd_ack, the FWD mean forward *traffic*,
3813  * the ACK itself goes "back" (towards root).
3814  * 
3815  * @param t Tunnel on which to send the ACK.
3816  * @param type Type of message that triggered the ACK transmission.
3817  */
3818 static void
3819 tunnel_send_fwd_ack (struct MeshTunnel *t, uint16_t type)
3820 {
3821   struct GNUNET_PeerIdentity id;
3822   uint32_t ack;
3823
3824   if (NULL != t->owner)
3825   {
3826     tunnel_send_client_fwd_ack (t);
3827     return;
3828   }
3829   /* Is it after unicast / multicast retransmission? */
3830   switch (type)
3831   {
3832     case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
3833     case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
3834       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3835                   "ACK due to FWD DATA retransmission\n");
3836       if (GNUNET_YES == t->nobuffer)
3837       {
3838         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, nobuffer\n");
3839         return;
3840       }
3841       break;
3842     case GNUNET_MESSAGE_TYPE_MESH_ACK:
3843     case GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK:
3844       break;
3845     default:
3846       GNUNET_break (0);
3847   }
3848
3849   /* Check if we need no retransmit the ACK */
3850   if (t->fwd_queue_max > t->fwd_queue_n * 4 &&
3851       GMC_is_pid_bigger(t->last_fwd_ack, t->fwd_pid))
3852   {
3853     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, buffer free\n");
3854     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3855                 "  t->qmax: %u, t->qn: %u\n",
3856                 t->fwd_queue_max, t->fwd_queue_n);
3857     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3858                 "  t->pid: %u, t->ack: %u\n",
3859                 t->fwd_pid, t->last_fwd_ack);
3860     return;
3861   }
3862
3863   /* Ok, ACK might be necessary, what PID to ACK? */
3864   ack = tunnel_get_fwd_ack (t);
3865
3866   /* If speed_min and not all children have ack'd, dont send yet */
3867   if (ack == t->last_fwd_ack)
3868   {
3869     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending FWD ACK, not ready\n");
3870     return;
3871   }
3872
3873   t->last_fwd_ack = ack;
3874   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
3875   send_ack (t, &id, ack);
3876   debug_fwd_ack++;
3877 }
3878
3879
3880 /**
3881  * Iterator to send a child node a BCK ACK to allow him to send more
3882  * to_origin data.
3883  *
3884  * @param cls Closure (tunnel).
3885  * @param id Id of the child node.
3886  */
3887 static void
3888 tunnel_send_child_bck_ack (void *cls,
3889                            GNUNET_PEER_Id id)
3890 {
3891   struct MeshTunnel *t = cls;
3892   struct MeshTunnelChildInfo *cinfo;
3893   struct GNUNET_PeerIdentity peer;
3894
3895   GNUNET_PEER_resolve (id, &peer);
3896   cinfo = tunnel_get_neighbor_fc (t, &peer);
3897
3898   if (cinfo->bck_ack != cinfo->pid &&
3899       GNUNET_NO == GMC_is_pid_bigger (cinfo->bck_ack, cinfo->pid))
3900     return;
3901
3902   cinfo->bck_ack++;
3903   send_ack (t, &peer, cinfo->bck_ack);
3904 }
3905
3906
3907 /**
3908  * @brief Send BCK ACKs to clients to allow them more to_origin traffic
3909  * 
3910  * Iterates over all clients and sends BCK ACKs to the ones that need it.
3911  * 
3912  * @param t Tunnel on which to send the BCK ACKs.
3913  */
3914 static void
3915 tunnel_send_clients_bck_ack (struct MeshTunnel *t)
3916 {
3917   unsigned int i;
3918   unsigned int tunnel_delta;
3919
3920   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Sending BCK ACK to clients\n");
3921
3922   tunnel_delta = t->bck_ack - t->bck_pid;
3923   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   tunnel delta: %u\n", tunnel_delta);
3924
3925   /* Find client whom to allow to send to origin (with lowest buffer space) */
3926   for (i = 0; i < t->nclients; i++)
3927   {
3928     struct MeshTunnelClientInfo *clinfo;
3929     unsigned int delta;
3930
3931     clinfo = &t->clients_fc[i];
3932     delta = clinfo->bck_ack - clinfo->bck_pid;
3933     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    client %u delta: %u\n",
3934          t->clients[i]->id, delta);
3935
3936     if ((GNUNET_NO == t->nobuffer && tunnel_delta > delta) ||
3937         (GNUNET_YES == t->nobuffer && 0 == delta))
3938     {
3939       uint32_t ack;
3940
3941       ack = clinfo->bck_pid;
3942       ack += t->nobuffer ? 1 : tunnel_delta;
3943       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3944                   "    sending ack to client %u: %u\n",
3945                   t->clients[i]->id, ack);
3946       send_local_ack (t, t->clients[i], ack);
3947       clinfo->bck_ack = ack;
3948     }
3949   }
3950 }
3951
3952
3953 /**
3954  * Send an ACK informing the children nodes and destination clients about
3955  * the available buffer space.
3956  * If buffering is off, send only on behalf of root (can be self).
3957  * If buffering is on, send when sent to predecessor and buffer space is free.
3958  * Note that although the name is bck_ack, the BCK mean backwards *traffic*,
3959  * the ACK itself goes "forward" (towards children/clients).
3960  * 
3961  * @param t Tunnel on which to send the ACK.
3962  * @param type Type of message that triggered the ACK transmission.
3963  */
3964 static void
3965 tunnel_send_bck_ack (struct MeshTunnel *t, uint16_t type)
3966 {
3967   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3968               "Sending BCK ACK on tunnel %u [%u] due to %s\n",
3969               t->id.oid, t->id.tid, GNUNET_MESH_DEBUG_M2S(type));
3970   /* Is it after data to_origin retransmission? */
3971   switch (type)
3972   {
3973     case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
3974       if (GNUNET_YES == t->nobuffer)
3975       {
3976         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3977                     "    Not sending ACK, nobuffer\n");
3978         return;
3979       }
3980       break;
3981     case GNUNET_MESSAGE_TYPE_MESH_ACK:
3982     case GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK:
3983       break;
3984     default:
3985       GNUNET_break (0);
3986   }
3987
3988   tunnel_send_clients_bck_ack (t);
3989   tree_iterate_children (t->tree, &tunnel_send_child_bck_ack, t);
3990 }
3991
3992
3993 /**
3994  * @brief Re-initiate traffic to this peer if necessary.
3995  *
3996  * Check if there is traffic queued towards this peer
3997  * and the core transmit handle is NULL (traffic was stalled).
3998  * If so, call core tmt rdy.
3999  *
4000  * @param cls Closure (unused)
4001  * @param peer_id Short ID of peer to which initiate traffic.
4002  */
4003 static void
4004 peer_unlock_queue(void *cls, GNUNET_PEER_Id peer_id)
4005 {
4006   struct MeshPeerInfo *peer;
4007   struct GNUNET_PeerIdentity id;
4008   struct MeshPeerQueue *q;
4009   size_t size;
4010
4011   peer = peer_info_get_short(peer_id);
4012   if (NULL != peer->core_transmit)
4013     return;
4014
4015   q = queue_get_next(peer);
4016   if (NULL == q)
4017   {
4018     /* Might br multicast traffic already sent to this particular peer but
4019      * not to other children in this tunnel.
4020      * This way t->queue_n would be > 0 but the queue of this particular peer
4021      * would be empty.
4022      */
4023     return;
4024   }
4025   size = q->size;
4026   GNUNET_PEER_resolve (peer->id, &id);
4027   peer->core_transmit =
4028         GNUNET_CORE_notify_transmit_ready(core_handle,
4029                                           0,
4030                                           0,
4031                                           GNUNET_TIME_UNIT_FOREVER_REL,
4032                                           &id,
4033                                           size,
4034                                           &queue_send,
4035                                           peer);
4036         return;
4037 }
4038
4039
4040 /**
4041  * @brief Allow transmission of FWD traffic on this tunnel
4042  *
4043  * Check if there is traffic queued towards any children
4044  * and the core transmit handle is NULL, and if so, call core tmt rdy.
4045  *
4046  * @param t Tunnel on which to unlock FWD traffic.
4047  */
4048 static void
4049 tunnel_unlock_fwd_queues (struct MeshTunnel *t)
4050 {
4051   if (0 == t->fwd_queue_n)
4052     return;
4053
4054   tree_iterate_children (t->tree, &peer_unlock_queue, NULL);
4055 }
4056
4057
4058 /**
4059  * @brief Allow transmission of BCK traffic on this tunnel
4060  *
4061  * Check if there is traffic queued towards the root of the tree
4062  * and the core transmit handle is NULL, and if so, call core tmt rdy.
4063  *
4064  * @param t Tunnel on which to unlock BCK traffic.
4065  */
4066 static void
4067 tunnel_unlock_bck_queue (struct MeshTunnel *t)
4068 {
4069   if (0 == t->bck_queue_n)
4070     return;
4071
4072   peer_unlock_queue(NULL, tree_get_predecessor(t->tree));
4073 }
4074
4075
4076 /**
4077  * Send a message to all peers in this tunnel that the tunnel is no longer
4078  * valid.
4079  *
4080  * @param t The tunnel whose peers to notify.
4081  */
4082 static void
4083 tunnel_send_destroy (struct MeshTunnel *t)
4084 {
4085   struct GNUNET_MESH_TunnelDestroy msg;
4086
4087   msg.header.size = htons (sizeof (msg));
4088   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY);
4089   GNUNET_PEER_resolve (t->id.oid, &msg.oid);
4090   msg.tid = htonl (t->id.tid);
4091   tunnel_send_multicast (t, &msg.header);
4092 }
4093
4094
4095 /**
4096  * Cancel all transmissions towards a neighbor that belong to a certain tunnel.
4097  *
4098  * @param cls Closure (Tunnel which to cancel).
4099  * @param neighbor_id Short ID of the neighbor to whom cancel the transmissions.
4100  */
4101 static void
4102 tunnel_cancel_queues (void *cls, GNUNET_PEER_Id neighbor_id)
4103 {
4104   struct MeshTunnel *t = cls;
4105   struct MeshPeerInfo *peer_info;
4106   struct MeshPeerQueue *pq;
4107   struct MeshPeerQueue *next;
4108
4109   peer_info = peer_info_get_short (neighbor_id);
4110   for (pq = peer_info->queue_head; NULL != pq; pq = next)
4111   {
4112     next = pq->next;
4113     if (pq->tunnel == t)
4114     {
4115       if (GNUNET_MESSAGE_TYPE_MESH_MULTICAST == pq->type ||
4116           GNUNET_MESSAGE_TYPE_MESH_UNICAST == pq->type ||
4117           GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == pq->type)
4118       {
4119         // Should have been removed on destroy children
4120         GNUNET_break (0);
4121       }
4122       queue_destroy (pq, GNUNET_YES);
4123     }
4124   }
4125   if (NULL == peer_info->queue_head && NULL != peer_info->core_transmit)
4126   {
4127     GNUNET_CORE_notify_transmit_ready_cancel(peer_info->core_transmit);
4128     peer_info->core_transmit = NULL;
4129   }
4130 }
4131
4132 /**
4133  * Destroy the tunnel and free any allocated resources linked to it.
4134  *
4135  * @param t the tunnel to destroy
4136  *
4137  * @return GNUNET_OK on success
4138  */
4139 static int
4140 tunnel_destroy (struct MeshTunnel *t)
4141 {
4142   struct MeshClient *c;
4143   struct GNUNET_HashCode hash;
4144   unsigned int i;
4145   int r;
4146
4147   if (NULL == t)
4148     return GNUNET_OK;
4149
4150   r = GNUNET_OK;
4151   c = t->owner;
4152 #if MESH_DEBUG
4153   {
4154     struct GNUNET_PeerIdentity id;
4155
4156     GNUNET_PEER_resolve (t->id.oid, &id);
4157     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s [%x]\n",
4158                 GNUNET_i2s (&id), t->id.tid);
4159     if (NULL != c)
4160       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
4161   }
4162 #endif
4163
4164   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
4165   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &hash, t))
4166   {
4167     GNUNET_break (0);
4168     r = GNUNET_SYSERR;
4169   }
4170
4171   if (NULL != c)
4172   {
4173     GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
4174     if (GNUNET_YES !=
4175         GNUNET_CONTAINER_multihashmap_remove (c->own_tunnels, &hash, t))
4176     {
4177       GNUNET_break (0);
4178       r = GNUNET_SYSERR;
4179     }
4180   }
4181
4182   GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
4183   for (i = 0; i < t->nclients; i++)
4184   {
4185     c = t->clients[i];
4186     if (GNUNET_YES !=
4187           GNUNET_CONTAINER_multihashmap_remove (c->incoming_tunnels, &hash, t))
4188     {
4189       GNUNET_break (0);
4190       r = GNUNET_SYSERR;
4191     }
4192   }
4193   for (i = 0; i < t->nignore; i++)
4194   {
4195     c = t->ignore[i];
4196     if (GNUNET_YES !=
4197           GNUNET_CONTAINER_multihashmap_remove (c->ignore_tunnels, &hash, t))
4198     {
4199       GNUNET_break (0);
4200       r = GNUNET_SYSERR;
4201     }
4202   }
4203
4204   if (t->nclients > 0)
4205   {
4206     if (GNUNET_YES !=
4207         GNUNET_CONTAINER_multihashmap_remove (incoming_tunnels, &hash, t))
4208     {
4209       GNUNET_break (0);
4210       r = GNUNET_SYSERR;
4211     }
4212     GNUNET_free (t->clients);
4213   }
4214
4215   if (NULL != t->peers)
4216   {
4217     GNUNET_CONTAINER_multihashmap_iterate (t->peers, &peer_info_delete_tunnel,
4218                                            t);
4219     GNUNET_CONTAINER_multihashmap_destroy (t->peers);
4220   }
4221
4222   GNUNET_CONTAINER_multihashmap_iterate (t->children_fc,
4223                                          &tunnel_destroy_child,
4224                                          t);
4225   GNUNET_CONTAINER_multihashmap_destroy (t->children_fc);
4226
4227   tree_iterate_children (t->tree, &tunnel_cancel_queues, t);
4228
4229   tree_destroy (t->tree);
4230
4231   if (NULL != t->regex_ctx)
4232     regex_cancel_search (t->regex_ctx);
4233   if (NULL != t->dht_get_type)
4234     GNUNET_DHT_get_stop (t->dht_get_type);
4235   if (GNUNET_SCHEDULER_NO_TASK != t->timeout_task)
4236     GNUNET_SCHEDULER_cancel (t->timeout_task);
4237   if (GNUNET_SCHEDULER_NO_TASK != t->path_refresh_task)
4238     GNUNET_SCHEDULER_cancel (t->path_refresh_task);
4239
4240   n_tunnels--;
4241   GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
4242   GNUNET_assert (0 <= n_tunnels);
4243   GNUNET_free (t);
4244   return r;
4245 }
4246
4247
4248 /**
4249  * Create a new tunnel
4250  * 
4251  * @param owner Who is the owner of the tunnel (short ID).
4252  * @param tid Tunnel Number of the tunnel.
4253  * @param client Clients that owns the tunnel, NULL for foreign tunnels.
4254  * @param local Tunnel Number for the tunnel, for the client point of view.
4255  * 
4256  * @return A new initialized tunnel. NULL on error.
4257  */
4258 static struct MeshTunnel *
4259 tunnel_new (GNUNET_PEER_Id owner,
4260             MESH_TunnelNumber tid,
4261             struct MeshClient *client,
4262             MESH_TunnelNumber local)
4263 {
4264   struct MeshTunnel *t;
4265   struct GNUNET_HashCode hash;
4266
4267   if (n_tunnels >= max_tunnels && NULL == client)
4268     return NULL;
4269
4270   t = GNUNET_malloc (sizeof (struct MeshTunnel));
4271   t->id.oid = owner;
4272   t->id.tid = tid;
4273   t->fwd_queue_max = (max_msgs_queue / max_tunnels) + 1;
4274   t->bck_queue_max = t->fwd_queue_max;
4275   t->tree = tree_new (owner);
4276   t->owner = client;
4277   t->fwd_pid = (uint32_t) -1; // Next (expected) = 0
4278   t->bck_pid = (uint32_t) -1; // Next (expected) = 0
4279   t->bck_ack = INITIAL_WINDOW_SIZE - 1;
4280   t->last_fwd_ack = INITIAL_WINDOW_SIZE - 1;
4281   t->local_tid = local;
4282   t->children_fc = GNUNET_CONTAINER_multihashmap_create (8);
4283   n_tunnels++;
4284   GNUNET_STATISTICS_update (stats, "# tunnels", 1, GNUNET_NO);
4285
4286   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
4287   if (GNUNET_OK !=
4288       GNUNET_CONTAINER_multihashmap_put (tunnels, &hash, t,
4289                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
4290   {
4291     GNUNET_break (0);
4292     tunnel_destroy (t);
4293     if (NULL != client)
4294     {
4295       GNUNET_break (0);
4296       GNUNET_SERVER_receive_done (client->handle, GNUNET_SYSERR);
4297     }
4298     return NULL;
4299   }
4300
4301   if (NULL != client)
4302   {
4303     GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
4304     if (GNUNET_OK !=
4305         GNUNET_CONTAINER_multihashmap_put (client->own_tunnels, &hash, t,
4306                                           GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
4307     {
4308       tunnel_destroy (t);
4309       GNUNET_break (0);
4310       GNUNET_SERVER_receive_done (client->handle, GNUNET_SYSERR);
4311       return NULL;
4312     }
4313   }
4314
4315   return t;
4316 }
4317
4318
4319 /**
4320  * Removes an explicit path from a tunnel, freeing all intermediate nodes
4321  * that are no longer needed, as well as nodes of no longer reachable peers.
4322  * The tunnel itself is also destoyed if results in a remote empty tunnel.
4323  *
4324  * @param t Tunnel from which to remove the path.
4325  * @param peer Short id of the peer which should be removed.
4326  */
4327 static void
4328 tunnel_delete_peer (struct MeshTunnel *t, GNUNET_PEER_Id peer)
4329 {
4330   if (GNUNET_NO == tree_del_peer (t->tree, peer, NULL, NULL))
4331     tunnel_destroy (t);
4332 }
4333
4334
4335 /**
4336  * tunnel_destroy_iterator: iterator for deleting each tunnel that belongs to a
4337  * client when the client disconnects. If the client is not the owner, the
4338  * owner will get notified if no more clients are in the tunnel and the client
4339  * get removed from the tunnel's list.
4340  *
4341  * @param cls closure (client that is disconnecting)
4342  * @param key the hash of the local tunnel id (used to access the hashmap)
4343  * @param value the value stored at the key (tunnel to destroy)
4344  *
4345  * @return GNUNET_OK, keep iterating.
4346  */
4347 static int
4348 tunnel_destroy_iterator (void *cls, const struct GNUNET_HashCode * key, void *value)
4349 {
4350   struct MeshTunnel *t = value;
4351   struct MeshClient *c = cls;
4352
4353   send_client_tunnel_disconnect(t, c);
4354   if (c != t->owner)
4355   {
4356     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4357                 "Client %u is destination, keeping the tunnel alive.\n", c->id);
4358     tunnel_delete_client(t, c);
4359     client_delete_tunnel(c, t);
4360     return GNUNET_OK;
4361   }
4362   tunnel_send_destroy(t);
4363   t->owner = NULL;
4364   t->destroy = GNUNET_YES;
4365
4366   return GNUNET_OK;
4367 }
4368
4369
4370 /**
4371  * Timeout function, destroys tunnel if called
4372  *
4373  * @param cls Closure (tunnel to destroy).
4374  * @param tc TaskContext
4375  */
4376 static void
4377 tunnel_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4378 {
4379   struct MeshTunnel *t = cls;
4380   struct GNUNET_PeerIdentity id;
4381
4382   t->timeout_task = GNUNET_SCHEDULER_NO_TASK;
4383   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4384     return;
4385   GNUNET_PEER_resolve(t->id.oid, &id);
4386   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4387               "Tunnel %s [%X] timed out. Destroying.\n",
4388               GNUNET_i2s(&id), t->id.tid);
4389   tunnel_destroy (t);
4390 }
4391
4392 /**
4393  * Resets the tunnel timeout. Starts it if no timeout was running.
4394  *
4395  * @param t Tunnel whose timeout to reset.
4396  *
4397  * TODO use heap to improve efficiency of scheduler.
4398  */
4399 static void
4400 tunnel_reset_timeout (struct MeshTunnel *t)
4401 {
4402   if (GNUNET_SCHEDULER_NO_TASK != t->timeout_task)
4403     GNUNET_SCHEDULER_cancel (t->timeout_task);
4404   t->timeout_task =
4405       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
4406                                     (refresh_path_time, 4), &tunnel_timeout, t);
4407 }
4408
4409
4410 /******************************************************************************/
4411 /****************      MESH NETWORK HANDLER HELPERS     ***********************/
4412 /******************************************************************************/
4413
4414 /**
4415  * Function to send a create path packet to a peer.
4416  *
4417  * @param cls closure
4418  * @param size number of bytes available in buf
4419  * @param buf where the callee should write the message
4420  * @return number of bytes written to buf
4421  */
4422 static size_t
4423 send_core_path_create (void *cls, size_t size, void *buf)
4424 {
4425   struct MeshPathInfo *info = cls;
4426   struct GNUNET_MESH_ManipulatePath *msg;
4427   struct GNUNET_PeerIdentity *peer_ptr;
4428   struct MeshTunnel *t = info->t;
4429   struct MeshPeerPath *p = info->path;
4430   size_t size_needed;
4431   uint32_t opt;
4432   int i;
4433
4434   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATE PATH sending...\n");
4435   size_needed =
4436       sizeof (struct GNUNET_MESH_ManipulatePath) +
4437       p->length * sizeof (struct GNUNET_PeerIdentity);
4438
4439   if (size < size_needed || NULL == buf)
4440   {
4441     GNUNET_break (0);
4442     return 0;
4443   }
4444   msg = (struct GNUNET_MESH_ManipulatePath *) buf;
4445   msg->header.size = htons (size_needed);
4446   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE);
4447   msg->tid = ntohl (t->id.tid);
4448
4449   opt = 0;
4450   if (GNUNET_YES == t->speed_min)
4451     opt |= MESH_TUNNEL_OPT_SPEED_MIN;
4452   if (GNUNET_YES == t->nobuffer)
4453     opt |= MESH_TUNNEL_OPT_NOBUFFER;
4454   msg->opt = htonl(opt);
4455   msg->reserved = 0;
4456
4457   peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
4458   for (i = 0; i < p->length; i++)
4459   {
4460     GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
4461   }
4462
4463   path_destroy (p);
4464   GNUNET_free (info);
4465
4466   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4467               "CREATE PATH (%u bytes long) sent!\n", size_needed);
4468   return size_needed;
4469 }
4470
4471
4472 /**
4473  * Fill the core buffer 
4474  *
4475  * @param cls closure (data itself)
4476  * @param size number of bytes available in buf
4477  * @param buf where the callee should write the message
4478  *
4479  * @return number of bytes written to buf
4480  */
4481 static size_t
4482 send_core_data_multicast (void *cls, size_t size, void *buf)
4483 {
4484   struct MeshTransmissionDescriptor *info = cls;
4485   size_t total_size;
4486
4487   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Multicast callback.\n");
4488   GNUNET_assert (NULL != info);
4489   GNUNET_assert (NULL != info->peer);
4490   total_size = info->mesh_data->data_len;
4491   GNUNET_assert (total_size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
4492
4493   if (total_size > size)
4494   {
4495     GNUNET_break (0);
4496     return 0;
4497   }
4498   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " copying data...\n");
4499   memcpy (buf, info->mesh_data->data, total_size);
4500 #if MESH_DEBUG
4501   {
4502     struct GNUNET_MESH_Multicast *mc;
4503     struct GNUNET_MessageHeader *mh;
4504
4505     mh = buf;
4506     if (ntohs (mh->type) == GNUNET_MESSAGE_TYPE_MESH_MULTICAST)
4507     {
4508       mc = (struct GNUNET_MESH_Multicast *) mh;
4509       mh = (struct GNUNET_MessageHeader *) &mc[1];
4510       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4511                   " multicast, payload type %s\n",
4512                   GNUNET_MESH_DEBUG_M2S (ntohs (mh->type)));
4513       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4514                   " multicast, payload size %u\n", ntohs (mh->size));
4515     }
4516     else
4517     {
4518       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " type %s\n",
4519                   GNUNET_MESH_DEBUG_M2S (ntohs (mh->type)));
4520     }
4521   }
4522 #endif
4523   data_descriptor_decrement_rc (info->mesh_data);
4524   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "freeing info...\n");
4525   GNUNET_free (info);
4526   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "return %u\n", total_size);
4527   return total_size;
4528 }
4529
4530
4531 /**
4532  * Creates a path ack message in buf and frees all unused resources.
4533  *
4534  * @param cls closure (MeshTransmissionDescriptor)
4535  * @param size number of bytes available in buf
4536  * @param buf where the callee should write the message
4537  * @return number of bytes written to buf
4538  */
4539 static size_t
4540 send_core_path_ack (void *cls, size_t size, void *buf)
4541 {
4542   struct MeshTransmissionDescriptor *info = cls;
4543   struct GNUNET_MESH_PathACK *msg = buf;
4544
4545   GNUNET_assert (NULL != info);
4546   if (sizeof (struct GNUNET_MESH_PathACK) > size)
4547   {
4548     GNUNET_break (0);
4549     return 0;
4550   }
4551   msg->header.size = htons (sizeof (struct GNUNET_MESH_PathACK));
4552   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_ACK);
4553   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
4554   msg->tid = htonl (info->origin->tid);
4555   msg->peer_id = my_full_id;
4556
4557   GNUNET_free (info);
4558   /* TODO add signature */
4559
4560   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "PATH ACK sent!\n");
4561   return sizeof (struct GNUNET_MESH_PathACK);
4562 }
4563
4564
4565 /**
4566  * Free a transmission that was already queued with all resources
4567  * associated to the request.
4568  *
4569  * @param queue Queue handler to cancel.
4570  * @param clear_cls Is it necessary to free associated cls?
4571  */
4572 static void
4573 queue_destroy (struct MeshPeerQueue *queue, int clear_cls)
4574 {
4575   struct MeshTransmissionDescriptor *dd;
4576   struct MeshPathInfo *path_info;
4577   struct MeshTunnelChildInfo *cinfo;
4578   struct GNUNET_PeerIdentity id;
4579   unsigned int i;
4580   unsigned int max;
4581
4582   if (GNUNET_YES == clear_cls)
4583   {
4584     switch (queue->type)
4585     {
4586       case GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY:
4587         GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "   cancelling TUNNEL_DESTROY\n");
4588         /* fall through */
4589       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4590       case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
4591       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4592         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4593                     "   type prebuilt (payload, tunnel destroy)\n");
4594         dd = queue->cls;
4595         data_descriptor_decrement_rc (dd->mesh_data);
4596         break;
4597       case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
4598         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   type create path\n");
4599         path_info = queue->cls;
4600         path_destroy (path_info->path);
4601         break;
4602       default:
4603         GNUNET_break (0);
4604         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4605                     "   type %s unknown!\n",
4606                     GNUNET_MESH_DEBUG_M2S(queue->type));
4607     }
4608     GNUNET_free_non_null (queue->cls);
4609   }
4610   GNUNET_CONTAINER_DLL_remove (queue->peer->queue_head,
4611                                queue->peer->queue_tail,
4612                                queue);
4613
4614   /* Delete from child_fc in the appropiate tunnel */
4615   max = queue->tunnel->fwd_queue_max;
4616   GNUNET_PEER_resolve (queue->peer->id, &id);
4617   cinfo = tunnel_get_neighbor_fc (queue->tunnel, &id);
4618   for (i = 0; i < cinfo->send_buffer_n; i++)
4619   {
4620     unsigned int i2;
4621     i2 = (cinfo->send_buffer_start + i) % max;
4622     if (cinfo->send_buffer[i2] == queue)
4623     {
4624       /* Found corresponding entry in the send_buffer. Move all others back. */
4625       unsigned int j;
4626       unsigned int j2;
4627       unsigned int j3;
4628
4629       for (j = i, j2 = 0, j3 = 0; j < cinfo->send_buffer_n - 1; j++)
4630       {
4631         j2 = (cinfo->send_buffer_start + j) % max;
4632         j3 = (cinfo->send_buffer_start + j + 1) % max;
4633         cinfo->send_buffer[j2] = cinfo->send_buffer[j3];
4634       }
4635
4636       cinfo->send_buffer[j3] = NULL;
4637
4638       cinfo->send_buffer_n--;
4639     }
4640   }
4641   //queue->
4642
4643   GNUNET_free (queue);
4644 }
4645
4646
4647 /**
4648  * @brief Get the next transmittable message from the queue.
4649  *
4650  * This will be the head, except in the case of being a data packet
4651  * not allowed by the destination peer.
4652  *
4653  * @param peer Destination peer.
4654  *
4655  * @return The next viable MeshPeerQueue element to send to that peer.
4656  *         NULL when there are no transmittable messages.
4657  */
4658 struct MeshPeerQueue *
4659 queue_get_next (const struct MeshPeerInfo *peer)
4660 {
4661   struct MeshPeerQueue *q;
4662   struct MeshTunnel *t;
4663   struct MeshTransmissionDescriptor *info;
4664   struct MeshTunnelChildInfo *cinfo;
4665   struct GNUNET_MESH_Unicast *ucast;
4666   struct GNUNET_MESH_ToOrigin *to_orig;
4667   struct GNUNET_MESH_Multicast *mcast;
4668   struct GNUNET_PeerIdentity id;
4669   uint32_t pid;
4670   uint32_t ack;
4671
4672   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   selecting message\n");
4673   for (q = peer->queue_head; NULL != q; q = q->next)
4674   {
4675     t = q->tunnel;
4676     info = q->cls;
4677     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4678                 "*********     %s\n",
4679                 GNUNET_MESH_DEBUG_M2S(q->type));
4680     switch (q->type)
4681     {
4682       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4683         ucast = (struct GNUNET_MESH_Unicast *) info->mesh_data->data;
4684         pid = ntohl (ucast->pid);
4685         GNUNET_PEER_resolve (info->peer->id, &id);
4686         cinfo = tunnel_get_neighbor_fc(t, &id);
4687         ack = cinfo->fwd_ack;
4688         break;
4689       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4690         to_orig = (struct GNUNET_MESH_ToOrigin *) info->mesh_data->data;
4691         pid = ntohl (to_orig->pid);
4692         ack = t->bck_ack;
4693         break;
4694       case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
4695         mcast = (struct GNUNET_MESH_Multicast *) info->mesh_data->data;
4696         if (GNUNET_MESSAGE_TYPE_MESH_MULTICAST != ntohs(mcast->header.type)) 
4697         {
4698           // Not a multicast payload: multicast control traffic (destroy, etc)
4699           return q;
4700         }
4701         pid = ntohl (mcast->pid);
4702         GNUNET_PEER_resolve (info->peer->id, &id);
4703         cinfo = tunnel_get_neighbor_fc(t, &id);
4704         ack = cinfo->fwd_ack;
4705         break;
4706       default:
4707         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4708                     "*********   OK!\n");
4709         return q;
4710     }
4711         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4712                     "*********     ACK: %u, PID: %u\n",
4713                     ack, pid);
4714     if (GNUNET_NO == GMC_is_pid_bigger(pid, ack))
4715     {
4716       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4717                   "*********   OK!\n");
4718       return q;
4719     }
4720     else
4721     {
4722       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4723                   "*********     NEXT!\n");
4724     }
4725   }
4726   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4727                 "*********   nothing found\n");
4728   return NULL;
4729 }
4730
4731
4732 /**
4733   * Core callback to write a queued packet to core buffer
4734   *
4735   * @param cls Closure (peer info).
4736   * @param size Number of bytes available in buf.
4737   * @param buf Where the to write the message.
4738   *
4739   * @return number of bytes written to buf
4740   */
4741 static size_t
4742 queue_send (void *cls, size_t size, void *buf)
4743 {
4744     struct MeshPeerInfo *peer = cls;
4745     struct GNUNET_MessageHeader *msg;
4746     struct MeshPeerQueue *queue;
4747     struct MeshTunnel *t;
4748     struct MeshTunnelChildInfo *cinfo;
4749     struct GNUNET_PeerIdentity dst_id;
4750     size_t data_size;
4751
4752     peer->core_transmit = NULL;
4753
4754     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "********* Queue send\n");
4755     queue = queue_get_next (peer);
4756
4757     /* Queue has no internal mesh traffic nor sendable payload */
4758     if (NULL == queue)
4759     {
4760       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   not ready, return\n");
4761       if (NULL == peer->queue_head)
4762         GNUNET_break (0); // Should've been canceled
4763       return 0;
4764     }
4765     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   not empty\n");
4766
4767     GNUNET_PEER_resolve (peer->id, &dst_id);
4768     /* Check if buffer size is enough for the message */
4769     if (queue->size > size)
4770     {
4771         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4772                     "*********   not enough room, reissue\n");
4773         peer->core_transmit =
4774             GNUNET_CORE_notify_transmit_ready (core_handle,
4775                                                0,
4776                                                0,
4777                                                GNUNET_TIME_UNIT_FOREVER_REL,
4778                                                &dst_id,
4779                                                queue->size,
4780                                                &queue_send,
4781                                                peer);
4782         return 0;
4783     }
4784     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   size ok\n");
4785
4786     t = queue->tunnel;
4787     if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == queue->type)
4788     {
4789       t->fwd_queue_n--;
4790       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4791                   "*********   unicast: t->q (%u/%u)\n",
4792                   t->fwd_queue_n, t->fwd_queue_max);
4793     }
4794     else if (GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == queue->type)
4795     {
4796       t->bck_queue_n--;
4797       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   to origin\n");
4798     }
4799
4800     /* Fill buf */
4801     switch (queue->type)
4802     {
4803       case 0:
4804       case GNUNET_MESSAGE_TYPE_MESH_ACK:
4805       case GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN:
4806       case GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY:
4807       case GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY:
4808         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4809                     "*********   raw: %s\n",
4810                     GNUNET_MESH_DEBUG_M2S (queue->type));
4811         /* Fall through */
4812       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4813       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4814         data_size = send_core_data_raw (queue->cls, size, buf);
4815         msg = (struct GNUNET_MessageHeader *) buf;
4816         switch (ntohs (msg->type)) // Type of preconstructed message
4817         {
4818           case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4819             tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_UNICAST);
4820             break;
4821           case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4822             tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
4823             break;
4824           default:
4825               break;
4826         }
4827         break;
4828       case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
4829         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   multicast\n");
4830         {
4831           struct MeshTransmissionDescriptor *info = queue->cls;
4832
4833           if ((1 == info->mesh_data->reference_counter
4834               && GNUNET_YES == t->speed_min)
4835               ||
4836               (info->mesh_data->total_out == info->mesh_data->reference_counter
4837               && GNUNET_NO == t->speed_min))
4838           {
4839             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4840                         "*********   considered sent\n");
4841             t->fwd_queue_n--;
4842           }
4843         }
4844         data_size = send_core_data_multicast(queue->cls, size, buf);
4845         tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
4846         break;
4847       case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
4848         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path create\n");
4849         data_size = send_core_path_create (queue->cls, size, buf);
4850         break;
4851       case GNUNET_MESSAGE_TYPE_MESH_PATH_ACK:
4852         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path ack\n");
4853         data_size = send_core_path_ack (queue->cls, size, buf);
4854         break;
4855       case GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE:
4856         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path keepalive\n");
4857         data_size = send_core_data_multicast (queue->cls, size, buf);
4858         break;
4859       default:
4860         GNUNET_break (0);
4861         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4862                     "*********   type unknown: %u\n",
4863                     queue->type);
4864         data_size = 0;
4865     }
4866     switch (queue->type)
4867     {
4868       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4869       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4870       case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
4871         cinfo = tunnel_get_neighbor_fc (t, &dst_id);
4872         if (cinfo->send_buffer[cinfo->send_buffer_start] != queue)
4873         {
4874           GNUNET_break (0);
4875           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4876                       "at pos %u (%p) != %p\n",
4877                       cinfo->send_buffer_start,
4878                       cinfo->send_buffer[cinfo->send_buffer_start],
4879                       queue);
4880         }
4881         if (cinfo->send_buffer_n > 0)
4882         {
4883           cinfo->send_buffer[cinfo->send_buffer_start] = NULL;
4884           cinfo->send_buffer_n--;
4885           cinfo->send_buffer_start++;
4886           cinfo->send_buffer_start %= t->fwd_queue_max;
4887         }
4888         else
4889         {
4890           GNUNET_break (0);
4891         }
4892         break;
4893       default:
4894         break;
4895     }
4896
4897     /* Free queue, but cls was freed by send_core_* */
4898     queue_destroy (queue, GNUNET_NO);
4899
4900     if (GNUNET_YES == t->destroy && 0 == t->fwd_queue_n)
4901     {
4902       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********  destroying tunnel!\n");
4903       tunnel_destroy (t);
4904     }
4905
4906     /* If more data in queue, send next */
4907     queue = queue_get_next(peer);
4908     if (NULL != queue)
4909     {
4910         struct GNUNET_PeerIdentity id;
4911
4912         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   more data!\n");
4913         GNUNET_PEER_resolve (peer->id, &id);
4914         peer->core_transmit =
4915             GNUNET_CORE_notify_transmit_ready(core_handle,
4916                                               0,
4917                                               0,
4918                                               GNUNET_TIME_UNIT_FOREVER_REL,
4919                                               &id,
4920                                               queue->size,
4921                                               &queue_send,
4922                                               peer);
4923     }
4924     else
4925     {
4926       if (NULL != peer->queue_head)
4927         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4928                     "*********   %s stalled\n",
4929                     GNUNET_i2s(&my_full_id));
4930     }
4931     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   return %d\n", data_size);
4932     return data_size;
4933 }
4934
4935
4936 /**
4937  * @brief Queue and pass message to core when possible.
4938  * 
4939  * If type is payload (UNICAST, TO_ORIGIN, MULTICAST) checks for queue status
4940  * and accounts for it. In case the queue is full, the message is dropped and
4941  * a break issued.
4942  * 
4943  * Otherwise, message is treated as internal and allowed to go regardless of 
4944  * queue status.
4945  *
4946  * @param cls Closure (@c type dependant). It will be used by queue_send to
4947  *            build the message to be sent if not already prebuilt.
4948  * @param type Type of the message, 0 for a raw message.
4949  * @param size Size of the message.
4950  * @param dst Neighbor to send message to.
4951  * @param t Tunnel this message belongs to.
4952  */
4953 static void
4954 queue_add (void *cls, uint16_t type, size_t size,
4955            struct MeshPeerInfo *dst, struct MeshTunnel *t)
4956 {
4957   struct MeshPeerQueue *queue;
4958   struct MeshTunnelChildInfo *cinfo;
4959   struct GNUNET_PeerIdentity id;
4960   unsigned int *max;
4961   unsigned int *n;
4962   unsigned int i;
4963
4964   n = NULL;
4965   if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == type ||
4966       GNUNET_MESSAGE_TYPE_MESH_MULTICAST == type)
4967   {
4968     n = &t->fwd_queue_n;
4969     max = &t->fwd_queue_max;
4970   }
4971   else if (GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == type)
4972   {
4973     n = &t->bck_queue_n;
4974     max = &t->bck_queue_max;
4975   }
4976   if (NULL != n) {
4977     if (*n >= *max)
4978     {
4979       if (NULL == t->owner)
4980         GNUNET_break_op(0);       // TODO: kill connection?
4981       else
4982         GNUNET_break(0);
4983       GNUNET_STATISTICS_update(stats, "# messages dropped (buffer full)",
4984                                1, GNUNET_NO);
4985       return;                       // Drop message
4986     }
4987     (*n)++;
4988   }
4989   queue = GNUNET_malloc (sizeof (struct MeshPeerQueue));
4990   queue->cls = cls;
4991   queue->type = type;
4992   queue->size = size;
4993   queue->peer = dst;
4994   queue->tunnel = t;
4995   GNUNET_CONTAINER_DLL_insert_tail (dst->queue_head, dst->queue_tail, queue);
4996   GNUNET_PEER_resolve (dst->id, &id);
4997   if (NULL == dst->core_transmit)
4998   {
4999       dst->core_transmit =
5000           GNUNET_CORE_notify_transmit_ready (core_handle,
5001                                              0,
5002                                              0,
5003                                              GNUNET_TIME_UNIT_FOREVER_REL,
5004                                              &id,
5005                                              size,
5006                                              &queue_send,
5007                                              dst);
5008   }
5009   if (NULL == n) // Is this internal mesh traffic?
5010     return;
5011
5012   // It's payload, keep track of buffer per peer.
5013   cinfo = tunnel_get_neighbor_fc(t, &id);
5014   i = (cinfo->send_buffer_start + cinfo->send_buffer_n) % t->fwd_queue_max;
5015   if (NULL != cinfo->send_buffer[i])
5016   {
5017     GNUNET_break (cinfo->send_buffer_n == t->fwd_queue_max); // aka i == start
5018     queue_destroy (cinfo->send_buffer[cinfo->send_buffer_start], GNUNET_YES);
5019     cinfo->send_buffer_start++;
5020     cinfo->send_buffer_start %= t->fwd_queue_max;
5021   }
5022   else
5023   {
5024     cinfo->send_buffer_n++;
5025   }
5026   cinfo->send_buffer[i] = queue;
5027   if (cinfo->send_buffer_n > t->fwd_queue_max)
5028   {
5029     GNUNET_break (0);
5030     cinfo->send_buffer_n = t->fwd_queue_max;
5031   }
5032 }
5033
5034
5035 /******************************************************************************/
5036 /********************      MESH NETWORK HANDLERS     **************************/
5037 /******************************************************************************/
5038
5039
5040 /**
5041  * Core handler for path creation
5042  *
5043  * @param cls closure
5044  * @param message message
5045  * @param peer peer identity this notification is about
5046  * @param atsi performance data
5047  * @param atsi_count number of records in 'atsi'
5048  *
5049  * @return GNUNET_OK to keep the connection open,
5050  *         GNUNET_SYSERR to close it (signal serious error)
5051  */
5052 static int
5053 handle_mesh_path_create (void *cls, const struct GNUNET_PeerIdentity *peer,
5054                          const struct GNUNET_MessageHeader *message,
5055                          const struct GNUNET_ATS_Information *atsi,
5056                          unsigned int atsi_count)
5057 {
5058   unsigned int own_pos;
5059   uint16_t size;
5060   uint16_t i;
5061   MESH_TunnelNumber tid;
5062   struct GNUNET_MESH_ManipulatePath *msg;
5063   struct GNUNET_PeerIdentity *pi;
5064   struct GNUNET_HashCode hash;
5065   struct MeshPeerPath *path;
5066   struct MeshPeerInfo *dest_peer_info;
5067   struct MeshPeerInfo *orig_peer_info;
5068   struct MeshTunnel *t;
5069
5070   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5071               "Received a path create msg [%s]\n",
5072               GNUNET_i2s (&my_full_id));
5073   size = ntohs (message->size);
5074   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
5075   {
5076     GNUNET_break_op (0);
5077     return GNUNET_OK;
5078   }
5079
5080   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
5081   if (size % sizeof (struct GNUNET_PeerIdentity))
5082   {
5083     GNUNET_break_op (0);
5084     return GNUNET_OK;
5085   }
5086   size /= sizeof (struct GNUNET_PeerIdentity);
5087   if (size < 2)
5088   {
5089     GNUNET_break_op (0);
5090     return GNUNET_OK;
5091   }
5092   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
5093   msg = (struct GNUNET_MESH_ManipulatePath *) message;
5094
5095   tid = ntohl (msg->tid);
5096   pi = (struct GNUNET_PeerIdentity *) &msg[1];
5097   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5098               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi), tid);
5099   t = tunnel_get (pi, tid);
5100   if (NULL == t) // FIXME only for INCOMING tunnels?
5101   {
5102     uint32_t opt;
5103
5104     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating tunnel\n");
5105     t = tunnel_new (GNUNET_PEER_intern (pi), tid, NULL, 0);
5106     if (NULL == t)
5107     {
5108       // FIXME notify failure
5109       return GNUNET_OK;
5110     }
5111     opt = ntohl (msg->opt);
5112     t->speed_min = (0 != (opt & MESH_TUNNEL_OPT_SPEED_MIN)) ?
5113                    GNUNET_YES : GNUNET_NO;
5114     t->nobuffer = (0 != (opt & MESH_TUNNEL_OPT_NOBUFFER)) ?
5115                   GNUNET_YES : GNUNET_NO;
5116     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5117                 "  speed_min: %d, nobuffer:%d\n",
5118                 t->speed_min, t->nobuffer);
5119
5120     if (GNUNET_YES == t->nobuffer)
5121     {
5122       t->bck_queue_max = 1;
5123       t->fwd_queue_max = 1;
5124     }
5125
5126     // FIXME only assign a local tid if a local client is interested (on demand)
5127     while (NULL != tunnel_get_incoming (next_local_tid))
5128       next_local_tid = (next_local_tid + 1) | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
5129     t->local_tid_dest = next_local_tid++;
5130     next_local_tid = next_local_tid | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
5131     // FIXME end
5132
5133     tunnel_reset_timeout (t);
5134     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
5135     if (GNUNET_OK !=
5136         GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
5137                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
5138     {
5139       tunnel_destroy (t);
5140       GNUNET_break (0);
5141       return GNUNET_OK;
5142     }
5143   }
5144   dest_peer_info =
5145       GNUNET_CONTAINER_multihashmap_get (peers, &pi[size - 1].hashPubKey);
5146   if (NULL == dest_peer_info)
5147   {
5148     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5149                 "  Creating PeerInfo for destination.\n");
5150     dest_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
5151     dest_peer_info->id = GNUNET_PEER_intern (&pi[size - 1]);
5152     GNUNET_CONTAINER_multihashmap_put (peers, &pi[size - 1].hashPubKey,
5153                                        dest_peer_info,
5154                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
5155   }
5156   orig_peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &pi->hashPubKey);
5157   if (NULL == orig_peer_info)
5158   {
5159     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5160                 "  Creating PeerInfo for origin.\n");
5161     orig_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
5162     orig_peer_info->id = GNUNET_PEER_intern (pi);
5163     GNUNET_CONTAINER_multihashmap_put (peers, &pi->hashPubKey, orig_peer_info,
5164                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
5165   }
5166   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
5167   path = path_new (size);
5168   own_pos = 0;
5169   for (i = 0; i < size; i++)
5170   {
5171     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
5172                 GNUNET_i2s (&pi[i]));
5173     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
5174     if (path->peers[i] == myid)
5175       own_pos = i;
5176   }
5177   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
5178   if (own_pos == 0)
5179   {
5180     /* cannot be self, must be 'not found' */
5181     /* create path: self not found in path through self */
5182     GNUNET_break_op (0);
5183     path_destroy (path);
5184     tunnel_destroy (t);
5185     return GNUNET_OK;
5186   }
5187   path_add_to_peers (path, GNUNET_NO);
5188   tunnel_add_path (t, path, own_pos);
5189   if (own_pos == size - 1)
5190   {
5191     /* It is for us! Send ack. */
5192     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
5193     peer_info_add_path_to_origin (orig_peer_info, path, GNUNET_NO);
5194     if (NULL == t->peers)
5195     {
5196       /* New tunnel! Notify clients on first payload message. */
5197       t->peers = GNUNET_CONTAINER_multihashmap_create (4);
5198     }
5199     GNUNET_break (GNUNET_SYSERR !=
5200                   GNUNET_CONTAINER_multihashmap_put (t->peers,
5201                                                      &my_full_id.hashPubKey,
5202                                                      peer_info_get
5203                                                      (&my_full_id),
5204                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE));
5205     send_path_ack (t);
5206   }
5207   else
5208   {
5209     struct MeshPeerPath *path2;
5210
5211     /* It's for somebody else! Retransmit. */
5212     path2 = path_duplicate (path);
5213     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Retransmitting.\n");
5214     peer_info_add_path (dest_peer_info, path2, GNUNET_NO);
5215     path2 = path_duplicate (path);
5216     peer_info_add_path_to_origin (orig_peer_info, path2, GNUNET_NO);
5217     send_create_path (dest_peer_info, path, t);
5218   }
5219   return GNUNET_OK;
5220 }
5221
5222
5223 /**
5224  * Core handler for path destruction
5225  *
5226  * @param cls closure
5227  * @param message message
5228  * @param peer peer identity this notification is about
5229  * @param atsi performance data
5230  * @param atsi_count number of records in 'atsi'
5231  *
5232  * @return GNUNET_OK to keep the connection open,
5233  *         GNUNET_SYSERR to close it (signal serious error)
5234  */
5235 static int
5236 handle_mesh_path_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
5237                           const struct GNUNET_MessageHeader *message,
5238                           const struct GNUNET_ATS_Information *atsi,
5239                           unsigned int atsi_count)
5240 {
5241   struct GNUNET_MESH_ManipulatePath *msg;
5242   struct GNUNET_PeerIdentity *pi;
5243   struct MeshPeerPath *path;
5244   struct MeshTunnel *t;
5245   unsigned int own_pos;
5246   unsigned int i;
5247   size_t size;
5248
5249   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5250               "Received a PATH DESTROY msg from %s\n", GNUNET_i2s (peer));
5251   size = ntohs (message->size);
5252   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
5253   {
5254     GNUNET_break_op (0);
5255     return GNUNET_OK;
5256   }
5257
5258   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
5259   if (size % sizeof (struct GNUNET_PeerIdentity))
5260   {
5261     GNUNET_break_op (0);
5262     return GNUNET_OK;
5263   }
5264   size /= sizeof (struct GNUNET_PeerIdentity);
5265   if (size < 2)
5266   {
5267     GNUNET_break_op (0);
5268     return GNUNET_OK;
5269   }
5270   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
5271
5272   msg = (struct GNUNET_MESH_ManipulatePath *) message;
5273   pi = (struct GNUNET_PeerIdentity *) &msg[1];
5274   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5275               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi),
5276               msg->tid);
5277   t = tunnel_get (pi, ntohl (msg->tid));
5278   if (NULL == t)
5279   {
5280     /* TODO notify back: we don't know this tunnel */
5281     GNUNET_break_op (0);
5282     return GNUNET_OK;
5283   }
5284   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
5285   path = path_new (size);
5286   own_pos = 0;
5287   for (i = 0; i < size; i++)
5288   {
5289     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
5290                 GNUNET_i2s (&pi[i]));
5291     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
5292     if (path->peers[i] == myid)
5293       own_pos = i;
5294   }
5295   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
5296   if (own_pos < path->length - 1)
5297     send_prebuilt_message (message, &pi[own_pos + 1], t);
5298   else
5299     send_client_tunnel_disconnect(t, NULL);
5300
5301   tunnel_delete_peer (t, path->peers[path->length - 1]);
5302   path_destroy (path);
5303   return GNUNET_OK;
5304 }
5305
5306
5307 /**
5308  * Core handler for notifications of broken paths
5309  *
5310  * @param cls closure
5311  * @param message message
5312  * @param peer peer identity this notification is about
5313  * @param atsi performance data
5314  * @param atsi_count number of records in 'atsi'
5315  *
5316  * @return GNUNET_OK to keep the connection open,
5317  *         GNUNET_SYSERR to close it (signal serious error)
5318  */
5319 static int
5320 handle_mesh_path_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
5321                          const struct GNUNET_MessageHeader *message,
5322                          const struct GNUNET_ATS_Information *atsi,
5323                          unsigned int atsi_count)
5324 {
5325   struct GNUNET_MESH_PathBroken *msg;
5326   struct MeshTunnel *t;
5327
5328   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5329               "Received a PATH BROKEN msg from %s\n", GNUNET_i2s (peer));
5330   msg = (struct GNUNET_MESH_PathBroken *) message;
5331   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
5332               GNUNET_i2s (&msg->peer1));
5333   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
5334               GNUNET_i2s (&msg->peer2));
5335   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5336   if (NULL == t)
5337   {
5338     GNUNET_break_op (0);
5339     return GNUNET_OK;
5340   }
5341   tunnel_notify_connection_broken (t, GNUNET_PEER_search (&msg->peer1),
5342                                    GNUNET_PEER_search (&msg->peer2));
5343   return GNUNET_OK;
5344
5345 }
5346
5347
5348 /**
5349  * Core handler for tunnel destruction
5350  *
5351  * @param cls closure
5352  * @param message message
5353  * @param peer peer identity this notification is about
5354  * @param atsi performance data
5355  * @param atsi_count number of records in 'atsi'
5356  *
5357  * @return GNUNET_OK to keep the connection open,
5358  *         GNUNET_SYSERR to close it (signal serious error)
5359  */
5360 static int
5361 handle_mesh_tunnel_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
5362                             const struct GNUNET_MessageHeader *message,
5363                             const struct GNUNET_ATS_Information *atsi,
5364                             unsigned int atsi_count)
5365 {
5366   struct GNUNET_MESH_TunnelDestroy *msg;
5367   struct MeshTunnel *t;
5368
5369   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5370               "Got a TUNNEL DESTROY packet from %s\n", GNUNET_i2s (peer));
5371   msg = (struct GNUNET_MESH_TunnelDestroy *) message;
5372   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for tunnel %s [%u]\n",
5373               GNUNET_i2s (&msg->oid), ntohl (msg->tid));
5374   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5375   if (NULL == t)
5376   {
5377     /* Probably already got the message from another path,
5378      * destroyed the tunnel and retransmitted to children.
5379      * Safe to ignore.
5380      */
5381     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel", 1, GNUNET_NO);
5382     return GNUNET_OK;
5383   }
5384   if (t->id.oid == myid)
5385   {
5386     GNUNET_break_op (0);
5387     return GNUNET_OK;
5388   }
5389   if (t->local_tid_dest >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
5390   {
5391     /* Tunnel was incoming, notify clients */
5392     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "INCOMING TUNNEL %X %X\n",
5393                 t->local_tid, t->local_tid_dest);
5394     send_clients_tunnel_destroy (t);
5395   }
5396   tunnel_send_destroy (t);
5397   t->destroy = GNUNET_YES;
5398   // TODO: add timeout to destroy the tunnel anyway
5399   return GNUNET_OK;
5400 }
5401
5402
5403 /**
5404  * Core handler for mesh network traffic going from the origin to a peer
5405  *
5406  * @param cls closure
5407  * @param peer peer identity this notification is about
5408  * @param message message
5409  * @param atsi performance data
5410  * @param atsi_count number of records in 'atsi'
5411  * @return GNUNET_OK to keep the connection open,
5412  *         GNUNET_SYSERR to close it (signal serious error)
5413  */
5414 static int
5415 handle_mesh_data_unicast (void *cls, const struct GNUNET_PeerIdentity *peer,
5416                           const struct GNUNET_MessageHeader *message,
5417                           const struct GNUNET_ATS_Information *atsi,
5418                           unsigned int atsi_count)
5419 {
5420   struct GNUNET_MESH_Unicast *msg;
5421   struct GNUNET_PeerIdentity *neighbor;
5422   struct MeshTunnelChildInfo *cinfo;
5423   struct MeshTunnel *t;
5424   GNUNET_PEER_Id dest_id;
5425   uint32_t pid;
5426   uint32_t ttl;
5427   size_t size;
5428
5429   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a unicast packet from %s\n",
5430               GNUNET_i2s (peer));
5431   /* Check size */
5432   size = ntohs (message->size);
5433   if (size <
5434       sizeof (struct GNUNET_MESH_Unicast) +
5435       sizeof (struct GNUNET_MessageHeader))
5436   {
5437     GNUNET_break (0);
5438     return GNUNET_OK;
5439   }
5440   msg = (struct GNUNET_MESH_Unicast *) message;
5441   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %s\n",
5442               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
5443   /* Check tunnel */
5444   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5445   if (NULL == t)
5446   {
5447     /* TODO notify back: we don't know this tunnel */
5448     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
5449     GNUNET_break_op (0);
5450     return GNUNET_OK;
5451   }
5452   pid = ntohl (msg->pid);
5453   if (t->fwd_pid == pid)
5454   {
5455     GNUNET_STATISTICS_update (stats, "# duplicate PID drops", 1, GNUNET_NO);
5456     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5457                 " Already seen pid %u, DROPPING!\n", pid);
5458     return GNUNET_OK;
5459   }
5460   else
5461   {
5462     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5463                 " pid %u not seen yet, forwarding\n", pid);
5464   }
5465
5466   t->skip += (pid - t->fwd_pid) - 1;
5467   t->fwd_pid = pid;
5468
5469   if (GMC_is_pid_bigger (pid, t->last_fwd_ack))
5470   {
5471     GNUNET_STATISTICS_update (stats, "# unsolicited unicast", 1, GNUNET_NO);
5472     GNUNET_break_op (0);
5473     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5474                 "Received PID %u, ACK %u\n",
5475                 pid, t->last_fwd_ack);
5476     return GNUNET_OK;
5477   }
5478
5479   tunnel_reset_timeout (t);
5480   dest_id = GNUNET_PEER_search (&msg->destination);
5481   if (dest_id == myid)
5482   {
5483     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5484                 "  it's for us! sending to clients...\n");
5485     GNUNET_STATISTICS_update (stats, "# unicast received", 1, GNUNET_NO);
5486     send_subscribed_clients (message, &msg[1].header, t);
5487     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_UNICAST);
5488     return GNUNET_OK;
5489   }
5490   ttl = ntohl (msg->ttl);
5491   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ttl);
5492   if (ttl == 0)
5493   {
5494     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
5495     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
5496     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5497     return GNUNET_OK;
5498   }
5499   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5500               "  not for us, retransmitting...\n");
5501
5502   neighbor = tree_get_first_hop (t->tree, dest_id);
5503   cinfo = tunnel_get_neighbor_fc (t, neighbor);
5504   cinfo->pid = pid;
5505   GNUNET_CONTAINER_multihashmap_iterate (t->children_fc,
5506                                          &tunnel_add_skip,
5507                                          &neighbor);
5508   if (GNUNET_YES == t->nobuffer &&
5509       GNUNET_YES == GMC_is_pid_bigger (pid, cinfo->fwd_ack))
5510   {
5511     GNUNET_STATISTICS_update (stats, "# unsolicited unicast", 1, GNUNET_NO);
5512     GNUNET_break_op (0);
5513     return GNUNET_OK;
5514   }
5515   send_prebuilt_message (message, neighbor, t);
5516   GNUNET_STATISTICS_update (stats, "# unicast forwarded", 1, GNUNET_NO);
5517   return GNUNET_OK;
5518 }
5519
5520
5521 /**
5522  * Core handler for mesh network traffic going from the origin to all peers
5523  *
5524  * @param cls closure
5525  * @param message message
5526  * @param peer peer identity this notification is about
5527  * @param atsi performance data
5528  * @param atsi_count number of records in 'atsi'
5529  * @return GNUNET_OK to keep the connection open,
5530  *         GNUNET_SYSERR to close it (signal serious error)
5531  *
5532  * TODO: Check who we got this from, to validate route.
5533  */
5534 static int
5535 handle_mesh_data_multicast (void *cls, const struct GNUNET_PeerIdentity *peer,
5536                             const struct GNUNET_MessageHeader *message,
5537                             const struct GNUNET_ATS_Information *atsi,
5538                             unsigned int atsi_count)
5539 {
5540   struct GNUNET_MESH_Multicast *msg;
5541   struct MeshTunnel *t;
5542   size_t size;
5543   uint32_t pid;
5544
5545   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a multicast packet from %s\n",
5546               GNUNET_i2s (peer));
5547   size = ntohs (message->size);
5548   if (sizeof (struct GNUNET_MESH_Multicast) +
5549       sizeof (struct GNUNET_MessageHeader) > size)
5550   {
5551     GNUNET_break_op (0);
5552     return GNUNET_OK;
5553   }
5554   msg = (struct GNUNET_MESH_Multicast *) message;
5555   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5556
5557   if (NULL == t)
5558   {
5559     /* TODO notify that we dont know that tunnel */
5560     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
5561     GNUNET_break_op (0);
5562     return GNUNET_OK;
5563   }
5564   pid = ntohl (msg->pid);
5565   if (t->fwd_pid == pid)
5566   {
5567     /* already seen this packet, drop */
5568     GNUNET_STATISTICS_update (stats, "# duplicate PID drops", 1, GNUNET_NO);
5569     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5570                 " Already seen pid %u, DROPPING!\n", pid);
5571     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5572     return GNUNET_OK;
5573   }
5574   else
5575   {
5576     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5577                 " pid %u not seen yet, forwarding\n", pid);
5578   }
5579   t->skip += (pid - t->fwd_pid) - 1;
5580   t->fwd_pid = pid;
5581   tunnel_reset_timeout (t);
5582
5583   /* Transmit to locally interested clients */
5584   if (NULL != t->peers &&
5585       GNUNET_CONTAINER_multihashmap_contains (t->peers, &my_full_id.hashPubKey))
5586   {
5587     GNUNET_STATISTICS_update (stats, "# multicast received", 1, GNUNET_NO);
5588     send_subscribed_clients (message, &msg[1].header, t);
5589     tunnel_send_fwd_ack(t, GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
5590   }
5591   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ntohl (msg->ttl));
5592   if (ntohl (msg->ttl) == 0)
5593   {
5594     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
5595     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
5596     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5597     return GNUNET_OK;
5598   }
5599   GNUNET_STATISTICS_update (stats, "# multicast forwarded", 1, GNUNET_NO);
5600   tunnel_send_multicast (t, message);
5601   return GNUNET_OK;
5602 }
5603
5604
5605 /**
5606  * Core handler for mesh network traffic toward the owner of a tunnel
5607  *
5608  * @param cls closure
5609  * @param message message
5610  * @param peer peer identity this notification is about
5611  * @param atsi performance data
5612  * @param atsi_count number of records in 'atsi'
5613  *
5614  * @return GNUNET_OK to keep the connection open,
5615  *         GNUNET_SYSERR to close it (signal serious error)
5616  */
5617 static int
5618 handle_mesh_data_to_orig (void *cls, const struct GNUNET_PeerIdentity *peer,
5619                           const struct GNUNET_MessageHeader *message,
5620                           const struct GNUNET_ATS_Information *atsi,
5621                           unsigned int atsi_count)
5622 {
5623   struct GNUNET_MESH_ToOrigin *msg;
5624   struct GNUNET_PeerIdentity id;
5625   struct MeshPeerInfo *peer_info;
5626   struct MeshTunnel *t;
5627   size_t size;
5628
5629
5630   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a ToOrigin packet from %s\n",
5631               GNUNET_i2s (peer));
5632   size = ntohs (message->size);
5633   if (size < sizeof (struct GNUNET_MESH_ToOrigin) +     /* Payload must be */
5634       sizeof (struct GNUNET_MessageHeader))     /* at least a header */
5635   {
5636     GNUNET_break_op (0);
5637     return GNUNET_OK;
5638   }
5639   msg = (struct GNUNET_MESH_ToOrigin *) message;
5640   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %s\n",
5641               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
5642   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5643
5644   if (NULL == t)
5645   {
5646     /* TODO notify that we dont know this tunnel (whom)? */
5647     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
5648     GNUNET_break_op (0);
5649     return GNUNET_OK;
5650   }
5651
5652   if (NULL != t->owner)
5653   {
5654     char cbuf[size];
5655     struct GNUNET_MESH_ToOrigin *copy;
5656
5657     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5658                 "  it's for us! sending to clients...\n");
5659     /* TODO signature verification */
5660     memcpy (cbuf, message, size);
5661     copy = (struct GNUNET_MESH_ToOrigin *) cbuf;
5662     copy->tid = htonl (t->local_tid);
5663     GNUNET_STATISTICS_update (stats, "# to origin received", 1, GNUNET_NO);
5664     GNUNET_SERVER_notification_context_unicast (nc, t->owner->handle,
5665                                                 &copy->header, GNUNET_NO);
5666     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
5667     return GNUNET_OK;
5668   }
5669   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5670               "  not for us, retransmitting...\n");
5671
5672   peer_info = peer_info_get (&msg->oid);
5673   if (NULL == peer_info)
5674   {
5675     /* unknown origin of tunnel */
5676     GNUNET_break (0);
5677     return GNUNET_OK;
5678   }
5679   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
5680   send_prebuilt_message (message, &id, t);
5681   GNUNET_STATISTICS_update (stats, "# to origin forwarded", 1, GNUNET_NO);
5682
5683   return GNUNET_OK;
5684 }
5685
5686
5687 /**
5688  * Core handler for mesh network traffic point-to-point acks.
5689  *
5690  * @param cls closure
5691  * @param message message
5692  * @param peer peer identity this notification is about
5693  * @param atsi performance data
5694  * @param atsi_count number of records in 'atsi'
5695  *
5696  * @return GNUNET_OK to keep the connection open,
5697  *         GNUNET_SYSERR to close it (signal serious error)
5698  */
5699 static int
5700 handle_mesh_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5701                  const struct GNUNET_MessageHeader *message,
5702                  const struct GNUNET_ATS_Information *atsi,
5703                  unsigned int atsi_count)
5704 {
5705   struct GNUNET_MESH_ACK *msg;
5706   struct MeshTunnel *t;
5707   uint32_t ack;
5708
5709   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK packet from %s!\n",
5710               GNUNET_i2s (peer));
5711   msg = (struct GNUNET_MESH_ACK *) message;
5712
5713   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5714
5715   if (NULL == t)
5716   {
5717     /* TODO notify that we dont know this tunnel (whom)? */
5718     GNUNET_STATISTICS_update (stats, "# ack on unknown tunnel", 1, GNUNET_NO);
5719     GNUNET_break_op (0);
5720     return GNUNET_OK;
5721   }
5722   ack = ntohl (msg->pid);
5723
5724   /* Is this a forward or backward ACK? */
5725   if (tree_get_predecessor(t->tree) != GNUNET_PEER_search(peer))
5726   {
5727     struct MeshTunnelChildInfo *cinfo;
5728
5729     debug_bck_ack++;
5730     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
5731     cinfo = tunnel_get_neighbor_fc (t, peer);
5732     cinfo->fwd_ack = ack;
5733     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5734     tunnel_unlock_fwd_queues (t);
5735   }
5736   else
5737   {
5738     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
5739     t->bck_ack = ack;
5740     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5741     tunnel_unlock_bck_queue (t);
5742   }
5743   return GNUNET_OK;
5744 }
5745
5746
5747 /**
5748  * Core handler for path ACKs
5749  *
5750  * @param cls closure
5751  * @param message message
5752  * @param peer peer identity this notification is about
5753  * @param atsi performance data
5754  * @param atsi_count number of records in 'atsi'
5755  *
5756  * @return GNUNET_OK to keep the connection open,
5757  *         GNUNET_SYSERR to close it (signal serious error)
5758  */
5759 static int
5760 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5761                       const struct GNUNET_MessageHeader *message,
5762                       const struct GNUNET_ATS_Information *atsi,
5763                       unsigned int atsi_count)
5764 {
5765   struct GNUNET_MESH_PathACK *msg;
5766   struct GNUNET_PeerIdentity id;
5767   struct MeshPeerInfo *peer_info;
5768   struct MeshPeerPath *p;
5769   struct MeshTunnel *t;
5770
5771   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a path ACK msg [%s]\n",
5772               GNUNET_i2s (&my_full_id));
5773   msg = (struct GNUNET_MESH_PathACK *) message;
5774   t = tunnel_get (&msg->oid, ntohl(msg->tid));
5775   if (NULL == t)
5776   {
5777     /* TODO notify that we don't know the tunnel */
5778     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel", 1, GNUNET_NO);
5779     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  don't know the tunnel %s [%X]!\n",
5780                 GNUNET_i2s (&msg->oid), ntohl(msg->tid));
5781     return GNUNET_OK;
5782   }
5783   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %s [%X]\n",
5784               GNUNET_i2s (&msg->oid), ntohl(msg->tid));
5785
5786   peer_info = peer_info_get (&msg->peer_id);
5787   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by peer %s\n",
5788               GNUNET_i2s (&msg->peer_id));
5789   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  via peer %s\n",
5790               GNUNET_i2s (peer));
5791
5792   if (NULL != t->regex_ctx && t->regex_ctx->info->peer == peer_info->id)
5793   {
5794     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5795                 "connect_by_string completed, stopping search\n");
5796     regex_cancel_search (t->regex_ctx);
5797     t->regex_ctx = NULL;
5798   }
5799
5800   /* Add paths to peers? */
5801   p = tree_get_path_to_peer (t->tree, peer_info->id);
5802   if (NULL != p)
5803   {
5804     path_add_to_peers (p, GNUNET_YES);
5805     path_destroy (p);
5806   }
5807   else
5808   {
5809     GNUNET_break (0);
5810   }
5811
5812   /* Message for us? */
5813   if (0 == memcmp (&msg->oid, &my_full_id, sizeof (struct GNUNET_PeerIdentity)))
5814   {
5815     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
5816     if (NULL == t->owner)
5817     {
5818       GNUNET_break_op (0);
5819       return GNUNET_OK;
5820     }
5821     if (NULL != t->dht_get_type)
5822     {
5823       GNUNET_DHT_get_stop (t->dht_get_type);
5824       t->dht_get_type = NULL;
5825     }
5826     if (tree_get_status (t->tree, peer_info->id) != MESH_PEER_READY)
5827     {
5828       tree_set_status (t->tree, peer_info->id, MESH_PEER_READY);
5829       send_client_peer_connected (t, peer_info->id);
5830     }
5831     return GNUNET_OK;
5832   }
5833
5834   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5835               "  not for us, retransmitting...\n");
5836   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
5837   peer_info = peer_info_get (&msg->oid);
5838   if (NULL == peer_info)
5839   {
5840     /* If we know the tunnel, we should DEFINITELY know the peer */
5841     GNUNET_break (0);
5842     return GNUNET_OK;
5843   }
5844   send_prebuilt_message (message, &id, t);
5845   return GNUNET_OK;
5846 }
5847
5848
5849 /**
5850  * Core handler for mesh keepalives.
5851  *
5852  * @param cls closure
5853  * @param message message
5854  * @param peer peer identity this notification is about
5855  * @param atsi performance data
5856  * @param atsi_count number of records in 'atsi'
5857  * @return GNUNET_OK to keep the connection open,
5858  *         GNUNET_SYSERR to close it (signal serious error)
5859  *
5860  * TODO: Check who we got this from, to validate route.
5861  */
5862 static int
5863 handle_mesh_keepalive (void *cls, const struct GNUNET_PeerIdentity *peer,
5864                        const struct GNUNET_MessageHeader *message,
5865                        const struct GNUNET_ATS_Information *atsi,
5866                        unsigned int atsi_count)
5867 {
5868   struct GNUNET_MESH_TunnelKeepAlive *msg;
5869   struct MeshTunnel *t;
5870
5871   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a keepalive packet from %s\n",
5872               GNUNET_i2s (peer));
5873
5874   msg = (struct GNUNET_MESH_TunnelKeepAlive *) message;
5875   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5876
5877   if (NULL == t)
5878   {
5879     /* TODO notify that we dont know that tunnel */
5880     GNUNET_STATISTICS_update (stats, "# keepalive on unknown tunnel", 1, GNUNET_NO);
5881     GNUNET_break_op (0);
5882     return GNUNET_OK;
5883   }
5884
5885   tunnel_reset_timeout (t);
5886
5887   GNUNET_STATISTICS_update (stats, "# keepalives forwarded", 1, GNUNET_NO);
5888   tunnel_send_multicast (t, message);
5889   return GNUNET_OK;
5890   }
5891
5892
5893
5894 /**
5895  * Functions to handle messages from core
5896  */
5897 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
5898   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
5899   {&handle_mesh_path_destroy, GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY, 0},
5900   {&handle_mesh_path_broken, GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN,
5901    sizeof (struct GNUNET_MESH_PathBroken)},
5902   {&handle_mesh_tunnel_destroy, GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY,
5903    sizeof (struct GNUNET_MESH_TunnelDestroy)},
5904   {&handle_mesh_data_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
5905   {&handle_mesh_data_multicast, GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
5906   {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE,
5907     sizeof (struct GNUNET_MESH_TunnelKeepAlive)},
5908   {&handle_mesh_data_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
5909   {&handle_mesh_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
5910     sizeof (struct GNUNET_MESH_ACK)},
5911   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
5912    sizeof (struct GNUNET_MESH_PathACK)},
5913   {NULL, 0, 0}
5914 };
5915
5916
5917
5918 /******************************************************************************/
5919 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
5920 /******************************************************************************/
5921
5922 /**
5923  * deregister_app: iterator for removing each application registered by a client
5924  *
5925  * @param cls closure
5926  * @param key the hash of the application id (used to access the hashmap)
5927  * @param value the value stored at the key (client)
5928  *
5929  * @return GNUNET_OK on success
5930  */
5931 static int
5932 deregister_app (void *cls, const struct GNUNET_HashCode * key, void *value)
5933 {
5934   struct GNUNET_CONTAINER_MultiHashMap *h = cls;
5935   GNUNET_break (GNUNET_YES ==
5936                 GNUNET_CONTAINER_multihashmap_remove (h, key, value));
5937   return GNUNET_OK;
5938 }
5939
5940 #if LATER
5941 /**
5942  * notify_client_connection_failure: notify a client that the connection to the
5943  * requested remote peer is not possible (for instance, no route found)
5944  * Function called when the socket is ready to queue more data. "buf" will be
5945  * NULL and "size" zero if the socket was closed for writing in the meantime.
5946  *
5947  * @param cls closure
5948  * @param size number of bytes available in buf
5949  * @param buf where the callee should write the message
5950  * @return number of bytes written to buf
5951  */
5952 static size_t
5953 notify_client_connection_failure (void *cls, size_t size, void *buf)
5954 {
5955   int size_needed;
5956   struct MeshPeerInfo *peer_info;
5957   struct GNUNET_MESH_PeerControl *msg;
5958   struct GNUNET_PeerIdentity id;
5959
5960   if (0 == size && NULL == buf)
5961   {
5962     // TODO retry? cancel?
5963     return 0;
5964   }
5965
5966   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
5967   peer_info = (struct MeshPeerInfo *) cls;
5968   msg = (struct GNUNET_MESH_PeerControl *) buf;
5969   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
5970   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
5971 //     msg->tunnel_id = htonl(peer_info->t->tid);
5972   GNUNET_PEER_resolve (peer_info->id, &id);
5973   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
5974
5975   return size_needed;
5976 }
5977 #endif
5978
5979
5980 /**
5981  * Send keepalive packets for a peer
5982  *
5983  * @param cls Closure (tunnel for which to send the keepalive).
5984  * @param tc Notification context.
5985  */
5986 static void
5987 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
5988 {
5989   struct MeshTunnel *t = cls;
5990   struct GNUNET_MESH_TunnelKeepAlive *msg;
5991   size_t size = sizeof (struct GNUNET_MESH_TunnelKeepAlive);
5992   char cbuf[size];
5993
5994   t->path_refresh_task = GNUNET_SCHEDULER_NO_TASK;
5995   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
5996   {
5997     return;
5998   }
5999
6000   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6001               "sending keepalive for tunnel %d\n", t->id.tid);
6002
6003   msg = (struct GNUNET_MESH_TunnelKeepAlive *) cbuf;
6004   msg->header.size = htons (size);
6005   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE);
6006   msg->oid = my_full_id;
6007   msg->tid = htonl (t->id.tid);
6008   tunnel_send_multicast (t, &msg->header);
6009
6010   t->path_refresh_task =
6011       GNUNET_SCHEDULER_add_delayed (refresh_path_time, &path_refresh, t);
6012   tunnel_reset_timeout(t);
6013 }
6014
6015
6016 /**
6017  * Function to process paths received for a new peer addition. The recorded
6018  * paths form the initial tunnel, which can be optimized later.
6019  * Called on each result obtained for the DHT search.
6020  *
6021  * @param cls closure
6022  * @param exp when will this value expire
6023  * @param key key of the result
6024  * @param get_path path of the get request
6025  * @param get_path_length lenght of get_path
6026  * @param put_path path of the put request
6027  * @param put_path_length length of the put_path
6028  * @param type type of the result
6029  * @param size number of bytes in data
6030  * @param data pointer to the result data
6031  *
6032  * TODO: re-issue the request after certain time? cancel after X results?
6033  */
6034 static void
6035 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
6036                     const struct GNUNET_HashCode * key,
6037                     const struct GNUNET_PeerIdentity *get_path,
6038                     unsigned int get_path_length,
6039                     const struct GNUNET_PeerIdentity *put_path,
6040                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
6041                     size_t size, const void *data)
6042 {
6043   struct MeshPathInfo *path_info = cls;
6044   struct MeshPeerPath *p;
6045   struct GNUNET_PeerIdentity pi;
6046   int i;
6047
6048   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
6049   GNUNET_PEER_resolve (path_info->peer->id, &pi);
6050   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", GNUNET_i2s (&pi));
6051
6052   p = path_build_from_dht (get_path, get_path_length, put_path,
6053                            put_path_length);
6054   path_add_to_peers (p, GNUNET_NO);
6055   path_destroy(p);
6056   for (i = 0; i < path_info->peer->ntunnels; i++)
6057   {
6058     tunnel_add_peer (path_info->peer->tunnels[i], path_info->peer);
6059     peer_info_connect (path_info->peer, path_info->t);
6060   }
6061
6062   return;
6063 }
6064
6065
6066 /**
6067  * Function to process paths received for a new peer addition. The recorded
6068  * paths form the initial tunnel, which can be optimized later.
6069  * Called on each result obtained for the DHT search.
6070  *
6071  * @param cls closure
6072  * @param exp when will this value expire
6073  * @param key key of the result
6074  * @param get_path path of the get request
6075  * @param get_path_length lenght of get_path
6076  * @param put_path path of the put request
6077  * @param put_path_length length of the put_path
6078  * @param type type of the result
6079  * @param size number of bytes in data
6080  * @param data pointer to the result data
6081  */
6082 static void
6083 dht_get_type_handler (void *cls, struct GNUNET_TIME_Absolute exp,
6084                       const struct GNUNET_HashCode * key,
6085                       const struct GNUNET_PeerIdentity *get_path,
6086                       unsigned int get_path_length,
6087                       const struct GNUNET_PeerIdentity *put_path,
6088                       unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
6089                       size_t size, const void *data)
6090 {
6091   const struct PBlock *pb = data;
6092   const struct GNUNET_PeerIdentity *pi = &pb->id;
6093   struct MeshTunnel *t = cls;
6094   struct MeshPeerInfo *peer_info;
6095   struct MeshPeerPath *p;
6096
6097   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got type DHT result!\n");
6098   if (size != sizeof (struct PBlock))
6099   {
6100     GNUNET_break_op (0);
6101     return;
6102   }
6103   if (ntohl(pb->type) != t->type)
6104   {
6105     GNUNET_break_op (0);
6106     return;
6107   }
6108   GNUNET_assert (NULL != t->owner);
6109   peer_info = peer_info_get (pi);
6110   (void) GNUNET_CONTAINER_multihashmap_put (t->peers, &pi->hashPubKey,
6111                                             peer_info,
6112                                             GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
6113
6114   p = path_build_from_dht (get_path, get_path_length, put_path,
6115                            put_path_length);
6116   path_add_to_peers (p, GNUNET_NO);
6117   path_destroy(p);
6118   tunnel_add_peer (t, peer_info);
6119   peer_info_connect (peer_info, t);
6120 }
6121
6122
6123 /**
6124  * Function to process DHT string to regex matching.
6125  * Called on each result obtained for the DHT search.
6126  *
6127  * @param cls closure (search context)
6128  * @param exp when will this value expire
6129  * @param key key of the result
6130  * @param get_path path of the get request (not used)
6131  * @param get_path_length lenght of get_path (not used)
6132  * @param put_path path of the put request (not used)
6133  * @param put_path_length length of the put_path (not used)
6134  * @param type type of the result
6135  * @param size number of bytes in data
6136  * @param data pointer to the result data
6137  */
6138 static void
6139 dht_get_string_accept_handler (void *cls, struct GNUNET_TIME_Absolute exp,
6140                                const struct GNUNET_HashCode * key,
6141                                const struct GNUNET_PeerIdentity *get_path,
6142                                unsigned int get_path_length,
6143                                const struct GNUNET_PeerIdentity *put_path,
6144                                unsigned int put_path_length,
6145                                enum GNUNET_BLOCK_Type type,
6146                                size_t size, const void *data)
6147 {
6148   const struct MeshRegexAccept *block = data;
6149   struct MeshRegexSearchContext *ctx = cls;
6150   struct MeshRegexSearchInfo *info = ctx->info;
6151   struct MeshPeerPath *p;
6152   struct MeshPeerInfo *peer_info;
6153
6154   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got regex results from DHT!\n");
6155   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", info->description);
6156
6157   peer_info = peer_info_get(&block->id);
6158   p = path_build_from_dht (get_path, get_path_length, put_path,
6159                            put_path_length);
6160   path_add_to_peers (p, GNUNET_NO);
6161   path_destroy(p);
6162
6163   tunnel_add_peer (info->t, peer_info);
6164   peer_info_connect (peer_info, info->t);
6165   if (0 == info->peer)
6166   {
6167     info->peer = peer_info->id;
6168   }
6169   else
6170   {
6171     GNUNET_array_append (info->peers, info->n_peers, peer_info->id);
6172   }
6173
6174   info->timeout = GNUNET_SCHEDULER_add_delayed (connect_timeout,
6175                                                 &regex_connect_timeout,
6176                                                 info);
6177
6178   return;
6179 }
6180
6181
6182 /**
6183  * Function to process DHT string to regex matching.
6184  * Called on each result obtained for the DHT search.
6185  *
6186  * @param cls closure (search context)
6187  * @param exp when will this value expire
6188  * @param key key of the result
6189  * @param get_path path of the get request (not used)
6190  * @param get_path_length lenght of get_path (not used)
6191  * @param put_path path of the put request (not used)
6192  * @param put_path_length length of the put_path (not used)
6193  * @param type type of the result
6194  * @param size number of bytes in data
6195  * @param data pointer to the result data
6196  *
6197  * TODO: re-issue the request after certain time? cancel after X results?
6198  */
6199 static void
6200 dht_get_string_handler (void *cls, struct GNUNET_TIME_Absolute exp,
6201                         const struct GNUNET_HashCode * key,
6202                         const struct GNUNET_PeerIdentity *get_path,
6203                         unsigned int get_path_length,
6204                         const struct GNUNET_PeerIdentity *put_path,
6205                         unsigned int put_path_length,
6206                         enum GNUNET_BLOCK_Type type,
6207                         size_t size, const void *data)
6208 {
6209   const struct MeshRegexBlock *block = data;
6210   struct MeshRegexSearchContext *ctx = cls;
6211   struct MeshRegexSearchInfo *info = ctx->info;
6212   void *copy;
6213   size_t len;
6214
6215   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6216               "DHT GET STRING RETURNED RESULTS\n");
6217   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6218               "  key: %s\n", GNUNET_h2s (key));
6219
6220   copy = GNUNET_malloc (size);
6221   memcpy (copy, data, size);
6222   GNUNET_break (GNUNET_OK ==
6223                 GNUNET_CONTAINER_multihashmap_put(info->dht_get_results, key, copy,
6224                                                   GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
6225   len = ntohl (block->n_proof);
6226   {
6227     char proof[len + 1];
6228
6229     memcpy (proof, &block[1], len);
6230     proof[len] = '\0';
6231     if (GNUNET_OK != GNUNET_REGEX_check_proof (proof, key))
6232     {
6233       GNUNET_break_op (0);
6234       return;
6235     }
6236   }
6237   len = strlen (info->description);
6238   if (len == ctx->position) // String processed
6239   {
6240     if (GNUNET_YES == ntohl (block->accepting))
6241     {
6242       regex_find_path(key, ctx);
6243     }
6244     else
6245     {
6246       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  block not accepting!\n");
6247       // FIXME REGEX this block not successful, wait for more? start timeout?
6248     }
6249     return;
6250   }
6251
6252   regex_next_edge (block, size, ctx);
6253
6254   return;
6255 }
6256
6257 /******************************************************************************/
6258 /*********************       MESH LOCAL HANDLES      **************************/
6259 /******************************************************************************/
6260
6261
6262 /**
6263  * Handler for client disconnection
6264  *
6265  * @param cls closure
6266  * @param client identification of the client; NULL
6267  *        for the last call when the server is destroyed
6268  */
6269 static void
6270 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
6271 {
6272   struct MeshClient *c;
6273   struct MeshClient *next;
6274   unsigned int i;
6275
6276   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected\n");
6277   if (client == NULL)
6278   {
6279     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (SERVER DOWN)\n");
6280     return;
6281   }
6282   c = clients;
6283   while (NULL != c)
6284   {
6285     if (c->handle != client)
6286     {
6287       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ... searching\n");
6288       c = c->next;
6289       continue;
6290     }
6291     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u)\n",
6292                 c->id);
6293     GNUNET_SERVER_client_drop (c->handle);
6294     c->shutting_down = GNUNET_YES;
6295     GNUNET_assert (NULL != c->own_tunnels);
6296     GNUNET_assert (NULL != c->incoming_tunnels);
6297     GNUNET_CONTAINER_multihashmap_iterate (c->own_tunnels,
6298                                            &tunnel_destroy_iterator, c);
6299     GNUNET_CONTAINER_multihashmap_iterate (c->incoming_tunnels,
6300                                            &tunnel_destroy_iterator, c);
6301     GNUNET_CONTAINER_multihashmap_iterate (c->ignore_tunnels,
6302                                            &tunnel_destroy_iterator, c);
6303     GNUNET_CONTAINER_multihashmap_destroy (c->own_tunnels);
6304     GNUNET_CONTAINER_multihashmap_destroy (c->incoming_tunnels);
6305     GNUNET_CONTAINER_multihashmap_destroy (c->ignore_tunnels);
6306
6307     /* deregister clients applications */
6308     if (NULL != c->apps)
6309     {
6310       GNUNET_CONTAINER_multihashmap_iterate (c->apps, &deregister_app, c->apps);
6311       GNUNET_CONTAINER_multihashmap_destroy (c->apps);
6312     }
6313     if (0 == GNUNET_CONTAINER_multihashmap_size (applications) &&
6314         GNUNET_SCHEDULER_NO_TASK != announce_applications_task)
6315     {
6316       GNUNET_SCHEDULER_cancel (announce_applications_task);
6317       announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
6318     }
6319     if (NULL != c->types)
6320       GNUNET_CONTAINER_multihashmap_destroy (c->types);
6321     for (i = 0; i < c->n_regex; i++)
6322     {
6323       GNUNET_free (c->regexes[i]);
6324     }
6325     GNUNET_free_non_null (c->regexes);
6326     if (GNUNET_SCHEDULER_NO_TASK != c->regex_announce_task)
6327       GNUNET_SCHEDULER_cancel (c->regex_announce_task);
6328     next = c->next;
6329     GNUNET_CONTAINER_DLL_remove (clients, clients_tail, c);
6330     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT FREE at %p\n", c);
6331     GNUNET_free (c);
6332     GNUNET_STATISTICS_update (stats, "# clients", -1, GNUNET_NO);
6333     c = next;
6334   }
6335   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   done!\n");
6336   return;
6337 }
6338
6339
6340 /**
6341  * Handler for new clients
6342  *
6343  * @param cls closure
6344  * @param client identification of the client
6345  * @param message the actual message, which includes messages the client wants
6346  */
6347 static void
6348 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
6349                          const struct GNUNET_MessageHeader *message)
6350 {
6351   struct GNUNET_MESH_ClientConnect *cc_msg;
6352   struct MeshClient *c;
6353   GNUNET_MESH_ApplicationType *a;
6354   unsigned int size;
6355   uint16_t ntypes;
6356   uint16_t *t;
6357   uint16_t napps;
6358   uint16_t i;
6359
6360   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected\n");
6361   /* Check data sanity */
6362   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
6363   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
6364   ntypes = ntohs (cc_msg->types);
6365   napps = ntohs (cc_msg->applications);
6366   if (size !=
6367       ntypes * sizeof (uint16_t) + napps * sizeof (GNUNET_MESH_ApplicationType))
6368   {
6369     GNUNET_break (0);
6370     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6371     return;
6372   }
6373
6374   /* Create new client structure */
6375   c = GNUNET_malloc (sizeof (struct MeshClient));
6376   c->id = next_client_id++;
6377   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT NEW %u\n", c->id);
6378   c->handle = client;
6379   GNUNET_SERVER_client_keep (client);
6380   a = (GNUNET_MESH_ApplicationType *) &cc_msg[1];
6381   if (napps > 0)
6382   {
6383     GNUNET_MESH_ApplicationType at;
6384     struct GNUNET_HashCode hc;
6385
6386     c->apps = GNUNET_CONTAINER_multihashmap_create (napps);
6387     for (i = 0; i < napps; i++)
6388     {
6389       at = ntohl (a[i]);
6390       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  app type: %u\n", at);
6391       GNUNET_CRYPTO_hash (&at, sizeof (at), &hc);
6392       /* store in clients hashmap */
6393       GNUNET_CONTAINER_multihashmap_put (c->apps, &hc, (void *) (long) at,
6394                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6395       /* store in global hashmap, for announcements */
6396       GNUNET_CONTAINER_multihashmap_put (applications, &hc, c,
6397                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6398     }
6399     if (GNUNET_SCHEDULER_NO_TASK == announce_applications_task)
6400       announce_applications_task =
6401           GNUNET_SCHEDULER_add_now (&announce_applications, NULL);
6402
6403   }
6404   if (ntypes > 0)
6405   {
6406     uint16_t u16;
6407     struct GNUNET_HashCode hc;
6408
6409     t = (uint16_t *) & a[napps];
6410     c->types = GNUNET_CONTAINER_multihashmap_create (ntypes);
6411     for (i = 0; i < ntypes; i++)
6412     {
6413       u16 = ntohs (t[i]);
6414       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  msg type: %u\n", u16);
6415       GNUNET_CRYPTO_hash (&u16, sizeof (u16), &hc);
6416
6417       /* store in clients hashmap */
6418       GNUNET_CONTAINER_multihashmap_put (c->types, &hc, c,
6419                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6420       /* store in global hashmap */
6421       GNUNET_CONTAINER_multihashmap_put (types, &hc, c,
6422                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6423     }
6424   }
6425   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6426               " client has %u+%u subscriptions\n", napps, ntypes);
6427
6428   GNUNET_CONTAINER_DLL_insert (clients, clients_tail, c);
6429   c->own_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
6430   c->incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
6431   c->ignore_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
6432   GNUNET_SERVER_notification_context_add (nc, client);
6433   GNUNET_STATISTICS_update (stats, "# clients", 1, GNUNET_NO);
6434
6435   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6436   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
6437 }
6438
6439
6440 /**
6441  * Handler for clients announcing available services by a regular expression.
6442  *
6443  * @param cls closure
6444  * @param client identification of the client
6445  * @param message the actual message, which includes messages the client wants
6446  */
6447 static void
6448 handle_local_announce_regex (void *cls, struct GNUNET_SERVER_Client *client,
6449                              const struct GNUNET_MessageHeader *message)
6450 {
6451   struct MeshClient *c;
6452   char *regex;
6453   size_t len;
6454
6455   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "announce regex started\n");
6456
6457   /* Sanity check for client registration */
6458   if (NULL == (c = client_get (client)))
6459   {
6460     GNUNET_break (0);
6461     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6462     return;
6463   }
6464   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6465
6466   len = ntohs (message->size) - sizeof(struct GNUNET_MessageHeader);
6467   regex = GNUNET_malloc (len + 1);
6468   memcpy (regex, &message[1], len);
6469   regex[len] = '\0';
6470   GNUNET_array_append (c->regexes, c->n_regex, regex);
6471   if (GNUNET_SCHEDULER_NO_TASK == c->regex_announce_task)
6472   {
6473     c->regex_announce_task = GNUNET_SCHEDULER_add_now(&announce_regex, c);
6474   }
6475   else
6476   {
6477     regex_put(regex);
6478   }
6479   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6480   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "announce regex processed\n");
6481 }
6482
6483
6484 /**
6485  * Handler for requests of new tunnels
6486  *
6487  * @param cls closure
6488  * @param client identification of the client
6489  * @param message the actual message
6490  */
6491 static void
6492 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
6493                             const struct GNUNET_MessageHeader *message)
6494 {
6495   struct GNUNET_MESH_TunnelMessage *t_msg;
6496   struct MeshTunnel *t;
6497   struct MeshClient *c;
6498   MESH_TunnelNumber tid;
6499
6500   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel requested\n");
6501
6502   /* Sanity check for client registration */
6503   if (NULL == (c = client_get (client)))
6504   {
6505     GNUNET_break (0);
6506     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6507     return;
6508   }
6509   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6510
6511   /* Message sanity check */
6512   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
6513   {
6514     GNUNET_break (0);
6515     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6516     return;
6517   }
6518
6519   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6520   /* Sanity check for tunnel numbering */
6521   tid = ntohl (t_msg->tunnel_id);
6522   if (0 == (tid & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
6523   {
6524     GNUNET_break (0);
6525     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6526     return;
6527   }
6528   /* Sanity check for duplicate tunnel IDs */
6529   if (NULL != tunnel_get_by_local_id (c, tid))
6530   {
6531     GNUNET_break (0);
6532     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6533     return;
6534   }
6535
6536   while (NULL != tunnel_get_by_pi (myid, next_tid))
6537     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
6538   t = tunnel_new (myid, next_tid++, c, tid);
6539   if (NULL == t)
6540   {
6541     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Tunnel creation failed.\n");
6542     GNUNET_break (0);
6543     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6544     return;
6545   }
6546   next_tid = next_tid & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
6547   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED TUNNEL %s [%x] (%x)\n",
6548               GNUNET_i2s (&my_full_id), t->id.tid, t->local_tid);
6549   t->peers = GNUNET_CONTAINER_multihashmap_create (32);
6550
6551   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel created\n");
6552   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6553   return;
6554 }
6555
6556
6557 /**
6558  * Handler for requests of deleting tunnels
6559  *
6560  * @param cls closure
6561  * @param client identification of the client
6562  * @param message the actual message
6563  */
6564 static void
6565 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
6566                              const struct GNUNET_MessageHeader *message)
6567 {
6568   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
6569   struct MeshClient *c;
6570   struct MeshTunnel *t;
6571   MESH_TunnelNumber tid;
6572
6573   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6574               "Got a DESTROY TUNNEL from client!\n");
6575
6576   /* Sanity check for client registration */
6577   if (NULL == (c = client_get (client)))
6578   {
6579     GNUNET_break (0);
6580     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6581     return;
6582   }
6583   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6584
6585   /* Message sanity check */
6586   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
6587   {
6588     GNUNET_break (0);
6589     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6590     return;
6591   }
6592
6593   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6594
6595   /* Retrieve tunnel */
6596   tid = ntohl (tunnel_msg->tunnel_id);
6597   t = tunnel_get_by_local_id(c, tid);
6598   if (NULL == t)
6599   {
6600     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
6601     GNUNET_break (0);
6602     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6603     return;
6604   }
6605   if (c != t->owner || tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
6606   {
6607     client_ignore_tunnel (c, t);
6608 #if 0
6609     // TODO: when to destroy incoming tunnel?
6610     if (t->nclients == 0)
6611     {
6612       GNUNET_assert (GNUNET_YES ==
6613                      GNUNET_CONTAINER_multihashmap_remove (incoming_tunnels,
6614                                                            &hash, t));
6615       GNUNET_assert (GNUNET_YES ==
6616                      GNUNET_CONTAINER_multihashmap_remove (t->peers,
6617                                                            &my_full_id.hashPubKey,
6618                                                            t));
6619     }
6620 #endif
6621     GNUNET_SERVER_receive_done (client, GNUNET_OK);
6622     return;
6623   }
6624   send_client_tunnel_disconnect(t, c);
6625   client_delete_tunnel(c, t);
6626
6627   /* Don't try to ACK the client about the tunnel_destroy multicast packet */
6628   t->owner = NULL;
6629   tunnel_send_destroy (t);
6630   t->destroy = GNUNET_YES;
6631   // The tunnel will be destroyed when the last message is transmitted.
6632   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6633   return;
6634 }
6635
6636
6637 /**
6638  * Handler for requests of seeting tunnel's speed.
6639  *
6640  * @param cls Closure (unused).
6641  * @param client Identification of the client.
6642  * @param message The actual message.
6643  */
6644 static void
6645 handle_local_tunnel_speed (void *cls, struct GNUNET_SERVER_Client *client,
6646                            const struct GNUNET_MessageHeader *message)
6647 {
6648   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
6649   struct MeshClient *c;
6650   struct MeshTunnel *t;
6651   MESH_TunnelNumber tid;
6652
6653   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6654               "Got a SPEED request from client!\n");
6655
6656   /* Sanity check for client registration */
6657   if (NULL == (c = client_get (client)))
6658   {
6659     GNUNET_break (0);
6660     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6661     return;
6662   }
6663
6664   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6665
6666   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6667
6668   /* Retrieve tunnel */
6669   tid = ntohl (tunnel_msg->tunnel_id);
6670   t = tunnel_get_by_local_id(c, tid);
6671   if (NULL == t)
6672   {
6673     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  tunnel %X not found\n", tid);
6674     GNUNET_break (0);
6675     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6676     return;
6677   }
6678
6679   switch (ntohs(message->type))
6680   {
6681       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MIN:
6682           t->speed_min = GNUNET_YES;
6683           break;
6684       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MAX:
6685           t->speed_min = GNUNET_NO;
6686           break;
6687       default:
6688           GNUNET_break (0);
6689   }
6690   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6691 }
6692
6693
6694 /**
6695  * Handler for requests of seeting tunnel's buffering policy.
6696  *
6697  * @param cls Closure (unused).
6698  * @param client Identification of the client.
6699  * @param message The actual message.
6700  */
6701 static void
6702 handle_local_tunnel_buffer (void *cls, struct GNUNET_SERVER_Client *client,
6703                             const struct GNUNET_MessageHeader *message)
6704 {
6705   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
6706   struct MeshClient *c;
6707   struct MeshTunnel *t;
6708   MESH_TunnelNumber tid;
6709
6710   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6711               "Got a BUFFER request from client!\n");
6712
6713   /* Sanity check for client registration */
6714   if (NULL == (c = client_get (client)))
6715   {
6716     GNUNET_break (0);
6717     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6718     return;
6719   }
6720   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6721
6722   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6723
6724   /* Retrieve tunnel */
6725   tid = ntohl (tunnel_msg->tunnel_id);
6726   t = tunnel_get_by_local_id(c, tid);
6727   if (NULL == t)
6728   {
6729     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
6730     GNUNET_break (0);
6731     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6732     return;
6733   }
6734
6735   switch (ntohs(message->type))
6736   {
6737       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER:
6738           t->nobuffer = GNUNET_NO;
6739           break;
6740       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER:
6741           t->nobuffer = GNUNET_YES;
6742           break;
6743       default:
6744           GNUNET_break (0);
6745   }
6746
6747   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6748 }
6749
6750
6751 /**
6752  * Handler for connection requests to new peers
6753  *
6754  * @param cls closure
6755  * @param client identification of the client
6756  * @param message the actual message (PeerControl)
6757  */
6758 static void
6759 handle_local_connect_add (void *cls, struct GNUNET_SERVER_Client *client,
6760                           const struct GNUNET_MessageHeader *message)
6761 {
6762   struct GNUNET_MESH_PeerControl *peer_msg;
6763   struct MeshPeerInfo *peer_info;
6764   struct MeshClient *c;
6765   struct MeshTunnel *t;
6766   MESH_TunnelNumber tid;
6767
6768   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got connection request\n");
6769   /* Sanity check for client registration */
6770   if (NULL == (c = client_get (client)))
6771   {
6772     GNUNET_break (0);
6773     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6774     return;
6775   }
6776   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6777
6778   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6779
6780   /* Sanity check for message size */
6781   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6782   {
6783     GNUNET_break (0);
6784     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6785     return;
6786   }
6787
6788   /* Tunnel exists? */
6789   tid = ntohl (peer_msg->tunnel_id);
6790   t = tunnel_get_by_local_id (c, tid);
6791   if (NULL == t)
6792   {
6793     GNUNET_break (0);
6794     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6795     return;
6796   }
6797
6798   /* Does client own tunnel? */
6799   if (t->owner->handle != client)
6800   {
6801     GNUNET_break (0);
6802     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6803     return;
6804   }
6805   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "     for %s\n",
6806               GNUNET_i2s (&peer_msg->peer));
6807   peer_info = peer_info_get (&peer_msg->peer);
6808
6809   tunnel_add_peer (t, peer_info);
6810   peer_info_connect (peer_info, t);
6811
6812   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6813   return;
6814 }
6815
6816
6817 /**
6818  * Handler for disconnection requests of peers in a tunnel
6819  *
6820  * @param cls closure
6821  * @param client identification of the client
6822  * @param message the actual message (PeerControl)
6823  */
6824 static void
6825 handle_local_connect_del (void *cls, struct GNUNET_SERVER_Client *client,
6826                           const struct GNUNET_MessageHeader *message)
6827 {
6828   struct GNUNET_MESH_PeerControl *peer_msg;
6829   struct MeshPeerInfo *peer_info;
6830   struct MeshClient *c;
6831   struct MeshTunnel *t;
6832   MESH_TunnelNumber tid;
6833
6834   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER DEL request\n");
6835   /* Sanity check for client registration */
6836   if (NULL == (c = client_get (client)))
6837   {
6838     GNUNET_break (0);
6839     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6840     return;
6841   }
6842   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6843
6844   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6845
6846   /* Sanity check for message size */
6847   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6848   {
6849     GNUNET_break (0);
6850     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6851     return;
6852   }
6853
6854   /* Tunnel exists? */
6855   tid = ntohl (peer_msg->tunnel_id);
6856   t = tunnel_get_by_local_id (c, tid);
6857   if (NULL == t)
6858   {
6859     GNUNET_break (0);
6860     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6861     return;
6862   }
6863   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
6864
6865   /* Does client own tunnel? */
6866   if (t->owner->handle != client)
6867   {
6868     GNUNET_break (0);
6869     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6870     return;
6871   }
6872
6873   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for peer %s\n",
6874               GNUNET_i2s (&peer_msg->peer));
6875   /* Is the peer in the tunnel? */
6876   peer_info =
6877       GNUNET_CONTAINER_multihashmap_get (t->peers, &peer_msg->peer.hashPubKey);
6878   if (NULL == peer_info)
6879   {
6880     GNUNET_break (0);
6881     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6882     return;
6883   }
6884
6885   /* Ok, delete peer from tunnel */
6886   GNUNET_CONTAINER_multihashmap_remove_all (t->peers,
6887                                             &peer_msg->peer.hashPubKey);
6888
6889   send_destroy_path (t, peer_info->id);
6890   tunnel_delete_peer (t, peer_info->id);
6891   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6892   return;
6893 }
6894
6895 /**
6896  * Handler for blacklist requests of peers in a tunnel
6897  *
6898  * @param cls closure
6899  * @param client identification of the client
6900  * @param message the actual message (PeerControl)
6901  * 
6902  * FIXME implement DHT block bloomfilter
6903  */
6904 static void
6905 handle_local_blacklist (void *cls, struct GNUNET_SERVER_Client *client,
6906                           const struct GNUNET_MessageHeader *message)
6907 {
6908   struct GNUNET_MESH_PeerControl *peer_msg;
6909   struct MeshClient *c;
6910   struct MeshTunnel *t;
6911   MESH_TunnelNumber tid;
6912
6913   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER BLACKLIST request\n");
6914   /* Sanity check for client registration */
6915   if (NULL == (c = client_get (client)))
6916   {
6917     GNUNET_break (0);
6918     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6919     return;
6920   }
6921   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6922
6923   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6924
6925   /* Sanity check for message size */
6926   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6927   {
6928     GNUNET_break (0);
6929     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6930     return;
6931   }
6932
6933   /* Tunnel exists? */
6934   tid = ntohl (peer_msg->tunnel_id);
6935   t = tunnel_get_by_local_id (c, tid);
6936   if (NULL == t)
6937   {
6938     GNUNET_break (0);
6939     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6940     return;
6941   }
6942   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
6943
6944   GNUNET_array_append(t->blacklisted, t->nblacklisted,
6945                       GNUNET_PEER_intern(&peer_msg->peer));
6946 }
6947
6948
6949 /**
6950  * Handler for unblacklist requests of peers in a tunnel
6951  *
6952  * @param cls closure
6953  * @param client identification of the client
6954  * @param message the actual message (PeerControl)
6955  */
6956 static void
6957 handle_local_unblacklist (void *cls, struct GNUNET_SERVER_Client *client,
6958                           const struct GNUNET_MessageHeader *message)
6959 {
6960   struct GNUNET_MESH_PeerControl *peer_msg;
6961   struct MeshClient *c;
6962   struct MeshTunnel *t;
6963   MESH_TunnelNumber tid;
6964   GNUNET_PEER_Id pid;
6965   unsigned int i;
6966
6967   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER UNBLACKLIST request\n");
6968   /* Sanity check for client registration */
6969   if (NULL == (c = client_get (client)))
6970   {
6971     GNUNET_break (0);
6972     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6973     return;
6974   }
6975   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6976
6977   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6978
6979   /* Sanity check for message size */
6980   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6981   {
6982     GNUNET_break (0);
6983     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6984     return;
6985   }
6986
6987   /* Tunnel exists? */
6988   tid = ntohl (peer_msg->tunnel_id);
6989   t = tunnel_get_by_local_id (c, tid);
6990   if (NULL == t)
6991   {
6992     GNUNET_break (0);
6993     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6994     return;
6995   }
6996   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
6997
6998   /* if peer is not known, complain */
6999   pid = GNUNET_PEER_search (&peer_msg->peer);
7000   if (0 == pid)
7001   {
7002     GNUNET_break (0);
7003     return;
7004   }
7005
7006   /* search and remove from list */
7007   for (i = 0; i < t->nblacklisted; i++)
7008   {
7009     if (t->blacklisted[i] == pid)
7010     {
7011       t->blacklisted[i] = t->blacklisted[t->nblacklisted - 1];
7012       GNUNET_array_grow (t->blacklisted, t->nblacklisted, t->nblacklisted - 1);
7013       return;
7014     }
7015   }
7016
7017   /* if peer hasn't been blacklisted, complain */
7018   GNUNET_break (0);
7019 }
7020
7021
7022 /**
7023  * Handler for connection requests to new peers by type
7024  *
7025  * @param cls closure
7026  * @param client identification of the client
7027  * @param message the actual message (ConnectPeerByType)
7028  */
7029 static void
7030 handle_local_connect_by_type (void *cls, struct GNUNET_SERVER_Client *client,
7031                               const struct GNUNET_MessageHeader *message)
7032 {
7033   struct GNUNET_MESH_ConnectPeerByType *connect_msg;
7034   struct MeshClient *c;
7035   struct MeshTunnel *t;
7036   struct GNUNET_HashCode hash;
7037   MESH_TunnelNumber tid;
7038
7039   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got connect by type request\n");
7040   /* Sanity check for client registration */
7041   if (NULL == (c = client_get (client)))
7042   {
7043     GNUNET_break (0);
7044     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7045     return;
7046   }
7047   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7048
7049   connect_msg = (struct GNUNET_MESH_ConnectPeerByType *) message;
7050
7051   /* Sanity check for message size */
7052   if (sizeof (struct GNUNET_MESH_ConnectPeerByType) !=
7053       ntohs (connect_msg->header.size))
7054   {
7055     GNUNET_break (0);
7056     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7057     return;
7058   }
7059
7060   /* Tunnel exists? */
7061   tid = ntohl (connect_msg->tunnel_id);
7062   t = tunnel_get_by_local_id (c, tid);
7063   if (NULL == t)
7064   {
7065     GNUNET_break (0);
7066     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7067     return;
7068   }
7069
7070   /* Does client own tunnel? */
7071   if (t->owner->handle != client)
7072   {
7073     GNUNET_break (0);
7074     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7075     return;
7076   }
7077
7078   /* Do WE have the service? */
7079   t->type = ntohl (connect_msg->type);
7080   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " type requested: %u\n", t->type);
7081   GNUNET_CRYPTO_hash (&t->type, sizeof (GNUNET_MESH_ApplicationType), &hash);
7082   if (GNUNET_CONTAINER_multihashmap_contains (applications, &hash) ==
7083       GNUNET_YES)
7084   {
7085     /* Yes! Fast forward, add ourselves to the tunnel and send the
7086      * good news to the client, and alert the destination client of
7087      * an incoming tunnel.
7088      *
7089      * FIXME send a path create to self, avoid code duplication
7090      */
7091     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " available locally\n");
7092     GNUNET_CONTAINER_multihashmap_put (t->peers, &my_full_id.hashPubKey,
7093                                        peer_info_get (&my_full_id),
7094                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
7095
7096     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " notifying client\n");
7097     send_client_peer_connected (t, myid);
7098     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Done\n");
7099     GNUNET_SERVER_receive_done (client, GNUNET_OK);
7100
7101     t->local_tid_dest = next_local_tid++;
7102     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
7103     GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
7104                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
7105
7106     return;
7107   }
7108   /* Ok, lets find a peer offering the service */
7109   if (NULL != t->dht_get_type)
7110   {
7111     GNUNET_DHT_get_stop (t->dht_get_type);
7112   }
7113   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " looking in DHT for %s\n",
7114               GNUNET_h2s (&hash));
7115   t->dht_get_type =
7116       GNUNET_DHT_get_start (dht_handle, 
7117                             GNUNET_BLOCK_TYPE_MESH_PEER_BY_TYPE,
7118                             &hash,
7119                             dht_replication_level,
7120                             GNUNET_DHT_RO_RECORD_ROUTE |
7121                             GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
7122                             NULL, 0,
7123                             &dht_get_type_handler, t);
7124
7125   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7126   return;
7127 }
7128
7129
7130 /**
7131  * Handler for connection requests to new peers by a string service description.
7132  *
7133  * @param cls closure
7134  * @param client identification of the client
7135  * @param message the actual message, which includes messages the client wants
7136  */
7137 static void
7138 handle_local_connect_by_string (void *cls, struct GNUNET_SERVER_Client *client,
7139                                 const struct GNUNET_MessageHeader *message)
7140 {
7141   struct GNUNET_MESH_ConnectPeerByString *msg;
7142   struct MeshRegexSearchContext *ctx;
7143   struct MeshRegexSearchInfo *info;
7144   struct GNUNET_DHT_GetHandle *get_h;
7145   struct GNUNET_HashCode key;
7146   struct MeshTunnel *t;
7147   struct MeshClient *c;
7148   MESH_TunnelNumber tid;
7149   const char *string;
7150   size_t size;
7151   size_t len;
7152   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7153               "Connect by string started\n");
7154   msg = (struct GNUNET_MESH_ConnectPeerByString *) message;
7155   size = htons (message->size);
7156
7157   /* Sanity check for client registration */
7158   if (NULL == (c = client_get (client)))
7159   {
7160     GNUNET_break (0);
7161     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7162     return;
7163   }
7164   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7165
7166   /* Message size sanity check */
7167   if (sizeof(struct GNUNET_MESH_ConnectPeerByString) >= size)
7168   {
7169     GNUNET_break (0);
7170     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7171     return;
7172   }
7173
7174   /* Tunnel exists? */
7175   tid = ntohl (msg->tunnel_id);
7176   t = tunnel_get_by_local_id (c, tid);
7177   if (NULL == t)
7178   {
7179     GNUNET_break (0);
7180     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7181     return;
7182   }
7183
7184   /* Does client own tunnel? */
7185   if (t->owner->handle != client)
7186   {
7187     GNUNET_break (0);
7188     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7189     return;
7190   }
7191
7192   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7193               "  on tunnel %s [%u]\n",
7194               GNUNET_i2s(&my_full_id),
7195               t->id.tid);
7196
7197   /* Only one connect_by_string allowed at the same time! */
7198   /* FIXME: allow more, return handle at api level to cancel, document */
7199   if (NULL != t->regex_ctx)
7200   {
7201     GNUNET_break (0);
7202     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7203     return;
7204   }
7205
7206   /* Find string itself */
7207   len = size - sizeof(struct GNUNET_MESH_ConnectPeerByString);
7208   string = (const char *) &msg[1];
7209
7210   /* Initialize context */
7211   size = GNUNET_REGEX_get_first_key(string, len, &key);
7212   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7213               "  consumed %u bits out of %u\n", size, len);
7214   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7215               "  looking for %s\n", GNUNET_h2s (&key));
7216
7217   info = GNUNET_malloc (sizeof (struct MeshRegexSearchInfo));
7218   info->t = t;
7219   info->description = GNUNET_malloc (len + 1);
7220   memcpy (info->description, string, len);
7221   info->description[len] = '\0';
7222   info->dht_get_handles = GNUNET_CONTAINER_multihashmap_create(32);
7223   info->dht_get_results = GNUNET_CONTAINER_multihashmap_create(32);
7224   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   string: %s\n", info->description);
7225
7226   ctx = GNUNET_malloc (sizeof (struct MeshRegexSearchContext));
7227   ctx->position = size;
7228   ctx->info = info;
7229   t->regex_ctx = ctx;
7230
7231   GNUNET_array_append (info->contexts, info->n_contexts, ctx);
7232
7233   /* Start search in DHT */
7234   get_h = GNUNET_DHT_get_start (dht_handle,    /* handle */
7235                                 GNUNET_BLOCK_TYPE_MESH_REGEX, /* type */
7236                                 &key,     /* key to search */
7237                                 dht_replication_level, /* replication level */
7238                                 GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
7239                                 NULL,       /* xquery */ // FIXME BLOOMFILTER
7240                                 0,     /* xquery bits */ // FIXME BLOOMFILTER SIZE
7241                                 &dht_get_string_handler, ctx);
7242
7243   GNUNET_break (GNUNET_OK ==
7244                 GNUNET_CONTAINER_multihashmap_put(info->dht_get_handles,
7245                                                   &key,
7246                                                   get_h,
7247                                                   GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
7248
7249   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7250   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "connect by string processed\n");
7251 }
7252
7253
7254 /**
7255  * Handler for client traffic directed to one peer
7256  *
7257  * @param cls closure
7258  * @param client identification of the client
7259  * @param message the actual message
7260  */
7261 static void
7262 handle_local_unicast (void *cls, struct GNUNET_SERVER_Client *client,
7263                       const struct GNUNET_MessageHeader *message)
7264 {
7265   struct MeshClient *c;
7266   struct MeshTunnel *t;
7267   struct MeshPeerInfo *pi;
7268   struct GNUNET_MESH_Unicast *data_msg;
7269   MESH_TunnelNumber tid;
7270   size_t size;
7271
7272   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7273               "Got a unicast request from a client!\n");
7274
7275   /* Sanity check for client registration */
7276   if (NULL == (c = client_get (client)))
7277   {
7278     GNUNET_break (0);
7279     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7280     return;
7281   }
7282   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7283
7284   data_msg = (struct GNUNET_MESH_Unicast *) message;
7285
7286   /* Sanity check for message size */
7287   size = ntohs (message->size);
7288   if (sizeof (struct GNUNET_MESH_Unicast) +
7289       sizeof (struct GNUNET_MessageHeader) > size)
7290   {
7291     GNUNET_break (0);
7292     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7293     return;
7294   }
7295
7296   /* Tunnel exists? */
7297   tid = ntohl (data_msg->tid);
7298   t = tunnel_get_by_local_id (c, tid);
7299   if (NULL == t)
7300   {
7301     GNUNET_break (0);
7302     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7303     return;
7304   }
7305
7306   /*  Is it a local tunnel? Then, does client own the tunnel? */
7307   if (t->owner->handle != client)
7308   {
7309     GNUNET_break (0);
7310     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7311     return;
7312   }
7313
7314   pi = GNUNET_CONTAINER_multihashmap_get (t->peers,
7315                                           &data_msg->destination.hashPubKey);
7316   /* Is the selected peer in the tunnel? */
7317   if (NULL == pi)
7318   {
7319     GNUNET_break (0);
7320     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7321     return;
7322   }
7323
7324   /* PID should be as expected */
7325   if (ntohl (data_msg->pid) != t->fwd_pid + 1)
7326   {
7327     GNUNET_break (0);
7328     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7329               "Unicast PID, expected %u, got %u\n",
7330               t->fwd_pid + 1, ntohl (data_msg->pid));
7331     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7332     return;
7333   }
7334
7335   /* Ok, everything is correct, send the message
7336    * (pretend we got it from a mesh peer)
7337    */
7338   {
7339     /* Work around const limitation */
7340     char buf[ntohs (message->size)] GNUNET_ALIGN;
7341     struct GNUNET_MESH_Unicast *copy;
7342
7343     copy = (struct GNUNET_MESH_Unicast *) buf;
7344     memcpy (buf, data_msg, size);
7345     copy->oid = my_full_id;
7346     copy->tid = htonl (t->id.tid);
7347     copy->ttl = htonl (default_ttl);
7348     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7349                 "  calling generic handler...\n");
7350     handle_mesh_data_unicast (NULL, &my_full_id, &copy->header, NULL, 0);
7351   }
7352   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "receive done OK\n");
7353   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7354
7355   return;
7356 }
7357
7358
7359 /**
7360  * Handler for client traffic directed to the origin
7361  *
7362  * @param cls closure
7363  * @param client identification of the client
7364  * @param message the actual message
7365  */
7366 static void
7367 handle_local_to_origin (void *cls, struct GNUNET_SERVER_Client *client,
7368                         const struct GNUNET_MessageHeader *message)
7369 {
7370   struct GNUNET_MESH_ToOrigin *data_msg;
7371   struct MeshTunnelClientInfo *clinfo;
7372   struct MeshClient *c;
7373   struct MeshTunnel *t;
7374   MESH_TunnelNumber tid;
7375   size_t size;
7376
7377   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7378               "Got a ToOrigin request from a client!\n");
7379   /* Sanity check for client registration */
7380   if (NULL == (c = client_get (client)))
7381   {
7382     GNUNET_break (0);
7383     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7384     return;
7385   }
7386   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7387
7388   data_msg = (struct GNUNET_MESH_ToOrigin *) message;
7389
7390   /* Sanity check for message size */
7391   size = ntohs (message->size);
7392   if (sizeof (struct GNUNET_MESH_ToOrigin) +
7393       sizeof (struct GNUNET_MessageHeader) > size)
7394   {
7395     GNUNET_break (0);
7396     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7397     return;
7398   }
7399
7400   /* Tunnel exists? */
7401   tid = ntohl (data_msg->tid);
7402   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
7403   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
7404   {
7405     GNUNET_break (0);
7406     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7407     return;
7408   }
7409   t = tunnel_get_by_local_id (c, tid);
7410   if (NULL == t)
7411   {
7412     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
7413     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
7414     GNUNET_break (0);
7415     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7416     return;
7417   }
7418
7419   /*  It should be sent by someone who has this as incoming tunnel. */
7420   if (GNUNET_NO == client_knows_tunnel (c, t))
7421   {
7422     GNUNET_break (0);
7423     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7424     return;
7425   }
7426
7427   /* PID should be as expected */
7428   clinfo = tunnel_get_client_fc (t, c);
7429   if (ntohl (data_msg->pid) != clinfo->bck_pid + 1)
7430   {
7431     GNUNET_break (0);
7432     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7433                 "To Origin PID, expected %u, got %u\n",
7434                 clinfo->bck_pid + 1,
7435                 ntohl (data_msg->pid));
7436     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7437     return;
7438   }
7439
7440   /* Ok, everything is correct, send the message
7441    * (pretend we got it from a mesh peer)
7442    */
7443   clinfo->bck_pid++;
7444   {
7445     char buf[ntohs (message->size)] GNUNET_ALIGN;
7446     struct GNUNET_MESH_ToOrigin *copy;
7447
7448     /* Work around const limitation */
7449     copy = (struct GNUNET_MESH_ToOrigin *) buf;
7450     memcpy (buf, data_msg, size);
7451     GNUNET_PEER_resolve (t->id.oid, &copy->oid);
7452     copy->tid = htonl (t->id.tid);
7453     copy->ttl = htonl (default_ttl);
7454     if (ntohl (copy->pid) != (t->bck_pid + 1))
7455     {
7456       GNUNET_break (0);
7457       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7458                   "To Origin PID, expected %u, got %u\n",
7459                   t->bck_pid + 1,
7460                   ntohl (copy->pid));
7461       return;
7462     }
7463     t->bck_pid++;
7464     copy->sender = my_full_id;
7465     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7466                 "  calling generic handler...\n");
7467     handle_mesh_data_to_orig (NULL, &my_full_id, &copy->header, NULL, 0);
7468   }
7469   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7470
7471   return;
7472 }
7473
7474
7475 /**
7476  * Handler for client traffic directed to all peers in a tunnel
7477  *
7478  * @param cls closure
7479  * @param client identification of the client
7480  * @param message the actual message
7481  */
7482 static void
7483 handle_local_multicast (void *cls, struct GNUNET_SERVER_Client *client,
7484                         const struct GNUNET_MessageHeader *message)
7485 {
7486   struct MeshClient *c;
7487   struct MeshTunnel *t;
7488   struct GNUNET_MESH_Multicast *data_msg;
7489   MESH_TunnelNumber tid;
7490
7491   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7492               "Got a multicast request from a client!\n");
7493
7494   /* Sanity check for client registration */
7495   if (NULL == (c = client_get (client)))
7496   {
7497     GNUNET_break (0);
7498     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7499     return;
7500   }
7501   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7502
7503   data_msg = (struct GNUNET_MESH_Multicast *) message;
7504
7505   /* Sanity check for message size */
7506   if (sizeof (struct GNUNET_MESH_Multicast) +
7507       sizeof (struct GNUNET_MessageHeader) > ntohs (data_msg->header.size))
7508   {
7509     GNUNET_break (0);
7510     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7511     return;
7512   }
7513
7514   /* Tunnel exists? */
7515   tid = ntohl (data_msg->tid);
7516   t = tunnel_get_by_local_id (c, tid);
7517   if (NULL == t)
7518   {
7519     GNUNET_break (0);
7520     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
7521     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
7522     GNUNET_break (0);
7523     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7524     return;
7525   }
7526
7527   /* Does client own tunnel? */
7528   if (t->owner->handle != client)
7529   {
7530     GNUNET_break (0);
7531     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7532     return;
7533   }
7534
7535   /* PID should be as expected */
7536   if (ntohl (data_msg->pid) != t->fwd_pid + 1)
7537   {
7538     GNUNET_break (0);
7539     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7540               "Multicast PID, expected %u, got %u\n",
7541               t->fwd_pid + 1, ntohl (data_msg->pid));
7542     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7543     return;
7544   }
7545
7546   {
7547     char buf[ntohs (message->size)] GNUNET_ALIGN;
7548     struct GNUNET_MESH_Multicast *copy;
7549
7550     copy = (struct GNUNET_MESH_Multicast *) buf;
7551     memcpy (buf, message, ntohs (message->size));
7552     copy->oid = my_full_id;
7553     copy->tid = htonl (t->id.tid);
7554     copy->ttl = htonl (default_ttl);
7555     GNUNET_assert (ntohl (copy->pid) == (t->fwd_pid + 1));
7556     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7557                 "  calling generic handler...\n");
7558     handle_mesh_data_multicast (client, &my_full_id, &copy->header, NULL, 0);
7559   }
7560
7561   GNUNET_SERVER_receive_done (t->owner->handle, GNUNET_OK);
7562   return;
7563 }
7564
7565
7566 /**
7567  * Handler for client's ACKs for payload traffic.
7568  *
7569  * @param cls Closure (unused).
7570  * @param client Identification of the client.
7571  * @param message The actual message.
7572  */
7573 static void
7574 handle_local_ack (void *cls, struct GNUNET_SERVER_Client *client,
7575                   const struct GNUNET_MessageHeader *message)
7576 {
7577   struct GNUNET_MESH_LocalAck *msg;
7578   struct MeshTunnel *t;
7579   struct MeshClient *c;
7580   MESH_TunnelNumber tid;
7581   uint32_t ack;
7582
7583   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a local ACK\n");
7584   /* Sanity check for client registration */
7585   if (NULL == (c = client_get (client)))
7586   {
7587     GNUNET_break (0);
7588     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7589     return;
7590   }
7591   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7592
7593   msg = (struct GNUNET_MESH_LocalAck *) message;
7594
7595   /* Tunnel exists? */
7596   tid = ntohl (msg->tunnel_id);
7597   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
7598   t = tunnel_get_by_local_id (c, tid);
7599   if (NULL == t)
7600   {
7601     GNUNET_break (0);
7602     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
7603     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
7604     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7605     return;
7606   }
7607
7608   ack = ntohl (msg->max_pid);
7609   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ack %u\n", ack);
7610
7611   /* Does client own tunnel? I.E: Is this and ACK for BCK traffic? */
7612   if (NULL != t->owner && t->owner->handle == client)
7613   {
7614     /* The client owns the tunnel, ACK is for data to_origin, send BCK ACK. */
7615     t->bck_ack = ack;
7616     tunnel_send_bck_ack(t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
7617   }
7618   else
7619   {
7620     /* The client doesn't own the tunnel, this ACK is for FWD traffic. */
7621     tunnel_set_client_fwd_ack (t, c, ack);
7622     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
7623   }
7624
7625   GNUNET_SERVER_receive_done (client, GNUNET_OK);  
7626
7627   return;
7628 }
7629
7630
7631 /**
7632  * Functions to handle messages from clients
7633  */
7634 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
7635   {&handle_local_new_client, NULL,
7636    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
7637   {&handle_local_announce_regex, NULL,
7638    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ANNOUNCE_REGEX, 0},
7639   {&handle_local_tunnel_create, NULL,
7640    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
7641    sizeof (struct GNUNET_MESH_TunnelMessage)},
7642   {&handle_local_tunnel_destroy, NULL,
7643    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
7644    sizeof (struct GNUNET_MESH_TunnelMessage)},
7645   {&handle_local_tunnel_speed, NULL,
7646    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MIN,
7647    sizeof (struct GNUNET_MESH_TunnelMessage)},
7648   {&handle_local_tunnel_speed, NULL,
7649    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MAX,
7650    sizeof (struct GNUNET_MESH_TunnelMessage)},
7651   {&handle_local_tunnel_buffer, NULL,
7652    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER,
7653    sizeof (struct GNUNET_MESH_TunnelMessage)},
7654   {&handle_local_tunnel_buffer, NULL,
7655    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER,
7656    sizeof (struct GNUNET_MESH_TunnelMessage)},
7657   {&handle_local_connect_add, NULL,
7658    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD,
7659    sizeof (struct GNUNET_MESH_PeerControl)},
7660   {&handle_local_connect_del, NULL,
7661    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL,
7662    sizeof (struct GNUNET_MESH_PeerControl)},
7663   {&handle_local_blacklist, NULL,
7664    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_BLACKLIST,
7665    sizeof (struct GNUNET_MESH_PeerControl)},
7666   {&handle_local_unblacklist, NULL,
7667    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_UNBLACKLIST,
7668    sizeof (struct GNUNET_MESH_PeerControl)},
7669   {&handle_local_connect_by_type, NULL,
7670    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE,
7671    sizeof (struct GNUNET_MESH_ConnectPeerByType)},
7672   {&handle_local_connect_by_string, NULL,
7673    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_STRING, 0},
7674   {&handle_local_unicast, NULL,
7675    GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
7676   {&handle_local_to_origin, NULL,
7677    GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
7678   {&handle_local_multicast, NULL,
7679    GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
7680   {&handle_local_ack, NULL,
7681    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK,
7682    sizeof (struct GNUNET_MESH_LocalAck)},
7683   {NULL, NULL, 0, 0}
7684 };
7685
7686
7687 /**
7688  * To be called on core init/fail.
7689  *
7690  * @param cls service closure
7691  * @param server handle to the server for this service
7692  * @param identity the public identity of this peer
7693  */
7694 static void
7695 core_init (void *cls, struct GNUNET_CORE_Handle *server,
7696            const struct GNUNET_PeerIdentity *identity)
7697 {
7698   static int i = 0;
7699   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
7700   core_handle = server;
7701   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)) ||
7702       NULL == server)
7703   {
7704     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
7705     GNUNET_SCHEDULER_shutdown (); // Try gracefully
7706     if (10 < i++)
7707       GNUNET_abort(); // Try harder
7708   }
7709   return;
7710 }
7711
7712
7713 /**
7714  * Method called whenever a given peer connects.
7715  *
7716  * @param cls closure
7717  * @param peer peer identity this notification is about
7718  * @param atsi performance data for the connection
7719  * @param atsi_count number of records in 'atsi'
7720  */
7721 static void
7722 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
7723               const struct GNUNET_ATS_Information *atsi,
7724               unsigned int atsi_count)
7725 {
7726   struct MeshPeerInfo *peer_info;
7727   struct MeshPeerPath *path;
7728
7729   DEBUG_CONN ("Peer connected\n");
7730   DEBUG_CONN ("     %s\n", GNUNET_i2s (&my_full_id));
7731   peer_info = peer_info_get (peer);
7732   if (myid == peer_info->id)
7733   {
7734     DEBUG_CONN ("     (self)\n");
7735     return;
7736   }
7737   else
7738   {
7739     DEBUG_CONN ("     %s\n", GNUNET_i2s (peer));
7740   }
7741   path = path_new (2);
7742   path->peers[0] = myid;
7743   path->peers[1] = peer_info->id;
7744   GNUNET_PEER_change_rc (myid, 1);
7745   GNUNET_PEER_change_rc (peer_info->id, 1);
7746   peer_info_add_path (peer_info, path, GNUNET_YES);
7747   GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
7748   return;
7749 }
7750
7751
7752 /**
7753  * Method called whenever a peer disconnects.
7754  *
7755  * @param cls closure
7756  * @param peer peer identity this notification is about
7757  */
7758 static void
7759 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
7760 {
7761   struct MeshPeerInfo *pi;
7762   struct MeshPeerQueue *q;
7763   struct MeshPeerQueue *n;
7764
7765   DEBUG_CONN ("Peer disconnected\n");
7766   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
7767   if (NULL == pi)
7768   {
7769     GNUNET_break (0);
7770     return;
7771   }
7772   q = pi->queue_head;
7773   while (NULL != q)
7774   {
7775       n = q->next;
7776       /* TODO try to reroute this traffic instead */
7777       queue_destroy(q, GNUNET_YES);
7778       q = n;
7779   }
7780   if (NULL != pi->core_transmit)
7781   {
7782     GNUNET_CORE_notify_transmit_ready_cancel(pi->core_transmit);
7783     pi->core_transmit = NULL;
7784   }
7785   peer_info_remove_path (pi, pi->id, myid);
7786   if (myid == pi->id)
7787   {
7788     DEBUG_CONN ("     (self)\n");
7789   }
7790   GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
7791   return;
7792 }
7793
7794
7795 /******************************************************************************/
7796 /************************      MAIN FUNCTIONS      ****************************/
7797 /******************************************************************************/
7798
7799 /**
7800  * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
7801  *
7802  * @param cls closure
7803  * @param key current key code
7804  * @param value value in the hash map
7805  * @return GNUNET_YES if we should continue to iterate,
7806  *         GNUNET_NO if not.
7807  */
7808 static int
7809 shutdown_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
7810 {
7811   struct MeshTunnel *t = value;
7812
7813   tunnel_destroy (t);
7814   return GNUNET_YES;
7815 }
7816
7817 /**
7818  * Iterator over peer hash map entries to destroy the tunnel during shutdown.
7819  *
7820  * @param cls closure
7821  * @param key current key code
7822  * @param value value in the hash map
7823  * @return GNUNET_YES if we should continue to iterate,
7824  *         GNUNET_NO if not.
7825  */
7826 static int
7827 shutdown_peer (void *cls, const struct GNUNET_HashCode * key, void *value)
7828 {
7829   struct MeshPeerInfo *p = value;
7830   struct MeshPeerQueue *q;
7831   struct MeshPeerQueue *n;
7832
7833   q = p->queue_head;
7834   while (NULL != q)
7835   {
7836       n = q->next;
7837       if (q->peer == p)
7838       {
7839         queue_destroy(q, GNUNET_YES);
7840       }
7841       q = n;
7842   }
7843   peer_info_destroy (p);
7844   return GNUNET_YES;
7845 }
7846
7847
7848 /**
7849  * Task run during shutdown.
7850  *
7851  * @param cls unused
7852  * @param tc unused
7853  */
7854 static void
7855 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
7856 {
7857   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
7858
7859   if (core_handle != NULL)
7860   {
7861     GNUNET_CORE_disconnect (core_handle);
7862     core_handle = NULL;
7863   }
7864  if (NULL != keygen)
7865   {
7866     GNUNET_CRYPTO_rsa_key_create_stop (keygen);
7867     keygen = NULL;
7868   }
7869   GNUNET_CONTAINER_multihashmap_iterate (tunnels, &shutdown_tunnel, NULL);
7870   GNUNET_CONTAINER_multihashmap_iterate (peers, &shutdown_peer, NULL);
7871   if (dht_handle != NULL)
7872   {
7873     GNUNET_DHT_disconnect (dht_handle);
7874     dht_handle = NULL;
7875   }
7876   if (nc != NULL)
7877   {
7878     GNUNET_SERVER_notification_context_destroy (nc);
7879     nc = NULL;
7880   }
7881   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
7882   {
7883     GNUNET_SCHEDULER_cancel (announce_id_task);
7884     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
7885   }
7886   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
7887 }
7888
7889
7890 /**
7891  * Callback for hostkey read/generation
7892  *
7893  * @param cls NULL
7894  * @param pk the private key
7895  * @param emsg error message
7896  */
7897 static void
7898 key_generation_cb (void *cls,
7899                    struct GNUNET_CRYPTO_RsaPrivateKey *pk,
7900                    const char *emsg)
7901 {
7902   struct MeshPeerInfo *peer;
7903   struct MeshPeerPath *p;
7904
7905   keygen = NULL;  
7906   if (NULL == pk)
7907   {
7908     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7909                 _("Mesh service could not access hostkey.  Exiting.\n"));
7910     GNUNET_SCHEDULER_shutdown ();
7911     return;
7912   }
7913   my_private_key = pk;
7914   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
7915   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
7916                       &my_full_id.hashPubKey);
7917   myid = GNUNET_PEER_intern (&my_full_id);
7918   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
7919               "Mesh for peer [%s] starting\n",
7920               GNUNET_i2s(&my_full_id));
7921
7922 //   transport_handle = GNUNET_TRANSPORT_connect(c,
7923 //                                               &my_full_id,
7924 //                                               NULL,
7925 //                                               NULL,
7926 //                                               NULL,
7927 //                                               NULL);
7928
7929
7930
7931   next_tid = 0;
7932   next_local_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
7933
7934
7935   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
7936   nc = GNUNET_SERVER_notification_context_create (server_handle, 1);
7937   GNUNET_SERVER_disconnect_notify (server_handle,
7938                                    &handle_local_client_disconnect, NULL);
7939
7940
7941   clients = NULL;
7942   clients_tail = NULL;
7943   next_client_id = 0;
7944
7945   announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
7946   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
7947
7948   /* Create a peer_info for the local peer */
7949   peer = peer_info_get (&my_full_id);
7950   p = path_new (1);
7951   p->peers[0] = myid;
7952   GNUNET_PEER_change_rc (myid, 1);
7953   peer_info_add_path (peer, p, GNUNET_YES);
7954   GNUNET_SERVER_resume (server_handle);
7955   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Mesh service running\n");
7956 }
7957
7958
7959 /**
7960  * Process mesh requests.
7961  *
7962  * @param cls closure
7963  * @param server the initialized server
7964  * @param c configuration to use
7965  */
7966 static void
7967 run (void *cls, struct GNUNET_SERVER_Handle *server,
7968      const struct GNUNET_CONFIGURATION_Handle *c)
7969 {
7970   char *keyfile;
7971
7972   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
7973   server_handle = server;
7974   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
7975                                      NULL,      /* Closure passed to MESH functions */
7976                                      &core_init,        /* Call core_init once connected */
7977                                      &core_connect,     /* Handle connects */
7978                                      &core_disconnect,  /* remove peers on disconnects */
7979                                      NULL,      /* Don't notify about all incoming messages */
7980                                      GNUNET_NO, /* For header only in notification */
7981                                      NULL,      /* Don't notify about all outbound messages */
7982                                      GNUNET_NO, /* For header-only out notification */
7983                                      core_handlers);    /* Register these handlers */
7984
7985   if (core_handle == NULL)
7986   {
7987     GNUNET_break (0);
7988     GNUNET_SCHEDULER_shutdown ();
7989     return;
7990   }
7991
7992   if (GNUNET_OK !=
7993       GNUNET_CONFIGURATION_get_value_filename (c, "GNUNETD", "HOSTKEY",
7994                                                &keyfile))
7995   {
7996     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7997                 _
7998                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
7999                 "mesh", "hostkey");
8000     GNUNET_SCHEDULER_shutdown ();
8001     return;
8002   }
8003
8004   if (GNUNET_OK !=
8005       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_PATH_TIME",
8006                                            &refresh_path_time))
8007   {
8008     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8009                 _
8010                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8011                 "mesh", "refresh path time");
8012     GNUNET_SCHEDULER_shutdown ();
8013     return;
8014   }
8015
8016   if (GNUNET_OK !=
8017       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "APP_ANNOUNCE_TIME",
8018                                            &app_announce_time))
8019   {
8020     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8021                 _
8022                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8023                 "mesh", "app announce time");
8024     GNUNET_SCHEDULER_shutdown ();
8025     return;
8026   }
8027
8028   if (GNUNET_OK !=
8029       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "ID_ANNOUNCE_TIME",
8030                                            &id_announce_time))
8031   {
8032     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8033                 _
8034                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8035                 "mesh", "id announce time");
8036     GNUNET_SCHEDULER_shutdown ();
8037     return;
8038   }
8039   else
8040   {
8041   }
8042
8043   if (GNUNET_OK !=
8044       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "UNACKNOWLEDGED_WAIT",
8045                                            &unacknowledged_wait_time))
8046   {
8047     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8048                 _
8049                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8050                 "mesh", "unacknowledged wait time");
8051     GNUNET_SCHEDULER_shutdown ();
8052     return;
8053   }
8054
8055   if (GNUNET_OK !=
8056       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "CONNECT_TIMEOUT",
8057                                            &connect_timeout))
8058   {
8059     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8060                 _
8061                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8062                 "mesh", "connect timeout");
8063     GNUNET_SCHEDULER_shutdown ();
8064     return;
8065   }
8066
8067   if (GNUNET_OK !=
8068       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
8069                                              &max_msgs_queue))
8070   {
8071     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8072                 _
8073                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8074                 "mesh", "max msgs queue");
8075     GNUNET_SCHEDULER_shutdown ();
8076     return;
8077   }
8078
8079   if (GNUNET_OK !=
8080       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_TUNNELS",
8081                                              &max_tunnels))
8082   {
8083     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8084                 _
8085                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8086                 "mesh", "max tunnels");
8087     GNUNET_SCHEDULER_shutdown ();
8088     return;
8089   }
8090
8091   if (GNUNET_OK !=
8092       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
8093                                              &default_ttl))
8094   {
8095     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
8096                 _
8097                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
8098                 "mesh", "default ttl", 64);
8099     default_ttl = 64;
8100   }
8101
8102   if (GNUNET_OK !=
8103       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DHT_REPLICATION_LEVEL",
8104                                              &dht_replication_level))
8105   {
8106     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
8107                 _
8108                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
8109                 "mesh", "dht replication level", 10);
8110     dht_replication_level = 10;
8111   }
8112
8113   tunnels = GNUNET_CONTAINER_multihashmap_create (32);
8114   incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
8115   peers = GNUNET_CONTAINER_multihashmap_create (32);
8116   applications = GNUNET_CONTAINER_multihashmap_create (32);
8117   types = GNUNET_CONTAINER_multihashmap_create (32);
8118
8119   dht_handle = GNUNET_DHT_connect (c, 64);
8120   if (NULL == dht_handle)
8121   {
8122     GNUNET_break (0);
8123   }
8124   stats = GNUNET_STATISTICS_create ("mesh", c);
8125
8126   GNUNET_SERVER_suspend (server_handle);
8127   /* Scheduled the task to clean up when shutdown is called */
8128   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
8129                                 NULL);
8130   keygen = GNUNET_CRYPTO_rsa_key_create_start (keyfile, &key_generation_cb, NULL);
8131   GNUNET_free (keyfile);
8132 }
8133
8134
8135 /**
8136  * The main function for the mesh service.
8137  *
8138  * @param argc number of arguments from the command line
8139  * @param argv command line arguments
8140  * @return 0 ok, 1 on error
8141  */
8142 int
8143 main (int argc, char *const *argv)
8144 {
8145   int ret;
8146   int r;
8147
8148   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
8149   r = GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
8150                           NULL);
8151   ret = (GNUNET_OK == r) ? 0 : 1;
8152   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");
8153
8154   INTERVAL_SHOW;
8155
8156   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
8157               "Mesh for peer [%s] FWD ACKs %u, BCK ACKs %u\n",
8158               GNUNET_i2s(&my_full_id), debug_fwd_ack, debug_bck_ack);
8159
8160   return ret;
8161 }