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