-fix fix
[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 (tree_get_predecessor(cinfo->t->tree), &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_PATH_KEEPALIVE:
4804         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4805                     "   prebuilt message\n");
4806         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4807                     "   type %s\n",
4808                     GNUNET_MESH_DEBUG_M2S(queue->type));
4809         dd = queue->cls;
4810         data_descriptor_decrement_rc (dd->mesh_data);
4811         break;
4812       case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
4813         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   type create path\n");
4814         path_info = queue->cls;
4815         path_destroy (path_info->path);
4816         break;
4817       default:
4818         GNUNET_break (0);
4819         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4820                     "   type %s unknown!\n",
4821                     GNUNET_MESH_DEBUG_M2S(queue->type));
4822     }
4823     GNUNET_free_non_null (queue->cls);
4824   }
4825   GNUNET_CONTAINER_DLL_remove (queue->peer->queue_head,
4826                                queue->peer->queue_tail,
4827                                queue);
4828
4829   /* Delete from child_fc in the appropiate tunnel */
4830   max = queue->tunnel->fwd_queue_max;
4831   GNUNET_PEER_resolve (queue->peer->id, &id);
4832   cinfo = tunnel_get_neighbor_fc (queue->tunnel, &id);
4833   if (NULL != cinfo)
4834   {
4835     for (i = 0; i < cinfo->send_buffer_n; i++)
4836     {
4837       unsigned int i2;
4838       i2 = (cinfo->send_buffer_start + i) % max;
4839       if (cinfo->send_buffer[i2] == queue)
4840       {
4841         /* Found corresponding entry in the send_buffer. Move all others back. */
4842         unsigned int j;
4843         unsigned int j2;
4844         unsigned int j3;
4845
4846         for (j = i, j2 = 0, j3 = 0; j < cinfo->send_buffer_n - 1; j++)
4847         {
4848           j2 = (cinfo->send_buffer_start + j) % max;
4849           j3 = (cinfo->send_buffer_start + j + 1) % max;
4850           cinfo->send_buffer[j2] = cinfo->send_buffer[j3];
4851         }
4852
4853         cinfo->send_buffer[j3] = NULL;
4854         cinfo->send_buffer_n--;
4855       }
4856     }
4857   }
4858
4859   GNUNET_free (queue);
4860 }
4861
4862
4863 /**
4864  * @brief Get the next transmittable message from the queue.
4865  *
4866  * This will be the head, except in the case of being a data packet
4867  * not allowed by the destination peer.
4868  *
4869  * @param peer Destination peer.
4870  *
4871  * @return The next viable MeshPeerQueue element to send to that peer.
4872  *         NULL when there are no transmittable messages.
4873  */
4874 struct MeshPeerQueue *
4875 queue_get_next (const struct MeshPeerInfo *peer)
4876 {
4877   struct MeshPeerQueue *q;
4878   struct MeshTunnel *t;
4879   struct MeshTransmissionDescriptor *info;
4880   struct MeshTunnelChildInfo *cinfo;
4881   struct GNUNET_MESH_Unicast *ucast;
4882   struct GNUNET_MESH_ToOrigin *to_orig;
4883   struct GNUNET_MESH_Multicast *mcast;
4884   struct GNUNET_PeerIdentity id;
4885   uint32_t pid;
4886   uint32_t ack;
4887
4888   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   selecting message\n");
4889   for (q = peer->queue_head; NULL != q; q = q->next)
4890   {
4891     t = q->tunnel;
4892     info = q->cls;
4893     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4894                 "*********     %s\n",
4895                 GNUNET_MESH_DEBUG_M2S(q->type));
4896     switch (q->type)
4897     {
4898       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4899         ucast = (struct GNUNET_MESH_Unicast *) info->mesh_data->data;
4900         pid = ntohl (ucast->pid);
4901         GNUNET_PEER_resolve (info->peer->id, &id);
4902         cinfo = tunnel_get_neighbor_fc(t, &id);
4903         ack = cinfo->fwd_ack;
4904         break;
4905       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4906         to_orig = (struct GNUNET_MESH_ToOrigin *) info->mesh_data->data;
4907         pid = ntohl (to_orig->pid);
4908         ack = t->bck_ack;
4909         break;
4910       case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
4911         mcast = (struct GNUNET_MESH_Multicast *) info->mesh_data->data;
4912         if (GNUNET_MESSAGE_TYPE_MESH_MULTICAST != ntohs(mcast->header.type)) 
4913         {
4914           // Not a multicast payload: multicast control traffic (destroy, etc)
4915           return q;
4916         }
4917         pid = ntohl (mcast->pid);
4918         GNUNET_PEER_resolve (info->peer->id, &id);
4919         cinfo = tunnel_get_neighbor_fc(t, &id);
4920         ack = cinfo->fwd_ack;
4921         break;
4922       default:
4923         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4924                     "*********   OK!\n");
4925         return q;
4926     }
4927         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4928                     "*********     ACK: %u, PID: %u\n",
4929                     ack, pid);
4930     if (GNUNET_NO == GMC_is_pid_bigger(pid, ack))
4931     {
4932       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4933                   "*********   OK!\n");
4934       return q;
4935     }
4936     else
4937     {
4938       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4939                   "*********     NEXT!\n");
4940     }
4941   }
4942   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4943                 "*********   nothing found\n");
4944   return NULL;
4945 }
4946
4947
4948 /**
4949   * Core callback to write a queued packet to core buffer
4950   *
4951   * @param cls Closure (peer info).
4952   * @param size Number of bytes available in buf.
4953   * @param buf Where the to write the message.
4954   *
4955   * @return number of bytes written to buf
4956   */
4957 static size_t
4958 queue_send (void *cls, size_t size, void *buf)
4959 {
4960     struct MeshPeerInfo *peer = cls;
4961     struct GNUNET_MessageHeader *msg;
4962     struct MeshPeerQueue *queue;
4963     struct MeshTunnel *t;
4964     struct MeshTunnelChildInfo *cinfo;
4965     struct GNUNET_PeerIdentity dst_id;
4966     size_t data_size;
4967
4968     peer->core_transmit = NULL;
4969     cinfo = NULL;
4970
4971     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "********* Queue send\n");
4972     queue = queue_get_next (peer);
4973
4974     /* Queue has no internal mesh traffic nor sendable payload */
4975     if (NULL == queue)
4976     {
4977       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   not ready, return\n");
4978       if (NULL == peer->queue_head)
4979         GNUNET_break (0); // Should've been canceled
4980       return 0;
4981     }
4982     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   not empty\n");
4983
4984     GNUNET_PEER_resolve (peer->id, &dst_id);
4985     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4986                 "*********   towards %s\n",
4987                 GNUNET_i2s(&dst_id));
4988     /* Check if buffer size is enough for the message */
4989     if (queue->size > size)
4990     {
4991         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4992                     "*********   not enough room, reissue\n");
4993         peer->core_transmit =
4994             GNUNET_CORE_notify_transmit_ready (core_handle,
4995                                                0,
4996                                                0,
4997                                                GNUNET_TIME_UNIT_FOREVER_REL,
4998                                                &dst_id,
4999                                                queue->size,
5000                                                &queue_send,
5001                                                peer);
5002         return 0;
5003     }
5004     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   size ok\n");
5005
5006     t = queue->tunnel;
5007     GNUNET_assert (0 < t->pending_messages);
5008     t->pending_messages--;
5009     if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == queue->type)
5010     {
5011       t->fwd_queue_n--;
5012       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5013                   "*********   unicast: t->q (%u/%u)\n",
5014                   t->fwd_queue_n, t->fwd_queue_max);
5015     }
5016     else if (GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == queue->type)
5017     {
5018       t->bck_queue_n--;
5019       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   to origin\n");
5020     }
5021
5022     /* Fill buf */
5023     switch (queue->type)
5024     {
5025       case 0:
5026       case GNUNET_MESSAGE_TYPE_MESH_ACK:
5027       case GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN:
5028       case GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY:
5029       case GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY:
5030         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5031                     "*********   raw: %s\n",
5032                     GNUNET_MESH_DEBUG_M2S (queue->type));
5033         /* Fall through */
5034       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
5035       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
5036         data_size = send_core_data_raw (queue->cls, size, buf);
5037         msg = (struct GNUNET_MessageHeader *) buf;
5038         switch (ntohs (msg->type)) // Type of preconstructed message
5039         {
5040           case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
5041             tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_UNICAST);
5042             break;
5043           case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
5044             tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
5045             break;
5046           default:
5047               break;
5048         }
5049         break;
5050       case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
5051         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   multicast\n");
5052         {
5053           struct MeshTransmissionDescriptor *info = queue->cls;
5054
5055           if ((1 == info->mesh_data->reference_counter
5056               && GNUNET_YES == t->speed_min)
5057               ||
5058               (info->mesh_data->total_out == info->mesh_data->reference_counter
5059               && GNUNET_NO == t->speed_min))
5060           {
5061             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5062                         "*********   considered sent\n");
5063             t->fwd_queue_n--;
5064           }
5065           else
5066           {
5067             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5068                         "*********   NOT considered sent yet\n");
5069             t->pending_messages++;
5070           }
5071         }
5072         data_size = send_core_data_multicast(queue->cls, size, buf);
5073         tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
5074         break;
5075       case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
5076         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path create\n");
5077         data_size = send_core_path_create (queue->cls, size, buf);
5078         break;
5079       case GNUNET_MESSAGE_TYPE_MESH_PATH_ACK:
5080         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path ack\n");
5081         data_size = send_core_path_ack (queue->cls, size, buf);
5082         break;
5083       case GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE:
5084         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path keepalive\n");
5085         data_size = send_core_data_multicast (queue->cls, size, buf);
5086         break;
5087       default:
5088         GNUNET_break (0);
5089         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5090                     "*********   type unknown: %u\n",
5091                     queue->type);
5092         data_size = 0;
5093     }
5094     switch (queue->type)
5095     {
5096       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
5097       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
5098       case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
5099         cinfo = tunnel_get_neighbor_fc (t, &dst_id);
5100         if (cinfo->send_buffer[cinfo->send_buffer_start] != queue)
5101         {
5102           GNUNET_break (0);
5103           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5104                       "at pos %u (%p) != %p\n",
5105                       cinfo->send_buffer_start,
5106                       cinfo->send_buffer[cinfo->send_buffer_start],
5107                       queue);
5108         }
5109         if (cinfo->send_buffer_n > 0)
5110         {
5111           cinfo->send_buffer[cinfo->send_buffer_start] = NULL;
5112           cinfo->send_buffer_n--;
5113           cinfo->send_buffer_start++;
5114           cinfo->send_buffer_start %= t->fwd_queue_max;
5115         }
5116         else
5117         {
5118           GNUNET_break (0);
5119         }
5120         break;
5121       default:
5122         break;
5123     }
5124
5125     /* Free queue, but cls was freed by send_core_* */
5126     queue_destroy (queue, GNUNET_NO);
5127
5128     if (GNUNET_YES == t->destroy && 0 == t->pending_messages)
5129     {
5130       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********  destroying tunnel!\n");
5131       tunnel_destroy (t);
5132     }
5133
5134     /* If more data in queue, send next */
5135     queue = queue_get_next(peer);
5136     if (NULL != queue)
5137     {
5138         struct GNUNET_PeerIdentity id;
5139
5140         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   more data!\n");
5141         GNUNET_PEER_resolve (peer->id, &id);
5142         peer->core_transmit =
5143             GNUNET_CORE_notify_transmit_ready(core_handle,
5144                                               0,
5145                                               0,
5146                                               GNUNET_TIME_UNIT_FOREVER_REL,
5147                                               &id,
5148                                               queue->size,
5149                                               &queue_send,
5150                                               peer);
5151     }
5152     else
5153     {
5154       if (NULL != peer->queue_head)
5155       {
5156         GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5157                     "*********   %s stalled\n",
5158                     GNUNET_i2s(&my_full_id));
5159         if (NULL == cinfo)
5160           cinfo = tunnel_get_neighbor_fc (t, &dst_id);
5161         cinfo->fc_poll = GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_SECONDS,
5162                                                      &tunnel_poll, cinfo);
5163       }
5164     }
5165     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   return %d\n", data_size);
5166     return data_size;
5167 }
5168
5169
5170 /**
5171  * @brief Queue and pass message to core when possible.
5172  * 
5173  * If type is payload (UNICAST, TO_ORIGIN, MULTICAST) checks for queue status
5174  * and accounts for it. In case the queue is full, the message is dropped and
5175  * a break issued.
5176  * 
5177  * Otherwise, message is treated as internal and allowed to go regardless of 
5178  * queue status.
5179  *
5180  * @param cls Closure (@c type dependant). It will be used by queue_send to
5181  *            build the message to be sent if not already prebuilt.
5182  * @param type Type of the message, 0 for a raw message.
5183  * @param size Size of the message.
5184  * @param dst Neighbor to send message to.
5185  * @param t Tunnel this message belongs to.
5186  */
5187 static void
5188 queue_add (void *cls, uint16_t type, size_t size,
5189            struct MeshPeerInfo *dst, struct MeshTunnel *t)
5190 {
5191   struct MeshPeerQueue *queue;
5192   struct MeshTunnelChildInfo *cinfo;
5193   struct GNUNET_PeerIdentity id;
5194   unsigned int *max;
5195   unsigned int *n;
5196   unsigned int i;
5197
5198   n = NULL;
5199   if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == type ||
5200       GNUNET_MESSAGE_TYPE_MESH_MULTICAST == type)
5201   {
5202     n = &t->fwd_queue_n;
5203     max = &t->fwd_queue_max;
5204   }
5205   else if (GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == type)
5206   {
5207     n = &t->bck_queue_n;
5208     max = &t->bck_queue_max;
5209   }
5210   if (NULL != n)
5211   {
5212     if (*n >= *max)
5213     {
5214       GNUNET_break(0);
5215       GNUNET_STATISTICS_update(stats,
5216                                "# messages dropped (buffer full)",
5217                                1, GNUNET_NO);
5218       return; // Drop message
5219     }
5220     (*n)++;
5221   }
5222   queue = GNUNET_malloc (sizeof (struct MeshPeerQueue));
5223   queue->cls = cls;
5224   queue->type = type;
5225   queue->size = size;
5226   queue->peer = dst;
5227   queue->tunnel = t;
5228   GNUNET_CONTAINER_DLL_insert_tail (dst->queue_head, dst->queue_tail, queue);
5229   GNUNET_PEER_resolve (dst->id, &id);
5230   if (NULL == dst->core_transmit)
5231   {
5232       dst->core_transmit =
5233           GNUNET_CORE_notify_transmit_ready (core_handle,
5234                                              0,
5235                                              0,
5236                                              GNUNET_TIME_UNIT_FOREVER_REL,
5237                                              &id,
5238                                              size,
5239                                              &queue_send,
5240                                              dst);
5241   }
5242   t->pending_messages++;
5243   if (NULL == n) // Is this internal mesh traffic?
5244     return;
5245
5246   // It's payload, keep track of buffer per peer.
5247   cinfo = tunnel_get_neighbor_fc(t, &id);
5248   i = (cinfo->send_buffer_start + cinfo->send_buffer_n) % t->fwd_queue_max;
5249   if (NULL != cinfo->send_buffer[i])
5250   {
5251     GNUNET_break (cinfo->send_buffer_n == t->fwd_queue_max); // aka i == start
5252     queue_destroy (cinfo->send_buffer[cinfo->send_buffer_start], GNUNET_YES);
5253     cinfo->send_buffer_start++;
5254     cinfo->send_buffer_start %= t->fwd_queue_max;
5255   }
5256   else
5257   {
5258     cinfo->send_buffer_n++;
5259   }
5260   cinfo->send_buffer[i] = queue;
5261   if (cinfo->send_buffer_n > t->fwd_queue_max)
5262   {
5263     GNUNET_break (0);
5264     cinfo->send_buffer_n = t->fwd_queue_max;
5265   }
5266 }
5267
5268
5269 /******************************************************************************/
5270 /********************      MESH NETWORK HANDLERS     **************************/
5271 /******************************************************************************/
5272
5273
5274 /**
5275  * Core handler for path creation
5276  *
5277  * @param cls closure
5278  * @param message message
5279  * @param peer peer identity this notification is about
5280  * @param atsi performance data
5281  * @param atsi_count number of records in 'atsi'
5282  *
5283  * @return GNUNET_OK to keep the connection open,
5284  *         GNUNET_SYSERR to close it (signal serious error)
5285  */
5286 static int
5287 handle_mesh_path_create (void *cls, const struct GNUNET_PeerIdentity *peer,
5288                          const struct GNUNET_MessageHeader *message,
5289                          const struct GNUNET_ATS_Information *atsi,
5290                          unsigned int atsi_count)
5291 {
5292   unsigned int own_pos;
5293   uint16_t size;
5294   uint16_t i;
5295   MESH_TunnelNumber tid;
5296   struct GNUNET_MESH_ManipulatePath *msg;
5297   struct GNUNET_PeerIdentity *pi;
5298   struct GNUNET_HashCode hash;
5299   struct MeshPeerPath *path;
5300   struct MeshPeerInfo *dest_peer_info;
5301   struct MeshPeerInfo *orig_peer_info;
5302   struct MeshTunnel *t;
5303
5304   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5305               "Received a path create msg [%s]\n",
5306               GNUNET_i2s (&my_full_id));
5307   size = ntohs (message->size);
5308   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
5309   {
5310     GNUNET_break_op (0);
5311     return GNUNET_OK;
5312   }
5313
5314   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
5315   if (size % sizeof (struct GNUNET_PeerIdentity))
5316   {
5317     GNUNET_break_op (0);
5318     return GNUNET_OK;
5319   }
5320   size /= sizeof (struct GNUNET_PeerIdentity);
5321   if (size < 2)
5322   {
5323     GNUNET_break_op (0);
5324     return GNUNET_OK;
5325   }
5326   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
5327   msg = (struct GNUNET_MESH_ManipulatePath *) message;
5328
5329   tid = ntohl (msg->tid);
5330   pi = (struct GNUNET_PeerIdentity *) &msg[1];
5331   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5332               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi), tid);
5333   t = tunnel_get (pi, tid);
5334   if (NULL == t) // FIXME only for INCOMING tunnels?
5335   {
5336     uint32_t opt;
5337
5338     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating tunnel\n");
5339     t = tunnel_new (GNUNET_PEER_intern (pi), tid, NULL, 0);
5340     if (NULL == t)
5341     {
5342       // FIXME notify failure
5343       return GNUNET_OK;
5344     }
5345     opt = ntohl (msg->opt);
5346     t->speed_min = (0 != (opt & MESH_TUNNEL_OPT_SPEED_MIN)) ?
5347                    GNUNET_YES : GNUNET_NO;
5348     if (0 != (opt & MESH_TUNNEL_OPT_NOBUFFER))
5349     {
5350       t->nobuffer = GNUNET_YES;
5351       t->last_fwd_ack = t->fwd_pid + 1;
5352     }
5353     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5354                 "  speed_min: %d, nobuffer:%d\n",
5355                 t->speed_min, t->nobuffer);
5356
5357     if (GNUNET_YES == t->nobuffer)
5358     {
5359       t->bck_queue_max = 1;
5360       t->fwd_queue_max = 1;
5361     }
5362
5363     // FIXME only assign a local tid if a local client is interested (on demand)
5364     while (NULL != tunnel_get_incoming (next_local_tid))
5365       next_local_tid = (next_local_tid + 1) | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
5366     t->local_tid_dest = next_local_tid++;
5367     next_local_tid = next_local_tid | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
5368     // FIXME end
5369
5370     tunnel_reset_timeout (t);
5371     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
5372     if (GNUNET_OK !=
5373         GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
5374                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
5375     {
5376       tunnel_destroy (t);
5377       GNUNET_break (0);
5378       return GNUNET_OK;
5379     }
5380   }
5381   dest_peer_info =
5382       GNUNET_CONTAINER_multihashmap_get (peers, &pi[size - 1].hashPubKey);
5383   if (NULL == dest_peer_info)
5384   {
5385     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5386                 "  Creating PeerInfo for destination.\n");
5387     dest_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
5388     dest_peer_info->id = GNUNET_PEER_intern (&pi[size - 1]);
5389     GNUNET_CONTAINER_multihashmap_put (peers, &pi[size - 1].hashPubKey,
5390                                        dest_peer_info,
5391                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
5392   }
5393   orig_peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &pi->hashPubKey);
5394   if (NULL == orig_peer_info)
5395   {
5396     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5397                 "  Creating PeerInfo for origin.\n");
5398     orig_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
5399     orig_peer_info->id = GNUNET_PEER_intern (pi);
5400     GNUNET_CONTAINER_multihashmap_put (peers, &pi->hashPubKey, orig_peer_info,
5401                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
5402   }
5403   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
5404   path = path_new (size);
5405   own_pos = 0;
5406   for (i = 0; i < size; i++)
5407   {
5408     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
5409                 GNUNET_i2s (&pi[i]));
5410     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
5411     if (path->peers[i] == myid)
5412       own_pos = i;
5413   }
5414   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
5415   if (own_pos == 0)
5416   {
5417     /* cannot be self, must be 'not found' */
5418     /* create path: self not found in path through self */
5419     GNUNET_break_op (0);
5420     path_destroy (path);
5421     tunnel_destroy (t);
5422     return GNUNET_OK;
5423   }
5424   path_add_to_peers (path, GNUNET_NO);
5425   tunnel_add_path (t, path, own_pos);
5426   if (own_pos == size - 1)
5427   {
5428     /* It is for us! Send ack. */
5429     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
5430     peer_info_add_path_to_origin (orig_peer_info, path, GNUNET_NO);
5431     if (NULL == t->peers)
5432     {
5433       /* New tunnel! Notify clients on first payload message. */
5434       t->peers = GNUNET_CONTAINER_multihashmap_create (4, GNUNET_NO);
5435     }
5436     GNUNET_break (GNUNET_SYSERR !=
5437                   GNUNET_CONTAINER_multihashmap_put (t->peers,
5438                                                      &my_full_id.hashPubKey,
5439                                                      peer_info_get
5440                                                      (&my_full_id),
5441                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE));
5442     send_path_ack (t);
5443   }
5444   else
5445   {
5446     struct MeshPeerPath *path2;
5447
5448     /* It's for somebody else! Retransmit. */
5449     path2 = path_duplicate (path);
5450     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Retransmitting.\n");
5451     peer_info_add_path (dest_peer_info, path2, GNUNET_NO);
5452     path2 = path_duplicate (path);
5453     peer_info_add_path_to_origin (orig_peer_info, path2, GNUNET_NO);
5454     send_create_path (dest_peer_info, path, t);
5455   }
5456   return GNUNET_OK;
5457 }
5458
5459
5460 /**
5461  * Core handler for path destruction
5462  *
5463  * @param cls closure
5464  * @param message message
5465  * @param peer peer identity this notification is about
5466  * @param atsi performance data
5467  * @param atsi_count number of records in 'atsi'
5468  *
5469  * @return GNUNET_OK to keep the connection open,
5470  *         GNUNET_SYSERR to close it (signal serious error)
5471  */
5472 static int
5473 handle_mesh_path_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
5474                           const struct GNUNET_MessageHeader *message,
5475                           const struct GNUNET_ATS_Information *atsi,
5476                           unsigned int atsi_count)
5477 {
5478   struct GNUNET_MESH_ManipulatePath *msg;
5479   struct GNUNET_PeerIdentity *pi;
5480   struct MeshPeerPath *path;
5481   struct MeshTunnel *t;
5482   unsigned int own_pos;
5483   unsigned int i;
5484   size_t size;
5485
5486   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5487               "Received a PATH DESTROY msg from %s\n", GNUNET_i2s (peer));
5488   size = ntohs (message->size);
5489   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
5490   {
5491     GNUNET_break_op (0);
5492     return GNUNET_OK;
5493   }
5494
5495   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
5496   if (size % sizeof (struct GNUNET_PeerIdentity))
5497   {
5498     GNUNET_break_op (0);
5499     return GNUNET_OK;
5500   }
5501   size /= sizeof (struct GNUNET_PeerIdentity);
5502   if (size < 2)
5503   {
5504     GNUNET_break_op (0);
5505     return GNUNET_OK;
5506   }
5507   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
5508
5509   msg = (struct GNUNET_MESH_ManipulatePath *) message;
5510   pi = (struct GNUNET_PeerIdentity *) &msg[1];
5511   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5512               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi),
5513               msg->tid);
5514   t = tunnel_get (pi, ntohl (msg->tid));
5515   if (NULL == t)
5516   {
5517     /* TODO notify back: we don't know this tunnel */
5518     GNUNET_break_op (0);
5519     return GNUNET_OK;
5520   }
5521   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
5522   path = path_new (size);
5523   own_pos = 0;
5524   for (i = 0; i < size; i++)
5525   {
5526     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
5527                 GNUNET_i2s (&pi[i]));
5528     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
5529     if (path->peers[i] == myid)
5530       own_pos = i;
5531   }
5532   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
5533   if (own_pos < path->length - 1)
5534     send_prebuilt_message (message, &pi[own_pos + 1], t);
5535   else
5536     send_client_tunnel_disconnect(t, NULL);
5537
5538   tunnel_delete_peer (t, path->peers[path->length - 1]);
5539   path_destroy (path);
5540   return GNUNET_OK;
5541 }
5542
5543
5544 /**
5545  * Core handler for notifications of broken paths
5546  *
5547  * @param cls closure
5548  * @param message message
5549  * @param peer peer identity this notification is about
5550  * @param atsi performance data
5551  * @param atsi_count number of records in 'atsi'
5552  *
5553  * @return GNUNET_OK to keep the connection open,
5554  *         GNUNET_SYSERR to close it (signal serious error)
5555  */
5556 static int
5557 handle_mesh_path_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
5558                          const struct GNUNET_MessageHeader *message,
5559                          const struct GNUNET_ATS_Information *atsi,
5560                          unsigned int atsi_count)
5561 {
5562   struct GNUNET_MESH_PathBroken *msg;
5563   struct MeshTunnel *t;
5564
5565   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5566               "Received a PATH BROKEN msg from %s\n", GNUNET_i2s (peer));
5567   msg = (struct GNUNET_MESH_PathBroken *) message;
5568   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
5569               GNUNET_i2s (&msg->peer1));
5570   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
5571               GNUNET_i2s (&msg->peer2));
5572   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5573   if (NULL == t)
5574   {
5575     GNUNET_break_op (0);
5576     return GNUNET_OK;
5577   }
5578   tunnel_notify_connection_broken (t, GNUNET_PEER_search (&msg->peer1),
5579                                    GNUNET_PEER_search (&msg->peer2));
5580   return GNUNET_OK;
5581
5582 }
5583
5584
5585 /**
5586  * Core handler for tunnel destruction
5587  *
5588  * @param cls closure
5589  * @param message message
5590  * @param peer peer identity this notification is about
5591  * @param atsi performance data
5592  * @param atsi_count number of records in 'atsi'
5593  *
5594  * @return GNUNET_OK to keep the connection open,
5595  *         GNUNET_SYSERR to close it (signal serious error)
5596  */
5597 static int
5598 handle_mesh_tunnel_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
5599                             const struct GNUNET_MessageHeader *message,
5600                             const struct GNUNET_ATS_Information *atsi,
5601                             unsigned int atsi_count)
5602 {
5603   struct GNUNET_MESH_TunnelDestroy *msg;
5604   struct MeshTunnel *t;
5605
5606   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5607               "Got a TUNNEL DESTROY packet from %s\n", GNUNET_i2s (peer));
5608   msg = (struct GNUNET_MESH_TunnelDestroy *) message;
5609   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for tunnel %s [%u]\n",
5610               GNUNET_i2s (&msg->oid), ntohl (msg->tid));
5611   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5612   if (NULL == t)
5613   {
5614     /* Probably already got the message from another path,
5615      * destroyed the tunnel and retransmitted to children.
5616      * Safe to ignore.
5617      */
5618     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel", 1, GNUNET_NO);
5619     return GNUNET_OK;
5620   }
5621   if (t->id.oid == myid)
5622   {
5623     GNUNET_break_op (0);
5624     return GNUNET_OK;
5625   }
5626   if (t->local_tid_dest >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
5627   {
5628     /* Tunnel was incoming, notify clients */
5629     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "INCOMING TUNNEL %X %X\n",
5630                 t->local_tid, t->local_tid_dest);
5631     send_clients_tunnel_destroy (t);
5632   }
5633   tunnel_send_destroy (t);
5634   t->destroy = GNUNET_YES;
5635   // TODO: add timeout to destroy the tunnel anyway
5636   return GNUNET_OK;
5637 }
5638
5639
5640 /**
5641  * Core handler for mesh network traffic going from the origin to a peer
5642  *
5643  * @param cls closure
5644  * @param peer peer identity this notification is about
5645  * @param message message
5646  * @param atsi performance data
5647  * @param atsi_count number of records in 'atsi'
5648  * @return GNUNET_OK to keep the connection open,
5649  *         GNUNET_SYSERR to close it (signal serious error)
5650  */
5651 static int
5652 handle_mesh_data_unicast (void *cls, const struct GNUNET_PeerIdentity *peer,
5653                           const struct GNUNET_MessageHeader *message,
5654                           const struct GNUNET_ATS_Information *atsi,
5655                           unsigned int atsi_count)
5656 {
5657   struct GNUNET_MESH_Unicast *msg;
5658   struct GNUNET_PeerIdentity *neighbor;
5659   struct MeshTunnelChildInfo *cinfo;
5660   struct MeshTunnel *t;
5661   GNUNET_PEER_Id dest_id;
5662   uint32_t pid;
5663   uint32_t ttl;
5664   size_t size;
5665
5666   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a unicast packet from %s\n",
5667               GNUNET_i2s (peer));
5668   /* Check size */
5669   size = ntohs (message->size);
5670   if (size <
5671       sizeof (struct GNUNET_MESH_Unicast) +
5672       sizeof (struct GNUNET_MessageHeader))
5673   {
5674     GNUNET_break (0);
5675     return GNUNET_OK;
5676   }
5677   msg = (struct GNUNET_MESH_Unicast *) message;
5678   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %s\n",
5679               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
5680   /* Check tunnel */
5681   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5682   if (NULL == t)
5683   {
5684     /* TODO notify back: we don't know this tunnel */
5685     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
5686     GNUNET_break_op (0);
5687     return GNUNET_OK;
5688   }
5689   pid = ntohl (msg->pid);
5690   if (t->fwd_pid == pid)
5691   {
5692     GNUNET_STATISTICS_update (stats, "# duplicate PID drops", 1, GNUNET_NO);
5693     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5694                 " Already seen pid %u, DROPPING!\n", pid);
5695     return GNUNET_OK;
5696   }
5697   else
5698   {
5699     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5700                 " pid %u not seen yet, forwarding\n", pid);
5701   }
5702
5703   t->skip += (pid - t->fwd_pid) - 1;
5704   t->fwd_pid = pid;
5705
5706   if (GMC_is_pid_bigger (pid, t->last_fwd_ack))
5707   {
5708     GNUNET_STATISTICS_update (stats, "# unsolicited unicast", 1, GNUNET_NO);
5709     GNUNET_break_op (0);
5710     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5711                 "Received PID %u, ACK %u\n",
5712                 pid, t->last_fwd_ack);
5713     return GNUNET_OK;
5714   }
5715
5716   tunnel_reset_timeout (t);
5717   dest_id = GNUNET_PEER_search (&msg->destination);
5718   if (dest_id == myid)
5719   {
5720     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5721                 "  it's for us! sending to clients...\n");
5722     GNUNET_STATISTICS_update (stats, "# unicast received", 1, GNUNET_NO);
5723     send_subscribed_clients (message, &msg[1].header, t);
5724     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_UNICAST);
5725     return GNUNET_OK;
5726   }
5727   ttl = ntohl (msg->ttl);
5728   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ttl);
5729   if (ttl == 0)
5730   {
5731     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
5732     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
5733     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5734     return GNUNET_OK;
5735   }
5736   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5737               "  not for us, retransmitting...\n");
5738
5739   neighbor = tree_get_first_hop (t->tree, dest_id);
5740   cinfo = tunnel_get_neighbor_fc (t, neighbor);
5741   cinfo->fwd_pid = pid;
5742   GNUNET_CONTAINER_multihashmap_iterate (t->children_fc,
5743                                          &tunnel_add_skip,
5744                                          &neighbor);
5745   if (GNUNET_YES == t->nobuffer &&
5746       GNUNET_YES == GMC_is_pid_bigger (pid, cinfo->fwd_ack))
5747   {
5748     GNUNET_STATISTICS_update (stats, "# unsolicited unicast", 1, GNUNET_NO);
5749     GNUNET_log (GNUNET_ERROR_TYPE_INFO, "  %u > %u\n", pid, cinfo->fwd_ack);
5750     GNUNET_break_op (0);
5751     return GNUNET_OK;
5752   }
5753   send_prebuilt_message (message, neighbor, t);
5754   GNUNET_STATISTICS_update (stats, "# unicast forwarded", 1, GNUNET_NO);
5755   return GNUNET_OK;
5756 }
5757
5758
5759 /**
5760  * Core handler for mesh network traffic going from the origin to all peers
5761  *
5762  * @param cls closure
5763  * @param message message
5764  * @param peer peer identity this notification is about
5765  * @param atsi performance data
5766  * @param atsi_count number of records in 'atsi'
5767  * @return GNUNET_OK to keep the connection open,
5768  *         GNUNET_SYSERR to close it (signal serious error)
5769  *
5770  * TODO: Check who we got this from, to validate route.
5771  */
5772 static int
5773 handle_mesh_data_multicast (void *cls, const struct GNUNET_PeerIdentity *peer,
5774                             const struct GNUNET_MessageHeader *message,
5775                             const struct GNUNET_ATS_Information *atsi,
5776                             unsigned int atsi_count)
5777 {
5778   struct GNUNET_MESH_Multicast *msg;
5779   struct MeshTunnel *t;
5780   size_t size;
5781   uint32_t pid;
5782
5783   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a multicast packet from %s\n",
5784               GNUNET_i2s (peer));
5785   size = ntohs (message->size);
5786   if (sizeof (struct GNUNET_MESH_Multicast) +
5787       sizeof (struct GNUNET_MessageHeader) > size)
5788   {
5789     GNUNET_break_op (0);
5790     return GNUNET_OK;
5791   }
5792   msg = (struct GNUNET_MESH_Multicast *) message;
5793   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5794
5795   if (NULL == t)
5796   {
5797     /* TODO notify that we dont know that tunnel */
5798     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
5799     GNUNET_break_op (0);
5800     return GNUNET_OK;
5801   }
5802   pid = ntohl (msg->pid);
5803   if (t->fwd_pid == pid)
5804   {
5805     /* already seen this packet, drop */
5806     GNUNET_STATISTICS_update (stats, "# duplicate PID drops", 1, GNUNET_NO);
5807     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5808                 " Already seen pid %u, DROPPING!\n", pid);
5809     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5810     return GNUNET_OK;
5811   }
5812   else
5813   {
5814     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5815                 " pid %u not seen yet, forwarding\n", pid);
5816   }
5817   t->skip += (pid - t->fwd_pid) - 1;
5818   t->fwd_pid = pid;
5819   tunnel_reset_timeout (t);
5820
5821   /* Transmit to locally interested clients */
5822   if (NULL != t->peers &&
5823       GNUNET_CONTAINER_multihashmap_contains (t->peers, &my_full_id.hashPubKey))
5824   {
5825     GNUNET_STATISTICS_update (stats, "# multicast received", 1, GNUNET_NO);
5826     send_subscribed_clients (message, &msg[1].header, t);
5827     tunnel_send_fwd_ack(t, GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
5828   }
5829   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ntohl (msg->ttl));
5830   if (ntohl (msg->ttl) == 0)
5831   {
5832     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
5833     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
5834     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5835     return GNUNET_OK;
5836   }
5837   GNUNET_STATISTICS_update (stats, "# multicast forwarded", 1, GNUNET_NO);
5838   tunnel_send_multicast (t, message);
5839   return GNUNET_OK;
5840 }
5841
5842
5843 /**
5844  * Core handler for mesh network traffic toward the owner of a tunnel
5845  *
5846  * @param cls closure
5847  * @param message message
5848  * @param peer peer identity this notification is about
5849  * @param atsi performance data
5850  * @param atsi_count number of records in 'atsi'
5851  *
5852  * @return GNUNET_OK to keep the connection open,
5853  *         GNUNET_SYSERR to close it (signal serious error)
5854  */
5855 static int
5856 handle_mesh_data_to_orig (void *cls, const struct GNUNET_PeerIdentity *peer,
5857                           const struct GNUNET_MessageHeader *message,
5858                           const struct GNUNET_ATS_Information *atsi,
5859                           unsigned int atsi_count)
5860 {
5861   struct GNUNET_MESH_ToOrigin *msg;
5862   struct GNUNET_PeerIdentity id;
5863   struct MeshPeerInfo *peer_info;
5864   struct MeshTunnel *t;
5865   struct MeshTunnelChildInfo *cinfo;
5866   size_t size;
5867   uint32_t pid;
5868
5869   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a ToOrigin packet from %s\n",
5870               GNUNET_i2s (peer));
5871   size = ntohs (message->size);
5872   if (size < sizeof (struct GNUNET_MESH_ToOrigin) +     /* Payload must be */
5873       sizeof (struct GNUNET_MessageHeader))     /* at least a header */
5874   {
5875     GNUNET_break_op (0);
5876     return GNUNET_OK;
5877   }
5878   msg = (struct GNUNET_MESH_ToOrigin *) message;
5879   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %s\n",
5880               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
5881   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5882   pid = ntohl (msg->pid);
5883
5884   if (NULL == t)
5885   {
5886     /* TODO notify that we dont know this tunnel (whom)? */
5887     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
5888     GNUNET_break_op (0);
5889     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5890                 "Received to_origin with PID %u on unknown tunnel\n",
5891                 pid);
5892     return GNUNET_OK;
5893   }
5894
5895   cinfo = tunnel_get_neighbor_fc(t, peer);
5896   if (NULL == cinfo)
5897   {
5898     GNUNET_break (0);
5899     return GNUNET_OK;
5900   }
5901
5902   if (cinfo->bck_pid == pid)
5903   {
5904     /* already seen this packet, drop */
5905     GNUNET_STATISTICS_update (stats, "# duplicate PID drops BCK", 1, GNUNET_NO);
5906     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5907                 " Already seen pid %u, DROPPING!\n", pid);
5908     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5909     return GNUNET_OK;
5910   }
5911
5912   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5913               " pid %u not seen yet, forwarding\n", pid);
5914   cinfo->bck_pid = pid;
5915
5916   if (NULL != t->owner)
5917   {
5918     char cbuf[size];
5919     struct GNUNET_MESH_ToOrigin *copy;
5920
5921     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5922                 "  it's for us! sending to clients...\n");
5923     /* TODO signature verification */
5924     memcpy (cbuf, message, size);
5925     copy = (struct GNUNET_MESH_ToOrigin *) cbuf;
5926     copy->tid = htonl (t->local_tid);
5927     t->bck_pid++;
5928     copy->pid = htonl (t->bck_pid);
5929     GNUNET_STATISTICS_update (stats, "# to origin received", 1, GNUNET_NO);
5930     GNUNET_SERVER_notification_context_unicast (nc, t->owner->handle,
5931                                                 &copy->header, GNUNET_NO);
5932     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
5933     return GNUNET_OK;
5934   }
5935   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5936               "  not for us, retransmitting...\n");
5937
5938   peer_info = peer_info_get (&msg->oid);
5939   if (NULL == peer_info)
5940   {
5941     /* unknown origin of tunnel */
5942     GNUNET_break (0);
5943     return GNUNET_OK;
5944   }
5945   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
5946   send_prebuilt_message (message, &id, t);
5947   GNUNET_STATISTICS_update (stats, "# to origin forwarded", 1, GNUNET_NO);
5948
5949   return GNUNET_OK;
5950 }
5951
5952
5953 /**
5954  * Core handler for mesh network traffic point-to-point acks.
5955  *
5956  * @param cls closure
5957  * @param message message
5958  * @param peer peer identity this notification is about
5959  * @param atsi performance data
5960  * @param atsi_count number of records in 'atsi'
5961  *
5962  * @return GNUNET_OK to keep the connection open,
5963  *         GNUNET_SYSERR to close it (signal serious error)
5964  */
5965 static int
5966 handle_mesh_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5967                  const struct GNUNET_MessageHeader *message,
5968                  const struct GNUNET_ATS_Information *atsi,
5969                  unsigned int atsi_count)
5970 {
5971   struct GNUNET_MESH_ACK *msg;
5972   struct MeshTunnel *t;
5973   uint32_t ack;
5974
5975   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK packet from %s!\n",
5976               GNUNET_i2s (peer));
5977   msg = (struct GNUNET_MESH_ACK *) message;
5978
5979   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5980
5981   if (NULL == t)
5982   {
5983     /* TODO notify that we dont know this tunnel (whom)? */
5984     GNUNET_STATISTICS_update (stats, "# ack on unknown tunnel", 1, GNUNET_NO);
5985     GNUNET_break_op (0);
5986     return GNUNET_OK;
5987   }
5988   ack = ntohl (msg->pid);
5989   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ACK %u\n", ack);
5990
5991   /* Is this a forward or backward ACK? */
5992   if (tree_get_predecessor(t->tree) != GNUNET_PEER_search(peer))
5993   {
5994     struct MeshTunnelChildInfo *cinfo;
5995
5996     debug_bck_ack++;
5997     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
5998     cinfo = tunnel_get_neighbor_fc (t, peer);
5999     cinfo->fwd_ack = ack;
6000     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
6001     tunnel_unlock_fwd_queues (t);
6002   }
6003   else
6004   {
6005     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
6006     t->bck_ack = ack;
6007     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
6008     tunnel_unlock_bck_queue (t);
6009   }
6010   return GNUNET_OK;
6011 }
6012
6013
6014 /**
6015  * Core handler for mesh network traffic point-to-point ack polls.
6016  *
6017  * @param cls closure
6018  * @param message message
6019  * @param peer peer identity this notification is about
6020  * @param atsi performance data
6021  * @param atsi_count number of records in 'atsi'
6022  *
6023  * @return GNUNET_OK to keep the connection open,
6024  *         GNUNET_SYSERR to close it (signal serious error)
6025  */
6026 static int
6027 handle_mesh_poll (void *cls, const struct GNUNET_PeerIdentity *peer,
6028                   const struct GNUNET_MessageHeader *message,
6029                   const struct GNUNET_ATS_Information *atsi,
6030                   unsigned int atsi_count)
6031 {
6032   struct GNUNET_MESH_Poll *msg;
6033   struct MeshTunnel *t;
6034
6035   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an POLL packet from %s!\n",
6036               GNUNET_i2s (peer));
6037
6038   msg = (struct GNUNET_MESH_Poll *) message;
6039
6040   t = tunnel_get (&msg->oid, ntohl (msg->tid));
6041
6042   if (NULL == t)
6043   {
6044     /* TODO notify that we dont know this tunnel (whom)? */
6045     GNUNET_STATISTICS_update (stats, "# poll on unknown tunnel", 1, GNUNET_NO);
6046     GNUNET_break_op (0);
6047     return GNUNET_OK;
6048   }
6049
6050   /* Is this a forward or backward ACK? */
6051   if (tree_get_predecessor(t->tree) != GNUNET_PEER_search(peer))
6052   {
6053     struct MeshTunnelChildInfo *cinfo;
6054
6055     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  from FWD\n");
6056     cinfo = tunnel_get_neighbor_fc (t, peer);
6057     cinfo->bck_ack = cinfo->fwd_pid; // mark as ready to send
6058     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_POLL);
6059   }
6060   else
6061   {
6062     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  from BCK\n");
6063     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_POLL);
6064   }
6065
6066   return GNUNET_OK;
6067 }
6068
6069
6070 /**
6071  * Core handler for path ACKs
6072  *
6073  * @param cls closure
6074  * @param message message
6075  * @param peer peer identity this notification is about
6076  * @param atsi performance data
6077  * @param atsi_count number of records in 'atsi'
6078  *
6079  * @return GNUNET_OK to keep the connection open,
6080  *         GNUNET_SYSERR to close it (signal serious error)
6081  */
6082 static int
6083 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
6084                       const struct GNUNET_MessageHeader *message,
6085                       const struct GNUNET_ATS_Information *atsi,
6086                       unsigned int atsi_count)
6087 {
6088   struct GNUNET_MESH_PathACK *msg;
6089   struct GNUNET_PeerIdentity id;
6090   struct MeshPeerInfo *peer_info;
6091   struct MeshPeerPath *p;
6092   struct MeshTunnel *t;
6093
6094   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a path ACK msg [%s]\n",
6095               GNUNET_i2s (&my_full_id));
6096   msg = (struct GNUNET_MESH_PathACK *) message;
6097   t = tunnel_get (&msg->oid, ntohl(msg->tid));
6098   if (NULL == t)
6099   {
6100     /* TODO notify that we don't know the tunnel */
6101     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel", 1, GNUNET_NO);
6102     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  don't know the tunnel %s [%X]!\n",
6103                 GNUNET_i2s (&msg->oid), ntohl(msg->tid));
6104     return GNUNET_OK;
6105   }
6106   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %s [%X]\n",
6107               GNUNET_i2s (&msg->oid), ntohl(msg->tid));
6108
6109   peer_info = peer_info_get (&msg->peer_id);
6110   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by peer %s\n",
6111               GNUNET_i2s (&msg->peer_id));
6112   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  via peer %s\n",
6113               GNUNET_i2s (peer));
6114
6115   if (NULL != t->regex_ctx && t->regex_ctx->info->peer == peer_info->id)
6116   {
6117     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6118                 "connect_by_string completed, stopping search\n");
6119     regex_cancel_search (t->regex_ctx);
6120     t->regex_ctx = NULL;
6121   }
6122
6123   /* Add paths to peers? */
6124   p = tree_get_path_to_peer (t->tree, peer_info->id);
6125   if (NULL != p)
6126   {
6127     path_add_to_peers (p, GNUNET_YES);
6128     path_destroy (p);
6129   }
6130   else
6131   {
6132     GNUNET_break (0);
6133   }
6134
6135   /* Message for us? */
6136   if (0 == memcmp (&msg->oid, &my_full_id, sizeof (struct GNUNET_PeerIdentity)))
6137   {
6138     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
6139     if (NULL == t->owner)
6140     {
6141       GNUNET_break_op (0);
6142       return GNUNET_OK;
6143     }
6144     if (NULL != t->dht_get_type)
6145     {
6146       GNUNET_DHT_get_stop (t->dht_get_type);
6147       t->dht_get_type = NULL;
6148     }
6149     if (tree_get_status (t->tree, peer_info->id) != MESH_PEER_READY)
6150     {
6151       tree_set_status (t->tree, peer_info->id, MESH_PEER_READY);
6152       send_client_peer_connected (t, peer_info->id);
6153     }
6154     return GNUNET_OK;
6155   }
6156
6157   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6158               "  not for us, retransmitting...\n");
6159   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
6160   peer_info = peer_info_get (&msg->oid);
6161   if (NULL == peer_info)
6162   {
6163     /* If we know the tunnel, we should DEFINITELY know the peer */
6164     GNUNET_break (0);
6165     return GNUNET_OK;
6166   }
6167   send_prebuilt_message (message, &id, t);
6168   return GNUNET_OK;
6169 }
6170
6171
6172 /**
6173  * Core handler for mesh keepalives.
6174  *
6175  * @param cls closure
6176  * @param message message
6177  * @param peer peer identity this notification is about
6178  * @param atsi performance data
6179  * @param atsi_count number of records in 'atsi'
6180  * @return GNUNET_OK to keep the connection open,
6181  *         GNUNET_SYSERR to close it (signal serious error)
6182  *
6183  * TODO: Check who we got this from, to validate route.
6184  */
6185 static int
6186 handle_mesh_keepalive (void *cls, const struct GNUNET_PeerIdentity *peer,
6187                        const struct GNUNET_MessageHeader *message,
6188                        const struct GNUNET_ATS_Information *atsi,
6189                        unsigned int atsi_count)
6190 {
6191   struct GNUNET_MESH_TunnelKeepAlive *msg;
6192   struct MeshTunnel *t;
6193
6194   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a keepalive packet from %s\n",
6195               GNUNET_i2s (peer));
6196
6197   msg = (struct GNUNET_MESH_TunnelKeepAlive *) message;
6198   t = tunnel_get (&msg->oid, ntohl (msg->tid));
6199
6200   if (NULL == t)
6201   {
6202     /* TODO notify that we dont know that tunnel */
6203     GNUNET_STATISTICS_update (stats, "# keepalive on unknown tunnel", 1, GNUNET_NO);
6204     GNUNET_break_op (0);
6205     return GNUNET_OK;
6206   }
6207
6208   tunnel_reset_timeout (t);
6209
6210   GNUNET_STATISTICS_update (stats, "# keepalives forwarded", 1, GNUNET_NO);
6211   tunnel_send_multicast (t, message);
6212   return GNUNET_OK;
6213   }
6214
6215
6216
6217 /**
6218  * Functions to handle messages from core
6219  */
6220 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
6221   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
6222   {&handle_mesh_path_destroy, GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY, 0},
6223   {&handle_mesh_path_broken, GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN,
6224    sizeof (struct GNUNET_MESH_PathBroken)},
6225   {&handle_mesh_tunnel_destroy, GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY,
6226    sizeof (struct GNUNET_MESH_TunnelDestroy)},
6227   {&handle_mesh_data_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
6228   {&handle_mesh_data_multicast, GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
6229   {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE,
6230     sizeof (struct GNUNET_MESH_TunnelKeepAlive)},
6231   {&handle_mesh_data_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
6232   {&handle_mesh_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
6233     sizeof (struct GNUNET_MESH_ACK)},
6234   {&handle_mesh_poll, GNUNET_MESSAGE_TYPE_MESH_POLL,
6235     sizeof (struct GNUNET_MESH_Poll)},
6236   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
6237    sizeof (struct GNUNET_MESH_PathACK)},
6238   {NULL, 0, 0}
6239 };
6240
6241
6242
6243 /******************************************************************************/
6244 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
6245 /******************************************************************************/
6246
6247 /**
6248  * deregister_app: iterator for removing each application registered by a client
6249  *
6250  * @param cls closure
6251  * @param key the hash of the application id (used to access the hashmap)
6252  * @param value the value stored at the key (client)
6253  *
6254  * @return GNUNET_OK on success
6255  */
6256 static int
6257 deregister_app (void *cls, const struct GNUNET_HashCode * key, void *value)
6258 {
6259   struct GNUNET_CONTAINER_MultiHashMap *h = cls;
6260   GNUNET_break (GNUNET_YES ==
6261                 GNUNET_CONTAINER_multihashmap_remove (h, key, value));
6262   return GNUNET_OK;
6263 }
6264
6265 #if LATER
6266 /**
6267  * notify_client_connection_failure: notify a client that the connection to the
6268  * requested remote peer is not possible (for instance, no route found)
6269  * Function called when the socket is ready to queue more data. "buf" will be
6270  * NULL and "size" zero if the socket was closed for writing in the meantime.
6271  *
6272  * @param cls closure
6273  * @param size number of bytes available in buf
6274  * @param buf where the callee should write the message
6275  * @return number of bytes written to buf
6276  */
6277 static size_t
6278 notify_client_connection_failure (void *cls, size_t size, void *buf)
6279 {
6280   int size_needed;
6281   struct MeshPeerInfo *peer_info;
6282   struct GNUNET_MESH_PeerControl *msg;
6283   struct GNUNET_PeerIdentity id;
6284
6285   if (0 == size && NULL == buf)
6286   {
6287     // TODO retry? cancel?
6288     return 0;
6289   }
6290
6291   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
6292   peer_info = (struct MeshPeerInfo *) cls;
6293   msg = (struct GNUNET_MESH_PeerControl *) buf;
6294   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
6295   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
6296 //     msg->tunnel_id = htonl(peer_info->t->tid);
6297   GNUNET_PEER_resolve (peer_info->id, &id);
6298   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
6299
6300   return size_needed;
6301 }
6302 #endif
6303
6304
6305 /**
6306  * Send keepalive packets for a peer
6307  *
6308  * @param cls Closure (tunnel for which to send the keepalive).
6309  * @param tc Notification context.
6310  */
6311 static void
6312 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
6313 {
6314   struct MeshTunnel *t = cls;
6315   struct GNUNET_MESH_TunnelKeepAlive *msg;
6316   size_t size = sizeof (struct GNUNET_MESH_TunnelKeepAlive);
6317   char cbuf[size];
6318
6319   t->path_refresh_task = GNUNET_SCHEDULER_NO_TASK;
6320   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
6321   {
6322     return;
6323   }
6324
6325   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6326               "sending keepalive for tunnel %d\n", t->id.tid);
6327
6328   msg = (struct GNUNET_MESH_TunnelKeepAlive *) cbuf;
6329   msg->header.size = htons (size);
6330   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE);
6331   msg->oid = my_full_id;
6332   msg->tid = htonl (t->id.tid);
6333   tunnel_send_multicast (t, &msg->header);
6334
6335   t->path_refresh_task =
6336       GNUNET_SCHEDULER_add_delayed (refresh_path_time, &path_refresh, t);
6337   tunnel_reset_timeout(t);
6338 }
6339
6340
6341 /**
6342  * Function to process paths received for a new peer addition. The recorded
6343  * paths form the initial tunnel, which can be optimized later.
6344  * Called on each result obtained for the DHT search.
6345  *
6346  * @param cls closure
6347  * @param exp when will this value expire
6348  * @param key key of the result
6349  * @param get_path path of the get request
6350  * @param get_path_length lenght of get_path
6351  * @param put_path path of the put request
6352  * @param put_path_length length of the put_path
6353  * @param type type of the result
6354  * @param size number of bytes in data
6355  * @param data pointer to the result data
6356  *
6357  * TODO: re-issue the request after certain time? cancel after X results?
6358  */
6359 static void
6360 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
6361                     const struct GNUNET_HashCode * key,
6362                     const struct GNUNET_PeerIdentity *get_path,
6363                     unsigned int get_path_length,
6364                     const struct GNUNET_PeerIdentity *put_path,
6365                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
6366                     size_t size, const void *data)
6367 {
6368   struct MeshPathInfo *path_info = cls;
6369   struct MeshPeerPath *p;
6370   struct GNUNET_PeerIdentity pi;
6371   int i;
6372
6373   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
6374   GNUNET_PEER_resolve (path_info->peer->id, &pi);
6375   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", GNUNET_i2s (&pi));
6376
6377   p = path_build_from_dht (get_path, get_path_length, put_path,
6378                            put_path_length);
6379   path_add_to_peers (p, GNUNET_NO);
6380   path_destroy(p);
6381   for (i = 0; i < path_info->peer->ntunnels; i++)
6382   {
6383     tunnel_add_peer (path_info->peer->tunnels[i], path_info->peer);
6384     peer_info_connect (path_info->peer, path_info->t);
6385   }
6386
6387   return;
6388 }
6389
6390
6391 /**
6392  * Function to process paths received for a new peer addition. The recorded
6393  * paths form the initial tunnel, which can be optimized later.
6394  * Called on each result obtained for the DHT search.
6395  *
6396  * @param cls closure
6397  * @param exp when will this value expire
6398  * @param key key of the result
6399  * @param get_path path of the get request
6400  * @param get_path_length lenght of get_path
6401  * @param put_path path of the put request
6402  * @param put_path_length length of the put_path
6403  * @param type type of the result
6404  * @param size number of bytes in data
6405  * @param data pointer to the result data
6406  */
6407 static void
6408 dht_get_type_handler (void *cls, struct GNUNET_TIME_Absolute exp,
6409                       const struct GNUNET_HashCode * key,
6410                       const struct GNUNET_PeerIdentity *get_path,
6411                       unsigned int get_path_length,
6412                       const struct GNUNET_PeerIdentity *put_path,
6413                       unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
6414                       size_t size, const void *data)
6415 {
6416   const struct PBlock *pb = data;
6417   const struct GNUNET_PeerIdentity *pi = &pb->id;
6418   struct MeshTunnel *t = cls;
6419   struct MeshPeerInfo *peer_info;
6420   struct MeshPeerPath *p;
6421
6422   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got type DHT result!\n");
6423   if (size != sizeof (struct PBlock))
6424   {
6425     GNUNET_break_op (0);
6426     return;
6427   }
6428   if (ntohl(pb->type) != t->type)
6429   {
6430     GNUNET_break_op (0);
6431     return;
6432   }
6433   GNUNET_assert (NULL != t->owner);
6434   peer_info = peer_info_get (pi);
6435   (void) GNUNET_CONTAINER_multihashmap_put (t->peers, &pi->hashPubKey,
6436                                             peer_info,
6437                                             GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
6438
6439   p = path_build_from_dht (get_path, get_path_length, put_path,
6440                            put_path_length);
6441   path_add_to_peers (p, GNUNET_NO);
6442   path_destroy(p);
6443   tunnel_add_peer (t, peer_info);
6444   peer_info_connect (peer_info, t);
6445 }
6446
6447
6448 /**
6449  * Function to process DHT string to regex matching.
6450  * Called on each result obtained for the DHT search.
6451  *
6452  * @param cls closure (search context)
6453  * @param exp when will this value expire
6454  * @param key key of the result
6455  * @param get_path path of the get request (not used)
6456  * @param get_path_length lenght of get_path (not used)
6457  * @param put_path path of the put request (not used)
6458  * @param put_path_length length of the put_path (not used)
6459  * @param type type of the result
6460  * @param size number of bytes in data
6461  * @param data pointer to the result data
6462  */
6463 static void
6464 dht_get_string_accept_handler (void *cls, struct GNUNET_TIME_Absolute exp,
6465                                const struct GNUNET_HashCode * key,
6466                                const struct GNUNET_PeerIdentity *get_path,
6467                                unsigned int get_path_length,
6468                                const struct GNUNET_PeerIdentity *put_path,
6469                                unsigned int put_path_length,
6470                                enum GNUNET_BLOCK_Type type,
6471                                size_t size, const void *data)
6472 {
6473   const struct MeshRegexAccept *block = data;
6474   struct MeshRegexSearchContext *ctx = cls;
6475   struct MeshRegexSearchInfo *info = ctx->info;
6476   struct MeshPeerPath *p;
6477   struct MeshPeerInfo *peer_info;
6478
6479   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got regex results from DHT!\n");
6480   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", info->description);
6481
6482   peer_info = peer_info_get(&block->id);
6483   p = path_build_from_dht (get_path, get_path_length, put_path,
6484                            put_path_length);
6485   path_add_to_peers (p, GNUNET_NO);
6486   path_destroy(p);
6487
6488   tunnel_add_peer (info->t, peer_info);
6489   peer_info_connect (peer_info, info->t);
6490   if (0 == info->peer)
6491   {
6492     info->peer = peer_info->id;
6493   }
6494   else
6495   {
6496     GNUNET_array_append (info->peers, info->n_peers, peer_info->id);
6497   }
6498
6499   info->timeout = GNUNET_SCHEDULER_add_delayed (connect_timeout,
6500                                                 &regex_connect_timeout,
6501                                                 info);
6502
6503   return;
6504 }
6505
6506
6507 /**
6508  * Function to process DHT string to regex matching.
6509  * Called on each result obtained for the DHT search.
6510  *
6511  * @param cls closure (search context)
6512  * @param exp when will this value expire
6513  * @param key key of the result
6514  * @param get_path path of the get request (not used)
6515  * @param get_path_length lenght of get_path (not used)
6516  * @param put_path path of the put request (not used)
6517  * @param put_path_length length of the put_path (not used)
6518  * @param type type of the result
6519  * @param size number of bytes in data
6520  * @param data pointer to the result data
6521  *
6522  * TODO: re-issue the request after certain time? cancel after X results?
6523  */
6524 static void
6525 dht_get_string_handler (void *cls, struct GNUNET_TIME_Absolute exp,
6526                         const struct GNUNET_HashCode * key,
6527                         const struct GNUNET_PeerIdentity *get_path,
6528                         unsigned int get_path_length,
6529                         const struct GNUNET_PeerIdentity *put_path,
6530                         unsigned int put_path_length,
6531                         enum GNUNET_BLOCK_Type type,
6532                         size_t size, const void *data)
6533 {
6534   const struct MeshRegexBlock *block = data;
6535   struct MeshRegexSearchContext *ctx = cls;
6536   struct MeshRegexSearchInfo *info = ctx->info;
6537   void *copy;
6538   size_t len;
6539
6540   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6541               "DHT GET STRING RETURNED RESULTS\n");
6542   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6543               "  key: %s\n", GNUNET_h2s (key));
6544
6545   copy = GNUNET_malloc (size);
6546   memcpy (copy, data, size);
6547   GNUNET_break (GNUNET_OK ==
6548                 GNUNET_CONTAINER_multihashmap_put(info->dht_get_results, key, copy,
6549                                                   GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
6550   len = ntohl (block->n_proof);
6551   {
6552     char proof[len + 1];
6553
6554     memcpy (proof, &block[1], len);
6555     proof[len] = '\0';
6556     if (GNUNET_OK != GNUNET_REGEX_check_proof (proof, key))
6557     {
6558       GNUNET_break_op (0);
6559       return;
6560     }
6561   }
6562   len = strlen (info->description);
6563   if (len == ctx->position) // String processed
6564   {
6565     if (GNUNET_YES == ntohl (block->accepting))
6566     {
6567       regex_find_path(key, ctx);
6568     }
6569     else
6570     {
6571       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  block not accepting!\n");
6572       // FIXME REGEX this block not successful, wait for more? start timeout?
6573     }
6574     return;
6575   }
6576
6577   regex_next_edge (block, size, ctx);
6578
6579   return;
6580 }
6581
6582 /******************************************************************************/
6583 /*********************       MESH LOCAL HANDLES      **************************/
6584 /******************************************************************************/
6585
6586
6587 /**
6588  * Handler for client disconnection
6589  *
6590  * @param cls closure
6591  * @param client identification of the client; NULL
6592  *        for the last call when the server is destroyed
6593  */
6594 static void
6595 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
6596 {
6597   struct MeshClient *c;
6598   struct MeshClient *next;
6599   unsigned int i;
6600
6601   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected\n");
6602   if (client == NULL)
6603   {
6604     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (SERVER DOWN)\n");
6605     return;
6606   }
6607
6608 //   return; uncomment for regex_profiler
6609   c = clients;
6610   while (NULL != c)
6611   {
6612     if (c->handle != client)
6613     {
6614       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ... searching\n");
6615       c = c->next;
6616       continue;
6617     }
6618     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u)\n",
6619                 c->id);
6620     GNUNET_SERVER_client_drop (c->handle);
6621     c->shutting_down = GNUNET_YES;
6622     GNUNET_assert (NULL != c->own_tunnels);
6623     GNUNET_assert (NULL != c->incoming_tunnels);
6624     GNUNET_CONTAINER_multihashmap_iterate (c->own_tunnels,
6625                                            &tunnel_destroy_iterator, c);
6626     GNUNET_CONTAINER_multihashmap_iterate (c->incoming_tunnels,
6627                                            &tunnel_destroy_iterator, c);
6628     GNUNET_CONTAINER_multihashmap_iterate (c->ignore_tunnels,
6629                                            &tunnel_destroy_iterator, c);
6630     GNUNET_CONTAINER_multihashmap_destroy (c->own_tunnels);
6631     GNUNET_CONTAINER_multihashmap_destroy (c->incoming_tunnels);
6632     GNUNET_CONTAINER_multihashmap_destroy (c->ignore_tunnels);
6633
6634     /* deregister clients applications */
6635     if (NULL != c->apps)
6636     {
6637       GNUNET_CONTAINER_multihashmap_iterate (c->apps, &deregister_app, c->apps);
6638       GNUNET_CONTAINER_multihashmap_destroy (c->apps);
6639     }
6640     if (0 == GNUNET_CONTAINER_multihashmap_size (applications) &&
6641         GNUNET_SCHEDULER_NO_TASK != announce_applications_task)
6642     {
6643       GNUNET_SCHEDULER_cancel (announce_applications_task);
6644       announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
6645     }
6646     if (NULL != c->types)
6647       GNUNET_CONTAINER_multihashmap_destroy (c->types);
6648     for (i = 0; i < c->n_regex; i++)
6649     {
6650       GNUNET_free (c->regexes[i].regex);
6651     }
6652     GNUNET_free_non_null (c->regexes);
6653     if (GNUNET_SCHEDULER_NO_TASK != c->regex_announce_task)
6654       GNUNET_SCHEDULER_cancel (c->regex_announce_task);
6655     next = c->next;
6656     GNUNET_CONTAINER_DLL_remove (clients, clients_tail, c);
6657     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT FREE at %p\n", c);
6658     GNUNET_free (c);
6659     GNUNET_STATISTICS_update (stats, "# clients", -1, GNUNET_NO);
6660     c = next;
6661   }
6662   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   done!\n");
6663   return;
6664 }
6665
6666
6667 /**
6668  * Handler for new clients
6669  *
6670  * @param cls closure
6671  * @param client identification of the client
6672  * @param message the actual message, which includes messages the client wants
6673  */
6674 static void
6675 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
6676                          const struct GNUNET_MessageHeader *message)
6677 {
6678   struct GNUNET_MESH_ClientConnect *cc_msg;
6679   struct MeshClient *c;
6680   GNUNET_MESH_ApplicationType *a;
6681   unsigned int size;
6682   uint16_t ntypes;
6683   uint16_t *t;
6684   uint16_t napps;
6685   uint16_t i;
6686
6687   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected\n");
6688   /* Check data sanity */
6689   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
6690   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
6691   ntypes = ntohs (cc_msg->types);
6692   napps = ntohs (cc_msg->applications);
6693   if (size !=
6694       ntypes * sizeof (uint16_t) + napps * sizeof (GNUNET_MESH_ApplicationType))
6695   {
6696     GNUNET_break (0);
6697     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6698     return;
6699   }
6700
6701   /* Create new client structure */
6702   c = GNUNET_malloc (sizeof (struct MeshClient));
6703   c->id = next_client_id++;
6704   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT NEW %u\n", c->id);
6705   c->handle = client;
6706   GNUNET_SERVER_client_keep (client);
6707   a = (GNUNET_MESH_ApplicationType *) &cc_msg[1];
6708   if (napps > 0)
6709   {
6710     GNUNET_MESH_ApplicationType at;
6711     struct GNUNET_HashCode hc;
6712
6713     c->apps = GNUNET_CONTAINER_multihashmap_create (napps, GNUNET_NO);
6714     for (i = 0; i < napps; i++)
6715     {
6716       at = ntohl (a[i]);
6717       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  app type: %u\n", at);
6718       GNUNET_CRYPTO_hash (&at, sizeof (at), &hc);
6719       /* store in clients hashmap */
6720       GNUNET_CONTAINER_multihashmap_put (c->apps, &hc, (void *) (long) at,
6721                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6722       /* store in global hashmap, for announcements */
6723       GNUNET_CONTAINER_multihashmap_put (applications, &hc, c,
6724                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6725     }
6726     if (GNUNET_SCHEDULER_NO_TASK == announce_applications_task)
6727       announce_applications_task =
6728           GNUNET_SCHEDULER_add_now (&announce_applications, NULL);
6729
6730   }
6731   if (ntypes > 0)
6732   {
6733     uint16_t u16;
6734     struct GNUNET_HashCode hc;
6735
6736     t = (uint16_t *) & a[napps];
6737     c->types = GNUNET_CONTAINER_multihashmap_create (ntypes, GNUNET_NO);
6738     for (i = 0; i < ntypes; i++)
6739     {
6740       u16 = ntohs (t[i]);
6741       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  msg type: %u\n", u16);
6742       GNUNET_CRYPTO_hash (&u16, sizeof (u16), &hc);
6743
6744       /* store in clients hashmap */
6745       GNUNET_CONTAINER_multihashmap_put (c->types, &hc, c,
6746                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6747       /* store in global hashmap */
6748       GNUNET_CONTAINER_multihashmap_put (types, &hc, c,
6749                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6750     }
6751   }
6752   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6753               " client has %u+%u subscriptions\n", napps, ntypes);
6754
6755   GNUNET_CONTAINER_DLL_insert (clients, clients_tail, c);
6756   c->own_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6757   c->incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6758   c->ignore_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6759   GNUNET_SERVER_notification_context_add (nc, client);
6760   GNUNET_STATISTICS_update (stats, "# clients", 1, GNUNET_NO);
6761
6762   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6763   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
6764 }
6765
6766
6767 /**
6768  * Handler for clients announcing available services by a regular expression.
6769  *
6770  * @param cls closure
6771  * @param client identification of the client
6772  * @param message the actual message, which includes messages the client wants
6773  */
6774 static void
6775 handle_local_announce_regex (void *cls, struct GNUNET_SERVER_Client *client,
6776                              const struct GNUNET_MessageHeader *message)
6777 {
6778   struct GNUNET_MESH_RegexAnnounce *msg;
6779   struct MeshRegexDescriptor rd;
6780   struct MeshClient *c;
6781   char *regex;
6782   size_t len;
6783
6784   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "announce regex started\n");
6785
6786   /* Sanity check for client registration */
6787   if (NULL == (c = client_get (client)))
6788   {
6789     GNUNET_break (0);
6790     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6791     return;
6792   }
6793   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6794
6795   msg = (struct GNUNET_MESH_RegexAnnounce *) message;
6796   len = ntohs (message->size) - sizeof(struct GNUNET_MESH_RegexAnnounce);
6797   regex = GNUNET_malloc (len + 1);
6798   memcpy (regex, &msg[1], len);
6799   regex[len] = '\0';
6800   rd.regex = regex;
6801   rd.compression = ntohs (msg->compression_characters);
6802   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  length %u\n", len);
6803   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regex %s\n", regex);
6804   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  cm %u\n", ntohs(rd.compression));
6805   GNUNET_array_append (c->regexes, c->n_regex, rd);
6806   if (GNUNET_SCHEDULER_NO_TASK == c->regex_announce_task)
6807   {
6808     c->regex_announce_task = GNUNET_SCHEDULER_add_now(&announce_regex, c);
6809   }
6810   else
6811   {
6812     regex_put(&rd);
6813   }
6814   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6815   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "announce regex processed\n");
6816 }
6817
6818
6819 /**
6820  * Handler for requests of new tunnels
6821  *
6822  * @param cls closure
6823  * @param client identification of the client
6824  * @param message the actual message
6825  */
6826 static void
6827 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
6828                             const struct GNUNET_MessageHeader *message)
6829 {
6830   struct GNUNET_MESH_TunnelMessage *t_msg;
6831   struct MeshTunnel *t;
6832   struct MeshClient *c;
6833   MESH_TunnelNumber tid;
6834
6835   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel requested\n");
6836
6837   /* Sanity check for client registration */
6838   if (NULL == (c = client_get (client)))
6839   {
6840     GNUNET_break (0);
6841     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6842     return;
6843   }
6844   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6845
6846   /* Message sanity check */
6847   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
6848   {
6849     GNUNET_break (0);
6850     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6851     return;
6852   }
6853
6854   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6855   /* Sanity check for tunnel numbering */
6856   tid = ntohl (t_msg->tunnel_id);
6857   if (0 == (tid & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
6858   {
6859     GNUNET_break (0);
6860     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6861     return;
6862   }
6863   /* Sanity check for duplicate tunnel IDs */
6864   if (NULL != tunnel_get_by_local_id (c, tid))
6865   {
6866     GNUNET_break (0);
6867     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6868     return;
6869   }
6870
6871   while (NULL != tunnel_get_by_pi (myid, next_tid))
6872     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
6873   t = tunnel_new (myid, next_tid++, c, tid);
6874   if (NULL == t)
6875   {
6876     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Tunnel creation failed.\n");
6877     GNUNET_break (0);
6878     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6879     return;
6880   }
6881   next_tid = next_tid & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
6882   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED TUNNEL %s [%x] (%x)\n",
6883               GNUNET_i2s (&my_full_id), t->id.tid, t->local_tid);
6884   t->peers = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6885
6886   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel created\n");
6887   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6888   return;
6889 }
6890
6891
6892 /**
6893  * Handler for requests of deleting tunnels
6894  *
6895  * @param cls closure
6896  * @param client identification of the client
6897  * @param message the actual message
6898  */
6899 static void
6900 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
6901                              const struct GNUNET_MessageHeader *message)
6902 {
6903   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
6904   struct MeshClient *c;
6905   struct MeshTunnel *t;
6906   MESH_TunnelNumber tid;
6907
6908   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6909               "Got a DESTROY TUNNEL from client!\n");
6910
6911   /* Sanity check for client registration */
6912   if (NULL == (c = client_get (client)))
6913   {
6914     GNUNET_break (0);
6915     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6916     return;
6917   }
6918   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6919
6920   /* Message sanity check */
6921   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
6922   {
6923     GNUNET_break (0);
6924     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6925     return;
6926   }
6927
6928   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6929
6930   /* Retrieve tunnel */
6931   tid = ntohl (tunnel_msg->tunnel_id);
6932   t = tunnel_get_by_local_id(c, tid);
6933   if (NULL == t)
6934   {
6935     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
6936     GNUNET_break (0);
6937     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6938     return;
6939   }
6940   if (c != t->owner || tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
6941   {
6942     client_ignore_tunnel (c, t);
6943 #if 0
6944     // TODO: when to destroy incoming tunnel?
6945     if (t->nclients == 0)
6946     {
6947       GNUNET_assert (GNUNET_YES ==
6948                      GNUNET_CONTAINER_multihashmap_remove (incoming_tunnels,
6949                                                            &hash, t));
6950       GNUNET_assert (GNUNET_YES ==
6951                      GNUNET_CONTAINER_multihashmap_remove (t->peers,
6952                                                            &my_full_id.hashPubKey,
6953                                                            t));
6954     }
6955 #endif
6956     GNUNET_SERVER_receive_done (client, GNUNET_OK);
6957     return;
6958   }
6959   send_client_tunnel_disconnect(t, c);
6960   client_delete_tunnel(c, t);
6961
6962   /* Don't try to ACK the client about the tunnel_destroy multicast packet */
6963   t->owner = NULL;
6964   tunnel_send_destroy (t);
6965   t->destroy = GNUNET_YES;
6966   // The tunnel will be destroyed when the last message is transmitted.
6967   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6968   return;
6969 }
6970
6971
6972 /**
6973  * Handler for requests of seeting tunnel's speed.
6974  *
6975  * @param cls Closure (unused).
6976  * @param client Identification of the client.
6977  * @param message The actual message.
6978  */
6979 static void
6980 handle_local_tunnel_speed (void *cls, struct GNUNET_SERVER_Client *client,
6981                            const struct GNUNET_MessageHeader *message)
6982 {
6983   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
6984   struct MeshClient *c;
6985   struct MeshTunnel *t;
6986   MESH_TunnelNumber tid;
6987
6988   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6989               "Got a SPEED request from client!\n");
6990
6991   /* Sanity check for client registration */
6992   if (NULL == (c = client_get (client)))
6993   {
6994     GNUNET_break (0);
6995     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6996     return;
6997   }
6998
6999   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7000
7001   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
7002
7003   /* Retrieve tunnel */
7004   tid = ntohl (tunnel_msg->tunnel_id);
7005   t = tunnel_get_by_local_id(c, tid);
7006   if (NULL == t)
7007   {
7008     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  tunnel %X not found\n", tid);
7009     GNUNET_break (0);
7010     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7011     return;
7012   }
7013
7014   switch (ntohs(message->type))
7015   {
7016       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MIN:
7017           t->speed_min = GNUNET_YES;
7018           break;
7019       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MAX:
7020           t->speed_min = GNUNET_NO;
7021           break;
7022       default:
7023           GNUNET_break (0);
7024   }
7025   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7026 }
7027
7028
7029 /**
7030  * Handler for requests of seeting tunnel's buffering policy.
7031  *
7032  * @param cls Closure (unused).
7033  * @param client Identification of the client.
7034  * @param message The actual message.
7035  */
7036 static void
7037 handle_local_tunnel_buffer (void *cls, struct GNUNET_SERVER_Client *client,
7038                             const struct GNUNET_MessageHeader *message)
7039 {
7040   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
7041   struct MeshClient *c;
7042   struct MeshTunnel *t;
7043   MESH_TunnelNumber tid;
7044
7045   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7046               "Got a BUFFER request from client!\n");
7047
7048   /* Sanity check for client registration */
7049   if (NULL == (c = client_get (client)))
7050   {
7051     GNUNET_break (0);
7052     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7053     return;
7054   }
7055   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7056
7057   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
7058
7059   /* Retrieve tunnel */
7060   tid = ntohl (tunnel_msg->tunnel_id);
7061   t = tunnel_get_by_local_id(c, tid);
7062   if (NULL == t)
7063   {
7064     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
7065     GNUNET_break (0);
7066     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7067     return;
7068   }
7069
7070   switch (ntohs(message->type))
7071   {
7072       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER:
7073           t->nobuffer = GNUNET_NO;
7074           break;
7075       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER:
7076           t->nobuffer = GNUNET_YES;
7077           break;
7078       default:
7079           GNUNET_break (0);
7080   }
7081
7082   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7083 }
7084
7085
7086 /**
7087  * Handler for connection requests to new peers
7088  *
7089  * @param cls closure
7090  * @param client identification of the client
7091  * @param message the actual message (PeerControl)
7092  */
7093 static void
7094 handle_local_connect_add (void *cls, struct GNUNET_SERVER_Client *client,
7095                           const struct GNUNET_MessageHeader *message)
7096 {
7097   struct GNUNET_MESH_PeerControl *peer_msg;
7098   struct MeshPeerInfo *peer_info;
7099   struct MeshClient *c;
7100   struct MeshTunnel *t;
7101   MESH_TunnelNumber tid;
7102
7103   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got connection request\n");
7104   /* Sanity check for client registration */
7105   if (NULL == (c = client_get (client)))
7106   {
7107     GNUNET_break (0);
7108     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7109     return;
7110   }
7111   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7112
7113   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
7114
7115   /* Sanity check for message size */
7116   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
7117   {
7118     GNUNET_break (0);
7119     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7120     return;
7121   }
7122
7123   /* Tunnel exists? */
7124   tid = ntohl (peer_msg->tunnel_id);
7125   t = tunnel_get_by_local_id (c, tid);
7126   if (NULL == t)
7127   {
7128     GNUNET_break (0);
7129     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7130     return;
7131   }
7132
7133   /* Does client own tunnel? */
7134   if (t->owner->handle != client)
7135   {
7136     GNUNET_break (0);
7137     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7138     return;
7139   }
7140   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "     for %s\n",
7141               GNUNET_i2s (&peer_msg->peer));
7142   peer_info = peer_info_get (&peer_msg->peer);
7143
7144   tunnel_add_peer (t, peer_info);
7145   peer_info_connect (peer_info, t);
7146
7147   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7148   return;
7149 }
7150
7151
7152 /**
7153  * Handler for disconnection requests of peers in a tunnel
7154  *
7155  * @param cls closure
7156  * @param client identification of the client
7157  * @param message the actual message (PeerControl)
7158  */
7159 static void
7160 handle_local_connect_del (void *cls, struct GNUNET_SERVER_Client *client,
7161                           const struct GNUNET_MessageHeader *message)
7162 {
7163   struct GNUNET_MESH_PeerControl *peer_msg;
7164   struct MeshPeerInfo *peer_info;
7165   struct MeshClient *c;
7166   struct MeshTunnel *t;
7167   MESH_TunnelNumber tid;
7168
7169   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER DEL request\n");
7170   /* Sanity check for client registration */
7171   if (NULL == (c = client_get (client)))
7172   {
7173     GNUNET_break (0);
7174     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7175     return;
7176   }
7177   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7178
7179   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
7180
7181   /* Sanity check for message size */
7182   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
7183   {
7184     GNUNET_break (0);
7185     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7186     return;
7187   }
7188
7189   /* Tunnel exists? */
7190   tid = ntohl (peer_msg->tunnel_id);
7191   t = tunnel_get_by_local_id (c, tid);
7192   if (NULL == t)
7193   {
7194     GNUNET_break (0);
7195     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7196     return;
7197   }
7198   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
7199
7200   /* Does client own tunnel? */
7201   if (t->owner->handle != client)
7202   {
7203     GNUNET_break (0);
7204     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7205     return;
7206   }
7207
7208   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for peer %s\n",
7209               GNUNET_i2s (&peer_msg->peer));
7210   /* Is the peer in the tunnel? */
7211   peer_info =
7212       GNUNET_CONTAINER_multihashmap_get (t->peers, &peer_msg->peer.hashPubKey);
7213   if (NULL == peer_info)
7214   {
7215     GNUNET_break (0);
7216     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7217     return;
7218   }
7219
7220   /* Ok, delete peer from tunnel */
7221   GNUNET_CONTAINER_multihashmap_remove_all (t->peers,
7222                                             &peer_msg->peer.hashPubKey);
7223
7224   send_destroy_path (t, peer_info->id);
7225   tunnel_delete_peer (t, peer_info->id);
7226   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7227   return;
7228 }
7229
7230 /**
7231  * Handler for blacklist requests of peers in a tunnel
7232  *
7233  * @param cls closure
7234  * @param client identification of the client
7235  * @param message the actual message (PeerControl)
7236  * 
7237  * FIXME implement DHT block bloomfilter
7238  */
7239 static void
7240 handle_local_blacklist (void *cls, struct GNUNET_SERVER_Client *client,
7241                           const struct GNUNET_MessageHeader *message)
7242 {
7243   struct GNUNET_MESH_PeerControl *peer_msg;
7244   struct MeshClient *c;
7245   struct MeshTunnel *t;
7246   MESH_TunnelNumber tid;
7247
7248   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER BLACKLIST request\n");
7249   /* Sanity check for client registration */
7250   if (NULL == (c = client_get (client)))
7251   {
7252     GNUNET_break (0);
7253     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7254     return;
7255   }
7256   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7257
7258   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
7259
7260   /* Sanity check for message size */
7261   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
7262   {
7263     GNUNET_break (0);
7264     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7265     return;
7266   }
7267
7268   /* Tunnel exists? */
7269   tid = ntohl (peer_msg->tunnel_id);
7270   t = tunnel_get_by_local_id (c, tid);
7271   if (NULL == t)
7272   {
7273     GNUNET_break (0);
7274     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7275     return;
7276   }
7277   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
7278
7279   GNUNET_array_append(t->blacklisted, t->nblacklisted,
7280                       GNUNET_PEER_intern(&peer_msg->peer));
7281 }
7282
7283
7284 /**
7285  * Handler for unblacklist requests of peers in a tunnel
7286  *
7287  * @param cls closure
7288  * @param client identification of the client
7289  * @param message the actual message (PeerControl)
7290  */
7291 static void
7292 handle_local_unblacklist (void *cls, struct GNUNET_SERVER_Client *client,
7293                           const struct GNUNET_MessageHeader *message)
7294 {
7295   struct GNUNET_MESH_PeerControl *peer_msg;
7296   struct MeshClient *c;
7297   struct MeshTunnel *t;
7298   MESH_TunnelNumber tid;
7299   GNUNET_PEER_Id pid;
7300   unsigned int i;
7301
7302   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER UNBLACKLIST request\n");
7303   /* Sanity check for client registration */
7304   if (NULL == (c = client_get (client)))
7305   {
7306     GNUNET_break (0);
7307     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7308     return;
7309   }
7310   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7311
7312   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
7313
7314   /* Sanity check for message size */
7315   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
7316   {
7317     GNUNET_break (0);
7318     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7319     return;
7320   }
7321
7322   /* Tunnel exists? */
7323   tid = ntohl (peer_msg->tunnel_id);
7324   t = tunnel_get_by_local_id (c, tid);
7325   if (NULL == t)
7326   {
7327     GNUNET_break (0);
7328     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7329     return;
7330   }
7331   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
7332
7333   /* if peer is not known, complain */
7334   pid = GNUNET_PEER_search (&peer_msg->peer);
7335   if (0 == pid)
7336   {
7337     GNUNET_break (0);
7338     return;
7339   }
7340
7341   /* search and remove from list */
7342   for (i = 0; i < t->nblacklisted; i++)
7343   {
7344     if (t->blacklisted[i] == pid)
7345     {
7346       t->blacklisted[i] = t->blacklisted[t->nblacklisted - 1];
7347       GNUNET_array_grow (t->blacklisted, t->nblacklisted, t->nblacklisted - 1);
7348       return;
7349     }
7350   }
7351
7352   /* if peer hasn't been blacklisted, complain */
7353   GNUNET_break (0);
7354 }
7355
7356
7357 /**
7358  * Handler for connection requests to new peers by type
7359  *
7360  * @param cls closure
7361  * @param client identification of the client
7362  * @param message the actual message (ConnectPeerByType)
7363  */
7364 static void
7365 handle_local_connect_by_type (void *cls, struct GNUNET_SERVER_Client *client,
7366                               const struct GNUNET_MessageHeader *message)
7367 {
7368   struct GNUNET_MESH_ConnectPeerByType *connect_msg;
7369   struct MeshClient *c;
7370   struct MeshTunnel *t;
7371   struct GNUNET_HashCode hash;
7372   MESH_TunnelNumber tid;
7373
7374   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got connect by type request\n");
7375   /* Sanity check for client registration */
7376   if (NULL == (c = client_get (client)))
7377   {
7378     GNUNET_break (0);
7379     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7380     return;
7381   }
7382   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7383
7384   connect_msg = (struct GNUNET_MESH_ConnectPeerByType *) message;
7385
7386   /* Sanity check for message size */
7387   if (sizeof (struct GNUNET_MESH_ConnectPeerByType) !=
7388       ntohs (connect_msg->header.size))
7389   {
7390     GNUNET_break (0);
7391     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7392     return;
7393   }
7394
7395   /* Tunnel exists? */
7396   tid = ntohl (connect_msg->tunnel_id);
7397   t = tunnel_get_by_local_id (c, tid);
7398   if (NULL == t)
7399   {
7400     GNUNET_break (0);
7401     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7402     return;
7403   }
7404
7405   /* Does client own tunnel? */
7406   if (t->owner->handle != client)
7407   {
7408     GNUNET_break (0);
7409     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7410     return;
7411   }
7412
7413   /* Do WE have the service? */
7414   t->type = ntohl (connect_msg->type);
7415   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " type requested: %u\n", t->type);
7416   GNUNET_CRYPTO_hash (&t->type, sizeof (GNUNET_MESH_ApplicationType), &hash);
7417   if (GNUNET_CONTAINER_multihashmap_contains (applications, &hash) ==
7418       GNUNET_YES)
7419   {
7420     /* Yes! Fast forward, add ourselves to the tunnel and send the
7421      * good news to the client, and alert the destination client of
7422      * an incoming tunnel.
7423      *
7424      * FIXME send a path create to self, avoid code duplication
7425      */
7426     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " available locally\n");
7427     GNUNET_CONTAINER_multihashmap_put (t->peers, &my_full_id.hashPubKey,
7428                                        peer_info_get (&my_full_id),
7429                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
7430
7431     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " notifying client\n");
7432     send_client_peer_connected (t, myid);
7433     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Done\n");
7434     GNUNET_SERVER_receive_done (client, GNUNET_OK);
7435
7436     t->local_tid_dest = next_local_tid++;
7437     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
7438     GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
7439                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
7440
7441     return;
7442   }
7443   /* Ok, lets find a peer offering the service */
7444   if (NULL != t->dht_get_type)
7445   {
7446     GNUNET_DHT_get_stop (t->dht_get_type);
7447   }
7448   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " looking in DHT for %s\n",
7449               GNUNET_h2s (&hash));
7450   t->dht_get_type =
7451       GNUNET_DHT_get_start (dht_handle, 
7452                             GNUNET_BLOCK_TYPE_MESH_PEER_BY_TYPE,
7453                             &hash,
7454                             dht_replication_level,
7455                             GNUNET_DHT_RO_RECORD_ROUTE |
7456                             GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
7457                             NULL, 0,
7458                             &dht_get_type_handler, t);
7459
7460   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7461   return;
7462 }
7463
7464
7465 /**
7466  * Handler for connection requests to new peers by a string service description.
7467  *
7468  * @param cls closure
7469  * @param client identification of the client
7470  * @param message the actual message, which includes messages the client wants
7471  */
7472 static void
7473 handle_local_connect_by_string (void *cls, struct GNUNET_SERVER_Client *client,
7474                                 const struct GNUNET_MessageHeader *message)
7475 {
7476   struct GNUNET_MESH_ConnectPeerByString *msg;
7477   struct MeshRegexSearchContext *ctx;
7478   struct MeshRegexSearchInfo *info;
7479   struct GNUNET_DHT_GetHandle *get_h;
7480   struct GNUNET_HashCode key;
7481   struct MeshTunnel *t;
7482   struct MeshClient *c;
7483   MESH_TunnelNumber tid;
7484   const char *string;
7485   size_t size;
7486   size_t len;
7487   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7488               "Connect by string started\n");
7489   msg = (struct GNUNET_MESH_ConnectPeerByString *) message;
7490   size = htons (message->size);
7491
7492   /* Sanity check for client registration */
7493   if (NULL == (c = client_get (client)))
7494   {
7495     GNUNET_break (0);
7496     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7497     return;
7498   }
7499   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7500
7501   /* Message size sanity check */
7502   if (sizeof(struct GNUNET_MESH_ConnectPeerByString) >= size)
7503   {
7504     GNUNET_break (0);
7505     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7506     return;
7507   }
7508
7509   /* Tunnel exists? */
7510   tid = ntohl (msg->tunnel_id);
7511   t = tunnel_get_by_local_id (c, tid);
7512   if (NULL == t)
7513   {
7514     GNUNET_break (0);
7515     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7516     return;
7517   }
7518
7519   /* Does client own tunnel? */
7520   if (t->owner->handle != client)
7521   {
7522     GNUNET_break (0);
7523     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7524     return;
7525   }
7526
7527   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7528               "  on tunnel %s [%u]\n",
7529               GNUNET_i2s(&my_full_id),
7530               t->id.tid);
7531
7532   /* Only one connect_by_string allowed at the same time! */
7533   /* FIXME: allow more, return handle at api level to cancel, document */
7534   if (NULL != t->regex_ctx)
7535   {
7536     GNUNET_break (0);
7537     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7538     return;
7539   }
7540
7541   /* Find string itself */
7542   len = size - sizeof(struct GNUNET_MESH_ConnectPeerByString);
7543   string = (const char *) &msg[1];
7544
7545   /* Initialize context */
7546   size = GNUNET_REGEX_get_first_key(string, len, &key);
7547   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7548               "  consumed %u bits out of %u\n", size, len);
7549   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7550               "  looking for %s\n", GNUNET_h2s (&key));
7551
7552   info = GNUNET_malloc (sizeof (struct MeshRegexSearchInfo));
7553   info->t = t;
7554   info->description = GNUNET_malloc (len + 1);
7555   memcpy (info->description, string, len);
7556   info->description[len] = '\0';
7557   info->dht_get_handles = GNUNET_CONTAINER_multihashmap_create(32, GNUNET_NO);
7558   info->dht_get_results = GNUNET_CONTAINER_multihashmap_create(32, GNUNET_NO);
7559   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   string: %s\n", info->description);
7560
7561   ctx = GNUNET_malloc (sizeof (struct MeshRegexSearchContext));
7562   ctx->position = size;
7563   ctx->info = info;
7564   t->regex_ctx = ctx;
7565
7566   GNUNET_array_append (info->contexts, info->n_contexts, ctx);
7567
7568   /* Start search in DHT */
7569   get_h = GNUNET_DHT_get_start (dht_handle,    /* handle */
7570                                 GNUNET_BLOCK_TYPE_MESH_REGEX, /* type */
7571                                 &key,     /* key to search */
7572                                 dht_replication_level, /* replication level */
7573                                 GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
7574                                 NULL,       /* xquery */ // FIXME BLOOMFILTER
7575                                 0,     /* xquery bits */ // FIXME BLOOMFILTER SIZE
7576                                 &dht_get_string_handler, ctx);
7577
7578   GNUNET_break (GNUNET_OK ==
7579                 GNUNET_CONTAINER_multihashmap_put(info->dht_get_handles,
7580                                                   &key,
7581                                                   get_h,
7582                                                   GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
7583
7584   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7585   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "connect by string processed\n");
7586 }
7587
7588
7589 /**
7590  * Handler for client traffic directed to one peer
7591  *
7592  * @param cls closure
7593  * @param client identification of the client
7594  * @param message the actual message
7595  */
7596 static void
7597 handle_local_unicast (void *cls, struct GNUNET_SERVER_Client *client,
7598                       const struct GNUNET_MessageHeader *message)
7599 {
7600   struct MeshClient *c;
7601   struct MeshTunnel *t;
7602   struct MeshPeerInfo *pi;
7603   struct GNUNET_MESH_Unicast *data_msg;
7604   MESH_TunnelNumber tid;
7605   size_t size;
7606
7607   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7608               "Got a unicast request from a client!\n");
7609
7610   /* Sanity check for client registration */
7611   if (NULL == (c = client_get (client)))
7612   {
7613     GNUNET_break (0);
7614     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7615     return;
7616   }
7617   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7618
7619   data_msg = (struct GNUNET_MESH_Unicast *) message;
7620
7621   /* Sanity check for message size */
7622   size = ntohs (message->size);
7623   if (sizeof (struct GNUNET_MESH_Unicast) +
7624       sizeof (struct GNUNET_MessageHeader) > size)
7625   {
7626     GNUNET_break (0);
7627     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7628     return;
7629   }
7630
7631   /* Tunnel exists? */
7632   tid = ntohl (data_msg->tid);
7633   t = tunnel_get_by_local_id (c, tid);
7634   if (NULL == t)
7635   {
7636     GNUNET_break (0);
7637     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7638     return;
7639   }
7640
7641   /*  Is it a local tunnel? Then, does client own the tunnel? */
7642   if (t->owner->handle != client)
7643   {
7644     GNUNET_break (0);
7645     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7646     return;
7647   }
7648
7649   pi = GNUNET_CONTAINER_multihashmap_get (t->peers,
7650                                           &data_msg->destination.hashPubKey);
7651   /* Is the selected peer in the tunnel? */
7652   if (NULL == pi)
7653   {
7654     GNUNET_break (0);
7655     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7656     return;
7657   }
7658
7659   /* PID should be as expected */
7660   if (ntohl (data_msg->pid) != t->fwd_pid + 1)
7661   {
7662     GNUNET_break (0);
7663     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7664               "Unicast PID, expected %u, got %u\n",
7665               t->fwd_pid + 1, ntohl (data_msg->pid));
7666     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7667     return;
7668   }
7669
7670   /* Ok, everything is correct, send the message
7671    * (pretend we got it from a mesh peer)
7672    */
7673   {
7674     /* Work around const limitation */
7675     char buf[ntohs (message->size)] GNUNET_ALIGN;
7676     struct GNUNET_MESH_Unicast *copy;
7677
7678     copy = (struct GNUNET_MESH_Unicast *) buf;
7679     memcpy (buf, data_msg, size);
7680     copy->oid = my_full_id;
7681     copy->tid = htonl (t->id.tid);
7682     copy->ttl = htonl (default_ttl);
7683     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7684                 "  calling generic handler...\n");
7685     handle_mesh_data_unicast (NULL, &my_full_id, &copy->header, NULL, 0);
7686   }
7687   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "receive done OK\n");
7688   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7689
7690   return;
7691 }
7692
7693
7694 /**
7695  * Handler for client traffic directed to the origin
7696  *
7697  * @param cls closure
7698  * @param client identification of the client
7699  * @param message the actual message
7700  */
7701 static void
7702 handle_local_to_origin (void *cls, struct GNUNET_SERVER_Client *client,
7703                         const struct GNUNET_MessageHeader *message)
7704 {
7705   struct GNUNET_MESH_ToOrigin *data_msg;
7706   struct MeshTunnelClientInfo *clinfo;
7707   struct MeshClient *c;
7708   struct MeshTunnel *t;
7709   MESH_TunnelNumber tid;
7710   size_t size;
7711
7712   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7713               "Got a ToOrigin request from a client!\n");
7714   /* Sanity check for client registration */
7715   if (NULL == (c = client_get (client)))
7716   {
7717     GNUNET_break (0);
7718     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7719     return;
7720   }
7721   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7722
7723   data_msg = (struct GNUNET_MESH_ToOrigin *) message;
7724
7725   /* Sanity check for message size */
7726   size = ntohs (message->size);
7727   if (sizeof (struct GNUNET_MESH_ToOrigin) +
7728       sizeof (struct GNUNET_MessageHeader) > size)
7729   {
7730     GNUNET_break (0);
7731     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7732     return;
7733   }
7734
7735   /* Tunnel exists? */
7736   tid = ntohl (data_msg->tid);
7737   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
7738   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
7739   {
7740     GNUNET_break (0);
7741     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7742     return;
7743   }
7744   t = tunnel_get_by_local_id (c, tid);
7745   if (NULL == t)
7746   {
7747     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
7748     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
7749     GNUNET_break (0);
7750     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7751     return;
7752   }
7753
7754   /*  It should be sent by someone who has this as incoming tunnel. */
7755   if (GNUNET_NO == client_knows_tunnel (c, t))
7756   {
7757     GNUNET_break (0);
7758     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7759     return;
7760   }
7761
7762   /* PID should be as expected */
7763   clinfo = tunnel_get_client_fc (t, c);
7764   if (ntohl (data_msg->pid) != clinfo->bck_pid + 1)
7765   {
7766     GNUNET_break (0);
7767     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7768                 "To Origin PID, expected %u, got %u\n",
7769                 clinfo->bck_pid + 1,
7770                 ntohl (data_msg->pid));
7771     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7772     return;
7773   }
7774   clinfo->bck_pid++;
7775
7776   /* Ok, everything is correct, send the message
7777    * (pretend we got it from a mesh peer)
7778    */
7779   {
7780     char buf[ntohs (message->size)] GNUNET_ALIGN;
7781     struct GNUNET_MESH_ToOrigin *copy;
7782
7783     /* Work around const limitation */
7784     copy = (struct GNUNET_MESH_ToOrigin *) buf;
7785     memcpy (buf, data_msg, size);
7786     GNUNET_PEER_resolve (t->id.oid, &copy->oid);
7787     copy->tid = htonl (t->id.tid);
7788     copy->ttl = htonl (default_ttl);
7789     copy->pid = htonl (t->bck_pid + 1);
7790
7791     copy->sender = my_full_id;
7792     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7793                 "  calling generic handler...\n");
7794     handle_mesh_data_to_orig (NULL, &my_full_id, &copy->header, NULL, 0);
7795   }
7796   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7797
7798   return;
7799 }
7800
7801
7802 /**
7803  * Handler for client traffic directed to all peers in a tunnel
7804  *
7805  * @param cls closure
7806  * @param client identification of the client
7807  * @param message the actual message
7808  */
7809 static void
7810 handle_local_multicast (void *cls, struct GNUNET_SERVER_Client *client,
7811                         const struct GNUNET_MessageHeader *message)
7812 {
7813   struct MeshClient *c;
7814   struct MeshTunnel *t;
7815   struct GNUNET_MESH_Multicast *data_msg;
7816   MESH_TunnelNumber tid;
7817
7818   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7819               "Got a multicast request from a client!\n");
7820
7821   /* Sanity check for client registration */
7822   if (NULL == (c = client_get (client)))
7823   {
7824     GNUNET_break (0);
7825     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7826     return;
7827   }
7828   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7829
7830   data_msg = (struct GNUNET_MESH_Multicast *) message;
7831
7832   /* Sanity check for message size */
7833   if (sizeof (struct GNUNET_MESH_Multicast) +
7834       sizeof (struct GNUNET_MessageHeader) > ntohs (data_msg->header.size))
7835   {
7836     GNUNET_break (0);
7837     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7838     return;
7839   }
7840
7841   /* Tunnel exists? */
7842   tid = ntohl (data_msg->tid);
7843   t = tunnel_get_by_local_id (c, tid);
7844   if (NULL == t)
7845   {
7846     GNUNET_break (0);
7847     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
7848     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
7849     GNUNET_break (0);
7850     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7851     return;
7852   }
7853
7854   /* Does client own tunnel? */
7855   if (t->owner->handle != client)
7856   {
7857     GNUNET_break (0);
7858     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7859     return;
7860   }
7861
7862   /* PID should be as expected */
7863   if (ntohl (data_msg->pid) != t->fwd_pid + 1)
7864   {
7865     GNUNET_break (0);
7866     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7867               "Multicast PID, expected %u, got %u\n",
7868               t->fwd_pid + 1, ntohl (data_msg->pid));
7869     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7870     return;
7871   }
7872
7873   {
7874     char buf[ntohs (message->size)] GNUNET_ALIGN;
7875     struct GNUNET_MESH_Multicast *copy;
7876
7877     copy = (struct GNUNET_MESH_Multicast *) buf;
7878     memcpy (buf, message, ntohs (message->size));
7879     copy->oid = my_full_id;
7880     copy->tid = htonl (t->id.tid);
7881     copy->ttl = htonl (default_ttl);
7882     GNUNET_assert (ntohl (copy->pid) == (t->fwd_pid + 1));
7883     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7884                 "  calling generic handler...\n");
7885     handle_mesh_data_multicast (client, &my_full_id, &copy->header, NULL, 0);
7886   }
7887
7888   GNUNET_SERVER_receive_done (t->owner->handle, GNUNET_OK);
7889   return;
7890 }
7891
7892
7893 /**
7894  * Handler for client's ACKs for payload traffic.
7895  *
7896  * @param cls Closure (unused).
7897  * @param client Identification of the client.
7898  * @param message The actual message.
7899  */
7900 static void
7901 handle_local_ack (void *cls, struct GNUNET_SERVER_Client *client,
7902                   const struct GNUNET_MessageHeader *message)
7903 {
7904   struct GNUNET_MESH_LocalAck *msg;
7905   struct MeshTunnel *t;
7906   struct MeshClient *c;
7907   MESH_TunnelNumber tid;
7908   uint32_t ack;
7909
7910   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a local ACK\n");
7911   /* Sanity check for client registration */
7912   if (NULL == (c = client_get (client)))
7913   {
7914     GNUNET_break (0);
7915     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7916     return;
7917   }
7918   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7919
7920   msg = (struct GNUNET_MESH_LocalAck *) message;
7921
7922   /* Tunnel exists? */
7923   tid = ntohl (msg->tunnel_id);
7924   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
7925   t = tunnel_get_by_local_id (c, tid);
7926   if (NULL == t)
7927   {
7928     GNUNET_break (0);
7929     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
7930     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
7931     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7932     return;
7933   }
7934
7935   ack = ntohl (msg->max_pid);
7936   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ack %u\n", ack);
7937
7938   /* Does client own tunnel? I.E: Is this and ACK for BCK traffic? */
7939   if (NULL != t->owner && t->owner->handle == client)
7940   {
7941     /* The client owns the tunnel, ACK is for data to_origin, send BCK ACK. */
7942     t->bck_ack = ack;
7943     tunnel_send_bck_ack(t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
7944   }
7945   else
7946   {
7947     /* The client doesn't own the tunnel, this ACK is for FWD traffic. */
7948     tunnel_set_client_fwd_ack (t, c, ack);
7949     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
7950   }
7951
7952   GNUNET_SERVER_receive_done (client, GNUNET_OK);  
7953
7954   return;
7955 }
7956
7957
7958 /**
7959  * Functions to handle messages from clients
7960  */
7961 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
7962   {&handle_local_new_client, NULL,
7963    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
7964   {&handle_local_announce_regex, NULL,
7965    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ANNOUNCE_REGEX, 0},
7966   {&handle_local_tunnel_create, NULL,
7967    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
7968    sizeof (struct GNUNET_MESH_TunnelMessage)},
7969   {&handle_local_tunnel_destroy, NULL,
7970    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
7971    sizeof (struct GNUNET_MESH_TunnelMessage)},
7972   {&handle_local_tunnel_speed, NULL,
7973    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MIN,
7974    sizeof (struct GNUNET_MESH_TunnelMessage)},
7975   {&handle_local_tunnel_speed, NULL,
7976    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MAX,
7977    sizeof (struct GNUNET_MESH_TunnelMessage)},
7978   {&handle_local_tunnel_buffer, NULL,
7979    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER,
7980    sizeof (struct GNUNET_MESH_TunnelMessage)},
7981   {&handle_local_tunnel_buffer, NULL,
7982    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER,
7983    sizeof (struct GNUNET_MESH_TunnelMessage)},
7984   {&handle_local_connect_add, NULL,
7985    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD,
7986    sizeof (struct GNUNET_MESH_PeerControl)},
7987   {&handle_local_connect_del, NULL,
7988    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL,
7989    sizeof (struct GNUNET_MESH_PeerControl)},
7990   {&handle_local_blacklist, NULL,
7991    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_BLACKLIST,
7992    sizeof (struct GNUNET_MESH_PeerControl)},
7993   {&handle_local_unblacklist, NULL,
7994    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_UNBLACKLIST,
7995    sizeof (struct GNUNET_MESH_PeerControl)},
7996   {&handle_local_connect_by_type, NULL,
7997    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE,
7998    sizeof (struct GNUNET_MESH_ConnectPeerByType)},
7999   {&handle_local_connect_by_string, NULL,
8000    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_STRING, 0},
8001   {&handle_local_unicast, NULL,
8002    GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
8003   {&handle_local_to_origin, NULL,
8004    GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
8005   {&handle_local_multicast, NULL,
8006    GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
8007   {&handle_local_ack, NULL,
8008    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK,
8009    sizeof (struct GNUNET_MESH_LocalAck)},
8010   {NULL, NULL, 0, 0}
8011 };
8012
8013
8014 /**
8015  * To be called on core init/fail.
8016  *
8017  * @param cls service closure
8018  * @param server handle to the server for this service
8019  * @param identity the public identity of this peer
8020  */
8021 static void
8022 core_init (void *cls, struct GNUNET_CORE_Handle *server,
8023            const struct GNUNET_PeerIdentity *identity)
8024 {
8025   static int i = 0;
8026   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
8027   core_handle = server;
8028   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)) ||
8029       NULL == server)
8030   {
8031     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
8032     GNUNET_SCHEDULER_shutdown (); // Try gracefully
8033     if (10 < i++)
8034       GNUNET_abort(); // Try harder
8035   }
8036   return;
8037 }
8038
8039
8040 /**
8041  * Method called whenever a given peer connects.
8042  *
8043  * @param cls closure
8044  * @param peer peer identity this notification is about
8045  * @param atsi performance data for the connection
8046  * @param atsi_count number of records in 'atsi'
8047  */
8048 static void
8049 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
8050               const struct GNUNET_ATS_Information *atsi,
8051               unsigned int atsi_count)
8052 {
8053   struct MeshPeerInfo *peer_info;
8054   struct MeshPeerPath *path;
8055
8056   DEBUG_CONN ("Peer connected\n");
8057   DEBUG_CONN ("     %s\n", GNUNET_i2s (&my_full_id));
8058   peer_info = peer_info_get (peer);
8059   if (myid == peer_info->id)
8060   {
8061     DEBUG_CONN ("     (self)\n");
8062     return;
8063   }
8064   else
8065   {
8066     DEBUG_CONN ("     %s\n", GNUNET_i2s (peer));
8067   }
8068   path = path_new (2);
8069   path->peers[0] = myid;
8070   path->peers[1] = peer_info->id;
8071   GNUNET_PEER_change_rc (myid, 1);
8072   GNUNET_PEER_change_rc (peer_info->id, 1);
8073   peer_info_add_path (peer_info, path, GNUNET_YES);
8074   GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
8075   return;
8076 }
8077
8078
8079 /**
8080  * Method called whenever a peer disconnects.
8081  *
8082  * @param cls closure
8083  * @param peer peer identity this notification is about
8084  */
8085 static void
8086 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
8087 {
8088   struct MeshPeerInfo *pi;
8089   struct MeshPeerQueue *q;
8090   struct MeshPeerQueue *n;
8091
8092   DEBUG_CONN ("Peer disconnected\n");
8093   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
8094   if (NULL == pi)
8095   {
8096     GNUNET_break (0);
8097     return;
8098   }
8099   q = pi->queue_head;
8100   while (NULL != q)
8101   {
8102       n = q->next;
8103       /* TODO try to reroute this traffic instead */
8104       queue_destroy(q, GNUNET_YES);
8105       q = n;
8106   }
8107   if (NULL != pi->core_transmit)
8108   {
8109     GNUNET_CORE_notify_transmit_ready_cancel(pi->core_transmit);
8110     pi->core_transmit = NULL;
8111   }
8112   peer_info_remove_path (pi, pi->id, myid);
8113   if (myid == pi->id)
8114   {
8115     DEBUG_CONN ("     (self)\n");
8116   }
8117   GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
8118   return;
8119 }
8120
8121
8122 /******************************************************************************/
8123 /************************      MAIN FUNCTIONS      ****************************/
8124 /******************************************************************************/
8125
8126 /**
8127  * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
8128  *
8129  * @param cls closure
8130  * @param key current key code
8131  * @param value value in the hash map
8132  * @return GNUNET_YES if we should continue to iterate,
8133  *         GNUNET_NO if not.
8134  */
8135 static int
8136 shutdown_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
8137 {
8138   struct MeshTunnel *t = value;
8139
8140   tunnel_destroy (t);
8141   return GNUNET_YES;
8142 }
8143
8144 /**
8145  * Iterator over peer hash map entries to destroy the tunnel during shutdown.
8146  *
8147  * @param cls closure
8148  * @param key current key code
8149  * @param value value in the hash map
8150  * @return GNUNET_YES if we should continue to iterate,
8151  *         GNUNET_NO if not.
8152  */
8153 static int
8154 shutdown_peer (void *cls, const struct GNUNET_HashCode * key, void *value)
8155 {
8156   struct MeshPeerInfo *p = value;
8157   struct MeshPeerQueue *q;
8158   struct MeshPeerQueue *n;
8159
8160   q = p->queue_head;
8161   while (NULL != q)
8162   {
8163       n = q->next;
8164       if (q->peer == p)
8165       {
8166         queue_destroy(q, GNUNET_YES);
8167       }
8168       q = n;
8169   }
8170   peer_info_destroy (p);
8171   return GNUNET_YES;
8172 }
8173
8174
8175 /**
8176  * Task run during shutdown.
8177  *
8178  * @param cls unused
8179  * @param tc unused
8180  */
8181 static void
8182 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
8183 {
8184   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
8185
8186   if (core_handle != NULL)
8187   {
8188     GNUNET_CORE_disconnect (core_handle);
8189     core_handle = NULL;
8190   }
8191  if (NULL != keygen)
8192   {
8193     GNUNET_CRYPTO_rsa_key_create_stop (keygen);
8194     keygen = NULL;
8195   }
8196   GNUNET_CONTAINER_multihashmap_iterate (tunnels, &shutdown_tunnel, NULL);
8197   GNUNET_CONTAINER_multihashmap_iterate (peers, &shutdown_peer, NULL);
8198   if (dht_handle != NULL)
8199   {
8200     GNUNET_DHT_disconnect (dht_handle);
8201     dht_handle = NULL;
8202   }
8203   if (nc != NULL)
8204   {
8205     GNUNET_SERVER_notification_context_destroy (nc);
8206     nc = NULL;
8207   }
8208   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
8209   {
8210     GNUNET_SCHEDULER_cancel (announce_id_task);
8211     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
8212   }
8213   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
8214 }
8215
8216
8217 /**
8218  * Callback for hostkey read/generation
8219  *
8220  * @param cls NULL
8221  * @param pk the private key
8222  * @param emsg error message
8223  */
8224 static void
8225 key_generation_cb (void *cls,
8226                    struct GNUNET_CRYPTO_RsaPrivateKey *pk,
8227                    const char *emsg)
8228 {
8229   struct MeshPeerInfo *peer;
8230   struct MeshPeerPath *p;
8231
8232   keygen = NULL;  
8233   if (NULL == pk)
8234   {
8235     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8236                 _("Mesh service could not access hostkey.  Exiting.\n"));
8237     GNUNET_SCHEDULER_shutdown ();
8238     return;
8239   }
8240   my_private_key = pk;
8241   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
8242   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
8243                       &my_full_id.hashPubKey);
8244   myid = GNUNET_PEER_intern (&my_full_id);
8245   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
8246               "Mesh for peer [%s] starting\n",
8247               GNUNET_i2s(&my_full_id));
8248
8249 //   transport_handle = GNUNET_TRANSPORT_connect(c,
8250 //                                               &my_full_id,
8251 //                                               NULL,
8252 //                                               NULL,
8253 //                                               NULL,
8254 //                                               NULL);
8255
8256
8257
8258   next_tid = 0;
8259   next_local_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
8260
8261
8262   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
8263   nc = GNUNET_SERVER_notification_context_create (server_handle, 1);
8264   GNUNET_SERVER_disconnect_notify (server_handle,
8265                                    &handle_local_client_disconnect, NULL);
8266
8267
8268   clients = NULL;
8269   clients_tail = NULL;
8270   next_client_id = 0;
8271
8272   announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
8273   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
8274
8275   /* Create a peer_info for the local peer */
8276   peer = peer_info_get (&my_full_id);
8277   p = path_new (1);
8278   p->peers[0] = myid;
8279   GNUNET_PEER_change_rc (myid, 1);
8280   peer_info_add_path (peer, p, GNUNET_YES);
8281   GNUNET_SERVER_resume (server_handle);
8282   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Mesh service running\n");
8283 }
8284
8285
8286 /**
8287  * Process mesh requests.
8288  *
8289  * @param cls closure
8290  * @param server the initialized server
8291  * @param c configuration to use
8292  */
8293 static void
8294 run (void *cls, struct GNUNET_SERVER_Handle *server,
8295      const struct GNUNET_CONFIGURATION_Handle *c)
8296 {
8297   char *keyfile;
8298
8299   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
8300   server_handle = server;
8301   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
8302                                      NULL,      /* Closure passed to MESH functions */
8303                                      &core_init,        /* Call core_init once connected */
8304                                      &core_connect,     /* Handle connects */
8305                                      &core_disconnect,  /* remove peers on disconnects */
8306                                      NULL,      /* Don't notify about all incoming messages */
8307                                      GNUNET_NO, /* For header only in notification */
8308                                      NULL,      /* Don't notify about all outbound messages */
8309                                      GNUNET_NO, /* For header-only out notification */
8310                                      core_handlers);    /* Register these handlers */
8311
8312   if (core_handle == NULL)
8313   {
8314     GNUNET_break (0);
8315     GNUNET_SCHEDULER_shutdown ();
8316     return;
8317   }
8318
8319   if (GNUNET_OK !=
8320       GNUNET_CONFIGURATION_get_value_filename (c, "GNUNETD", "HOSTKEY",
8321                                                &keyfile))
8322   {
8323     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8324                 _
8325                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8326                 "mesh", "hostkey");
8327     GNUNET_SCHEDULER_shutdown ();
8328     return;
8329   }
8330
8331   if (GNUNET_OK !=
8332       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_PATH_TIME",
8333                                            &refresh_path_time))
8334   {
8335     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8336                 _
8337                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8338                 "mesh", "refresh path time");
8339     GNUNET_SCHEDULER_shutdown ();
8340     return;
8341   }
8342
8343   if (GNUNET_OK !=
8344       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "APP_ANNOUNCE_TIME",
8345                                            &app_announce_time))
8346   {
8347     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8348                 _
8349                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8350                 "mesh", "app announce time");
8351     GNUNET_SCHEDULER_shutdown ();
8352     return;
8353   }
8354   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "APP_ANNOUNCE_TIME %llu ms\n", app_announce_time.rel_value);
8355
8356   if (GNUNET_OK !=
8357       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "ID_ANNOUNCE_TIME",
8358                                            &id_announce_time))
8359   {
8360     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8361                 _
8362                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8363                 "mesh", "id announce time");
8364     GNUNET_SCHEDULER_shutdown ();
8365     return;
8366   }
8367   else
8368   {
8369   }
8370
8371   if (GNUNET_OK !=
8372       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "CONNECT_TIMEOUT",
8373                                            &connect_timeout))
8374   {
8375     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8376                 _
8377                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8378                 "mesh", "connect timeout");
8379     GNUNET_SCHEDULER_shutdown ();
8380     return;
8381   }
8382
8383   if (GNUNET_OK !=
8384       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
8385                                              &max_msgs_queue))
8386   {
8387     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8388                 _
8389                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8390                 "mesh", "max msgs queue");
8391     GNUNET_SCHEDULER_shutdown ();
8392     return;
8393   }
8394
8395   if (GNUNET_OK !=
8396       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_TUNNELS",
8397                                              &max_tunnels))
8398   {
8399     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
8400                 _
8401                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
8402                 "mesh", "max tunnels");
8403     GNUNET_SCHEDULER_shutdown ();
8404     return;
8405   }
8406
8407   if (GNUNET_OK !=
8408       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
8409                                              &default_ttl))
8410   {
8411     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
8412                 _
8413                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
8414                 "mesh", "default ttl", 64);
8415     default_ttl = 64;
8416   }
8417
8418   if (GNUNET_OK !=
8419       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DHT_REPLICATION_LEVEL",
8420                                              &dht_replication_level))
8421   {
8422     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
8423                 _
8424                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
8425                 "mesh", "dht replication level", 10);
8426     dht_replication_level = 10;
8427   }
8428
8429   tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
8430   incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
8431   peers = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
8432   applications = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
8433   types = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
8434
8435   dht_handle = GNUNET_DHT_connect (c, 64);
8436   if (NULL == dht_handle)
8437   {
8438     GNUNET_break (0);
8439   }
8440   stats = GNUNET_STATISTICS_create ("mesh", c);
8441
8442   GNUNET_SERVER_suspend (server_handle);
8443   /* Scheduled the task to clean up when shutdown is called */
8444   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
8445                                 NULL);
8446   keygen = GNUNET_CRYPTO_rsa_key_create_start (keyfile, &key_generation_cb, NULL);
8447   GNUNET_free (keyfile);
8448 }
8449
8450
8451 /**
8452  * The main function for the mesh service.
8453  *
8454  * @param argc number of arguments from the command line
8455  * @param argv command line arguments
8456  * @return 0 ok, 1 on error
8457  */
8458 int
8459 main (int argc, char *const *argv)
8460 {
8461   int ret;
8462   int r;
8463
8464   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
8465   r = GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
8466                           NULL);
8467   ret = (GNUNET_OK == r) ? 0 : 1;
8468   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");
8469
8470   INTERVAL_SHOW;
8471
8472   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
8473               "Mesh for peer [%s] FWD ACKs %u, BCK ACKs %u\n",
8474               GNUNET_i2s(&my_full_id), debug_fwd_ack, debug_bck_ack);
8475
8476   return ret;
8477 }