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