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