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