- refactoring, documentation
[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 /**
1644  * Get the higher ACK value out of two values, taking in account overflow.
1645  *
1646  * @param a First ACK value.
1647  * @param b Second ACK value.
1648  *
1649  * @return Highest ACK value from the two.
1650  */
1651 static uint32_t
1652 max_ack (uint32_t a, uint32_t b)
1653 {
1654   if (PID_OVERFLOW(b, a) || (a > b && !PID_OVERFLOW(a, b)))
1655     return a;
1656   return b;
1657 }
1658
1659
1660 /**
1661  * Get the lower ACK value out of two values, taking in account overflow.
1662  *
1663  * @param a First ACK value.
1664  * @param b Second ACK value.
1665  *
1666  * @return Lowest ACK value from the two.
1667  */
1668 static uint32_t
1669 min_ack (uint32_t a, uint32_t b)
1670 {
1671   return (max_ack (a, b) == a) ? b : a;
1672 }
1673
1674
1675 /**
1676  * Decrements the reference counter and frees all resources if needed
1677  *
1678  * @param mesh_data Data Descriptor used in a multicast message.
1679  *                  Freed no longer needed (last message).
1680  */
1681 static void
1682 data_descriptor_decrement_rc (struct MeshData *mesh_data)
1683 {
1684   /* Make sure it's a multicast packet */
1685   GNUNET_assert (NULL != mesh_data->reference_counter);
1686
1687   if (0 == --(*(mesh_data->reference_counter)))
1688   {
1689     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Last copy!\n");
1690     if (NULL != mesh_data->task)
1691     {
1692       if (GNUNET_SCHEDULER_NO_TASK != *(mesh_data->task))
1693       {
1694         GNUNET_SCHEDULER_cancel (*(mesh_data->task));
1695         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " notifying client...\n");
1696         GNUNET_SERVER_receive_done (mesh_data->t->owner->handle, GNUNET_OK);
1697       }
1698       GNUNET_free (mesh_data->task);
1699     }
1700     GNUNET_free (mesh_data->reference_counter);
1701     GNUNET_free (mesh_data->data);
1702     GNUNET_free (mesh_data);
1703   }
1704 }
1705
1706
1707 /**
1708  * Check if client has registered with the service and has not disconnected
1709  *
1710  * @param client the client to check
1711  *
1712  * @return non-NULL if client exists in the global DLL
1713  */
1714 static struct MeshClient *
1715 client_get (struct GNUNET_SERVER_Client *client)
1716 {
1717   struct MeshClient *c;
1718
1719   c = clients;
1720   while (NULL != c)
1721   {
1722     if (c->handle == client)
1723       return c;
1724     c = c->next;
1725   }
1726   return NULL;
1727 }
1728
1729
1730 /**
1731  * Checks if a given client has subscribed to certain message type
1732  *
1733  * @param message_type Type of message to check
1734  * @param c Client to check
1735  *
1736  * @return GNUNET_YES or GNUNET_NO, depending on subscription status
1737  */
1738 static int
1739 client_is_subscribed (uint16_t message_type, struct MeshClient *c)
1740 {
1741   struct GNUNET_HashCode hc;
1742
1743   if (NULL == c->types)
1744     return GNUNET_NO;
1745   GNUNET_CRYPTO_hash (&message_type, sizeof (uint16_t), &hc);
1746   return GNUNET_CONTAINER_multihashmap_contains (c->types, &hc);
1747 }
1748
1749
1750 /**
1751  * Allow a client to send more data after transmitting a multicast message
1752  * which some neighbor has not yet accepted altough a reasonable time has
1753  * passed.
1754  *
1755  * @param cls Closure (DataDescriptor containing the task identifier)
1756  * @param tc Task Context
1757  * 
1758  * FIXME reference counter cshould be just int
1759  */
1760 static void
1761 client_allow_send (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1762 {
1763   struct MeshData *mdata = cls;
1764
1765   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1766     return;
1767   GNUNET_assert (NULL != mdata->reference_counter);
1768   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1769               "CLIENT ALLOW SEND DESPITE %u COPIES PENDING\n",
1770               *(mdata->reference_counter));
1771   *(mdata->task) = GNUNET_SCHEDULER_NO_TASK;
1772   GNUNET_SERVER_receive_done (mdata->t->owner->handle, GNUNET_OK);
1773 }
1774
1775
1776 /**
1777  * Check whether client wants traffic from a tunnel.
1778  *
1779  * @param c Client to check.
1780  * @param t Tunnel to be found.
1781  *
1782  * @return GNUNET_YES if client knows tunnel.
1783  * 
1784  * TODO look in client hashmap
1785  */
1786 static int
1787 client_wants_tunnel (struct MeshClient *c, struct MeshTunnel *t)
1788 {
1789   unsigned int i;
1790
1791   for (i = 0; i < t->nclients; i++)
1792     if (t->clients[i] == c)
1793       return GNUNET_YES;
1794   return GNUNET_NO;
1795 }
1796
1797
1798 /**
1799  * Check whether client has been informed about a tunnel.
1800  *
1801  * @param c Client to check.
1802  * @param t Tunnel to be found.
1803  *
1804  * @return GNUNET_YES if client knows tunnel.
1805  * 
1806  * TODO look in client hashmap
1807  */
1808 static int
1809 client_knows_tunnel (struct MeshClient *c, struct MeshTunnel *t)
1810 {
1811   unsigned int i;
1812
1813   for (i = 0; i < t->nignore; i++)
1814     if (t->ignore[i] == c)
1815       return GNUNET_YES;
1816   return client_wants_tunnel(c, t);
1817 }
1818
1819
1820 /**
1821  * Marks a client as uninterested in traffic from the tunnel, updating both
1822  * client and tunnel to reflect this.
1823  *
1824  * @param c Client that doesn't want traffic anymore.
1825  * @param t Tunnel which should be ignored.
1826  *
1827  * FIXME when to delete an incoming tunnel?
1828  */
1829 static void
1830 client_ignore_tunnel (struct MeshClient *c, struct MeshTunnel *t)
1831 {
1832   struct GNUNET_HashCode hash;
1833
1834   GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
1835   GNUNET_break (GNUNET_YES ==
1836                 GNUNET_CONTAINER_multihashmap_remove (c->incoming_tunnels,
1837                                                       &hash, t));
1838   GNUNET_break (GNUNET_YES ==
1839                 GNUNET_CONTAINER_multihashmap_put (c->ignore_tunnels, &hash, t,
1840                                                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
1841   tunnel_delete_active_client (t, c);
1842   GNUNET_array_append (t->ignore, t->nignore, c);
1843 }
1844
1845
1846 /**
1847  * Deletes a tunnel from a client (either owner or destination). To be used on
1848  * tunnel destroy, otherwise, use client_ignore_tunnel.
1849  *
1850  * @param c Client whose tunnel to delete.
1851  * @param t Tunnel which should be deleted.
1852  */
1853 static void
1854 client_delete_tunnel (struct MeshClient *c, struct MeshTunnel *t)
1855 {
1856   struct GNUNET_HashCode hash;
1857
1858   if (c == t->owner)
1859   {
1860     GNUNET_CRYPTO_hash(&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
1861     GNUNET_assert (GNUNET_YES ==
1862                    GNUNET_CONTAINER_multihashmap_remove (c->own_tunnels,
1863                                                          &hash,
1864                                                          t));
1865   }
1866   else
1867   {
1868     GNUNET_CRYPTO_hash(&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
1869     // FIXME XOR?
1870     GNUNET_assert (GNUNET_YES ==
1871                    GNUNET_CONTAINER_multihashmap_remove (c->incoming_tunnels,
1872                                                          &hash,
1873                                                          t) ||
1874                    GNUNET_YES ==
1875                    GNUNET_CONTAINER_multihashmap_remove (c->ignore_tunnels,
1876                                                          &hash,
1877                                                          t));
1878   }
1879 }
1880
1881
1882 /**
1883  * Send the message to all clients that have subscribed to its type
1884  *
1885  * @param msg Pointer to the message itself
1886  * @param payload Pointer to the payload of the message.
1887  * @return number of clients this message was sent to
1888  */
1889 static unsigned int
1890 send_subscribed_clients (const struct GNUNET_MessageHeader *msg,
1891                          const struct GNUNET_MessageHeader *payload)
1892 {
1893   struct GNUNET_PeerIdentity *oid;
1894   struct MeshClient *c;
1895   struct MeshTunnel *t;
1896   MESH_TunnelNumber *tid;
1897   unsigned int count;
1898   uint16_t type;
1899   char cbuf[htons (msg->size)];
1900
1901   type = ntohs (payload->type);
1902   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending to clients...\n");
1903   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "message of type %u\n", type);
1904
1905   memcpy (cbuf, msg, sizeof (cbuf));
1906   switch (htons (msg->type))
1907   {
1908     struct GNUNET_MESH_Unicast *uc;
1909     struct GNUNET_MESH_Multicast *mc;
1910     struct GNUNET_MESH_ToOrigin *to;
1911
1912   case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
1913     uc = (struct GNUNET_MESH_Unicast *) cbuf;
1914     tid = &uc->tid;
1915     oid = &uc->oid;
1916     break;
1917   case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
1918     mc = (struct GNUNET_MESH_Multicast *) cbuf;
1919     tid = &mc->tid;
1920     oid = &mc->oid;
1921     break;
1922   case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
1923     to = (struct GNUNET_MESH_ToOrigin *) cbuf;
1924     tid = &to->tid;
1925     oid = &to->oid;
1926     break;
1927   default:
1928     GNUNET_break (0);
1929     return 0;
1930   }
1931   t = tunnel_get (oid, ntohl (*tid));
1932   if (NULL == t)
1933   {
1934     GNUNET_break (0);
1935     return 0;
1936   }
1937
1938   for (count = 0, c = clients; c != NULL; c = c->next)
1939   {
1940     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   client %u\n", c->id);
1941     if (client_is_subscribed (type, c))
1942     {
1943       if (htons (msg->type) == GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN)
1944       {
1945         if (c != t->owner)
1946           continue;
1947         *tid = htonl (t->local_tid);
1948       }
1949       else
1950       {
1951         if (GNUNET_NO == client_knows_tunnel (c, t))
1952         {
1953           /* This client doesn't know the tunnel */
1954           struct GNUNET_MESH_TunnelNotification tmsg;
1955           struct GNUNET_HashCode hash;
1956
1957           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "     sending tunnel create\n");
1958           tmsg.header.size = htons (sizeof (tmsg));
1959           tmsg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
1960           GNUNET_PEER_resolve (t->id.oid, &tmsg.peer);
1961           tmsg.tunnel_id = htonl (t->local_tid_dest);
1962           GNUNET_SERVER_notification_context_unicast (nc, c->handle,
1963                                                       &tmsg.header, GNUNET_NO);
1964           tunnel_add_client (t, c);
1965           GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber),
1966                               &hash);
1967           GNUNET_break (GNUNET_OK == GNUNET_CONTAINER_multihashmap_put (
1968                                        c->incoming_tunnels, &hash, t,
1969                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
1970         }
1971         *tid = htonl (t->local_tid_dest);
1972       }
1973
1974       /* Check if the client wants to get traffic from the tunnel */
1975       if (GNUNET_NO == client_wants_tunnel(c, t))
1976         continue;
1977       count++;
1978       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "     sending\n");
1979       GNUNET_SERVER_notification_context_unicast (nc, c->handle,
1980                                                   (struct GNUNET_MessageHeader
1981                                                    *) cbuf, GNUNET_NO);
1982     }
1983   }
1984   return count;
1985 }
1986
1987
1988 /**
1989  * Notify the client that owns the tunnel that a peer has connected to it
1990  * (the requested path to it has been confirmed).
1991  *
1992  * @param t Tunnel whose owner to notify
1993  * @param id Short id of the peer that has connected
1994  */
1995 static void
1996 send_client_peer_connected (const struct MeshTunnel *t, const GNUNET_PEER_Id id)
1997 {
1998   struct GNUNET_MESH_PeerControl pc;
1999
2000   pc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD);
2001   pc.header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
2002   pc.tunnel_id = htonl (t->local_tid);
2003   GNUNET_PEER_resolve (id, &pc.peer);
2004   GNUNET_SERVER_notification_context_unicast (nc, t->owner->handle, &pc.header,
2005                                               GNUNET_NO);
2006 }
2007
2008
2009 /**
2010  * Notify a client about how many more payload packages will we accept
2011  * on a given tunnel.
2012  *
2013  * @param c Client.
2014  * @param t Tunnel.
2015  */
2016 static void
2017 send_client_tunnel_ack (struct MeshClient *c, struct MeshTunnel *t)
2018 {
2019   struct GNUNET_MESH_LocalAck msg;
2020   uint32_t ack;
2021
2022   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2023               "Sending client ACK on tunnel %X\n",
2024               t->local_tid);
2025   if (NULL == c)
2026     return;
2027
2028   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " to client %u\n", c->id);
2029
2030   ack = tunnel_get_fwd_ack (t);
2031
2032   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ack %u\n", ack);
2033   if (t->last_ack == ack)
2034     return;
2035
2036   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " sending!\n");
2037   t->last_ack = ack;
2038   msg.header.size = htons (sizeof (msg));
2039   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
2040   msg.tunnel_id = htonl (t->local_tid);
2041   msg.max_pid = htonl (ack);
2042
2043   GNUNET_SERVER_notification_context_unicast (nc, c->handle,
2044                                               &msg.header, GNUNET_NO);
2045 }
2046
2047
2048 /**
2049  * Notify all clients (not depending on registration status) that the incoming
2050  * tunnel is no longer valid.
2051  *
2052  * @param t Tunnel that was destroyed.
2053  */
2054 static void
2055 send_clients_tunnel_destroy (struct MeshTunnel *t)
2056 {
2057   struct GNUNET_MESH_TunnelMessage msg;
2058
2059   msg.header.size = htons (sizeof (msg));
2060   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
2061   msg.tunnel_id = htonl (t->local_tid_dest);
2062   GNUNET_SERVER_notification_context_broadcast (nc, &msg.header, GNUNET_NO);
2063 }
2064
2065
2066 /**
2067  * Notify clients of tunnel disconnections, if needed.
2068  * In case the origin disconnects, the destination clients get a tunnel destroy
2069  * notification. If the last destination disconnects (only one remaining client
2070  * in tunnel), the origin gets a (local ID) peer disconnected.
2071  * Note that the function must be called BEFORE removing the client from
2072  * the tunnel.
2073  *
2074  * @param t Tunnel that was destroyed.
2075  * @param c Client that disconnected.
2076  */
2077 static void
2078 send_client_tunnel_disconnect (struct MeshTunnel *t, struct MeshClient *c)
2079 {
2080   unsigned int i;
2081
2082   if (c == t->owner)
2083   {
2084     struct GNUNET_MESH_TunnelMessage msg;
2085
2086     msg.header.size = htons (sizeof (msg));
2087     msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
2088     msg.tunnel_id = htonl (t->local_tid_dest);
2089     for (i = 0; i < t->nclients; i++)
2090       GNUNET_SERVER_notification_context_unicast (nc, t->clients[i]->handle,
2091                                                   &msg.header, GNUNET_NO);
2092   }
2093   // FIXME when to disconnect an incoming tunnel?
2094   else if (1 == t->nclients && NULL != t->owner)
2095   {
2096     struct GNUNET_MESH_PeerControl msg;
2097
2098     msg.header.size = htons (sizeof (msg));
2099     msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL);
2100     msg.tunnel_id = htonl (t->local_tid);
2101     msg.peer = my_full_id;
2102     GNUNET_SERVER_notification_context_unicast (nc, t->owner->handle,
2103                                                 &msg.header, GNUNET_NO);
2104   }
2105 }
2106
2107
2108 /**
2109  * Retrieve the MeshPeerInfo stucture associated with the peer, create one
2110  * and insert it in the appropiate structures if the peer is not known yet.
2111  *
2112  * @param peer Full identity of the peer.
2113  *
2114  * @return Existing or newly created peer info.
2115  */
2116 static struct MeshPeerInfo *
2117 peer_info_get (const struct GNUNET_PeerIdentity *peer)
2118 {
2119   struct MeshPeerInfo *peer_info;
2120
2121   peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
2122   if (NULL == peer_info)
2123   {
2124     peer_info =
2125         (struct MeshPeerInfo *) GNUNET_malloc (sizeof (struct MeshPeerInfo));
2126     GNUNET_CONTAINER_multihashmap_put (peers, &peer->hashPubKey, peer_info,
2127                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2128     peer_info->id = GNUNET_PEER_intern (peer);
2129   }
2130
2131   return peer_info;
2132 }
2133
2134
2135 /**
2136  * Retrieve the MeshPeerInfo stucture associated with the peer, create one
2137  * and insert it in the appropiate structures if the peer is not known yet.
2138  *
2139  * @param peer Short identity of the peer.
2140  *
2141  * @return Existing or newly created peer info.
2142  */
2143 static struct MeshPeerInfo *
2144 peer_info_get_short (const GNUNET_PEER_Id peer)
2145 {
2146   struct GNUNET_PeerIdentity id;
2147
2148   GNUNET_PEER_resolve (peer, &id);
2149   return peer_info_get (&id);
2150 }
2151
2152
2153 /**
2154  * Iterator to remove the tunnel from the list of tunnels a peer participates
2155  * in.
2156  *
2157  * @param cls Closure (tunnel info)
2158  * @param key GNUNET_PeerIdentity of the peer (unused)
2159  * @param value PeerInfo of the peer
2160  *
2161  * @return always GNUNET_YES, to keep iterating
2162  */
2163 static int
2164 peer_info_delete_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
2165 {
2166   struct MeshTunnel *t = cls;
2167   struct MeshPeerInfo *peer = value;
2168   unsigned int i;
2169
2170   for (i = 0; i < peer->ntunnels; i++)
2171   {
2172     if (0 ==
2173         memcmp (&peer->tunnels[i]->id, &t->id, sizeof (struct MESH_TunnelID)))
2174     {
2175       peer->ntunnels--;
2176       peer->tunnels[i] = peer->tunnels[peer->ntunnels];
2177       peer->tunnels = GNUNET_realloc (peer->tunnels, peer->ntunnels);
2178       return GNUNET_YES;
2179     }
2180   }
2181   return GNUNET_YES;
2182 }
2183
2184
2185 /**
2186   * Core callback to write a pre-constructed data packet to core buffer
2187   *
2188   * @param cls Closure (MeshTransmissionDescriptor with data in "data" member).
2189   * @param size Number of bytes available in buf.
2190   * @param buf Where the to write the message.
2191   *
2192   * @return number of bytes written to buf
2193   */
2194 static size_t
2195 send_core_data_raw (void *cls, size_t size, void *buf)
2196 {
2197   struct MeshTransmissionDescriptor *info = cls;
2198   struct GNUNET_MessageHeader *msg;
2199   size_t total_size;
2200
2201   GNUNET_assert (NULL != info);
2202   GNUNET_assert (NULL != info->mesh_data);
2203   msg = (struct GNUNET_MessageHeader *) info->mesh_data->data;
2204   total_size = ntohs (msg->size);
2205
2206   if (total_size > size)
2207   {
2208     GNUNET_break (0);
2209     return 0;
2210   }
2211   memcpy (buf, msg, total_size);
2212   data_descriptor_decrement_rc (info->mesh_data);
2213   GNUNET_free (info);
2214   return total_size;
2215 }
2216
2217
2218 /**
2219  * Sends an already built non-multicast message to a peer,
2220  * properly registrating all used resources.
2221  *
2222  * @param message Message to send. Function makes a copy of it.
2223  * @param peer Short ID of the neighbor whom to send the message.
2224  * @param t Tunnel on which this message is transmitted.
2225  */
2226 static void
2227 send_message (const struct GNUNET_MessageHeader *message,
2228               const struct GNUNET_PeerIdentity *peer,
2229               struct MeshTunnel *t)
2230 {
2231   struct MeshTransmissionDescriptor *info;
2232   struct MeshPeerInfo *neighbor;
2233   struct MeshPeerPath *p;
2234   size_t size;
2235
2236 //   GNUNET_TRANSPORT_try_connect(); FIXME use?
2237
2238   size = ntohs (message->size);
2239   info = GNUNET_malloc (sizeof (struct MeshTransmissionDescriptor));
2240   info->mesh_data = GNUNET_malloc (sizeof (struct MeshData));
2241   info->mesh_data->data = GNUNET_malloc (size);
2242   memcpy (info->mesh_data->data, message, size);
2243   if (ntohs(message->type) == GNUNET_MESSAGE_TYPE_MESH_UNICAST)
2244   {
2245     struct GNUNET_MESH_Unicast *m;
2246
2247     m = (struct GNUNET_MESH_Unicast *) info->mesh_data->data;
2248     m->ttl = htonl (ntohl (m->ttl) - 1);
2249   }
2250   info->mesh_data->data_len = size;
2251   info->mesh_data->reference_counter = GNUNET_malloc (sizeof (unsigned int));
2252   *info->mesh_data->reference_counter = 1;
2253   neighbor = peer_info_get (peer);
2254   for (p = neighbor->path_head; NULL != p; p = p->next)
2255   {
2256     if (2 >= p->length)
2257     {
2258       break;
2259     }
2260   }
2261   if (NULL == p)
2262   {
2263     GNUNET_break (0); // FIXME sometimes fails (testing disconnect?)
2264     GNUNET_free (info->mesh_data->data);
2265     GNUNET_free (info->mesh_data);
2266     GNUNET_free (info);
2267     return;
2268   }
2269   info->peer = neighbor;
2270   queue_add (info,
2271              0,
2272              size,
2273              neighbor,
2274              t);
2275 }
2276
2277
2278 /**
2279  * Sends a CREATE PATH message for a path to a peer, properly registrating
2280  * all used resources.
2281  *
2282  * @param peer PeerInfo of the final peer for whom this path is being created.
2283  * @param p Path itself.
2284  * @param t Tunnel for which the path is created.
2285  */
2286 static void
2287 send_create_path (struct MeshPeerInfo *peer, struct MeshPeerPath *p,
2288                   struct MeshTunnel *t)
2289 {
2290   struct GNUNET_PeerIdentity id;
2291   struct MeshPathInfo *path_info;
2292   struct MeshPeerInfo *neighbor;
2293
2294   unsigned int i;
2295
2296   if (NULL == p)
2297   {
2298     p = tree_get_path_to_peer (t->tree, peer->id);
2299     if (NULL == p)
2300     {
2301       GNUNET_break (0);
2302       return;
2303     }
2304   }
2305   for (i = 0; i < p->length; i++)
2306   {
2307     if (p->peers[i] == myid)
2308       break;
2309   }
2310   if (i >= p->length - 1)
2311   {
2312     path_destroy (p);
2313     GNUNET_break (0);
2314     return;
2315   }
2316   GNUNET_PEER_resolve (p->peers[i + 1], &id);
2317
2318   path_info = GNUNET_malloc (sizeof (struct MeshPathInfo));
2319   path_info->path = p;
2320   path_info->t = t;
2321   neighbor = peer_info_get (&id);
2322   path_info->peer = neighbor;
2323   queue_add (path_info,
2324              GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE,
2325              sizeof (struct GNUNET_MESH_ManipulatePath) +
2326                 (p->length * sizeof (struct GNUNET_PeerIdentity)),
2327              neighbor,
2328              t);
2329 }
2330
2331
2332 /**
2333  * Sends a DESTROY PATH message to free resources for a path in a tunnel
2334  *
2335  * @param t Tunnel whose path to destroy.
2336  * @param destination Short ID of the peer to whom the path to destroy.
2337  */
2338 static void
2339 send_destroy_path (struct MeshTunnel *t, GNUNET_PEER_Id destination)
2340 {
2341   struct MeshPeerPath *p;
2342   size_t size;
2343
2344   p = tree_get_path_to_peer (t->tree, destination);
2345   if (NULL == p)
2346   {
2347     GNUNET_break (0);
2348     return;
2349   }
2350   size = sizeof (struct GNUNET_MESH_ManipulatePath);
2351   size += p->length * sizeof (struct GNUNET_PeerIdentity);
2352   {
2353     struct GNUNET_MESH_ManipulatePath *msg;
2354     struct GNUNET_PeerIdentity *pi;
2355     char cbuf[size];
2356     unsigned int i;
2357
2358     msg = (struct GNUNET_MESH_ManipulatePath *) cbuf;
2359     msg->header.size = htons (size);
2360     msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY);
2361     msg->tid = htonl (t->id.tid);
2362     pi = (struct GNUNET_PeerIdentity *) &msg[1];
2363     for (i = 0; i < p->length; i++)
2364     {
2365       GNUNET_PEER_resolve (p->peers[i], &pi[i]);
2366     }
2367     send_message (&msg->header, tree_get_first_hop (t->tree, destination), t);
2368   }
2369   path_destroy (p);
2370 }
2371
2372
2373 /**
2374  * Try to establish a new connection to this peer.
2375  * Use the best path for the given tunnel.
2376  * If the peer doesn't have any path to it yet, try to get one.
2377  * If the peer already has some path, send a CREATE PATH towards it.
2378  *
2379  * @param peer PeerInfo of the peer.
2380  * @param t Tunnel for which to create the path, if possible.
2381  */
2382 static void
2383 peer_info_connect (struct MeshPeerInfo *peer, struct MeshTunnel *t)
2384 {
2385   struct MeshPeerPath *p;
2386   struct MeshPathInfo *path_info;
2387
2388   if (NULL != peer->path_head)
2389   {
2390     p = tree_get_path_to_peer (t->tree, peer->id);
2391     if (NULL == p)
2392     {
2393       GNUNET_break (0);
2394       return;
2395     }
2396
2397     // FIXME always send create path to self
2398     if (p->length > 1)
2399     {
2400       send_create_path (peer, p, t);
2401     }
2402     else
2403     {
2404       struct GNUNET_HashCode hash;
2405
2406       path_destroy (p);
2407       send_client_peer_connected (t, myid);
2408       t->local_tid_dest = next_local_tid++;
2409       GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber),
2410                           &hash);
2411       if (GNUNET_OK !=
2412           GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
2413                                              GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2414       {
2415         GNUNET_break (0);
2416         return;
2417       }
2418     }
2419   }
2420   else if (NULL == peer->dhtget)
2421   {
2422     struct GNUNET_PeerIdentity id;
2423
2424     GNUNET_PEER_resolve (peer->id, &id);
2425     path_info = GNUNET_malloc (sizeof (struct MeshPathInfo));
2426     path_info->peer = peer;
2427     path_info->t = t;
2428     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2429                 "  Starting DHT GET for peer %s\n", GNUNET_i2s (&id));
2430     peer->dhtgetcls = path_info;
2431     peer->dhtget = GNUNET_DHT_get_start (dht_handle,    /* handle */
2432                                          GNUNET_BLOCK_TYPE_MESH_PEER, /* type */
2433                                          &id.hashPubKey,     /* key to search */
2434                                          dht_replication_level, /* replication level */
2435                                          GNUNET_DHT_RO_RECORD_ROUTE |
2436                                          GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
2437                                          NULL,       /* xquery */ // FIXME BLOOMFILTER
2438                                          0,     /* xquery bits */ // FIXME BLOOMFILTER SIZE
2439                                          &dht_get_id_handler, path_info);
2440   }
2441   /* Otherwise, there is no path but the DHT get is already started. */
2442 }
2443
2444
2445 /**
2446  * Task to delay the connection of a peer
2447  *
2448  * @param cls Closure (path info with tunnel and peer to connect).
2449  *            Will be free'd on exection.
2450  * @param tc TaskContext
2451  */
2452 static void
2453 peer_info_connect_task (void *cls,
2454                         const struct GNUNET_SCHEDULER_TaskContext *tc)
2455 {
2456   struct MeshPathInfo *path_info = cls;
2457
2458   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2459   {
2460     GNUNET_free (cls);
2461     return;
2462   }
2463   peer_info_connect (path_info->peer, path_info->t);
2464   GNUNET_free (cls);
2465 }
2466
2467
2468 /**
2469  * Destroy the peer_info and free any allocated resources linked to it
2470  *
2471  * @param pi The peer_info to destroy.
2472  *
2473  * @return GNUNET_OK on success
2474  */
2475 static int
2476 peer_info_destroy (struct MeshPeerInfo *pi)
2477 {
2478   struct GNUNET_PeerIdentity id;
2479   struct MeshPeerPath *p;
2480   struct MeshPeerPath *nextp;
2481
2482   GNUNET_PEER_resolve (pi->id, &id);
2483   GNUNET_PEER_change_rc (pi->id, -1);
2484
2485   if (GNUNET_YES !=
2486       GNUNET_CONTAINER_multihashmap_remove (peers, &id.hashPubKey, pi))
2487   {
2488     GNUNET_break (0);
2489     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2490                 "removing peer %s, not in hashmap\n", GNUNET_i2s (&id));
2491   }
2492   if (NULL != pi->dhtget)
2493   {
2494     GNUNET_DHT_get_stop (pi->dhtget);
2495     GNUNET_free (pi->dhtgetcls);
2496   }
2497   p = pi->path_head;
2498   while (NULL != p)
2499   {
2500     nextp = p->next;
2501     GNUNET_CONTAINER_DLL_remove (pi->path_head, pi->path_tail, p);
2502     path_destroy (p);
2503     p = nextp;
2504   }
2505   GNUNET_free (pi);
2506   return GNUNET_OK;
2507 }
2508
2509
2510 /**
2511  * Remove all paths that rely on a direct connection between p1 and p2
2512  * from the peer itself and notify all tunnels about it.
2513  *
2514  * @param peer PeerInfo of affected peer.
2515  * @param p1 GNUNET_PEER_Id of one peer.
2516  * @param p2 GNUNET_PEER_Id of another peer that was connected to the first and
2517  *           no longer is.
2518  *
2519  * TODO: optimize (see below)
2520  */
2521 static void
2522 peer_info_remove_path (struct MeshPeerInfo *peer, GNUNET_PEER_Id p1,
2523                        GNUNET_PEER_Id p2)
2524 {
2525   struct MeshPeerPath *p;
2526   struct MeshPeerPath *aux;
2527   struct MeshPeerInfo *peer_d;
2528   GNUNET_PEER_Id d;
2529   unsigned int destroyed;
2530   unsigned int best;
2531   unsigned int cost;
2532   unsigned int i;
2533
2534   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "peer_info_remove_path\n");
2535   destroyed = 0;
2536   p = peer->path_head;
2537   while (NULL != p)
2538   {
2539     aux = p->next;
2540     for (i = 0; i < (p->length - 1); i++)
2541     {
2542       if ((p->peers[i] == p1 && p->peers[i + 1] == p2) ||
2543           (p->peers[i] == p2 && p->peers[i + 1] == p1))
2544       {
2545         GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, p);
2546         path_destroy (p);
2547         destroyed++;
2548         break;
2549       }
2550     }
2551     p = aux;
2552   }
2553   if (0 == destroyed)
2554     return;
2555
2556   for (i = 0; i < peer->ntunnels; i++)
2557   {
2558     d = tunnel_notify_connection_broken (peer->tunnels[i], p1, p2);
2559     if (0 == d)
2560       continue;
2561     /* TODO
2562      * Problem: one or more peers have been deleted from the tunnel tree.
2563      * We don't know who they are to try to add them again.
2564      * We need to try to find a new path for each of the disconnected peers.
2565      * Some of them might already have a path to reach them that does not
2566      * involve p1 and p2. Adding all anew might render in a better tree than
2567      * the trivial immediate fix.
2568      *
2569      * Trivial immiediate fix: try to reconnect to the disconnected node. All
2570      * its children will be reachable trough him.
2571      */
2572     peer_d = peer_info_get_short (d);
2573     best = UINT_MAX;
2574     aux = NULL;
2575     for (p = peer_d->path_head; NULL != p; p = p->next)
2576     {
2577       if ((cost = tree_get_path_cost (peer->tunnels[i]->tree, p)) < best)
2578       {
2579         best = cost;
2580         aux = p;
2581       }
2582     }
2583     if (NULL != aux)
2584     {
2585       /* No callback, as peer will be already disconnected and a connection
2586        * scheduled by tunnel_notify_connection_broken.
2587        */
2588       tree_add_path (peer->tunnels[i]->tree, aux, NULL, NULL);
2589     }
2590     else
2591     {
2592       peer_info_connect (peer_d, peer->tunnels[i]);
2593     }
2594   }
2595   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "peer_info_remove_path END\n");
2596 }
2597
2598
2599 /**
2600  * Add the path to the peer and update the path used to reach it in case this
2601  * is the shortest.
2602  *
2603  * @param peer_info Destination peer to add the path to.
2604  * @param path New path to add. Last peer must be the peer in arg 1.
2605  *             Path will be either used of freed if already known.
2606  * @param trusted Do we trust that this path is real?
2607  */
2608 void
2609 peer_info_add_path (struct MeshPeerInfo *peer_info, struct MeshPeerPath *path,
2610                     int trusted)
2611 {
2612   struct MeshPeerPath *aux;
2613   unsigned int l;
2614   unsigned int l2;
2615
2616   if ((NULL == peer_info) || (NULL == path))
2617   {
2618     GNUNET_break (0);
2619     path_destroy (path);
2620     return;
2621   }
2622   if (path->peers[path->length - 1] != peer_info->id)
2623   {
2624     GNUNET_break (0);
2625     path_destroy (path);
2626     return;
2627   }
2628   if (path->length <= 2 && GNUNET_NO == trusted)
2629   {
2630     /* Only allow CORE to tell us about direct paths */
2631     path_destroy (path);
2632     return;
2633   }
2634   GNUNET_assert (peer_info->id == path->peers[path->length - 1]);
2635   for (l = 1; l < path->length; l++)
2636   {
2637     if (path->peers[l] == myid)
2638     {
2639       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shortening path by %u\n", l);
2640       for (l2 = 0; l2 < path->length - l; l2++)
2641       {
2642         path->peers[l2] = path->peers[l + l2];
2643       }
2644       path->length -= l;
2645       l = 1;
2646       path->peers =
2647           GNUNET_realloc (path->peers, path->length * sizeof (GNUNET_PEER_Id));
2648     }
2649   }
2650 #if MESH_DEBUG
2651   {
2652     struct GNUNET_PeerIdentity id;
2653
2654     GNUNET_PEER_resolve (peer_info->id, &id);
2655     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "adding path [%u] to peer %s\n",
2656                 path->length, GNUNET_i2s (&id));
2657   }
2658 #endif
2659   l = path_get_length (path);
2660   if (0 == l)
2661   {
2662     GNUNET_free (path);
2663     return;
2664   }
2665
2666   GNUNET_assert (peer_info->id == path->peers[path->length - 1]);
2667   for (aux = peer_info->path_head; aux != NULL; aux = aux->next)
2668   {
2669     l2 = path_get_length (aux);
2670     if (l2 > l)
2671     {
2672       GNUNET_CONTAINER_DLL_insert_before (peer_info->path_head,
2673                                           peer_info->path_tail, aux, path);
2674       return;
2675     }
2676     else
2677     {
2678       if (l2 == l && memcmp (path->peers, aux->peers, l) == 0)
2679       {
2680         path_destroy (path);
2681         return;
2682       }
2683     }
2684   }
2685   GNUNET_CONTAINER_DLL_insert_tail (peer_info->path_head, peer_info->path_tail,
2686                                     path);
2687   return;
2688 }
2689
2690
2691 /**
2692  * Add the path to the origin peer and update the path used to reach it in case
2693  * this is the shortest.
2694  * The path is given in peer_info -> destination, therefore we turn the path
2695  * upside down first.
2696  *
2697  * @param peer_info Peer to add the path to, being the origin of the path.
2698  * @param path New path to add after being inversed.
2699  * @param trusted Do we trust that this path is real?
2700  */
2701 static void
2702 peer_info_add_path_to_origin (struct MeshPeerInfo *peer_info,
2703                               struct MeshPeerPath *path, int trusted)
2704 {
2705   path_invert (path);
2706   peer_info_add_path (peer_info, path, trusted);
2707 }
2708
2709
2710 /**
2711  * Build a PeerPath from the paths returned from the DHT, reversing the paths
2712  * to obtain a local peer -> destination path and interning the peer ids.
2713  *
2714  * @return Newly allocated and created path
2715  */
2716 static struct MeshPeerPath *
2717 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
2718                      unsigned int get_path_length,
2719                      const struct GNUNET_PeerIdentity *put_path,
2720                      unsigned int put_path_length)
2721 {
2722   struct MeshPeerPath *p;
2723   GNUNET_PEER_Id id;
2724   int i;
2725
2726   p = path_new (1);
2727   p->peers[0] = myid;
2728   GNUNET_PEER_change_rc (myid, 1);
2729   i = get_path_length;
2730   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   GET has %d hops.\n", i);
2731   for (i--; i >= 0; i--)
2732   {
2733     id = GNUNET_PEER_intern (&get_path[i]);
2734     if (p->length > 0 && id == p->peers[p->length - 1])
2735     {
2736       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Optimizing 1 hop out.\n");
2737       GNUNET_PEER_change_rc (id, -1);
2738     }
2739     else
2740     {
2741       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Adding from GET: %s.\n",
2742                   GNUNET_i2s (&get_path[i]));
2743       p->length++;
2744       p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
2745       p->peers[p->length - 1] = id;
2746     }
2747   }
2748   i = put_path_length;
2749   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   PUT has %d hops.\n", i);
2750   for (i--; i >= 0; i--)
2751   {
2752     id = GNUNET_PEER_intern (&put_path[i]);
2753     if (id == myid)
2754     {
2755       /* PUT path went through us, so discard the path up until now and start
2756        * from here to get a much shorter (and loop-free) path.
2757        */
2758       path_destroy (p);
2759       p = path_new (0);
2760     }
2761     if (p->length > 0 && id == p->peers[p->length - 1])
2762     {
2763       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Optimizing 1 hop out.\n");
2764       GNUNET_PEER_change_rc (id, -1);
2765     }
2766     else
2767     {
2768       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Adding from PUT: %s.\n",
2769                   GNUNET_i2s (&put_path[i]));
2770       p->length++;
2771       p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
2772       p->peers[p->length - 1] = id;
2773     }
2774   }
2775 #if MESH_DEBUG
2776   if (get_path_length > 0)
2777     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (first of GET: %s)\n",
2778                 GNUNET_i2s (&get_path[0]));
2779   if (put_path_length > 0)
2780     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (first of PUT: %s)\n",
2781                 GNUNET_i2s (&put_path[0]));
2782   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   In total: %d hops\n",
2783               p->length);
2784   for (i = 0; i < p->length; i++)
2785   {
2786     struct GNUNET_PeerIdentity peer_id;
2787
2788     GNUNET_PEER_resolve (p->peers[i], &peer_id);
2789     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "       %u: %s\n", p->peers[i],
2790                 GNUNET_i2s (&peer_id));
2791   }
2792 #endif
2793   return p;
2794 }
2795
2796
2797 /**
2798  * Adds a path to the peer_infos of all the peers in the path
2799  *
2800  * @param p Path to process.
2801  * @param confirmed Whether we know if the path works or not.
2802  */
2803 static void
2804 path_add_to_peers (struct MeshPeerPath *p, int confirmed)
2805 {
2806   unsigned int i;
2807
2808   /* TODO: invert and add */
2809   for (i = 0; i < p->length && p->peers[i] != myid; i++) /* skip'em */ ;
2810   for (i++; i < p->length; i++)
2811   {
2812     struct MeshPeerInfo *aux;
2813     struct MeshPeerPath *copy;
2814
2815     aux = peer_info_get_short (p->peers[i]);
2816     copy = path_duplicate (p);
2817     copy->length = i + 1;
2818     peer_info_add_path (aux, copy, GNUNET_NO);
2819   }
2820 }
2821
2822
2823 /**
2824  * Send keepalive packets for a peer
2825  *
2826  * @param cls Closure (tunnel for which to send the keepalive).
2827  * @param tc Notification context.
2828  *
2829  * TODO: implement explicit multicast keepalive?
2830  */
2831 static void
2832 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
2833
2834
2835 /**
2836  * Search for a tunnel among the incoming tunnels
2837  *
2838  * @param tid the local id of the tunnel
2839  *
2840  * @return tunnel handler, NULL if doesn't exist
2841  */
2842 static struct MeshTunnel *
2843 tunnel_get_incoming (MESH_TunnelNumber tid)
2844 {
2845   struct GNUNET_HashCode hash;
2846
2847   GNUNET_assert (tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV);
2848   GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
2849   return GNUNET_CONTAINER_multihashmap_get (incoming_tunnels, &hash);
2850 }
2851
2852
2853 /**
2854  * Search for a tunnel among the tunnels for a client
2855  *
2856  * @param c the client whose tunnels to search in
2857  * @param tid the local id of the tunnel
2858  *
2859  * @return tunnel handler, NULL if doesn't exist
2860  */
2861 static struct MeshTunnel *
2862 tunnel_get_by_local_id (struct MeshClient *c, MESH_TunnelNumber tid)
2863 {
2864   if (tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
2865   {
2866     return tunnel_get_incoming (tid);
2867   }
2868   else
2869   {
2870     struct GNUNET_HashCode hash;
2871
2872     GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
2873     return GNUNET_CONTAINER_multihashmap_get (c->own_tunnels, &hash);
2874   }
2875 }
2876
2877
2878 /**
2879  * Search for a tunnel by global ID using PEER_ID
2880  *
2881  * @param pi owner of the tunnel
2882  * @param tid global tunnel number
2883  *
2884  * @return tunnel handler, NULL if doesn't exist
2885  */
2886 static struct MeshTunnel *
2887 tunnel_get_by_pi (GNUNET_PEER_Id pi, MESH_TunnelNumber tid)
2888 {
2889   struct MESH_TunnelID id;
2890   struct GNUNET_HashCode hash;
2891
2892   id.oid = pi;
2893   id.tid = tid;
2894
2895   GNUNET_CRYPTO_hash (&id, sizeof (struct MESH_TunnelID), &hash);
2896   return GNUNET_CONTAINER_multihashmap_get (tunnels, &hash);
2897 }
2898
2899
2900 /**
2901  * Search for a tunnel by global ID using full PeerIdentities
2902  *
2903  * @param oid owner of the tunnel
2904  * @param tid global tunnel number
2905  *
2906  * @return tunnel handler, NULL if doesn't exist
2907  */
2908 static struct MeshTunnel *
2909 tunnel_get (struct GNUNET_PeerIdentity *oid, MESH_TunnelNumber tid)
2910 {
2911   return tunnel_get_by_pi (GNUNET_PEER_search (oid), tid);
2912 }
2913
2914
2915 /**
2916  * Delete an active client from the tunnel.
2917  * 
2918  * @param t Tunnel.
2919  * @param c Client.
2920  */
2921 static void
2922 tunnel_delete_active_client (struct MeshTunnel *t, const struct MeshClient *c)
2923 {
2924   unsigned int i;
2925
2926   for (i = 0; i < t->nclients; i++)
2927   {
2928     if (t->clients[i] == c)
2929     {
2930       t->clients[i] = t->clients[t->nclients - 1];
2931       t->clients_acks[i] = t->clients_acks[t->nclients - 1];
2932       GNUNET_array_grow (t->clients, t->nclients, t->nclients - 1);
2933       t->nclients++;
2934       GNUNET_array_grow (t->clients_acks, t->nclients, t->nclients - 1);
2935       break;
2936     }
2937   }
2938 }
2939
2940
2941 /**
2942  * Delete an ignored client from the tunnel.
2943  * 
2944  * @param t Tunnel.
2945  * @param c Client.
2946  */
2947 static void
2948 tunnel_delete_ignored_client (struct MeshTunnel *t, const struct MeshClient *c)
2949 {
2950   unsigned int i;
2951
2952   for (i = 0; i < t->nignore; i++)
2953   {
2954     if (t->ignore[i] == c)
2955     {
2956       t->ignore[i] = t->ignore[t->nignore - 1];
2957       GNUNET_array_grow (t->ignore, t->nignore, t->nignore - 1);
2958       break;
2959     }
2960   }
2961 }
2962
2963
2964 /**
2965  * Delete a client from the tunnel. It should be only done on
2966  * client disconnection, otherwise use client_ignore_tunnel.
2967  * 
2968  * @param t Tunnel.
2969  * @param c Client.
2970  */
2971 static void
2972 tunnel_delete_client (struct MeshTunnel *t, const struct MeshClient *c)
2973 {
2974   tunnel_delete_ignored_client (t, c);
2975   tunnel_delete_active_client (t, c);
2976 }
2977
2978
2979 /**
2980  * Iterator to free MeshTunnelChildInfo of tunnel children.
2981  *
2982  * @param cls Closure (tunnel info).
2983  * @param key Hash of GNUNET_PEER_Id (unused).
2984  * @param value MeshTunnelChildInfo of the child.
2985  *
2986  * @return always GNUNET_YES, to keep iterating
2987  */
2988 static int
2989 tunnel_destroy_child (void *cls,
2990                       const struct GNUNET_HashCode * key,
2991                       void *value)
2992 {
2993   GNUNET_free (value);
2994   return GNUNET_YES;
2995 }
2996
2997
2998 /**
2999  * Callback used to notify a client owner of a tunnel that a peer has
3000  * disconnected, most likely because of a path change.
3001  *
3002  * @param cls Closure (tunnel this notification is about).
3003  * @param peer_id Short ID of disconnected peer.
3004  */
3005 void
3006 tunnel_notify_client_peer_disconnected (void *cls, GNUNET_PEER_Id peer_id)
3007 {
3008   struct MeshTunnel *t = cls;
3009   struct MeshPeerInfo *peer;
3010   struct MeshPathInfo *path_info;
3011
3012   if (NULL != t->owner && NULL != nc)
3013   {
3014     struct GNUNET_MESH_PeerControl msg;
3015
3016     msg.header.size = htons (sizeof (msg));
3017     msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL);
3018     msg.tunnel_id = htonl (t->local_tid);
3019     GNUNET_PEER_resolve (peer_id, &msg.peer);
3020     GNUNET_SERVER_notification_context_unicast (nc, t->owner->handle,
3021                                                 &msg.header, GNUNET_NO);
3022   }
3023   peer = peer_info_get_short (peer_id);
3024   path_info = GNUNET_malloc (sizeof (struct MeshPathInfo));
3025   path_info->peer = peer;
3026   path_info->t = t;
3027   GNUNET_SCHEDULER_add_now (&peer_info_connect_task, path_info);
3028 }
3029
3030
3031 /**
3032  * Add a peer to a tunnel, accomodating paths accordingly and initializing all
3033  * needed rescources.
3034  * If peer already exists, reevaluate shortest path and change if different.
3035  *
3036  * @param t Tunnel we want to add a new peer to
3037  * @param peer PeerInfo of the peer being added
3038  *
3039  */
3040 static void
3041 tunnel_add_peer (struct MeshTunnel *t, struct MeshPeerInfo *peer)
3042 {
3043   struct GNUNET_PeerIdentity id;
3044   struct MeshPeerPath *best_p;
3045   struct MeshPeerPath *p;
3046   unsigned int best_cost;
3047   unsigned int cost;
3048
3049   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "tunnel_add_peer\n");
3050   GNUNET_PEER_resolve (peer->id, &id);
3051   if (GNUNET_NO ==
3052       GNUNET_CONTAINER_multihashmap_contains (t->peers, &id.hashPubKey))
3053   {
3054     t->peers_total++;
3055     GNUNET_array_append (peer->tunnels, peer->ntunnels, t);
3056     GNUNET_assert (GNUNET_OK ==
3057                    GNUNET_CONTAINER_multihashmap_put (t->peers, &id.hashPubKey,
3058                                                       peer,
3059                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
3060   }
3061
3062   if (NULL != (p = peer->path_head))
3063   {
3064     best_p = p;
3065     best_cost = tree_get_path_cost (t->tree, p);
3066     while (NULL != p)
3067     {
3068       if ((cost = tree_get_path_cost (t->tree, p)) < best_cost)
3069       {
3070         best_cost = cost;
3071         best_p = p;
3072       }
3073       p = p->next;
3074     }
3075     tree_add_path (t->tree, best_p, &tunnel_notify_client_peer_disconnected, t);
3076     if (GNUNET_SCHEDULER_NO_TASK == t->path_refresh_task)
3077       t->path_refresh_task =
3078           GNUNET_SCHEDULER_add_delayed (refresh_path_time, &path_refresh, t);
3079   }
3080   else
3081   {
3082     /* Start a DHT get */
3083     peer_info_connect (peer, t);
3084   }
3085   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "tunnel_add_peer END\n");
3086 }
3087
3088 /**
3089  * Add a path to a tunnel which we don't own, just to remember the next hop.
3090  * If destination node was already in the tunnel, the first hop information
3091  * will be replaced with the new path.
3092  *
3093  * @param t Tunnel we want to add a new peer to
3094  * @param p Path to add
3095  * @param own_pos Position of local node in path.
3096  *
3097  */
3098 static void
3099 tunnel_add_path (struct MeshTunnel *t, struct MeshPeerPath *p,
3100                  unsigned int own_pos)
3101 {
3102   struct GNUNET_PeerIdentity id;
3103
3104   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "tunnel_add_path\n");
3105   GNUNET_assert (0 != own_pos);
3106   tree_add_path (t->tree, p, NULL, NULL);
3107   if (own_pos < p->length - 1)
3108   {
3109     GNUNET_PEER_resolve (p->peers[own_pos + 1], &id);
3110     tree_update_first_hops (t->tree, myid, &id);
3111   }
3112   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "tunnel_add_path END\n");
3113 }
3114
3115
3116 /**
3117  * Notifies a tunnel that a connection has broken that affects at least
3118  * some of its peers. Sends a notification towards the root of the tree.
3119  * In case the peer is the owner of the tree, notifies the client that owns
3120  * the tunnel and tries to reconnect.
3121  *
3122  * @param t Tunnel affected.
3123  * @param p1 Peer that got disconnected from p2.
3124  * @param p2 Peer that got disconnected from p1.
3125  *
3126  * @return Short ID of the peer disconnected (either p1 or p2).
3127  *         0 if the tunnel remained unaffected.
3128  */
3129 static GNUNET_PEER_Id
3130 tunnel_notify_connection_broken (struct MeshTunnel *t, GNUNET_PEER_Id p1,
3131                                  GNUNET_PEER_Id p2)
3132 {
3133   GNUNET_PEER_Id pid;
3134
3135   pid =
3136       tree_notify_connection_broken (t->tree, p1, p2,
3137                                      &tunnel_notify_client_peer_disconnected,
3138                                      t);
3139   if (myid != p1 && myid != p2)
3140   {
3141     return pid;
3142   }
3143   if (pid != myid)
3144   {
3145     if (tree_get_predecessor (t->tree) != 0)
3146     {
3147       /* We are the peer still connected, notify owner of the disconnection. */
3148       struct GNUNET_MESH_PathBroken msg;
3149       struct GNUNET_PeerIdentity neighbor;
3150
3151       msg.header.size = htons (sizeof (msg));
3152       msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN);
3153       GNUNET_PEER_resolve (t->id.oid, &msg.oid);
3154       msg.tid = htonl (t->id.tid);
3155       msg.peer1 = my_full_id;
3156       GNUNET_PEER_resolve (pid, &msg.peer2);
3157       GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &neighbor);
3158       send_message (&msg.header, &neighbor, t);
3159     }
3160   }
3161   return pid;
3162 }
3163
3164
3165 /**
3166  * Send a multicast packet to a neighbor.
3167  *
3168  * @param cls Closure (Info about the multicast packet)
3169  * @param neighbor_id Short ID of the neighbor to send the packet to.
3170  */
3171 static void
3172 tunnel_send_multicast_iterator (void *cls, GNUNET_PEER_Id neighbor_id)
3173 {
3174   struct MeshData *mdata = cls;
3175   struct MeshTransmissionDescriptor *info;
3176   struct GNUNET_PeerIdentity neighbor;
3177
3178   info = GNUNET_malloc (sizeof (struct MeshTransmissionDescriptor));
3179
3180   info->mesh_data = mdata;
3181   (*(mdata->reference_counter)) ++;
3182   info->destination = neighbor_id;
3183   GNUNET_PEER_resolve (neighbor_id, &neighbor);
3184   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   sending to %s...\n",
3185               GNUNET_i2s (&neighbor));
3186   info->peer = peer_info_get (&neighbor);
3187   GNUNET_assert (NULL != info->peer);
3188   queue_add(info,
3189             GNUNET_MESSAGE_TYPE_MESH_MULTICAST,
3190             info->mesh_data->data_len,
3191             info->peer,
3192             mdata->t);
3193 }
3194
3195
3196 /**
3197  * Send a message in a tunnel in multicast, sending a copy to each child node
3198  * down the local one in the tunnel tree.
3199  *
3200  * @param t Tunnel in which to send the data.
3201  * @param msg Message to be sent.
3202  * @param internal Has the service generated this message?
3203  */
3204 static void
3205 tunnel_send_multicast (struct MeshTunnel *t,
3206                        const struct GNUNET_MessageHeader *msg,
3207                        int internal)
3208 {
3209   struct MeshData *mdata;
3210
3211   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3212               " sending a multicast packet...\n");
3213   mdata = GNUNET_malloc (sizeof (struct MeshData));
3214   mdata->data_len = ntohs (msg->size);
3215   mdata->reference_counter = GNUNET_malloc (sizeof (unsigned int));
3216   mdata->t = t;
3217   mdata->data = GNUNET_malloc (mdata->data_len);
3218   memcpy (mdata->data, msg, mdata->data_len);
3219   if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_MESH_MULTICAST)
3220   {
3221     struct GNUNET_MESH_Multicast *mcast;
3222
3223     mcast = (struct GNUNET_MESH_Multicast *) mdata->data;
3224     mcast->ttl = htonl (ntohl (mcast->ttl) - 1);
3225     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  data packet, ttl: %u\n",
3226                 ntohl (mcast->ttl));
3227   }
3228   else
3229   {
3230     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  not a data packet, no ttl\n");
3231   }
3232   if (NULL != t->owner && GNUNET_YES != t->owner->shutting_down
3233       && GNUNET_NO == internal)
3234   {
3235     mdata->task = GNUNET_malloc (sizeof (GNUNET_SCHEDULER_TaskIdentifier));
3236     (*(mdata->task)) =
3237         GNUNET_SCHEDULER_add_delayed (unacknowledged_wait_time, &client_allow_send,
3238                                       mdata);
3239     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "timeout task %u\n",
3240                 *(mdata->task));
3241   }
3242
3243   tree_iterate_children (t->tree, &tunnel_send_multicast_iterator, mdata);
3244   if (*(mdata->reference_counter) == 0)
3245   {
3246     GNUNET_free (mdata->data);
3247     GNUNET_free (mdata->reference_counter);
3248     if (NULL != mdata->task)
3249     {
3250       GNUNET_SCHEDULER_cancel(*(mdata->task));
3251       GNUNET_free (mdata->task);
3252       GNUNET_SERVER_receive_done (t->owner->handle, GNUNET_OK);
3253     }
3254     // FIXME change order?
3255     GNUNET_free (mdata);
3256   }
3257   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3258               " sending a multicast packet done\n");
3259   return;
3260 }
3261
3262
3263 /**
3264  * Increase the SKIP value of all peers that
3265  * have not received a unicast message.
3266  *
3267  * @param cls Closure (ID of the peer that HAS received the message).
3268  * @param key ID of the neighbor.
3269  * @param value Information about the neighbor.
3270  *
3271  * @return GNUNET_YES to keep iterating.
3272  */
3273 static int
3274 tunnel_add_skip (void *cls,
3275                  const struct GNUNET_HashCode * key,
3276                  void *value)
3277 {
3278   struct GNUNET_PeerIdentity *neighbor = cls;
3279   struct MeshTunnelChildInfo *cinfo = value;
3280
3281   /* TODO compare only pointers? key == neighbor? */
3282   if (0 == memcmp (&neighbor->hashPubKey, key, sizeof (struct GNUNET_HashCode)))
3283   {
3284     return GNUNET_YES;
3285   }
3286   cinfo->skip++;
3287   return GNUNET_YES;
3288 }
3289
3290
3291
3292 /**
3293  * Iterator to get the appropiate ACK value from all children nodes.
3294  *
3295  * @param cls Closue (tunnel).
3296  * @param id Id of the child node.
3297  */
3298 static void
3299 tunnel_get_child_ack (void *cls,
3300                       GNUNET_PEER_Id id)
3301 {
3302   struct GNUNET_PeerIdentity peer_id;
3303   struct MeshTunnelChildInfo *cinfo;
3304   struct MeshTunnelChildIteratorContext *ctx = cls;
3305   struct MeshTunnel *t = ctx->t;
3306   uint32_t ack;
3307
3308   GNUNET_PEER_resolve (id, &peer_id);
3309   cinfo = GNUNET_CONTAINER_multihashmap_get (t->children_fc,
3310                                              &peer_id.hashPubKey);
3311   if (NULL == cinfo)
3312   {
3313     cinfo = GNUNET_malloc (sizeof (struct MeshTunnelChildInfo));
3314     cinfo->id = id;
3315     cinfo->pid = t->pid;
3316     cinfo->skip = t->pid;
3317     cinfo->max_pid = ack =  t->pid + 1;
3318     GNUNET_assert (GNUNET_OK ==
3319                    GNUNET_CONTAINER_multihashmap_put(t->children_fc,
3320                                                      &peer_id.hashPubKey,
3321                                                      cinfo,
3322                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
3323   }
3324   else
3325   {
3326     ack = cinfo->max_pid;
3327   }
3328
3329   if (0 == ctx->max_child_ack)
3330     ctx->max_child_ack = ack;
3331
3332   if (GNUNET_YES == t->speed_min)
3333   {
3334     ctx->max_child_ack = ctx->max_child_ack > ack ? ack : ctx->max_child_ack;
3335   }
3336   else
3337   {
3338     ctx->max_child_ack = ctx->max_child_ack > ack ? ctx->max_child_ack : ack;
3339   }
3340
3341 }
3342
3343
3344 /**
3345  * Get the maximum PID allowed to transmit to any
3346  * tunnel child of the local peer, depending on the tunnel
3347  * buffering/speed settings.
3348  *
3349  * @param t Tunnel.
3350  *
3351  * @return Maximum PID allowed (uint32 MAX), -1 if node has no children.
3352  */
3353 static int64_t
3354 tunnel_get_children_ack (struct MeshTunnel *t)
3355 {
3356   struct MeshTunnelChildIteratorContext ctx;
3357   ctx.t = t;
3358   ctx.max_child_ack = 0;
3359   ctx.nchildren = 0;
3360   tree_iterate_children (t->tree, tunnel_get_child_ack, &ctx);
3361
3362   if (0 == ctx.nchildren)
3363     return -1LL;
3364
3365   return (int64_t) ctx.max_child_ack;
3366 }
3367
3368
3369 /**
3370  * Add a client to a tunnel, initializing all needed data structures.
3371  * 
3372  * @param t Tunnel to which add the client.
3373  * @param c Client which to add to the tunnel.
3374  */
3375 static void
3376 tunnel_add_client (struct MeshTunnel *t, struct MeshClient *c)
3377 {
3378   uint32_t ack;
3379
3380   GNUNET_array_append (t->clients, t->nclients, c);
3381   t->nclients--;
3382   ack = t->pid + 1;
3383   GNUNET_array_append (t->clients_acks, t->nclients, ack);
3384 }
3385
3386
3387 /**
3388  * Set the ACK value of a client in a particular tunnel.
3389  * 
3390  * @param t Tunnel affected.
3391  * @param c Client whose ACK to set.
3392  * @param ack ACK value.
3393  */
3394 static void
3395 tunnel_set_client_ack (struct MeshTunnel *t,
3396                        struct MeshClient *c, 
3397                        uint32_t ack)
3398 {
3399   unsigned int i;
3400
3401   for (i = 0; i < t->nclients; i++)
3402   {
3403     if (t->clients[i] != c)
3404       continue;
3405     t->clients_acks[i] = ack;
3406     return;
3407   }
3408   GNUNET_break (0);
3409 }
3410
3411
3412 /**
3413  * Get the ACK value of a client in a particular tunnel.
3414  * 
3415  * @param t Tunnel on which to look.
3416  * @param c Client whose ACK to get.
3417  * 
3418  * @return ACK value.
3419  */
3420 uint32_t // FIXME static when used!!
3421 tunnel_get_client_ack (struct MeshTunnel *t,
3422                        struct MeshClient *c)
3423 {
3424   unsigned int i;
3425
3426   for (i = 0; i < t->nclients; i++)
3427   {
3428     if (t->clients[i] != c)
3429       continue;
3430     return t->clients_acks[i];
3431   }
3432   GNUNET_break (0);
3433   return t->clients_acks[0];
3434 }
3435
3436
3437 /**
3438  * Get the highest ACK value of all clients in a particular tunnel,
3439  * according to the buffering/speed settings.
3440  * 
3441  * @param t Tunnel on which to look.
3442  * 
3443  * @return Corresponding ACK value.
3444  */
3445 static uint32_t
3446 tunnel_get_clients_ack (struct MeshTunnel *t)
3447 {
3448   unsigned int i;
3449   uint32_t ack;
3450
3451   for (ack = 0, i = 0; i < t->nclients; i++)
3452   {
3453     if (0 == ack ||
3454         (GNUNET_YES == t->speed_min && t->clients_acks[i] < ack) ||
3455         (GNUNET_NO == t->speed_min && t->clients_acks[i] > ack))
3456     {
3457       ack = t->clients_acks[i];
3458     }
3459   }
3460
3461   if (GNUNET_YES == t->nobuffer && ack > t->pid)
3462     ack = t->pid + 1;
3463
3464   return ack;
3465 }
3466
3467
3468 /**
3469  * Get the current ack value for a tunnel, taking in account the tunnel
3470  * mode and the status of all children nodes.
3471  *
3472  * @param t Tunnel.
3473  *
3474  * @return Maximum PID allowed.
3475  */
3476 static uint32_t
3477 tunnel_get_fwd_ack (struct MeshTunnel *t)
3478 {
3479   uint32_t count;
3480   uint32_t buffer_free;
3481   int64_t child_ack;
3482   uint32_t client_ack;
3483   uint32_t ack;
3484
3485   count = t->pid - t->skip;
3486   buffer_free = t->queue_max - t->queue_n;
3487   ack = count + buffer_free; // Might overflow 32bits, it's ok!
3488   child_ack = tunnel_get_children_ack (t);
3489   if (-1 == child_ack)
3490     ack = client_ack = tunnel_get_clients_ack (t);
3491
3492   if (GNUNET_YES == t->speed_min)
3493   {
3494     ack = min_ack (child_ack, ack);
3495     ack = min_ack (client_ack, ack);
3496   }
3497   else
3498   {
3499     ack = max_ack (child_ack, ack);
3500     ack = max_ack (client_ack, ack);
3501   }
3502   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "c %u, bf %u, ch %u, cl %u\n",
3503               count, buffer_free, child_ack, client_ack);
3504   return ack;
3505 }
3506
3507 /**
3508  * Get the current ack value for a tunnel, taking in account the tunnel
3509  * mode and the status of all children nodes.
3510  *
3511  * @param t Tunnel.
3512  *
3513  * @return Maximum PID allowed.
3514  */
3515 static uint32_t
3516 tunnel_get_bck_ack (struct MeshTunnel *t)
3517 {
3518   uint32_t ack;
3519
3520   ack = 0;
3521
3522   return ack;
3523 }
3524
3525
3526 /**
3527  * Send an ACK informing the predecessor about the available buffer space.
3528  * In case there is no predecessor, inform the owning client.
3529  * If buffering is off, send only on behalf of children or self if endpoint.
3530  * If buffering is on, send when sent to children and buffer space is free.
3531  * Note that although the name is fwd_ack, the FWD mean forward *traffic*,
3532  * the ACK itself goes "back" (towards root).
3533  * 
3534  * @param t Tunnel on which to send the ACK.
3535  * @param type Type of message that triggered the ACK transmission.
3536  */
3537 static void
3538 tunnel_send_fwd_ack (struct MeshTunnel *t, uint16_t type)
3539 {
3540   struct GNUNET_MESH_ACK msg;
3541   struct GNUNET_PeerIdentity id;
3542   uint32_t ack;
3543
3544   if (NULL != t->owner)
3545   {
3546     send_client_tunnel_ack (t->owner, t);
3547     return;
3548   }
3549   /* Is it after unicast / multicast retransmission? */
3550   if (GNUNET_MESSAGE_TYPE_MESH_ACK != type)
3551   {
3552     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "ACK via DATA retransmission\n");
3553     if (GNUNET_YES == t->nobuffer)
3554     {
3555       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, nobuffer\n");
3556       return;
3557     }
3558     if (t->queue_max > t->queue_n * 2)
3559     {
3560       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, buffer free\n");
3561       return;
3562     }
3563   }
3564
3565   /* Ok, ACK might be necessary, what PID to ACK? */
3566   ack = tunnel_get_fwd_ack (t);
3567
3568   /* If speed_min and not all children have ack'd, dont send yet */
3569   if (ack == t->last_ack)
3570   {
3571     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, not ready\n");
3572     return;
3573   }
3574
3575   t->last_ack = ack;
3576   msg.pid = htonl (ack);
3577
3578   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
3579
3580   msg.header.size = htons (sizeof (msg));
3581   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_ACK);
3582   msg.tid = htonl (t->id.tid);
3583   GNUNET_PEER_resolve(t->id.oid, &msg.oid);
3584   send_message (&msg.header, &id, t);
3585 }
3586
3587
3588 /**
3589  * Send an ACK informing the children nodes about the available buffer space.
3590  * In case there is no child node, inform the destination clients.
3591  * If buffering is off, send only on behalf of root (can be self).
3592  * If buffering is on, send when sent to predecessor and buffer space is free.
3593  * Note that although the name is bck_ack, the BCK mean backwards *traffic*,
3594  * the ACK itself goes "forward" (towards children/clients).
3595  * 
3596  * @param t Tunnel on which to send the ACK.
3597  * @param type Type of message that triggered the ACK transmission.
3598  */
3599 static void
3600 tunnel_send_bck_ack (struct MeshTunnel *t, uint16_t type)
3601 {
3602   struct GNUNET_MESH_ACK msg;
3603   struct GNUNET_PeerIdentity id;
3604   uint32_t ack;
3605
3606   if (NULL != t->owner)
3607   {
3608     send_client_tunnel_ack (t->owner, t);
3609     return;
3610   }
3611   /* Is it after unicast / multicast retransmission? */
3612   if (GNUNET_MESSAGE_TYPE_MESH_ACK != type)
3613   {
3614     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "ACK via DATA retransmission\n");
3615     if (GNUNET_YES == t->nobuffer)
3616     {
3617       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, nobuffer\n");
3618       return;
3619     }
3620     if (t->queue_max > t->queue_n * 2)
3621     {
3622       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, buffer free\n");
3623       return;
3624     }
3625   }
3626
3627   /* Ok, ACK might be necessary, what PID to ACK? */
3628   ack = tunnel_get_bck_ack (t);
3629
3630   /* If speed_min and not all children have ack'd, dont send yet */
3631   if (ack == t->last_ack)
3632   {
3633     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, not ready\n");
3634     return;
3635   }
3636
3637   t->last_ack = ack;
3638   msg.pid = htonl (ack);
3639
3640   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
3641
3642   msg.header.size = htons (sizeof (msg));
3643   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_ACK);
3644   msg.tid = htonl (t->id.tid);
3645   GNUNET_PEER_resolve(t->id.oid, &msg.oid);
3646   send_message (&msg.header, &id, t);
3647 }
3648
3649
3650 /**
3651  * Send a message to all peers in this tunnel that the tunnel is no longer
3652  * valid.
3653  *
3654  * @param t The tunnel whose peers to notify.
3655  */
3656 static void
3657 tunnel_send_destroy (struct MeshTunnel *t)
3658 {
3659   struct GNUNET_MESH_TunnelDestroy msg;
3660
3661   msg.header.size = htons (sizeof (msg));
3662   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY);
3663   GNUNET_PEER_resolve (t->id.oid, &msg.oid);
3664   msg.tid = htonl (t->id.tid);
3665   tunnel_send_multicast (t, &msg.header, GNUNET_NO);
3666 }
3667
3668
3669 /**
3670  * Cancel all transmissions towards a neighbor that belong to a certain tunnel.
3671  *
3672  * @param cls Closure (Tunnel which to cancel).
3673  * @param neighbor_id Short ID of the neighbor to whom cancel the transmissions.
3674  */
3675 static void
3676 tunnel_cancel_queues (void *cls, GNUNET_PEER_Id neighbor_id)
3677 {
3678   struct MeshTunnel *t = cls;
3679   struct MeshPeerInfo *peer_info;
3680   struct MeshPeerQueue *pq;
3681   struct MeshPeerQueue *next;
3682
3683   peer_info = peer_info_get_short (neighbor_id);
3684   for (pq = peer_info->queue_head; NULL != pq; pq = next)
3685   {
3686     next = pq->next;
3687     if (pq->tunnel == t)
3688     {
3689       queue_destroy (pq, GNUNET_YES);
3690     }
3691   }
3692   if (NULL == peer_info->queue_head && NULL != peer_info->core_transmit)
3693   {
3694     GNUNET_CORE_notify_transmit_ready_cancel(peer_info->core_transmit);
3695     peer_info->core_transmit = NULL;
3696   }
3697 }
3698
3699 /**
3700  * Destroy the tunnel and free any allocated resources linked to it.
3701  *
3702  * @param t the tunnel to destroy
3703  *
3704  * @return GNUNET_OK on success
3705  */
3706 static int
3707 tunnel_destroy (struct MeshTunnel *t)
3708 {
3709   struct MeshClient *c;
3710   struct GNUNET_HashCode hash;
3711   unsigned int i;
3712   int r;
3713
3714   if (NULL == t)
3715     return GNUNET_OK;
3716
3717   tree_iterate_children (t->tree, &tunnel_cancel_queues, t);
3718
3719   r = GNUNET_OK;
3720   c = t->owner;
3721 #if MESH_DEBUG
3722   {
3723     struct GNUNET_PeerIdentity id;
3724
3725     GNUNET_PEER_resolve (t->id.oid, &id);
3726     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s [%x]\n",
3727                 GNUNET_i2s (&id), t->id.tid);
3728     if (NULL != c)
3729       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
3730   }
3731 #endif
3732
3733   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
3734   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &hash, t))
3735   {
3736     r = GNUNET_SYSERR;
3737   }
3738
3739   GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
3740   if (NULL != c &&
3741       GNUNET_YES !=
3742       GNUNET_CONTAINER_multihashmap_remove (c->own_tunnels, &hash, t))
3743   {
3744     r = GNUNET_SYSERR;
3745   }
3746   GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
3747   for (i = 0; i < t->nclients; i++)
3748   {
3749     c = t->clients[i];
3750     if (GNUNET_YES !=
3751           GNUNET_CONTAINER_multihashmap_remove (c->incoming_tunnels, &hash, t))
3752     {
3753       r = GNUNET_SYSERR;
3754     }
3755   }
3756   for (i = 0; i < t->nignore; i++)
3757   {
3758     c = t->ignore[i];
3759     if (GNUNET_YES !=
3760           GNUNET_CONTAINER_multihashmap_remove (c->ignore_tunnels, &hash, t))
3761     {
3762       r = GNUNET_SYSERR;
3763     }
3764   }
3765   if (t->nclients > 0)
3766   {
3767     if (GNUNET_YES !=
3768         GNUNET_CONTAINER_multihashmap_remove (incoming_tunnels, &hash, t))
3769     {
3770       r = GNUNET_SYSERR;
3771     }
3772     GNUNET_free (t->clients);
3773   }
3774   if (NULL != t->peers)
3775   {
3776     GNUNET_CONTAINER_multihashmap_iterate (t->peers, &peer_info_delete_tunnel,
3777                                            t);
3778     GNUNET_CONTAINER_multihashmap_destroy (t->peers);
3779   }
3780
3781   GNUNET_CONTAINER_multihashmap_iterate (t->children_fc,
3782                                          &tunnel_destroy_child,
3783                                          t);
3784   GNUNET_CONTAINER_multihashmap_destroy (t->children_fc);
3785
3786   tree_destroy (t->tree);
3787
3788   if (NULL != t->regex_ctx)
3789     regex_cancel_search (t->regex_ctx);
3790   if (NULL != t->dht_get_type)
3791     GNUNET_DHT_get_stop (t->dht_get_type);
3792   if (GNUNET_SCHEDULER_NO_TASK != t->timeout_task)
3793     GNUNET_SCHEDULER_cancel (t->timeout_task);
3794   if (GNUNET_SCHEDULER_NO_TASK != t->path_refresh_task)
3795     GNUNET_SCHEDULER_cancel (t->path_refresh_task);
3796
3797   n_tunnels--;
3798   GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
3799   GNUNET_assert (0 <= n_tunnels);
3800   GNUNET_free (t);
3801   return r;
3802 }
3803
3804
3805 /**
3806  * Create a new tunnel
3807  * 
3808  * @param owner Who is the owner of the tunnel (short ID).
3809  * @param tid Tunnel Number of the tunnel.
3810  * @param client Clients that owns the tunnel, NULL for foreign tunnels.
3811  * @param local Tunnel Number for the tunnel, for the client point of view.
3812  * 
3813  * @return A new initialized tunnel. NULL on error.
3814  */
3815 static struct MeshTunnel *
3816 tunnel_new (GNUNET_PEER_Id owner,
3817             MESH_TunnelNumber tid,
3818             struct MeshClient *client,
3819             MESH_TunnelNumber local)
3820 {
3821   struct MeshTunnel *t;
3822   struct GNUNET_HashCode hash;
3823   
3824   if (n_tunnels >= max_tunnels && NULL == client)
3825     return NULL;
3826
3827   t = GNUNET_malloc (sizeof (struct MeshTunnel));
3828   t->id.oid = owner;
3829   t->id.tid = tid;
3830   t->queue_max = (max_msgs_queue / max_tunnels) + 1;
3831   t->tree = tree_new (owner);
3832   t->owner = client;
3833   t->local_tid = local;
3834   t->children_fc = GNUNET_CONTAINER_multihashmap_create (8);
3835   n_tunnels++;
3836   GNUNET_STATISTICS_update (stats, "# tunnels", 1, GNUNET_NO);
3837
3838   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
3839   if (GNUNET_OK !=
3840       GNUNET_CONTAINER_multihashmap_put (tunnels, &hash, t,
3841                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
3842   {
3843     GNUNET_break (0);
3844     tunnel_destroy (t);
3845     if (NULL != client)
3846     {
3847       GNUNET_break (0);
3848       GNUNET_SERVER_receive_done (client->handle, GNUNET_SYSERR);
3849     }
3850     return NULL;
3851   }
3852
3853   if (NULL != client)
3854   {
3855     GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
3856     if (GNUNET_OK !=
3857         GNUNET_CONTAINER_multihashmap_put (client->own_tunnels, &hash, t,
3858                                           GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
3859     {
3860       tunnel_destroy (t);
3861       GNUNET_break (0);
3862       GNUNET_SERVER_receive_done (client->handle, GNUNET_SYSERR);
3863       return NULL;
3864     }
3865   }
3866
3867   return t;
3868 }
3869
3870
3871 /**
3872  * Removes an explicit path from a tunnel, freeing all intermediate nodes
3873  * that are no longer needed, as well as nodes of no longer reachable peers.
3874  * The tunnel itself is also destoyed if results in a remote empty tunnel.
3875  *
3876  * @param t Tunnel from which to remove the path.
3877  * @param peer Short id of the peer which should be removed.
3878  */
3879 static void
3880 tunnel_delete_peer (struct MeshTunnel *t, GNUNET_PEER_Id peer)
3881 {
3882   if (GNUNET_NO == tree_del_peer (t->tree, peer, NULL, NULL))
3883     tunnel_destroy (t);
3884 }
3885
3886
3887 /**
3888  * tunnel_destroy_iterator: iterator for deleting each tunnel that belongs to a
3889  * client when the client disconnects. If the client is not the owner, the
3890  * owner will get notified if no more clients are in the tunnel and the client
3891  * get removed from the tunnel's list.
3892  *
3893  * @param cls closure (client that is disconnecting)
3894  * @param key the hash of the local tunnel id (used to access the hashmap)
3895  * @param value the value stored at the key (tunnel to destroy)
3896  *
3897  * @return GNUNET_OK on success
3898  */
3899 static int
3900 tunnel_destroy_iterator (void *cls, const struct GNUNET_HashCode * key, void *value)
3901 {
3902   struct MeshTunnel *t = value;
3903   struct MeshClient *c = cls;
3904   int r;
3905
3906   send_client_tunnel_disconnect(t, c);
3907   if (c != t->owner)
3908   {
3909     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3910                 "Client %u is destination, keeping the tunnel alive.\n", c->id);
3911     tunnel_delete_client(t, c);
3912     client_delete_tunnel(c, t);
3913     return GNUNET_OK;
3914   }
3915   tunnel_send_destroy(t);
3916   r = tunnel_destroy (t);
3917   return r;
3918 }
3919
3920
3921 /**
3922  * Timeout function, destroys tunnel if called
3923  *
3924  * @param cls Closure (tunnel to destroy).
3925  * @param tc TaskContext
3926  */
3927 static void
3928 tunnel_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3929 {
3930   struct MeshTunnel *t = cls;
3931
3932   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3933     return;
3934   t->timeout_task = GNUNET_SCHEDULER_NO_TASK;
3935   tunnel_destroy (t);
3936 }
3937
3938 /**
3939  * Resets the tunnel timeout. Starts it if no timeout was running.
3940  *
3941  * @param t Tunnel whose timeout to reset.
3942  */
3943 static void
3944 tunnel_reset_timeout (struct MeshTunnel *t)
3945 {
3946   if (GNUNET_SCHEDULER_NO_TASK != t->timeout_task)
3947     GNUNET_SCHEDULER_cancel (t->timeout_task);
3948   t->timeout_task =
3949       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
3950                                     (refresh_path_time, 4), &tunnel_timeout, t);
3951 }
3952
3953
3954 /******************************************************************************/
3955 /****************      MESH NETWORK HANDLER HELPERS     ***********************/
3956 /******************************************************************************/
3957
3958 /**
3959  * Function to send a create path packet to a peer.
3960  *
3961  * @param cls closure
3962  * @param size number of bytes available in buf
3963  * @param buf where the callee should write the message
3964  * @return number of bytes written to buf
3965  */
3966 static size_t
3967 send_core_path_create (void *cls, size_t size, void *buf)
3968 {
3969   struct MeshPathInfo *info = cls;
3970   struct GNUNET_MESH_ManipulatePath *msg;
3971   struct GNUNET_PeerIdentity *peer_ptr;
3972   struct MeshTunnel *t = info->t;
3973   struct MeshPeerPath *p = info->path;
3974   size_t size_needed;
3975   uint32_t opt;
3976   int i;
3977
3978   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATE PATH sending...\n");
3979   size_needed =
3980       sizeof (struct GNUNET_MESH_ManipulatePath) +
3981       p->length * sizeof (struct GNUNET_PeerIdentity);
3982
3983   if (size < size_needed || NULL == buf)
3984   {
3985     GNUNET_break (0);
3986     return 0;
3987   }
3988   msg = (struct GNUNET_MESH_ManipulatePath *) buf;
3989   msg->header.size = htons (size_needed);
3990   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE);
3991   msg->tid = ntohl (t->id.tid);
3992
3993   if (GNUNET_YES == t->speed_min)
3994     opt = MESH_TUNNEL_OPT_SPEED_MIN;
3995   if (GNUNET_YES == t->nobuffer)
3996     opt |= MESH_TUNNEL_OPT_NOBUFFER;
3997   msg->opt = htonl(opt);
3998
3999   peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
4000   for (i = 0; i < p->length; i++)
4001   {
4002     GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
4003   }
4004
4005   path_destroy (p);
4006   GNUNET_free (info);
4007
4008   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4009               "CREATE PATH (%u bytes long) sent!\n", size_needed);
4010   return size_needed;
4011 }
4012
4013
4014 /**
4015  * Fill the core buffer 
4016  *
4017  * @param cls closure (data itself)
4018  * @param size number of bytes available in buf
4019  * @param buf where the callee should write the message
4020  *
4021  * @return number of bytes written to buf
4022  */
4023 static size_t
4024 send_core_data_multicast (void *cls, size_t size, void *buf)
4025 {
4026   struct MeshTransmissionDescriptor *info = cls;
4027   size_t total_size;
4028
4029   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Multicast callback.\n");
4030   GNUNET_assert (NULL != info);
4031   GNUNET_assert (NULL != info->peer);
4032   total_size = info->mesh_data->data_len;
4033   GNUNET_assert (total_size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
4034
4035   if (total_size > size)
4036   {
4037     GNUNET_break (0);
4038     return 0;
4039   }
4040   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " copying data...\n");
4041   memcpy (buf, info->mesh_data->data, total_size);
4042 #if MESH_DEBUG
4043   {
4044     struct GNUNET_MESH_Multicast *mc;
4045     struct GNUNET_MessageHeader *mh;
4046
4047     mh = buf;
4048     if (ntohs (mh->type) == GNUNET_MESSAGE_TYPE_MESH_MULTICAST)
4049     {
4050       mc = (struct GNUNET_MESH_Multicast *) mh;
4051       mh = (struct GNUNET_MessageHeader *) &mc[1];
4052       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4053                   " multicast, payload type %u\n", ntohs (mh->type));
4054       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4055                   " multicast, payload size %u\n", ntohs (mh->size));
4056     }
4057     else
4058     {
4059       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " type %u\n",
4060                   ntohs (mh->type));
4061     }
4062   }
4063 #endif
4064   data_descriptor_decrement_rc (info->mesh_data);
4065   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "freeing info...\n");
4066   GNUNET_free (info);
4067   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "return %u\n", total_size);
4068   return total_size;
4069 }
4070
4071
4072 /**
4073  * Creates a path ack message in buf and frees all unused resources.
4074  *
4075  * @param cls closure (MeshTransmissionDescriptor)
4076  * @param size number of bytes available in buf
4077  * @param buf where the callee should write the message
4078  * @return number of bytes written to buf
4079  */
4080 static size_t
4081 send_core_path_ack (void *cls, size_t size, void *buf)
4082 {
4083   struct MeshTransmissionDescriptor *info = cls;
4084   struct GNUNET_MESH_PathACK *msg = buf;
4085
4086   GNUNET_assert (NULL != info);
4087   if (sizeof (struct GNUNET_MESH_PathACK) > size)
4088   {
4089     GNUNET_break (0);
4090     return 0;
4091   }
4092   msg->header.size = htons (sizeof (struct GNUNET_MESH_PathACK));
4093   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_ACK);
4094   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
4095   msg->tid = htonl (info->origin->tid);
4096   msg->peer_id = my_full_id;
4097
4098   GNUNET_free (info);
4099   /* TODO add signature */
4100
4101   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "PATH ACK sent!\n");
4102   return sizeof (struct GNUNET_MESH_PathACK);
4103 }
4104
4105
4106 /**
4107  * Free a transmission that was already queued with all resources
4108  * associated to the request.
4109  *
4110  * @param queue Queue handler to cancel.
4111  * @param clear_cls Is it necessary to free associated cls?
4112  */
4113 static void
4114 queue_destroy (struct MeshPeerQueue *queue, int clear_cls)
4115 {
4116   struct MeshTransmissionDescriptor *dd;
4117   struct MeshPathInfo *path_info;
4118
4119   if (GNUNET_YES == clear_cls)
4120   {
4121     switch (queue->type)
4122     {
4123     case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4124     case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
4125     case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4126         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   type payload\n");
4127         dd = queue->cls;
4128         data_descriptor_decrement_rc (dd->mesh_data);
4129         break;
4130     case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
4131         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   type create path\n");
4132         path_info = queue->cls;
4133         path_destroy (path_info->path);
4134         break;
4135     default:
4136         GNUNET_break (0);
4137         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   type unknown!\n");
4138     }
4139     GNUNET_free_non_null (queue->cls);
4140   }
4141   GNUNET_CONTAINER_DLL_remove (queue->peer->queue_head,
4142                                queue->peer->queue_tail,
4143                                queue);
4144   GNUNET_free (queue);
4145 }
4146
4147
4148 /**
4149   * Core callback to write a queued packet to core buffer
4150   *
4151   * @param cls Closure (peer info).
4152   * @param size Number of bytes available in buf.
4153   * @param buf Where the to write the message.
4154   *
4155   * @return number of bytes written to buf
4156   */
4157 static size_t
4158 queue_send (void *cls, size_t size, void *buf)
4159 {
4160     struct MeshPeerInfo *peer = cls;
4161     struct GNUNET_MessageHeader *msg;
4162     struct MeshPeerQueue *queue;
4163     struct MeshTunnel *t;
4164     size_t data_size;
4165
4166     peer->core_transmit = NULL;
4167     queue = peer->queue_head;
4168
4169     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "********* Queue send\n");
4170
4171     /* If queue is empty, send should have been cancelled */
4172     if (NULL == queue)
4173     {
4174         GNUNET_break(0);
4175         return 0;
4176     }
4177     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   not empty\n");
4178
4179     /* Check if buffer size is enough for the message */
4180     if (queue->size > size)
4181     {
4182         struct GNUNET_PeerIdentity id;
4183
4184         GNUNET_PEER_resolve (peer->id, &id);
4185         peer->core_transmit =
4186             GNUNET_CORE_notify_transmit_ready(core_handle,
4187                                               0,
4188                                               0,
4189                                               GNUNET_TIME_UNIT_FOREVER_REL,
4190                                               &id,
4191                                               queue->size,
4192                                               &queue_send,
4193                                               peer);
4194         return 0;
4195     }
4196     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   size ok\n");
4197
4198     t = queue->tunnel;
4199     t->queue_n--;
4200
4201     /* Fill buf */
4202     switch (queue->type)
4203     {
4204         case 0: // RAW data (preconstructed message, retransmission, etc)
4205             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   raw\n");
4206             data_size = send_core_data_raw (queue->cls, size, buf);
4207             msg = (struct GNUNET_MessageHeader *) buf;
4208             switch (ntohs (msg->type)) // Type of payload
4209             {
4210               case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4211                 tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_UNICAST);
4212                 break;
4213               case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4214                 tunnel_send_bck_ack(t, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
4215                 break;
4216               default:
4217                   break;
4218             }
4219             break;
4220         case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
4221             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   multicast\n");
4222             data_size = send_core_data_multicast(queue->cls, size, buf);
4223             tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
4224             break;
4225         case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
4226             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path create\n");
4227             data_size = send_core_path_create(queue->cls, size, buf);
4228             break;
4229         case GNUNET_MESSAGE_TYPE_MESH_PATH_ACK:
4230             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path ack\n");
4231             data_size = send_core_path_ack(queue->cls, size, buf);
4232             break;
4233         default:
4234             GNUNET_break (0);
4235             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   type unknown\n");
4236             data_size = 0;
4237     }
4238
4239     /* Free queue, but cls was freed by send_core_* */
4240     queue_destroy (queue, GNUNET_NO);
4241
4242     if (GNUNET_YES == t->destroy && 0 == t->queue_n)
4243     {
4244       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********  destroying tunnel!\n");
4245       tunnel_destroy (t);
4246     }
4247
4248     /* If more data in queue, send next */
4249     if (NULL != peer->queue_head)
4250     {
4251         struct GNUNET_PeerIdentity id;
4252
4253         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   more data!\n");
4254         GNUNET_PEER_resolve (peer->id, &id);
4255         peer->core_transmit =
4256             GNUNET_CORE_notify_transmit_ready(core_handle,
4257                                               0,
4258                                               0,
4259                                               GNUNET_TIME_UNIT_FOREVER_REL,
4260                                               &id,
4261                                               peer->queue_head->size,
4262                                               &queue_send,
4263                                               peer);
4264     }
4265     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   return %d\n", data_size);
4266     return data_size;
4267 }
4268
4269
4270 /**
4271  * Queue and pass message to core when possible.
4272  *
4273  * @param cls Closure (type dependant).
4274  * @param type Type of the message, 0 for a raw message.
4275  * @param size Size of the message.
4276  * @param dst Neighbor to send message to.
4277  * @param t Tunnel this message belongs to.
4278  */
4279 static void
4280 queue_add (void *cls, uint16_t type, size_t size,
4281            struct MeshPeerInfo *dst, struct MeshTunnel *t)
4282 {
4283     struct MeshPeerQueue *queue;
4284
4285     if (t->queue_n >= t->queue_max)
4286     {
4287       if (NULL == t->owner)
4288         GNUNET_break_op(0);       // TODO: kill connection?
4289       else
4290         GNUNET_break(0);
4291       return;                       // Drop message
4292     }
4293     t->queue_n++;
4294     queue = GNUNET_malloc (sizeof (struct MeshPeerQueue));
4295     queue->cls = cls;
4296     queue->type = type;
4297     queue->size = size;
4298     queue->peer = dst;
4299     queue->tunnel = t;
4300     GNUNET_CONTAINER_DLL_insert_tail (dst->queue_head, dst->queue_tail, queue);
4301     if (NULL == dst->core_transmit)
4302     {
4303         struct GNUNET_PeerIdentity id;
4304
4305         GNUNET_PEER_resolve (dst->id, &id);
4306         dst->core_transmit =
4307             GNUNET_CORE_notify_transmit_ready(core_handle,
4308                                               0,
4309                                               0,
4310                                               GNUNET_TIME_UNIT_FOREVER_REL,
4311                                               &id,
4312                                               size,
4313                                               &queue_send,
4314                                               dst);
4315     }
4316 }
4317
4318
4319 /******************************************************************************/
4320 /********************      MESH NETWORK HANDLERS     **************************/
4321 /******************************************************************************/
4322
4323
4324 /**
4325  * Core handler for path creation
4326  *
4327  * @param cls closure
4328  * @param message message
4329  * @param peer peer identity this notification is about
4330  * @param atsi performance data
4331  * @param atsi_count number of records in 'atsi'
4332  *
4333  * @return GNUNET_OK to keep the connection open,
4334  *         GNUNET_SYSERR to close it (signal serious error)
4335  */
4336 static int
4337 handle_mesh_path_create (void *cls, const struct GNUNET_PeerIdentity *peer,
4338                          const struct GNUNET_MessageHeader *message,
4339                          const struct GNUNET_ATS_Information *atsi,
4340                          unsigned int atsi_count)
4341 {
4342   unsigned int own_pos;
4343   uint16_t size;
4344   uint16_t i;
4345   MESH_TunnelNumber tid;
4346   struct GNUNET_MESH_ManipulatePath *msg;
4347   struct GNUNET_PeerIdentity *pi;
4348   struct GNUNET_HashCode hash;
4349   struct MeshPeerPath *path;
4350   struct MeshPeerInfo *dest_peer_info;
4351   struct MeshPeerInfo *orig_peer_info;
4352   struct MeshTunnel *t;
4353
4354   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4355               "Received a path create msg [%s]\n",
4356               GNUNET_i2s (&my_full_id));
4357   size = ntohs (message->size);
4358   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
4359   {
4360     GNUNET_break_op (0);
4361     return GNUNET_OK;
4362   }
4363
4364   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
4365   if (size % sizeof (struct GNUNET_PeerIdentity))
4366   {
4367     GNUNET_break_op (0);
4368     return GNUNET_OK;
4369   }
4370   size /= sizeof (struct GNUNET_PeerIdentity);
4371   if (size < 2)
4372   {
4373     GNUNET_break_op (0);
4374     return GNUNET_OK;
4375   }
4376   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
4377   msg = (struct GNUNET_MESH_ManipulatePath *) message;
4378
4379   tid = ntohl (msg->tid);
4380   pi = (struct GNUNET_PeerIdentity *) &msg[1];
4381   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4382               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi), tid);
4383   t = tunnel_get (pi, tid);
4384   if (NULL == t) // FIXME only for INCOMING tunnels?
4385   {
4386     uint32_t opt;
4387
4388     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating tunnel\n");
4389     t = tunnel_new (GNUNET_PEER_intern (pi), tid, NULL, 0);
4390     if (NULL == t)
4391     {
4392       // FIXME notify failure
4393       return GNUNET_OK;
4394     }
4395     opt = ntohl (msg->opt);
4396     t->speed_min = (0 != (opt & MESH_TUNNEL_OPT_SPEED_MIN)) ?
4397                    GNUNET_YES : GNUNET_NO;
4398     t->nobuffer = (0 != (opt & MESH_TUNNEL_OPT_NOBUFFER)) ?
4399                   GNUNET_YES : GNUNET_NO;
4400
4401     if (GNUNET_YES == t->nobuffer)
4402       t->queue_max = 1;
4403
4404     while (NULL != tunnel_get_incoming (next_local_tid))
4405       next_local_tid = (next_local_tid + 1) | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
4406     t->local_tid_dest = next_local_tid++;
4407     next_local_tid = next_local_tid | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
4408
4409     tunnel_reset_timeout (t);
4410     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
4411     if (GNUNET_OK !=
4412         GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
4413                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
4414     {
4415       tunnel_destroy (t);
4416       GNUNET_break (0);
4417       return GNUNET_OK;
4418     }
4419   }
4420   dest_peer_info =
4421       GNUNET_CONTAINER_multihashmap_get (peers, &pi[size - 1].hashPubKey);
4422   if (NULL == dest_peer_info)
4423   {
4424     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4425                 "  Creating PeerInfo for destination.\n");
4426     dest_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
4427     dest_peer_info->id = GNUNET_PEER_intern (&pi[size - 1]);
4428     GNUNET_CONTAINER_multihashmap_put (peers, &pi[size - 1].hashPubKey,
4429                                        dest_peer_info,
4430                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
4431   }
4432   orig_peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &pi->hashPubKey);
4433   if (NULL == orig_peer_info)
4434   {
4435     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4436                 "  Creating PeerInfo for origin.\n");
4437     orig_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
4438     orig_peer_info->id = GNUNET_PEER_intern (pi);
4439     GNUNET_CONTAINER_multihashmap_put (peers, &pi->hashPubKey, orig_peer_info,
4440                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
4441   }
4442   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
4443   path = path_new (size);
4444   own_pos = 0;
4445   for (i = 0; i < size; i++)
4446   {
4447     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
4448                 GNUNET_i2s (&pi[i]));
4449     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
4450     if (path->peers[i] == myid)
4451       own_pos = i;
4452   }
4453   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
4454   if (own_pos == 0)
4455   {
4456     /* cannot be self, must be 'not found' */
4457     /* create path: self not found in path through self */
4458     GNUNET_break_op (0);
4459     path_destroy (path);
4460     /* FIXME error. destroy tunnel? leave for timeout? */
4461     return 0;
4462   }
4463   path_add_to_peers (path, GNUNET_NO);
4464   tunnel_add_path (t, path, own_pos);
4465   if (own_pos == size - 1)
4466   {
4467     /* It is for us! Send ack. */
4468     struct MeshTransmissionDescriptor *info;
4469
4470     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
4471     peer_info_add_path_to_origin (orig_peer_info, path, GNUNET_NO);
4472     if (NULL == t->peers)
4473     {
4474       /* New tunnel! Notify clients on data. */
4475       t->peers = GNUNET_CONTAINER_multihashmap_create (4);
4476     }
4477     GNUNET_break (GNUNET_SYSERR !=
4478                   GNUNET_CONTAINER_multihashmap_put (t->peers,
4479                                                      &my_full_id.hashPubKey,
4480                                                      peer_info_get
4481                                                      (&my_full_id),
4482                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE));
4483     info = GNUNET_malloc (sizeof (struct MeshTransmissionDescriptor));
4484     info->origin = &t->id;
4485     info->peer = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
4486     GNUNET_assert (NULL != info->peer);
4487     queue_add(info,
4488               GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
4489               sizeof (struct GNUNET_MESH_PathACK),
4490               info->peer,
4491               t);
4492   }
4493   else
4494   {
4495     struct MeshPeerPath *path2;
4496
4497     /* It's for somebody else! Retransmit. */
4498     path2 = path_duplicate (path);
4499     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Retransmitting.\n");
4500     peer_info_add_path (dest_peer_info, path2, GNUNET_NO);
4501     path2 = path_duplicate (path);
4502     peer_info_add_path_to_origin (orig_peer_info, path2, GNUNET_NO);
4503     send_create_path (dest_peer_info, path, t);
4504   }
4505   return GNUNET_OK;
4506 }
4507
4508
4509 /**
4510  * Core handler for path destruction
4511  *
4512  * @param cls closure
4513  * @param message message
4514  * @param peer peer identity this notification is about
4515  * @param atsi performance data
4516  * @param atsi_count number of records in 'atsi'
4517  *
4518  * @return GNUNET_OK to keep the connection open,
4519  *         GNUNET_SYSERR to close it (signal serious error)
4520  */
4521 static int
4522 handle_mesh_path_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
4523                           const struct GNUNET_MessageHeader *message,
4524                           const struct GNUNET_ATS_Information *atsi,
4525                           unsigned int atsi_count)
4526 {
4527   struct GNUNET_MESH_ManipulatePath *msg;
4528   struct GNUNET_PeerIdentity *pi;
4529   struct MeshPeerPath *path;
4530   struct MeshTunnel *t;
4531   unsigned int own_pos;
4532   unsigned int i;
4533   size_t size;
4534
4535   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4536               "Received a PATH DESTROY msg from %s\n", GNUNET_i2s (peer));
4537   size = ntohs (message->size);
4538   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
4539   {
4540     GNUNET_break_op (0);
4541     return GNUNET_OK;
4542   }
4543
4544   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
4545   if (size % sizeof (struct GNUNET_PeerIdentity))
4546   {
4547     GNUNET_break_op (0);
4548     return GNUNET_OK;
4549   }
4550   size /= sizeof (struct GNUNET_PeerIdentity);
4551   if (size < 2)
4552   {
4553     GNUNET_break_op (0);
4554     return GNUNET_OK;
4555   }
4556   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
4557
4558   msg = (struct GNUNET_MESH_ManipulatePath *) message;
4559   pi = (struct GNUNET_PeerIdentity *) &msg[1];
4560   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4561               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi),
4562               msg->tid);
4563   t = tunnel_get (pi, ntohl (msg->tid));
4564   if (NULL == t)
4565   {
4566     /* TODO notify back: we don't know this tunnel */
4567     GNUNET_break_op (0);
4568     return GNUNET_OK;
4569   }
4570   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
4571   path = path_new (size);
4572   own_pos = 0;
4573   for (i = 0; i < size; i++)
4574   {
4575     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
4576                 GNUNET_i2s (&pi[i]));
4577     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
4578     if (path->peers[i] == myid)
4579       own_pos = i;
4580   }
4581   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
4582   if (own_pos < path->length - 1)
4583     send_message (message, &pi[own_pos + 1], t);
4584   else
4585     send_client_tunnel_disconnect(t, NULL);
4586
4587   tunnel_delete_peer (t, path->peers[path->length - 1]);
4588   path_destroy (path);
4589   return GNUNET_OK;
4590 }
4591
4592
4593 /**
4594  * Core handler for notifications of broken paths
4595  *
4596  * @param cls closure
4597  * @param message message
4598  * @param peer peer identity this notification is about
4599  * @param atsi performance data
4600  * @param atsi_count number of records in 'atsi'
4601  *
4602  * @return GNUNET_OK to keep the connection open,
4603  *         GNUNET_SYSERR to close it (signal serious error)
4604  */
4605 static int
4606 handle_mesh_path_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
4607                          const struct GNUNET_MessageHeader *message,
4608                          const struct GNUNET_ATS_Information *atsi,
4609                          unsigned int atsi_count)
4610 {
4611   struct GNUNET_MESH_PathBroken *msg;
4612   struct MeshTunnel *t;
4613
4614   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4615               "Received a PATH BROKEN msg from %s\n", GNUNET_i2s (peer));
4616   msg = (struct GNUNET_MESH_PathBroken *) message;
4617   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
4618               GNUNET_i2s (&msg->peer1));
4619   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
4620               GNUNET_i2s (&msg->peer2));
4621   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4622   if (NULL == t)
4623   {
4624     GNUNET_break_op (0);
4625     return GNUNET_OK;
4626   }
4627   tunnel_notify_connection_broken (t, GNUNET_PEER_search (&msg->peer1),
4628                                    GNUNET_PEER_search (&msg->peer2));
4629   return GNUNET_OK;
4630
4631 }
4632
4633
4634 /**
4635  * Core handler for tunnel destruction
4636  *
4637  * @param cls closure
4638  * @param message message
4639  * @param peer peer identity this notification is about
4640  * @param atsi performance data
4641  * @param atsi_count number of records in 'atsi'
4642  *
4643  * @return GNUNET_OK to keep the connection open,
4644  *         GNUNET_SYSERR to close it (signal serious error)
4645  */
4646 static int
4647 handle_mesh_tunnel_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
4648                             const struct GNUNET_MessageHeader *message,
4649                             const struct GNUNET_ATS_Information *atsi,
4650                             unsigned int atsi_count)
4651 {
4652   struct GNUNET_MESH_TunnelDestroy *msg;
4653   struct MeshTunnel *t;
4654
4655   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4656               "Got a TUNNEL DESTROY packet from %s\n", GNUNET_i2s (peer));
4657   msg = (struct GNUNET_MESH_TunnelDestroy *) message;
4658   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for tunnel %s [%u]\n",
4659               GNUNET_i2s (&msg->oid), ntohl (msg->tid));
4660   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4661   if (NULL == t)
4662   {
4663     /* Probably already got the message from another path,
4664      * destroyed the tunnel and retransmitted to children.
4665      * Safe to ignore.
4666      */
4667     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel", 1, GNUNET_NO);
4668     return GNUNET_OK;
4669   }
4670   if (t->id.oid == myid)
4671   {
4672     GNUNET_break_op (0);
4673     return GNUNET_OK;
4674   }
4675   if (t->local_tid_dest >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
4676   {
4677     /* Tunnel was incoming, notify clients */
4678     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "INCOMING TUNNEL %X %X\n",
4679                 t->local_tid, t->local_tid_dest);
4680     send_clients_tunnel_destroy (t);
4681   }
4682   tunnel_send_destroy (t);
4683   t->destroy = GNUNET_YES;
4684   // TODO: add timeout to destroy the tunnel anyway
4685   return GNUNET_OK;
4686 }
4687
4688
4689 /**
4690  * Core handler for mesh network traffic going from the origin to a peer
4691  *
4692  * @param cls closure
4693  * @param peer peer identity this notification is about
4694  * @param message message
4695  * @param atsi performance data
4696  * @param atsi_count number of records in 'atsi'
4697  * @return GNUNET_OK to keep the connection open,
4698  *         GNUNET_SYSERR to close it (signal serious error)
4699  */
4700 static int
4701 handle_mesh_data_unicast (void *cls, const struct GNUNET_PeerIdentity *peer,
4702                           const struct GNUNET_MessageHeader *message,
4703                           const struct GNUNET_ATS_Information *atsi,
4704                           unsigned int atsi_count)
4705 {
4706   struct GNUNET_MESH_Unicast *msg;
4707   struct GNUNET_PeerIdentity *neighbor;
4708   struct MeshTunnelChildInfo *cinfo;
4709   struct MeshTunnel *t;
4710   GNUNET_PEER_Id dest_id;
4711   uint32_t pid;
4712   uint32_t ttl;
4713   size_t size;
4714
4715   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a unicast packet from %s\n",
4716               GNUNET_i2s (peer));
4717   size = ntohs (message->size);
4718   if (size <
4719       sizeof (struct GNUNET_MESH_Unicast) +
4720       sizeof (struct GNUNET_MessageHeader))
4721   {
4722     GNUNET_break (0);
4723     return GNUNET_OK;
4724   }
4725   msg = (struct GNUNET_MESH_Unicast *) message;
4726   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %u\n",
4727               ntohs (msg[1].header.type));
4728   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4729   if (NULL == t)
4730   {
4731     /* TODO notify back: we don't know this tunnel */
4732     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
4733     GNUNET_break_op (0);
4734     return GNUNET_OK;
4735   }
4736   pid = ntohl (msg->pid);
4737   if (t->pid == pid)
4738   {
4739     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
4740     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4741                 " Already seen pid %u, DROPPING!\n", pid);
4742     return GNUNET_OK;
4743   }
4744   else
4745   {
4746     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4747                 " pid %u not seen yet, forwarding\n", pid);
4748   }
4749   t->skip += (pid - t->pid) - 1;
4750   t->pid = pid;
4751   tunnel_reset_timeout (t);
4752   dest_id = GNUNET_PEER_search (&msg->destination);
4753   if (dest_id == myid)
4754   {
4755     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4756                 "  it's for us! sending to clients...\n");
4757     GNUNET_STATISTICS_update (stats, "# unicast received", 1, GNUNET_NO);
4758     send_subscribed_clients (message, (struct GNUNET_MessageHeader *) &msg[1]);
4759     // FIXME send after client processes the packet
4760     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
4761     return GNUNET_OK;
4762   }
4763   ttl = ntohl (msg->ttl);
4764   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ttl);
4765   if (ttl == 0)
4766   {
4767     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
4768     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
4769     return GNUNET_OK;
4770   }
4771   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4772               "  not for us, retransmitting...\n");
4773   GNUNET_STATISTICS_update (stats, "# unicast forwarded", 1, GNUNET_NO);
4774
4775   neighbor = tree_get_first_hop (t->tree, dest_id);
4776   cinfo = GNUNET_CONTAINER_multihashmap_get (t->children_fc,
4777                                              &neighbor->hashPubKey);
4778   if (NULL == cinfo)
4779   {
4780     cinfo = GNUNET_malloc (sizeof (struct MeshTunnelChildInfo));
4781     cinfo->id = GNUNET_PEER_intern (neighbor);
4782     cinfo->skip = pid;
4783     cinfo->max_pid = pid + t->queue_max - t->queue_n; // FIXME review
4784
4785     GNUNET_assert (GNUNET_OK ==
4786                    GNUNET_CONTAINER_multihashmap_put (t->children_fc,
4787                        &neighbor->hashPubKey,
4788                        cinfo,
4789                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
4790   }
4791   cinfo->pid = pid;
4792   GNUNET_CONTAINER_multihashmap_iterate (t->children_fc,
4793                                          &tunnel_add_skip,
4794                                          &neighbor);
4795   send_message (message, neighbor, t);
4796   return GNUNET_OK;
4797 }
4798
4799
4800 /**
4801  * Core handler for mesh network traffic going from the origin to all peers
4802  *
4803  * @param cls closure
4804  * @param message message
4805  * @param peer peer identity this notification is about
4806  * @param atsi performance data
4807  * @param atsi_count number of records in 'atsi'
4808  * @return GNUNET_OK to keep the connection open,
4809  *         GNUNET_SYSERR to close it (signal serious error)
4810  *
4811  * TODO: Check who we got this from, to validate route.
4812  */
4813 static int
4814 handle_mesh_data_multicast (void *cls, const struct GNUNET_PeerIdentity *peer,
4815                             const struct GNUNET_MessageHeader *message,
4816                             const struct GNUNET_ATS_Information *atsi,
4817                             unsigned int atsi_count)
4818 {
4819   struct GNUNET_MESH_Multicast *msg;
4820   struct MeshTunnel *t;
4821   size_t size;
4822   uint32_t pid;
4823
4824   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a multicast packet from %s\n",
4825               GNUNET_i2s (peer));
4826   size = ntohs (message->size);
4827   if (sizeof (struct GNUNET_MESH_Multicast) +
4828       sizeof (struct GNUNET_MessageHeader) > size)
4829   {
4830     GNUNET_break_op (0);
4831     return GNUNET_OK;
4832   }
4833   msg = (struct GNUNET_MESH_Multicast *) message;
4834   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4835
4836   if (NULL == t)
4837   {
4838     /* TODO notify that we dont know that tunnel */
4839     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
4840     GNUNET_break_op (0);
4841     return GNUNET_OK;
4842   }
4843   pid = ntohl (msg->pid);
4844   if (t->pid == pid)
4845   {
4846     /* already seen this packet, drop */
4847     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
4848     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4849                 " Already seen pid %u, DROPPING!\n", pid);
4850     return GNUNET_OK;
4851   }
4852   else
4853   {
4854     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4855                 " pid %u not seen yet, forwarding\n", pid);
4856   }
4857   t->skip += (pid - t->pid) - 1;
4858   t->pid = pid;
4859   tunnel_reset_timeout (t);
4860
4861   /* Transmit to locally interested clients */
4862   if (NULL != t->peers &&
4863       GNUNET_CONTAINER_multihashmap_contains (t->peers, &my_full_id.hashPubKey))
4864   {
4865     GNUNET_STATISTICS_update (stats, "# multicast received", 1, GNUNET_NO);
4866     send_subscribed_clients (message, &msg[1].header);
4867   }
4868   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ntohl (msg->ttl));
4869   if (ntohl (msg->ttl) == 0)
4870   {
4871     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
4872     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
4873     return GNUNET_OK;
4874   }
4875   GNUNET_STATISTICS_update (stats, "# multicast forwarded", 1, GNUNET_NO);
4876   tunnel_send_multicast (t, message, GNUNET_NO);
4877   return GNUNET_OK;
4878 }
4879
4880
4881 /**
4882  * Core handler for mesh network traffic toward the owner of a tunnel
4883  *
4884  * @param cls closure
4885  * @param message message
4886  * @param peer peer identity this notification is about
4887  * @param atsi performance data
4888  * @param atsi_count number of records in 'atsi'
4889  *
4890  * @return GNUNET_OK to keep the connection open,
4891  *         GNUNET_SYSERR to close it (signal serious error)
4892  */
4893 static int
4894 handle_mesh_data_to_orig (void *cls, const struct GNUNET_PeerIdentity *peer,
4895                           const struct GNUNET_MessageHeader *message,
4896                           const struct GNUNET_ATS_Information *atsi,
4897                           unsigned int atsi_count)
4898 {
4899   struct GNUNET_MESH_ToOrigin *msg;
4900   struct GNUNET_PeerIdentity id;
4901   struct MeshPeerInfo *peer_info;
4902   struct MeshTunnel *t;
4903   size_t size;
4904
4905   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a ToOrigin packet from %s\n",
4906               GNUNET_i2s (peer));
4907   size = ntohs (message->size);
4908   if (size < sizeof (struct GNUNET_MESH_ToOrigin) +     /* Payload must be */
4909       sizeof (struct GNUNET_MessageHeader))     /* at least a header */
4910   {
4911     GNUNET_break_op (0);
4912     return GNUNET_OK;
4913   }
4914   msg = (struct GNUNET_MESH_ToOrigin *) message;
4915   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %u\n",
4916               ntohs (msg[1].header.type));
4917   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4918
4919   if (NULL == t)
4920   {
4921     /* TODO notify that we dont know this tunnel (whom)? */
4922     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
4923     GNUNET_break_op (0);
4924     return GNUNET_OK;
4925   }
4926
4927   if (t->id.oid == myid)
4928   {
4929     char cbuf[size];
4930     struct GNUNET_MESH_ToOrigin *copy;
4931
4932     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4933                 "  it's for us! sending to clients...\n");
4934     if (NULL == t->owner)
4935     {
4936       /* got data packet for ownerless tunnel */
4937       GNUNET_STATISTICS_update (stats, "# data on ownerless tunnel",
4938                                 1, GNUNET_NO);
4939       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  no clients!\n");
4940       GNUNET_break_op (0);
4941       return GNUNET_OK;
4942     }
4943     /* TODO signature verification */
4944     memcpy (cbuf, message, size);
4945     copy = (struct GNUNET_MESH_ToOrigin *) cbuf;
4946     copy->tid = htonl (t->local_tid);
4947     GNUNET_STATISTICS_update (stats, "# to origin received", 1, GNUNET_NO);
4948     GNUNET_SERVER_notification_context_unicast (nc, t->owner->handle,
4949                                                 &copy->header, GNUNET_NO);
4950     return GNUNET_OK;
4951   }
4952   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4953               "  not for us, retransmitting...\n");
4954
4955   peer_info = peer_info_get (&msg->oid);
4956   if (NULL == peer_info)
4957   {
4958     /* unknown origin of tunnel */
4959     GNUNET_break (0);
4960     return GNUNET_OK;
4961   }
4962   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
4963   send_message (message, &id, t);
4964   GNUNET_STATISTICS_update (stats, "# to origin forwarded", 1, GNUNET_NO);
4965
4966   return GNUNET_OK;
4967 }
4968
4969
4970 /**
4971  * Core handler for mesh network traffic point-to-point acks.
4972  *
4973  * @param cls closure
4974  * @param message message
4975  * @param peer peer identity this notification is about
4976  * @param atsi performance data
4977  * @param atsi_count number of records in 'atsi'
4978  *
4979  * @return GNUNET_OK to keep the connection open,
4980  *         GNUNET_SYSERR to close it (signal serious error)
4981  */
4982 static int
4983 handle_mesh_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
4984                  const struct GNUNET_MessageHeader *message,
4985                  const struct GNUNET_ATS_Information *atsi,
4986                  unsigned int atsi_count)
4987 {
4988   struct GNUNET_MESH_ACK *msg;
4989   struct MeshTunnelChildInfo *cinfo;
4990   struct MeshTunnel *t;
4991   uint32_t ack;
4992
4993   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got an ACK packet from %s\n",
4994               GNUNET_i2s (peer));
4995   msg = (struct GNUNET_MESH_ACK *) message;
4996   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %u\n",
4997               ntohs (msg[1].header.type));
4998   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4999
5000   if (NULL == t)
5001   {
5002     /* TODO notify that we dont know this tunnel (whom)? */
5003     GNUNET_STATISTICS_update (stats, "# ack on unknown tunnel", 1, GNUNET_NO);
5004     GNUNET_break_op (0);
5005     return GNUNET_OK;
5006   }
5007   ack = ntohl (msg->pid);
5008   cinfo = GNUNET_CONTAINER_multihashmap_get (t->children_fc,
5009                                              &peer->hashPubKey);
5010   if (NULL == cinfo)
5011   {
5012     GNUNET_break_op (0);
5013     return GNUNET_OK;
5014   }
5015   cinfo->max_pid = ack;
5016   tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5017   return GNUNET_OK;
5018 }
5019
5020
5021 /**
5022  * Core handler for path ACKs
5023  *
5024  * @param cls closure
5025  * @param message message
5026  * @param peer peer identity this notification is about
5027  * @param atsi performance data
5028  * @param atsi_count number of records in 'atsi'
5029  *
5030  * @return GNUNET_OK to keep the connection open,
5031  *         GNUNET_SYSERR to close it (signal serious error)
5032  */
5033 static int
5034 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5035                       const struct GNUNET_MessageHeader *message,
5036                       const struct GNUNET_ATS_Information *atsi,
5037                       unsigned int atsi_count)
5038 {
5039   struct GNUNET_MESH_PathACK *msg;
5040   struct GNUNET_PeerIdentity id;
5041   struct MeshPeerInfo *peer_info;
5042   struct MeshPeerPath *p;
5043   struct MeshTunnel *t;
5044
5045   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a path ACK msg [%s]\n",
5046               GNUNET_i2s (&my_full_id));
5047   msg = (struct GNUNET_MESH_PathACK *) message;
5048   t = tunnel_get (&msg->oid, ntohl(msg->tid));
5049   if (NULL == t)
5050   {
5051     /* TODO notify that we don't know the tunnel */
5052     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel", 1, GNUNET_NO);
5053     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  don't know the tunnel %s [%X]!\n",
5054                 GNUNET_i2s (&msg->oid), ntohl(msg->tid));
5055     return GNUNET_OK;
5056   }
5057   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %s [%X]\n",
5058               GNUNET_i2s (&msg->oid), ntohl(msg->tid));
5059
5060   peer_info = peer_info_get (&msg->peer_id);
5061   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by peer %s\n",
5062               GNUNET_i2s (&msg->peer_id));
5063   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  via peer %s\n",
5064               GNUNET_i2s (peer));
5065
5066   if (NULL != t->regex_ctx && t->regex_ctx->info->peer == peer_info->id)
5067   {
5068     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5069                 "connect_by_string completed, stopping search\n");
5070     regex_cancel_search (t->regex_ctx);
5071     t->regex_ctx = NULL;
5072   }
5073
5074   /* Add paths to peers? */
5075   p = tree_get_path_to_peer (t->tree, peer_info->id);
5076   if (NULL != p)
5077   {
5078     path_add_to_peers (p, GNUNET_YES);
5079     path_destroy (p);
5080   }
5081   else
5082   {
5083     GNUNET_break (0);
5084   }
5085
5086   /* Message for us? */
5087   if (0 == memcmp (&msg->oid, &my_full_id, sizeof (struct GNUNET_PeerIdentity)))
5088   {
5089     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
5090     if (NULL == t->owner)
5091     {
5092       GNUNET_break_op (0);
5093       return GNUNET_OK;
5094     }
5095     if (NULL != t->dht_get_type)
5096     {
5097       GNUNET_DHT_get_stop (t->dht_get_type);
5098       t->dht_get_type = NULL;
5099     }
5100     if (tree_get_status (t->tree, peer_info->id) != MESH_PEER_READY)
5101     {
5102       tree_set_status (t->tree, peer_info->id, MESH_PEER_READY);
5103       send_client_peer_connected (t, peer_info->id);
5104     }
5105     return GNUNET_OK;
5106   }
5107
5108   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5109               "  not for us, retransmitting...\n");
5110   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
5111   peer_info = peer_info_get (&msg->oid);
5112   if (NULL == peer_info)
5113   {
5114     /* If we know the tunnel, we should DEFINITELY know the peer */
5115     GNUNET_break (0);
5116     return GNUNET_OK;
5117   }
5118   send_message (message, &id, t);
5119   return GNUNET_OK;
5120 }
5121
5122
5123 /**
5124  * Functions to handle messages from core
5125  */
5126 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
5127   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
5128   {&handle_mesh_path_destroy, GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY, 0},
5129   {&handle_mesh_path_broken, GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN,
5130    sizeof (struct GNUNET_MESH_PathBroken)},
5131   {&handle_mesh_tunnel_destroy, GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY,
5132    sizeof (struct GNUNET_MESH_TunnelDestroy)},
5133   {&handle_mesh_data_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
5134   {&handle_mesh_data_multicast, GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
5135   {&handle_mesh_data_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
5136   {&handle_mesh_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
5137     sizeof (struct GNUNET_MESH_ACK)},
5138   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
5139    sizeof (struct GNUNET_MESH_PathACK)},
5140   {NULL, 0, 0}
5141 };
5142
5143
5144
5145 /******************************************************************************/
5146 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
5147 /******************************************************************************/
5148
5149 /**
5150  * deregister_app: iterator for removing each application registered by a client
5151  *
5152  * @param cls closure
5153  * @param key the hash of the application id (used to access the hashmap)
5154  * @param value the value stored at the key (client)
5155  *
5156  * @return GNUNET_OK on success
5157  */
5158 static int
5159 deregister_app (void *cls, const struct GNUNET_HashCode * key, void *value)
5160 {
5161   struct GNUNET_CONTAINER_MultiHashMap *h = cls;
5162   GNUNET_break (GNUNET_YES ==
5163                 GNUNET_CONTAINER_multihashmap_remove (h, key, value));
5164   return GNUNET_OK;
5165 }
5166
5167 #if LATER
5168 /**
5169  * notify_client_connection_failure: notify a client that the connection to the
5170  * requested remote peer is not possible (for instance, no route found)
5171  * Function called when the socket is ready to queue more data. "buf" will be
5172  * NULL and "size" zero if the socket was closed for writing in the meantime.
5173  *
5174  * @param cls closure
5175  * @param size number of bytes available in buf
5176  * @param buf where the callee should write the message
5177  * @return number of bytes written to buf
5178  */
5179 static size_t
5180 notify_client_connection_failure (void *cls, size_t size, void *buf)
5181 {
5182   int size_needed;
5183   struct MeshPeerInfo *peer_info;
5184   struct GNUNET_MESH_PeerControl *msg;
5185   struct GNUNET_PeerIdentity id;
5186
5187   if (0 == size && NULL == buf)
5188   {
5189     // TODO retry? cancel?
5190     return 0;
5191   }
5192
5193   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
5194   peer_info = (struct MeshPeerInfo *) cls;
5195   msg = (struct GNUNET_MESH_PeerControl *) buf;
5196   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
5197   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
5198 //     msg->tunnel_id = htonl(peer_info->t->tid);
5199   GNUNET_PEER_resolve (peer_info->id, &id);
5200   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
5201
5202   return size_needed;
5203 }
5204 #endif
5205
5206
5207 /**
5208  * Send keepalive packets for a peer
5209  *
5210  * @param cls Closure (tunnel for which to send the keepalive).
5211  * @param tc Notification context.
5212  *
5213  * TODO: implement explicit multicast keepalive?
5214  */
5215 static void
5216 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
5217 {
5218   struct MeshTunnel *t = cls;
5219   struct GNUNET_MessageHeader *payload;
5220   struct GNUNET_MESH_Multicast *msg;
5221   size_t size =
5222       sizeof (struct GNUNET_MESH_Multicast) +
5223       sizeof (struct GNUNET_MessageHeader);
5224   char cbuf[size];
5225
5226   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
5227   {
5228     return;
5229   }
5230   t->path_refresh_task = GNUNET_SCHEDULER_NO_TASK;
5231
5232   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5233               "sending keepalive for tunnel %d\n", t->id.tid);
5234
5235   msg = (struct GNUNET_MESH_Multicast *) cbuf;
5236   msg->header.size = htons (size);
5237   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
5238   msg->oid = my_full_id;
5239   msg->tid = htonl (t->id.tid);
5240   msg->ttl = htonl (default_ttl);
5241   msg->pid = htonl (t->pid + 1);
5242   t->pid++;
5243   payload = (struct GNUNET_MessageHeader *) &msg[1];
5244   payload->size = htons (sizeof (struct GNUNET_MessageHeader));
5245   payload->type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE);
5246   tunnel_send_multicast (t, &msg->header, GNUNET_YES);
5247
5248   t->path_refresh_task =
5249       GNUNET_SCHEDULER_add_delayed (refresh_path_time, &path_refresh, t);
5250   return;
5251 }
5252
5253
5254 /**
5255  * Function to process paths received for a new peer addition. The recorded
5256  * paths form the initial tunnel, which can be optimized later.
5257  * Called on each result obtained for the DHT search.
5258  *
5259  * @param cls closure
5260  * @param exp when will this value expire
5261  * @param key key of the result
5262  * @param get_path path of the get request
5263  * @param get_path_length lenght of get_path
5264  * @param put_path path of the put request
5265  * @param put_path_length length of the put_path
5266  * @param type type of the result
5267  * @param size number of bytes in data
5268  * @param data pointer to the result data
5269  *
5270  * TODO: re-issue the request after certain time? cancel after X results?
5271  */
5272 static void
5273 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
5274                     const struct GNUNET_HashCode * key,
5275                     const struct GNUNET_PeerIdentity *get_path,
5276                     unsigned int get_path_length,
5277                     const struct GNUNET_PeerIdentity *put_path,
5278                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
5279                     size_t size, const void *data)
5280 {
5281   struct MeshPathInfo *path_info = cls;
5282   struct MeshPeerPath *p;
5283   struct GNUNET_PeerIdentity pi;
5284   int i;
5285
5286   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
5287   GNUNET_PEER_resolve (path_info->peer->id, &pi);
5288   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", GNUNET_i2s (&pi));
5289
5290   p = path_build_from_dht (get_path, get_path_length, put_path,
5291                            put_path_length);
5292   path_add_to_peers (p, GNUNET_NO);
5293   path_destroy(p);
5294   for (i = 0; i < path_info->peer->ntunnels; i++)
5295   {
5296     tunnel_add_peer (path_info->peer->tunnels[i], path_info->peer);
5297     peer_info_connect (path_info->peer, path_info->t);
5298   }
5299
5300   return;
5301 }
5302
5303
5304 /**
5305  * Function to process paths received for a new peer addition. The recorded
5306  * paths form the initial tunnel, which can be optimized later.
5307  * Called on each result obtained for the DHT search.
5308  *
5309  * @param cls closure
5310  * @param exp when will this value expire
5311  * @param key key of the result
5312  * @param get_path path of the get request
5313  * @param get_path_length lenght of get_path
5314  * @param put_path path of the put request
5315  * @param put_path_length length of the put_path
5316  * @param type type of the result
5317  * @param size number of bytes in data
5318  * @param data pointer to the result data
5319  */
5320 static void
5321 dht_get_type_handler (void *cls, struct GNUNET_TIME_Absolute exp,
5322                       const struct GNUNET_HashCode * key,
5323                       const struct GNUNET_PeerIdentity *get_path,
5324                       unsigned int get_path_length,
5325                       const struct GNUNET_PeerIdentity *put_path,
5326                       unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
5327                       size_t size, const void *data)
5328 {
5329   const struct PBlock *pb = data;
5330   const struct GNUNET_PeerIdentity *pi = &pb->id;
5331   struct MeshTunnel *t = cls;
5332   struct MeshPeerInfo *peer_info;
5333   struct MeshPeerPath *p;
5334
5335   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got type DHT result!\n");
5336   if (size != sizeof (struct PBlock))
5337   {
5338     GNUNET_break_op (0);
5339     return;
5340   }
5341   if (ntohl(pb->type) != t->type)
5342   {
5343     GNUNET_break_op (0);
5344     return;
5345   }
5346   GNUNET_assert (NULL != t->owner);
5347   peer_info = peer_info_get (pi);
5348   (void) GNUNET_CONTAINER_multihashmap_put (t->peers, &pi->hashPubKey,
5349                                             peer_info,
5350                                             GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
5351
5352   p = path_build_from_dht (get_path, get_path_length, put_path,
5353                            put_path_length);
5354   path_add_to_peers (p, GNUNET_NO);
5355   path_destroy(p);
5356   tunnel_add_peer (t, peer_info);
5357   peer_info_connect (peer_info, t);
5358 }
5359
5360
5361 /**
5362  * Function to process DHT string to regex matching.
5363  * Called on each result obtained for the DHT search.
5364  *
5365  * @param cls closure (search context)
5366  * @param exp when will this value expire
5367  * @param key key of the result
5368  * @param get_path path of the get request (not used)
5369  * @param get_path_length lenght of get_path (not used)
5370  * @param put_path path of the put request (not used)
5371  * @param put_path_length length of the put_path (not used)
5372  * @param type type of the result
5373  * @param size number of bytes in data
5374  * @param data pointer to the result data
5375  */
5376 static void
5377 dht_get_string_accept_handler (void *cls, struct GNUNET_TIME_Absolute exp,
5378                                const struct GNUNET_HashCode * key,
5379                                const struct GNUNET_PeerIdentity *get_path,
5380                                unsigned int get_path_length,
5381                                const struct GNUNET_PeerIdentity *put_path,
5382                                unsigned int put_path_length,
5383                                enum GNUNET_BLOCK_Type type,
5384                                size_t size, const void *data)
5385 {
5386   const struct MeshRegexAccept *block = data;
5387   struct MeshRegexSearchContext *ctx = cls;
5388   struct MeshRegexSearchInfo *info = ctx->info;
5389   struct MeshPeerPath *p;
5390   struct MeshPeerInfo *peer_info;
5391
5392   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got regex results from DHT!\n");
5393   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", info->description);
5394
5395   peer_info = peer_info_get(&block->id);
5396   p = path_build_from_dht (get_path, get_path_length, put_path,
5397                            put_path_length);
5398   path_add_to_peers (p, GNUNET_NO);
5399   path_destroy(p);
5400
5401   tunnel_add_peer (info->t, peer_info);
5402   peer_info_connect (peer_info, info->t);
5403   if (0 == info->peer)
5404   {
5405     info->peer = peer_info->id;
5406   }
5407   else
5408   {
5409     GNUNET_array_append (info->peers, info->n_peers, peer_info->id);
5410   }
5411
5412   info->timeout = GNUNET_SCHEDULER_add_delayed (connect_timeout,
5413                                                 &regex_connect_timeout,
5414                                                 info);
5415
5416   return;
5417 }
5418
5419
5420 /**
5421  * Function to process DHT string to regex matching.
5422  * Called on each result obtained for the DHT search.
5423  *
5424  * @param cls closure (search context)
5425  * @param exp when will this value expire
5426  * @param key key of the result
5427  * @param get_path path of the get request (not used)
5428  * @param get_path_length lenght of get_path (not used)
5429  * @param put_path path of the put request (not used)
5430  * @param put_path_length length of the put_path (not used)
5431  * @param type type of the result
5432  * @param size number of bytes in data
5433  * @param data pointer to the result data
5434  *
5435  * TODO: re-issue the request after certain time? cancel after X results?
5436  */
5437 static void
5438 dht_get_string_handler (void *cls, struct GNUNET_TIME_Absolute exp,
5439                         const struct GNUNET_HashCode * key,
5440                         const struct GNUNET_PeerIdentity *get_path,
5441                         unsigned int get_path_length,
5442                         const struct GNUNET_PeerIdentity *put_path,
5443                         unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
5444                         size_t size, const void *data)
5445 {
5446   const struct MeshRegexBlock *block = data;
5447   struct MeshRegexSearchContext *ctx = cls;
5448   struct MeshRegexSearchInfo *info = ctx->info;
5449   void *copy;
5450   size_t len;
5451
5452   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5453               "DHT GET STRING RETURNED RESULTS\n");
5454   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5455               "  key: %s\n", GNUNET_h2s (key));
5456
5457   copy = GNUNET_malloc (size);
5458   memcpy (copy, data, size);
5459   GNUNET_break (GNUNET_OK ==
5460                 GNUNET_CONTAINER_multihashmap_put(info->dht_get_results, key, copy,
5461                                                   GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
5462   len = ntohl (block->n_proof);
5463   {
5464     char proof[len + 1];
5465
5466     memcpy (proof, &block[1], len);
5467     proof[len] = '\0';
5468     if (GNUNET_OK != GNUNET_REGEX_check_proof (proof, key))
5469     {
5470       GNUNET_break_op (0);
5471       return;
5472     }
5473   }
5474   len = strlen (info->description);
5475   if (len == ctx->position) // String processed
5476   {
5477     if (GNUNET_YES == ntohl (block->accepting))
5478     {
5479       regex_find_path(key, ctx);
5480     }
5481     else
5482     {
5483       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  block not accepting!\n");
5484       // FIXME REGEX this block not successful, wait for more? start timeout?
5485     }
5486     return;
5487   }
5488   GNUNET_break (GNUNET_OK ==
5489                 GNUNET_MESH_regex_block_iterate (block, size,
5490                                                  &regex_edge_iterator, ctx));
5491   return;
5492 }
5493
5494 /******************************************************************************/
5495 /*********************       MESH LOCAL HANDLES      **************************/
5496 /******************************************************************************/
5497
5498
5499 /**
5500  * Handler for client disconnection
5501  *
5502  * @param cls closure
5503  * @param client identification of the client; NULL
5504  *        for the last call when the server is destroyed
5505  */
5506 static void
5507 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
5508 {
5509   struct MeshClient *c;
5510   struct MeshClient *next;
5511   unsigned int i;
5512
5513   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected\n");
5514   if (client == NULL)
5515   {
5516     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (SERVER DOWN)\n");
5517     return;
5518   }
5519   c = clients;
5520   while (NULL != c)
5521   {
5522     if (c->handle != client)
5523     {
5524       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ... searching\n");
5525       c = c->next;
5526       continue;
5527     }
5528     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u)\n",
5529                 c->id);
5530     GNUNET_SERVER_client_drop (c->handle);
5531     c->shutting_down = GNUNET_YES;
5532     GNUNET_assert (NULL != c->own_tunnels);
5533     GNUNET_assert (NULL != c->incoming_tunnels);
5534     GNUNET_CONTAINER_multihashmap_iterate (c->own_tunnels,
5535                                            &tunnel_destroy_iterator, c);
5536     GNUNET_CONTAINER_multihashmap_iterate (c->incoming_tunnels,
5537                                            &tunnel_destroy_iterator, c);
5538     GNUNET_CONTAINER_multihashmap_iterate (c->ignore_tunnels,
5539                                            &tunnel_destroy_iterator, c);
5540     GNUNET_CONTAINER_multihashmap_destroy (c->own_tunnels);
5541     GNUNET_CONTAINER_multihashmap_destroy (c->incoming_tunnels);
5542     GNUNET_CONTAINER_multihashmap_destroy (c->ignore_tunnels);
5543
5544     /* deregister clients applications */
5545     if (NULL != c->apps)
5546     {
5547       GNUNET_CONTAINER_multihashmap_iterate (c->apps, &deregister_app, c->apps);
5548       GNUNET_CONTAINER_multihashmap_destroy (c->apps);
5549     }
5550     if (0 == GNUNET_CONTAINER_multihashmap_size (applications) &&
5551         GNUNET_SCHEDULER_NO_TASK != announce_applications_task)
5552     {
5553       GNUNET_SCHEDULER_cancel (announce_applications_task);
5554       announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
5555     }
5556     if (NULL != c->types)
5557       GNUNET_CONTAINER_multihashmap_destroy (c->types);
5558     for (i = 0; i < c->n_regex; i++)
5559     {
5560       GNUNET_free (c->regexes[i]);
5561     }
5562     GNUNET_free_non_null (c->regexes);
5563     if (GNUNET_SCHEDULER_NO_TASK != c->regex_announce_task)
5564       GNUNET_SCHEDULER_cancel (c->regex_announce_task);
5565     next = c->next;
5566     GNUNET_CONTAINER_DLL_remove (clients, clients_tail, c);
5567     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT FREE at %p\n", c);
5568     GNUNET_free (c);
5569     GNUNET_STATISTICS_update (stats, "# clients", -1, GNUNET_NO);
5570     c = next;
5571   }
5572   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   done!\n");
5573   return;
5574 }
5575
5576
5577 /**
5578  * Handler for new clients
5579  *
5580  * @param cls closure
5581  * @param client identification of the client
5582  * @param message the actual message, which includes messages the client wants
5583  */
5584 static void
5585 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
5586                          const struct GNUNET_MessageHeader *message)
5587 {
5588   struct GNUNET_MESH_ClientConnect *cc_msg;
5589   struct MeshClient *c;
5590   GNUNET_MESH_ApplicationType *a;
5591   unsigned int size;
5592   uint16_t ntypes;
5593   uint16_t *t;
5594   uint16_t napps;
5595   uint16_t i;
5596
5597   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected\n");
5598   /* Check data sanity */
5599   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
5600   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
5601   ntypes = ntohs (cc_msg->types);
5602   napps = ntohs (cc_msg->applications);
5603   if (size !=
5604       ntypes * sizeof (uint16_t) + napps * sizeof (GNUNET_MESH_ApplicationType))
5605   {
5606     GNUNET_break (0);
5607     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5608     return;
5609   }
5610
5611   /* Create new client structure */
5612   c = GNUNET_malloc (sizeof (struct MeshClient));
5613   c->id = next_client_id++;
5614   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT NEW %u\n", c->id);
5615   c->handle = client;
5616   GNUNET_SERVER_client_keep (client);
5617   a = (GNUNET_MESH_ApplicationType *) &cc_msg[1];
5618   if (napps > 0)
5619   {
5620     GNUNET_MESH_ApplicationType at;
5621     struct GNUNET_HashCode hc;
5622
5623     c->apps = GNUNET_CONTAINER_multihashmap_create (napps);
5624     for (i = 0; i < napps; i++)
5625     {
5626       at = ntohl (a[i]);
5627       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  app type: %u\n", at);
5628       GNUNET_CRYPTO_hash (&at, sizeof (at), &hc);
5629       /* store in clients hashmap */
5630       GNUNET_CONTAINER_multihashmap_put (c->apps, &hc, (void *) (long) at,
5631                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
5632       /* store in global hashmap, for announcements */
5633       GNUNET_CONTAINER_multihashmap_put (applications, &hc, c,
5634                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
5635     }
5636     if (GNUNET_SCHEDULER_NO_TASK == announce_applications_task)
5637       announce_applications_task =
5638           GNUNET_SCHEDULER_add_now (&announce_applications, NULL);
5639
5640   }
5641   if (ntypes > 0)
5642   {
5643     uint16_t u16;
5644     struct GNUNET_HashCode hc;
5645
5646     t = (uint16_t *) & a[napps];
5647     c->types = GNUNET_CONTAINER_multihashmap_create (ntypes);
5648     for (i = 0; i < ntypes; i++)
5649     {
5650       u16 = ntohs (t[i]);
5651       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  msg type: %u\n", u16);
5652       GNUNET_CRYPTO_hash (&u16, sizeof (u16), &hc);
5653
5654       /* store in clients hashmap */
5655       GNUNET_CONTAINER_multihashmap_put (c->types, &hc, c,
5656                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
5657       /* store in global hashmap */
5658       GNUNET_CONTAINER_multihashmap_put (types, &hc, c,
5659                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
5660     }
5661   }
5662   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5663               " client has %u+%u subscriptions\n", napps, ntypes);
5664
5665   GNUNET_CONTAINER_DLL_insert (clients, clients_tail, c);
5666   c->own_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
5667   c->incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
5668   c->ignore_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
5669   GNUNET_SERVER_notification_context_add (nc, client);
5670   GNUNET_STATISTICS_update (stats, "# clients", 1, GNUNET_NO);
5671
5672   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5673   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
5674 }
5675
5676
5677 /**
5678  * Handler for clients announcing available services by a regular expression.
5679  *
5680  * @param cls closure
5681  * @param client identification of the client
5682  * @param message the actual message, which includes messages the client wants
5683  */
5684 static void
5685 handle_local_announce_regex (void *cls, struct GNUNET_SERVER_Client *client,
5686                              const struct GNUNET_MessageHeader *message)
5687 {
5688   struct MeshClient *c;
5689   char *regex;
5690   size_t len;
5691
5692   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "announce regex started\n");
5693
5694   /* Sanity check for client registration */
5695   if (NULL == (c = client_get (client)))
5696   {
5697     GNUNET_break (0);
5698     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5699     return;
5700   }
5701   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
5702
5703   len = ntohs (message->size) - sizeof(struct GNUNET_MessageHeader);
5704   regex = GNUNET_malloc (len + 1);
5705   memcpy (regex, &message[1], len);
5706   regex[len] = '\0';
5707   GNUNET_array_append (c->regexes, c->n_regex, regex);
5708   if (GNUNET_SCHEDULER_NO_TASK == c->regex_announce_task)
5709   {
5710     c->regex_announce_task = GNUNET_SCHEDULER_add_now(&announce_regex, c);
5711   }
5712   else
5713   {
5714     regex_put(regex);
5715   }
5716   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5717   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "announce regex processed\n");
5718 }
5719
5720
5721 /**
5722  * Handler for requests of new tunnels
5723  *
5724  * @param cls closure
5725  * @param client identification of the client
5726  * @param message the actual message
5727  */
5728 static void
5729 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
5730                             const struct GNUNET_MessageHeader *message)
5731 {
5732   struct GNUNET_MESH_TunnelMessage *t_msg;
5733   struct MeshTunnel *t;
5734   struct MeshClient *c;
5735
5736   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel requested\n");
5737
5738   /* Sanity check for client registration */
5739   if (NULL == (c = client_get (client)))
5740   {
5741     GNUNET_break (0);
5742     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5743     return;
5744   }
5745   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
5746
5747   /* Message sanity check */
5748   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
5749   {
5750     GNUNET_break (0);
5751     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5752     return;
5753   }
5754
5755   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
5756   /* Sanity check for tunnel numbering */
5757   if (0 == (ntohl (t_msg->tunnel_id) & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
5758   {
5759     GNUNET_break (0);
5760     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5761     return;
5762   }
5763   /* Sanity check for duplicate tunnel IDs */
5764   if (NULL != tunnel_get_by_local_id (c, ntohl (t_msg->tunnel_id)))
5765   {
5766     GNUNET_break (0);
5767     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5768     return;
5769   }
5770
5771   while (NULL != tunnel_get_by_pi (myid, next_tid))
5772     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
5773   t = tunnel_new (myid, next_tid++, c, ntohl (t_msg->tunnel_id));
5774   if (NULL == t)
5775   {
5776     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Tunnel creation failed.\n");
5777     GNUNET_break (0);
5778     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5779     return;
5780   }
5781   next_tid = next_tid & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
5782   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED TUNNEL %s [%x] (%x)\n",
5783               GNUNET_i2s (&my_full_id), t->id.tid, t->local_tid);
5784   t->peers = GNUNET_CONTAINER_multihashmap_create (32);
5785
5786   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel created\n");
5787   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5788   return;
5789 }
5790
5791
5792 /**
5793  * Handler for requests of deleting tunnels
5794  *
5795  * @param cls closure
5796  * @param client identification of the client
5797  * @param message the actual message
5798  */
5799 static void
5800 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
5801                              const struct GNUNET_MessageHeader *message)
5802 {
5803   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
5804   struct MeshClient *c;
5805   struct MeshTunnel *t;
5806   MESH_TunnelNumber tid;
5807
5808   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5809               "Got a DESTROY TUNNEL from client!\n");
5810
5811   /* Sanity check for client registration */
5812   if (NULL == (c = client_get (client)))
5813   {
5814     GNUNET_break (0);
5815     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5816     return;
5817   }
5818   /* Message sanity check */
5819   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
5820   {
5821     GNUNET_break (0);
5822     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5823     return;
5824   }
5825   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
5826   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
5827
5828   /* Retrieve tunnel */
5829   tid = ntohl (tunnel_msg->tunnel_id);
5830   t = tunnel_get_by_local_id(c, tid);
5831   if (NULL == t)
5832   {
5833     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
5834     GNUNET_break (0);
5835     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5836     return;
5837   }
5838   if (c != t->owner || tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
5839   {
5840     client_ignore_tunnel (c, t);
5841 #if 0
5842     // TODO: when to destroy incoming tunnel?
5843     if (t->nclients == 0)
5844     {
5845       GNUNET_assert (GNUNET_YES ==
5846                      GNUNET_CONTAINER_multihashmap_remove (incoming_tunnels,
5847                                                            &hash, t));
5848       GNUNET_assert (GNUNET_YES ==
5849                      GNUNET_CONTAINER_multihashmap_remove (t->peers,
5850                                                            &my_full_id.hashPubKey,
5851                                                            t));
5852     }
5853 #endif
5854     GNUNET_SERVER_receive_done (client, GNUNET_OK);
5855     return;
5856   }
5857   send_client_tunnel_disconnect(t, c);
5858   client_delete_tunnel(c, t);
5859
5860   /* Don't try to ACK the client about the tunnel_destroy multicast packet */
5861   t->owner = NULL;
5862   tunnel_send_destroy (t);
5863   t->destroy = GNUNET_YES;
5864   // The tunnel will be destroyed when the last message is transmitted.
5865   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5866   return;
5867 }
5868
5869
5870 /**
5871  * Handler for requests of seeting tunnel's speed.
5872  *
5873  * @param cls Closure (unused).
5874  * @param client Identification of the client.
5875  * @param message The actual message.
5876  */
5877 static void
5878 handle_local_tunnel_speed (void *cls, struct GNUNET_SERVER_Client *client,
5879                            const struct GNUNET_MessageHeader *message)
5880 {
5881   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
5882   struct MeshClient *c;
5883   struct MeshTunnel *t;
5884   MESH_TunnelNumber tid;
5885
5886   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5887               "Got a SPEED request from client!\n");
5888
5889   /* Sanity check for client registration */
5890   if (NULL == (c = client_get (client)))
5891   {
5892     GNUNET_break (0);
5893     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5894     return;
5895   }
5896
5897   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
5898   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
5899
5900   /* Retrieve tunnel */
5901   tid = ntohl (tunnel_msg->tunnel_id);
5902   t = tunnel_get_by_local_id(c, tid);
5903   if (NULL == t)
5904   {
5905     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  tunnel %X not found\n", tid);
5906     GNUNET_break (0);
5907     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5908     return;
5909   }
5910
5911   switch (ntohs(message->type))
5912   {
5913       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MIN:
5914           t->speed_min = GNUNET_YES;
5915           break;
5916       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MAX:
5917           t->speed_min = GNUNET_NO;
5918           break;
5919       default:
5920           GNUNET_break (0);
5921   }
5922   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5923 }
5924
5925
5926 /**
5927  * Handler for requests of seeting tunnel's buffering policy.
5928  *
5929  * @param cls Closure (unused).
5930  * @param client Identification of the client.
5931  * @param message The actual message.
5932  */
5933 static void
5934 handle_local_tunnel_buffer (void *cls, struct GNUNET_SERVER_Client *client,
5935                             const struct GNUNET_MessageHeader *message)
5936 {
5937   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
5938   struct MeshClient *c;
5939   struct MeshTunnel *t;
5940   MESH_TunnelNumber tid;
5941
5942   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5943               "Got a BUFFER request from client!\n");
5944
5945   /* Sanity check for client registration */
5946   if (NULL == (c = client_get (client)))
5947   {
5948     GNUNET_break (0);
5949     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5950     return;
5951   }
5952
5953   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
5954   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
5955
5956   /* Retrieve tunnel */
5957   tid = ntohl (tunnel_msg->tunnel_id);
5958   t = tunnel_get_by_local_id(c, tid);
5959   if (NULL == t)
5960   {
5961     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
5962     GNUNET_break (0);
5963     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5964     return;
5965   }
5966
5967   switch (ntohs(message->type))
5968   {
5969       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER:
5970           t->nobuffer = GNUNET_NO;
5971           break;
5972       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER:
5973           t->nobuffer = GNUNET_YES;
5974           break;
5975       default:
5976           GNUNET_break (0);
5977   }
5978
5979   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5980 }
5981
5982
5983 /**
5984  * Handler for connection requests to new peers
5985  *
5986  * @param cls closure
5987  * @param client identification of the client
5988  * @param message the actual message (PeerControl)
5989  */
5990 static void
5991 handle_local_connect_add (void *cls, struct GNUNET_SERVER_Client *client,
5992                           const struct GNUNET_MessageHeader *message)
5993 {
5994   struct GNUNET_MESH_PeerControl *peer_msg;
5995   struct MeshPeerInfo *peer_info;
5996   struct MeshClient *c;
5997   struct MeshTunnel *t;
5998   MESH_TunnelNumber tid;
5999
6000   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got connection request\n");
6001   /* Sanity check for client registration */
6002   if (NULL == (c = client_get (client)))
6003   {
6004     GNUNET_break (0);
6005     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6006     return;
6007   }
6008
6009   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6010   /* Sanity check for message size */
6011   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6012   {
6013     GNUNET_break (0);
6014     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6015     return;
6016   }
6017
6018   /* Tunnel exists? */
6019   tid = ntohl (peer_msg->tunnel_id);
6020   t = tunnel_get_by_local_id (c, tid);
6021   if (NULL == t)
6022   {
6023     GNUNET_break (0);
6024     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6025     return;
6026   }
6027
6028   /* Does client own tunnel? */
6029   if (t->owner->handle != client)
6030   {
6031     GNUNET_break (0);
6032     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6033     return;
6034   }
6035   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "     for %s\n",
6036               GNUNET_i2s (&peer_msg->peer));
6037   peer_info = peer_info_get (&peer_msg->peer);
6038
6039   tunnel_add_peer (t, peer_info);
6040   peer_info_connect (peer_info, t);
6041
6042   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6043   return;
6044 }
6045
6046
6047 /**
6048  * Handler for disconnection requests of peers in a tunnel
6049  *
6050  * @param cls closure
6051  * @param client identification of the client
6052  * @param message the actual message (PeerControl)
6053  */
6054 static void
6055 handle_local_connect_del (void *cls, struct GNUNET_SERVER_Client *client,
6056                           const struct GNUNET_MessageHeader *message)
6057 {
6058   struct GNUNET_MESH_PeerControl *peer_msg;
6059   struct MeshPeerInfo *peer_info;
6060   struct MeshClient *c;
6061   struct MeshTunnel *t;
6062   MESH_TunnelNumber tid;
6063
6064   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER DEL request\n");
6065   /* Sanity check for client registration */
6066   if (NULL == (c = client_get (client)))
6067   {
6068     GNUNET_break (0);
6069     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6070     return;
6071   }
6072   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6073   /* Sanity check for message size */
6074   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6075   {
6076     GNUNET_break (0);
6077     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6078     return;
6079   }
6080
6081   /* Tunnel exists? */
6082   tid = ntohl (peer_msg->tunnel_id);
6083   t = tunnel_get_by_local_id (c, tid);
6084   if (NULL == t)
6085   {
6086     GNUNET_break (0);
6087     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6088     return;
6089   }
6090   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
6091
6092   /* Does client own tunnel? */
6093   if (t->owner->handle != client)
6094   {
6095     GNUNET_break (0);
6096     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6097     return;
6098   }
6099
6100   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for peer %s\n",
6101               GNUNET_i2s (&peer_msg->peer));
6102   /* Is the peer in the tunnel? */
6103   peer_info =
6104       GNUNET_CONTAINER_multihashmap_get (t->peers, &peer_msg->peer.hashPubKey);
6105   if (NULL == peer_info)
6106   {
6107     GNUNET_break (0);
6108     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6109     return;
6110   }
6111
6112   /* Ok, delete peer from tunnel */
6113   GNUNET_CONTAINER_multihashmap_remove_all (t->peers,
6114                                             &peer_msg->peer.hashPubKey);
6115
6116   send_destroy_path (t, peer_info->id);
6117   tunnel_delete_peer (t, peer_info->id);
6118   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6119   return;
6120 }
6121
6122 /**
6123  * Handler for blacklist requests of peers in a tunnel
6124  *
6125  * @param cls closure
6126  * @param client identification of the client
6127  * @param message the actual message (PeerControl)
6128  */
6129 static void
6130 handle_local_blacklist (void *cls, struct GNUNET_SERVER_Client *client,
6131                           const struct GNUNET_MessageHeader *message)
6132 {
6133   struct GNUNET_MESH_PeerControl *peer_msg;
6134   struct MeshClient *c;
6135   struct MeshTunnel *t;
6136   MESH_TunnelNumber tid;
6137
6138   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER BLACKLIST request\n");
6139   /* Sanity check for client registration */
6140   if (NULL == (c = client_get (client)))
6141   {
6142     GNUNET_break (0);
6143     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6144     return;
6145   }
6146   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6147
6148   /* Sanity check for message size */
6149   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6150   {
6151     GNUNET_break (0);
6152     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6153     return;
6154   }
6155
6156   /* Tunnel exists? */
6157   tid = ntohl (peer_msg->tunnel_id);
6158   t = tunnel_get_by_local_id (c, tid);
6159   if (NULL == t)
6160   {
6161     GNUNET_break (0);
6162     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6163     return;
6164   }
6165   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
6166
6167   GNUNET_array_append(t->blacklisted, t->nblacklisted,
6168                       GNUNET_PEER_intern(&peer_msg->peer));
6169 }
6170
6171
6172 /**
6173  * Handler for unblacklist requests of peers in a tunnel
6174  *
6175  * @param cls closure
6176  * @param client identification of the client
6177  * @param message the actual message (PeerControl)
6178  */
6179 static void
6180 handle_local_unblacklist (void *cls, struct GNUNET_SERVER_Client *client,
6181                           const struct GNUNET_MessageHeader *message)
6182 {
6183   struct GNUNET_MESH_PeerControl *peer_msg;
6184   struct MeshClient *c;
6185   struct MeshTunnel *t;
6186   MESH_TunnelNumber tid;
6187   GNUNET_PEER_Id pid;
6188   unsigned int i;
6189
6190   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER UNBLACKLIST request\n");
6191   /* Sanity check for client registration */
6192   if (NULL == (c = client_get (client)))
6193   {
6194     GNUNET_break (0);
6195     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6196     return;
6197   }
6198   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6199
6200   /* Sanity check for message size */
6201   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6202   {
6203     GNUNET_break (0);
6204     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6205     return;
6206   }
6207
6208   /* Tunnel exists? */
6209   tid = ntohl (peer_msg->tunnel_id);
6210   t = tunnel_get_by_local_id (c, tid);
6211   if (NULL == t)
6212   {
6213     GNUNET_break (0);
6214     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6215     return;
6216   }
6217   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
6218
6219   /* if peer is not known, complain */
6220   pid = GNUNET_PEER_search (&peer_msg->peer);
6221   if (0 == pid)
6222   {
6223     GNUNET_break (0);
6224     return;
6225   }
6226
6227   /* search and remove from list */
6228   for (i = 0; i < t->nblacklisted; i++)
6229   {
6230     if (t->blacklisted[i] == pid)
6231     {
6232       t->blacklisted[i] = t->blacklisted[t->nblacklisted - 1];
6233       GNUNET_array_grow (t->blacklisted, t->nblacklisted, t->nblacklisted - 1);
6234       return;
6235     }
6236   }
6237
6238   /* if peer hasn't been blacklisted, complain */
6239   GNUNET_break (0);
6240 }
6241
6242
6243 /**
6244  * Handler for connection requests to new peers by type
6245  *
6246  * @param cls closure
6247  * @param client identification of the client
6248  * @param message the actual message (ConnectPeerByType)
6249  */
6250 static void
6251 handle_local_connect_by_type (void *cls, struct GNUNET_SERVER_Client *client,
6252                               const struct GNUNET_MessageHeader *message)
6253 {
6254   struct GNUNET_MESH_ConnectPeerByType *connect_msg;
6255   struct MeshClient *c;
6256   struct MeshTunnel *t;
6257   struct GNUNET_HashCode hash;
6258   MESH_TunnelNumber tid;
6259
6260   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got connect by type request\n");
6261   /* Sanity check for client registration */
6262   if (NULL == (c = client_get (client)))
6263   {
6264     GNUNET_break (0);
6265     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6266     return;
6267   }
6268
6269   connect_msg = (struct GNUNET_MESH_ConnectPeerByType *) message;
6270   /* Sanity check for message size */
6271   if (sizeof (struct GNUNET_MESH_ConnectPeerByType) !=
6272       ntohs (connect_msg->header.size))
6273   {
6274     GNUNET_break (0);
6275     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6276     return;
6277   }
6278
6279   /* Tunnel exists? */
6280   tid = ntohl (connect_msg->tunnel_id);
6281   t = tunnel_get_by_local_id (c, tid);
6282   if (NULL == t)
6283   {
6284     GNUNET_break (0);
6285     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6286     return;
6287   }
6288
6289   /* Does client own tunnel? */
6290   if (t->owner->handle != client)
6291   {
6292     GNUNET_break (0);
6293     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6294     return;
6295   }
6296
6297   /* Do WE have the service? */
6298   t->type = ntohl (connect_msg->type);
6299   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " type requested: %u\n", t->type);
6300   GNUNET_CRYPTO_hash (&t->type, sizeof (GNUNET_MESH_ApplicationType), &hash);
6301   if (GNUNET_CONTAINER_multihashmap_contains (applications, &hash) ==
6302       GNUNET_YES)
6303   {
6304     /* Yes! Fast forward, add ourselves to the tunnel and send the
6305      * good news to the client, and alert the destination client of
6306      * an incoming tunnel.
6307      *
6308      * FIXME send a path create to self, avoid code duplication
6309      */
6310     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " available locally\n");
6311     GNUNET_CONTAINER_multihashmap_put (t->peers, &my_full_id.hashPubKey,
6312                                        peer_info_get (&my_full_id),
6313                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
6314
6315     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " notifying client\n");
6316     send_client_peer_connected (t, myid);
6317     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Done\n");
6318     GNUNET_SERVER_receive_done (client, GNUNET_OK);
6319
6320     t->local_tid_dest = next_local_tid++;
6321     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
6322     GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
6323                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
6324
6325     return;
6326   }
6327   /* Ok, lets find a peer offering the service */
6328   if (NULL != t->dht_get_type)
6329   {
6330     GNUNET_DHT_get_stop (t->dht_get_type);
6331   }
6332   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " looking in DHT for %s\n",
6333               GNUNET_h2s (&hash));
6334   t->dht_get_type =
6335       GNUNET_DHT_get_start (dht_handle, 
6336                             GNUNET_BLOCK_TYPE_MESH_PEER_BY_TYPE,
6337                             &hash,
6338                             dht_replication_level,
6339                             GNUNET_DHT_RO_RECORD_ROUTE |
6340                             GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
6341                             NULL, 0,
6342                             &dht_get_type_handler, t);
6343
6344   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6345   return;
6346 }
6347
6348
6349 /**
6350  * Handler for connection requests to new peers by a string service description.
6351  *
6352  * @param cls closure
6353  * @param client identification of the client
6354  * @param message the actual message, which includes messages the client wants
6355  */
6356 static void
6357 handle_local_connect_by_string (void *cls, struct GNUNET_SERVER_Client *client,
6358                                 const struct GNUNET_MessageHeader *message)
6359 {
6360   struct GNUNET_MESH_ConnectPeerByString *msg;
6361   struct MeshRegexSearchContext *ctx;
6362   struct MeshRegexSearchInfo *info;
6363   struct GNUNET_DHT_GetHandle *get_h;
6364   struct GNUNET_HashCode key;
6365   struct MeshTunnel *t;
6366   struct MeshClient *c;
6367   MESH_TunnelNumber tid;
6368   const char *string;
6369   size_t size;
6370   size_t len;
6371   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6372               "Connect by string started\n");
6373   msg = (struct GNUNET_MESH_ConnectPeerByString *) message;
6374   size = htons (message->size);
6375
6376   /* Sanity check for client registration */
6377   if (NULL == (c = client_get (client)))
6378   {
6379     GNUNET_break (0);
6380     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6381     return;
6382   }
6383
6384   /* Message size sanity check */
6385   if (sizeof(struct GNUNET_MESH_ConnectPeerByString) >= size)
6386   {
6387     GNUNET_break (0);
6388     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6389     return;
6390   }
6391
6392   /* Tunnel exists? */
6393   tid = ntohl (msg->tunnel_id);
6394   t = tunnel_get_by_local_id (c, tid);
6395   if (NULL == t)
6396   {
6397     GNUNET_break (0);
6398     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6399     return;
6400   }
6401
6402   /* Does client own tunnel? */
6403   if (t->owner->handle != client)
6404   {
6405     GNUNET_break (0);
6406     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6407     return;
6408   }
6409
6410   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6411               "  on tunnel %s [%u]\n",
6412               GNUNET_i2s(&my_full_id),
6413               t->id.tid);
6414
6415   /* Only one connect_by_string allowed at the same time! */
6416   /* FIXME: allow more, return handle at api level to cancel, document */
6417   if (NULL != t->regex_ctx)
6418   {
6419     GNUNET_break (0);
6420     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6421     return;
6422   }
6423
6424   /* Find string itself */
6425   len = size - sizeof(struct GNUNET_MESH_ConnectPeerByString);
6426   string = (const char *) &msg[1];
6427
6428   /* Initialize context */
6429   size = GNUNET_REGEX_get_first_key(string, len, &key);
6430   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6431               "  consumed %u bits out of %u\n", size, len);
6432   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6433               "  looking for %s\n", GNUNET_h2s (&key));
6434
6435   info = GNUNET_malloc (sizeof (struct MeshRegexSearchInfo));
6436   info->t = t;
6437   info->description = GNUNET_malloc (len + 1);
6438   memcpy (info->description, string, len);
6439   info->description[len] = '\0';
6440   info->dht_get_handles = GNUNET_CONTAINER_multihashmap_create(32);
6441   info->dht_get_results = GNUNET_CONTAINER_multihashmap_create(32);
6442   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   string: %s\n", info->description);
6443
6444   ctx = GNUNET_malloc (sizeof (struct MeshRegexSearchContext));
6445   ctx->position = size;
6446   ctx->info = info;
6447   t->regex_ctx = ctx;
6448
6449   GNUNET_array_append (info->contexts, info->n_contexts, ctx);
6450
6451   /* Start search in DHT */
6452   get_h = GNUNET_DHT_get_start (dht_handle,    /* handle */
6453                                 GNUNET_BLOCK_TYPE_MESH_REGEX, /* type */
6454                                 &key,     /* key to search */
6455                                 dht_replication_level, /* replication level */
6456                                 GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
6457                                 NULL,       /* xquery */ // FIXME BLOOMFILTER
6458                                 0,     /* xquery bits */ // FIXME BLOOMFILTER SIZE
6459                                 &dht_get_string_handler, ctx);
6460
6461   GNUNET_break (GNUNET_OK ==
6462                 GNUNET_CONTAINER_multihashmap_put(info->dht_get_handles,
6463                                                   &key,
6464                                                   get_h,
6465                                                   GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
6466
6467   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6468   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "connect by string processed\n");
6469 }
6470
6471
6472 /**
6473  * Handler for client traffic directed to one peer
6474  *
6475  * @param cls closure
6476  * @param client identification of the client
6477  * @param message the actual message
6478  */
6479 static void
6480 handle_local_unicast (void *cls, struct GNUNET_SERVER_Client *client,
6481                       const struct GNUNET_MessageHeader *message)
6482 {
6483   struct MeshClient *c;
6484   struct MeshTunnel *t;
6485   struct MeshPeerInfo *pi;
6486   struct GNUNET_MESH_Unicast *data_msg;
6487   MESH_TunnelNumber tid;
6488   size_t size;
6489
6490   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6491               "Got a unicast request from a client!\n");
6492
6493   /* Sanity check for client registration */
6494   if (NULL == (c = client_get (client)))
6495   {
6496     GNUNET_break (0);
6497     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6498     return;
6499   }
6500   data_msg = (struct GNUNET_MESH_Unicast *) message;
6501   /* Sanity check for message size */
6502   size = ntohs (message->size);
6503   if (sizeof (struct GNUNET_MESH_Unicast) +
6504       sizeof (struct GNUNET_MessageHeader) > size)
6505   {
6506     GNUNET_break (0);
6507     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6508     return;
6509   }
6510
6511   /* Tunnel exists? */
6512   tid = ntohl (data_msg->tid);
6513   t = tunnel_get_by_local_id (c, tid);
6514   if (NULL == t)
6515   {
6516     GNUNET_break (0);
6517     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6518     return;
6519   }
6520
6521   /*  Is it a local tunnel? Then, does client own the tunnel? */
6522   if (t->owner->handle != client)
6523   {
6524     GNUNET_break (0);
6525     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6526     return;
6527   }
6528
6529   pi = GNUNET_CONTAINER_multihashmap_get (t->peers,
6530                                           &data_msg->destination.hashPubKey);
6531   /* Is the selected peer in the tunnel? */
6532   if (NULL == pi)
6533   {
6534     GNUNET_break (0);
6535     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6536     return;
6537   }
6538
6539   /* Ok, everything is correct, send the message
6540    * (pretend we got it from a mesh peer)
6541    */
6542   {
6543     char buf[ntohs (message->size)] GNUNET_ALIGN;
6544     struct GNUNET_MESH_Unicast *copy;
6545
6546     /* Work around const limitation */
6547     copy = (struct GNUNET_MESH_Unicast *) buf;
6548     memcpy (buf, data_msg, size);
6549     copy->oid = my_full_id;
6550     copy->tid = htonl (t->id.tid);
6551     copy->ttl = htonl (default_ttl);
6552     copy->pid = htonl (t->pid + 1);
6553     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6554                 "  calling generic handler...\n");
6555     handle_mesh_data_unicast (NULL, &my_full_id, &copy->header, NULL, 0);
6556   }
6557   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "receive done OK\n");
6558   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6559   return;
6560 }
6561
6562
6563 /**
6564  * Handler for client traffic directed to the origin
6565  *
6566  * @param cls closure
6567  * @param client identification of the client
6568  * @param message the actual message
6569  */
6570 static void
6571 handle_local_to_origin (void *cls, struct GNUNET_SERVER_Client *client,
6572                         const struct GNUNET_MessageHeader *message)
6573 {
6574   struct GNUNET_MESH_ToOrigin *data_msg;
6575   struct GNUNET_PeerIdentity id;
6576   struct MeshClient *c;
6577   struct MeshTunnel *t;
6578   MESH_TunnelNumber tid;
6579   size_t size;
6580
6581   /* Sanity check for client registration */
6582   if (NULL == (c = client_get (client)))
6583   {
6584     GNUNET_break (0);
6585     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6586     return;
6587   }
6588   data_msg = (struct GNUNET_MESH_ToOrigin *) message;
6589   /* Sanity check for message size */
6590   size = ntohs (message->size);
6591   if (sizeof (struct GNUNET_MESH_ToOrigin) +
6592       sizeof (struct GNUNET_MessageHeader) > size)
6593   {
6594     GNUNET_break (0);
6595     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6596     return;
6597   }
6598
6599   /* Tunnel exists? */
6600   tid = ntohl (data_msg->tid);
6601   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6602               "Got a ToOrigin request from a client! Tunnel %X\n", tid);
6603   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
6604   {
6605     GNUNET_break (0);
6606     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6607     return;
6608   }
6609   t = tunnel_get_by_local_id (c, tid);
6610   if (NULL == t)
6611   {
6612     GNUNET_break (0);
6613     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6614     return;
6615   }
6616
6617   /*  It should be sent by someone who has this as incoming tunnel. */
6618   if (-1 == client_knows_tunnel (c, t))
6619   {
6620     GNUNET_break (0);
6621     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6622     return;
6623   }
6624   GNUNET_PEER_resolve (t->id.oid, &id);
6625
6626   /* Ok, everything is correct, send the message
6627    * (pretend we got it from a mesh peer)
6628    */
6629   {
6630     char buf[ntohs (message->size)] GNUNET_ALIGN;
6631     struct GNUNET_MESH_ToOrigin *copy;
6632
6633     /* Work around const limitation */
6634     copy = (struct GNUNET_MESH_ToOrigin *) buf;
6635     memcpy (buf, data_msg, size);
6636     copy->oid = id;
6637     copy->tid = htonl (t->id.tid);
6638     copy->sender = my_full_id;
6639     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6640                 "  calling generic handler...\n");
6641     handle_mesh_data_to_orig (NULL, &my_full_id, &copy->header, NULL, 0);
6642   }
6643   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6644   return;
6645 }
6646
6647
6648 /**
6649  * Handler for client traffic directed to all peers in a tunnel
6650  *
6651  * @param cls closure
6652  * @param client identification of the client
6653  * @param message the actual message
6654  */
6655 static void
6656 handle_local_multicast (void *cls, struct GNUNET_SERVER_Client *client,
6657                         const struct GNUNET_MessageHeader *message)
6658 {
6659   struct MeshClient *c;
6660   struct MeshTunnel *t;
6661   struct GNUNET_MESH_Multicast *data_msg;
6662   MESH_TunnelNumber tid;
6663
6664   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6665               "Got a multicast request from a client!\n");
6666
6667   /* Sanity check for client registration */
6668   if (NULL == (c = client_get (client)))
6669   {
6670     GNUNET_break (0);
6671     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6672     return;
6673   }
6674   data_msg = (struct GNUNET_MESH_Multicast *) message;
6675   /* Sanity check for message size */
6676   if (sizeof (struct GNUNET_MESH_Multicast) +
6677       sizeof (struct GNUNET_MessageHeader) > ntohs (data_msg->header.size))
6678   {
6679     GNUNET_break (0);
6680     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6681     return;
6682   }
6683
6684   /* Tunnel exists? */
6685   tid = ntohl (data_msg->tid);
6686   t = tunnel_get_by_local_id (c, tid);
6687   if (NULL == t)
6688   {
6689     GNUNET_break (0);
6690     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6691     return;
6692   }
6693
6694   /* Does client own tunnel? */
6695   if (t->owner->handle != client)
6696   {
6697     GNUNET_break (0);
6698     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6699     return;
6700   }
6701
6702   {
6703     char buf[ntohs (message->size)] GNUNET_ALIGN;
6704     struct GNUNET_MESH_Multicast *copy;
6705
6706     copy = (struct GNUNET_MESH_Multicast *) buf;
6707     memcpy (buf, message, ntohs (message->size));
6708     copy->oid = my_full_id;
6709     copy->tid = htonl (t->id.tid);
6710     copy->ttl = htonl (default_ttl);
6711     copy->pid = htonl (t->pid + 1);
6712     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6713                 "  calling generic handler...\n");
6714     handle_mesh_data_multicast (client, &my_full_id, &copy->header, NULL, 0);
6715   }
6716
6717   /* receive done gets called when last copy is sent to a neighbor */
6718   return;
6719 }
6720
6721
6722 /**
6723  * Handler for client ACKs for payload traffic.
6724  *
6725  * @param cls Closure (unused).
6726  * @param client Identification of the client.
6727  * @param message The actual message.
6728  */
6729 static void
6730 handle_local_ack (void *cls, struct GNUNET_SERVER_Client *client,
6731                   const struct GNUNET_MessageHeader *message)
6732 {
6733   struct GNUNET_MESH_LocalAck *msg;
6734   struct MeshTunnel *t;
6735   struct MeshClient *c;
6736   MESH_TunnelNumber tid;
6737
6738   /* Sanity check for client registration */
6739   if (NULL == (c = client_get (client)))
6740   {
6741     GNUNET_break (0);
6742     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6743     return;
6744   }
6745
6746   msg = (struct GNUNET_MESH_LocalAck *) message;
6747   /* Tunnel exists? */
6748   tid = ntohl (msg->tunnel_id);
6749   t = tunnel_get_by_local_id (c, tid);
6750   if (NULL == t)
6751   {
6752     GNUNET_break (0);
6753     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6754     return;
6755   }
6756
6757   /* Does client own tunnel? */
6758   if (NULL != t->owner && t->owner->handle == client)
6759   {
6760     GNUNET_break (0);
6761     // FIXME TODO
6762   }
6763   else
6764   {
6765     tunnel_set_client_ack (t, c, ntohl (msg->max_pid));
6766   }
6767
6768   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6769   return;
6770 }
6771
6772
6773 /**
6774  * Functions to handle messages from clients
6775  */
6776 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
6777   {&handle_local_new_client, NULL,
6778    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
6779   {&handle_local_announce_regex, NULL,
6780    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ANNOUNCE_REGEX, 0},
6781   {&handle_local_tunnel_create, NULL,
6782    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
6783    sizeof (struct GNUNET_MESH_TunnelMessage)},
6784   {&handle_local_tunnel_destroy, NULL,
6785    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
6786    sizeof (struct GNUNET_MESH_TunnelMessage)},
6787   {&handle_local_tunnel_speed, NULL,
6788    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MIN,
6789    sizeof (struct GNUNET_MESH_TunnelMessage)},
6790   {&handle_local_tunnel_speed, NULL,
6791    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MAX,
6792    sizeof (struct GNUNET_MESH_TunnelMessage)},
6793   {&handle_local_tunnel_buffer, NULL,
6794    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER,
6795    sizeof (struct GNUNET_MESH_TunnelMessage)},
6796   {&handle_local_tunnel_buffer, NULL,
6797    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER,
6798    sizeof (struct GNUNET_MESH_TunnelMessage)},
6799   {&handle_local_connect_add, NULL,
6800    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD,
6801    sizeof (struct GNUNET_MESH_PeerControl)},
6802   {&handle_local_connect_del, NULL,
6803    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL,
6804    sizeof (struct GNUNET_MESH_PeerControl)},
6805   {&handle_local_blacklist, NULL,
6806    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_BLACKLIST,
6807    sizeof (struct GNUNET_MESH_PeerControl)},
6808   {&handle_local_unblacklist, NULL,
6809    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_UNBLACKLIST,
6810    sizeof (struct GNUNET_MESH_PeerControl)},
6811   {&handle_local_connect_by_type, NULL,
6812    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE,
6813    sizeof (struct GNUNET_MESH_ConnectPeerByType)},
6814   {&handle_local_connect_by_string, NULL,
6815    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_STRING, 0},
6816   {&handle_local_unicast, NULL,
6817    GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
6818   {&handle_local_to_origin, NULL,
6819    GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
6820   {&handle_local_multicast, NULL,
6821    GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
6822   {&handle_local_ack, NULL,
6823    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK,
6824    sizeof (struct GNUNET_MESH_LocalAck)},
6825   {NULL, NULL, 0, 0}
6826 };
6827
6828
6829 /**
6830  * To be called on core init/fail.
6831  *
6832  * @param cls service closure
6833  * @param server handle to the server for this service
6834  * @param identity the public identity of this peer
6835  */
6836 static void
6837 core_init (void *cls, struct GNUNET_CORE_Handle *server,
6838            const struct GNUNET_PeerIdentity *identity)
6839 {
6840   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
6841   core_handle = server;
6842   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)) ||
6843       NULL == server)
6844   {
6845     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
6846     GNUNET_SCHEDULER_shutdown ();
6847   }
6848   return;
6849 }
6850
6851
6852 /**
6853  * Method called whenever a given peer connects.
6854  *
6855  * @param cls closure
6856  * @param peer peer identity this notification is about
6857  * @param atsi performance data for the connection
6858  * @param atsi_count number of records in 'atsi'
6859  */
6860 static void
6861 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
6862               const struct GNUNET_ATS_Information *atsi,
6863               unsigned int atsi_count)
6864 {
6865   struct MeshPeerInfo *peer_info;
6866   struct MeshPeerPath *path;
6867
6868   DEBUG_CONN ("Peer connected\n");
6869   DEBUG_CONN ("     %s\n", GNUNET_i2s (&my_full_id));
6870   peer_info = peer_info_get (peer);
6871   if (myid == peer_info->id)
6872   {
6873     DEBUG_CONN ("     (self)\n");
6874     return;
6875   }
6876   else
6877   {
6878     DEBUG_CONN ("     %s\n", GNUNET_i2s (peer));
6879   }
6880   path = path_new (2);
6881   path->peers[0] = myid;
6882   path->peers[1] = peer_info->id;
6883   GNUNET_PEER_change_rc (myid, 1);
6884   GNUNET_PEER_change_rc (peer_info->id, 1);
6885   peer_info_add_path (peer_info, path, GNUNET_YES);
6886   GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
6887   return;
6888 }
6889
6890
6891 /**
6892  * Method called whenever a peer disconnects.
6893  *
6894  * @param cls closure
6895  * @param peer peer identity this notification is about
6896  */
6897 static void
6898 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
6899 {
6900   struct MeshPeerInfo *pi;
6901   struct MeshPeerQueue *q;
6902   struct MeshPeerQueue *n;
6903
6904   DEBUG_CONN ("Peer disconnected\n");
6905   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
6906   if (NULL == pi)
6907   {
6908     GNUNET_break (0);
6909     return;
6910   }
6911   q = pi->queue_head;
6912   while (NULL != q)
6913   {
6914       n = q->next;
6915       if (q->peer == pi)
6916       {
6917         /* try to reroute this traffic instead */
6918         queue_destroy(q, GNUNET_YES);
6919       }
6920       q = n;
6921   }
6922   peer_info_remove_path (pi, pi->id, myid);
6923   if (myid == pi->id)
6924   {
6925     DEBUG_CONN ("     (self)\n");
6926   }
6927   GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
6928   return;
6929 }
6930
6931
6932 /******************************************************************************/
6933 /************************      MAIN FUNCTIONS      ****************************/
6934 /******************************************************************************/
6935
6936 /**
6937  * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
6938  *
6939  * @param cls closure
6940  * @param key current key code
6941  * @param value value in the hash map
6942  * @return GNUNET_YES if we should continue to iterate,
6943  *         GNUNET_NO if not.
6944  */
6945 static int
6946 shutdown_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
6947 {
6948   struct MeshTunnel *t = value;
6949
6950   tunnel_destroy (t);
6951   return GNUNET_YES;
6952 }
6953
6954 /**
6955  * Iterator over peer hash map entries to destroy the tunnel during shutdown.
6956  *
6957  * @param cls closure
6958  * @param key current key code
6959  * @param value value in the hash map
6960  * @return GNUNET_YES if we should continue to iterate,
6961  *         GNUNET_NO if not.
6962  */
6963 static int
6964 shutdown_peer (void *cls, const struct GNUNET_HashCode * key, void *value)
6965 {
6966   struct MeshPeerInfo *p = value;
6967   struct MeshPeerQueue *q;
6968   struct MeshPeerQueue *n;
6969
6970   q = p->queue_head;
6971   while (NULL != q)
6972   {
6973       n = q->next;
6974       if (q->peer == p)
6975       {
6976         queue_destroy(q, GNUNET_YES);
6977       }
6978       q = n;
6979   }
6980   peer_info_destroy (p);
6981   return GNUNET_YES;
6982 }
6983
6984 /**
6985  * Task run during shutdown.
6986  *
6987  * @param cls unused
6988  * @param tc unused
6989  */
6990 static void
6991 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
6992 {
6993   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
6994
6995   if (core_handle != NULL)
6996   {
6997     GNUNET_CORE_disconnect (core_handle);
6998     core_handle = NULL;
6999   }
7000   GNUNET_CONTAINER_multihashmap_iterate (tunnels, &shutdown_tunnel, NULL);
7001   GNUNET_CONTAINER_multihashmap_iterate (peers, &shutdown_peer, NULL);
7002   if (dht_handle != NULL)
7003   {
7004     GNUNET_DHT_disconnect (dht_handle);
7005     dht_handle = NULL;
7006   }
7007   if (nc != NULL)
7008   {
7009     GNUNET_SERVER_notification_context_destroy (nc);
7010     nc = NULL;
7011   }
7012   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
7013   {
7014     GNUNET_SCHEDULER_cancel (announce_id_task);
7015     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
7016   }
7017   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
7018 }
7019
7020 /**
7021  * Process mesh requests.
7022  *
7023  * @param cls closure
7024  * @param server the initialized server
7025  * @param c configuration to use
7026  */
7027 static void
7028 run (void *cls, struct GNUNET_SERVER_Handle *server,
7029      const struct GNUNET_CONFIGURATION_Handle *c)
7030 {
7031   struct MeshPeerInfo *peer;
7032   struct MeshPeerPath *p;
7033   char *keyfile;
7034
7035   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
7036   server_handle = server;
7037   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
7038                                      NULL,      /* Closure passed to MESH functions */
7039                                      &core_init,        /* Call core_init once connected */
7040                                      &core_connect,     /* Handle connects */
7041                                      &core_disconnect,  /* remove peers on disconnects */
7042                                      NULL,      /* Don't notify about all incoming messages */
7043                                      GNUNET_NO, /* For header only in notification */
7044                                      NULL,      /* Don't notify about all outbound messages */
7045                                      GNUNET_NO, /* For header-only out notification */
7046                                      core_handlers);    /* Register these handlers */
7047
7048   if (core_handle == NULL)
7049   {
7050     GNUNET_break (0);
7051     GNUNET_SCHEDULER_shutdown ();
7052     return;
7053   }
7054
7055   if (GNUNET_OK !=
7056       GNUNET_CONFIGURATION_get_value_filename (c, "GNUNETD", "HOSTKEY",
7057                                                &keyfile))
7058   {
7059     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7060                 _
7061                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7062                 "hostkey");
7063     GNUNET_SCHEDULER_shutdown ();
7064     return;
7065   }
7066
7067   if (GNUNET_OK !=
7068       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_PATH_TIME",
7069                                            &refresh_path_time))
7070   {
7071     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7072                 _
7073                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7074                 "refresh path time");
7075     GNUNET_SCHEDULER_shutdown ();
7076     return;
7077   }
7078
7079   if (GNUNET_OK !=
7080       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "APP_ANNOUNCE_TIME",
7081                                            &app_announce_time))
7082   {
7083     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7084                 _
7085                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7086                 "app announce time");
7087     GNUNET_SCHEDULER_shutdown ();
7088     return;
7089   }
7090
7091   if (GNUNET_OK !=
7092       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "ID_ANNOUNCE_TIME",
7093                                            &id_announce_time))
7094   {
7095     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7096                 _
7097                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7098                 "id announce time");
7099     GNUNET_SCHEDULER_shutdown ();
7100     return;
7101   }
7102
7103   if (GNUNET_OK !=
7104       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "UNACKNOWLEDGED_WAIT",
7105                                            &unacknowledged_wait_time))
7106   {
7107     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7108                 _
7109                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7110                 "unacknowledged wait time");
7111     GNUNET_SCHEDULER_shutdown ();
7112     return;
7113   }
7114
7115   if (GNUNET_OK !=
7116       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "CONNECT_TIMEOUT",
7117                                            &connect_timeout))
7118   {
7119     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7120                 _
7121                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7122                 "connect timeout");
7123     GNUNET_SCHEDULER_shutdown ();
7124     return;
7125   }
7126
7127   if (GNUNET_OK !=
7128       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
7129                                              &max_msgs_queue))
7130   {
7131     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7132                 _
7133                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7134                 "max msgs queue");
7135     GNUNET_SCHEDULER_shutdown ();
7136     return;
7137   }
7138
7139   if (GNUNET_OK !=
7140       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_TUNNELS",
7141                                              &max_tunnels))
7142   {
7143     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7144                 _
7145                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7146                 "max tunnels");
7147     GNUNET_SCHEDULER_shutdown ();
7148     return;
7149   }
7150
7151   if (GNUNET_OK !=
7152       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
7153                                              &default_ttl))
7154   {
7155     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7156                 _
7157                 ("Mesh service is lacking key configuration settings (%s). Using default (%u).\n"),
7158                 "default ttl", 64);
7159     default_ttl = 64;
7160   }
7161
7162   if (GNUNET_OK !=
7163       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DHT_REPLICATION_LEVEL",
7164                                              &dht_replication_level))
7165   {
7166     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7167                 _
7168                 ("Mesh service is lacking key configuration settings (%s). Using default (%u).\n"),
7169                 "dht replication level", 10);
7170     dht_replication_level = 10;
7171   }
7172
7173   
7174   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
7175   GNUNET_free (keyfile);
7176   if (my_private_key == NULL)
7177   {
7178     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7179                 _("Mesh service could not access hostkey.  Exiting.\n"));
7180     GNUNET_SCHEDULER_shutdown ();
7181     return;
7182   }
7183   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
7184   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
7185                       &my_full_id.hashPubKey);
7186   myid = GNUNET_PEER_intern (&my_full_id);
7187
7188 //   transport_handle = GNUNET_TRANSPORT_connect(c,
7189 //                                               &my_full_id,
7190 //                                               NULL,
7191 //                                               NULL,
7192 //                                               NULL,
7193 //                                               NULL);
7194
7195   dht_handle = GNUNET_DHT_connect (c, 64);
7196   if (dht_handle == NULL)
7197   {
7198     GNUNET_break (0);
7199   }
7200
7201   stats = GNUNET_STATISTICS_create ("mesh", c);
7202
7203
7204   next_tid = 0;
7205   next_local_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
7206
7207   tunnels = GNUNET_CONTAINER_multihashmap_create (32);
7208   incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
7209   peers = GNUNET_CONTAINER_multihashmap_create (32);
7210   applications = GNUNET_CONTAINER_multihashmap_create (32);
7211   types = GNUNET_CONTAINER_multihashmap_create (32);
7212
7213   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
7214   nc = GNUNET_SERVER_notification_context_create (server_handle, 1);
7215   GNUNET_SERVER_disconnect_notify (server_handle,
7216                                    &handle_local_client_disconnect, NULL);
7217
7218
7219   clients = NULL;
7220   clients_tail = NULL;
7221   next_client_id = 0;
7222
7223   announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
7224   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
7225
7226   /* Create a peer_info for the local peer */
7227   peer = peer_info_get (&my_full_id);
7228   p = path_new (1);
7229   p->peers[0] = myid;
7230   GNUNET_PEER_change_rc (myid, 1);
7231   peer_info_add_path (peer, p, GNUNET_YES);
7232
7233   /* Scheduled the task to clean up when shutdown is called */
7234   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
7235                                 NULL);
7236
7237   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "end of run()\n");
7238 }
7239
7240 /**
7241  * The main function for the mesh service.
7242  *
7243  * @param argc number of arguments from the command line
7244  * @param argv command line arguments
7245  * @return 0 ok, 1 on error
7246  */
7247 int
7248 main (int argc, char *const *argv)
7249 {
7250   int ret;
7251
7252   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
7253   ret =
7254       (GNUNET_OK ==
7255        GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
7256                            NULL)) ? 0 : 1;
7257   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");
7258
7259   return ret;
7260 }