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