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