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