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