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