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