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