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