6c87e5448a14340bea00035baea00706d3c92220
[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  * 
3532  * @param t Tunnel on which to send the ACK.
3533  * @param type Type of message that triggered the ACK transmission.
3534  */
3535 static void
3536 tunnel_send_ack (struct MeshTunnel *t, uint16_t type)
3537 {
3538   struct GNUNET_MESH_ACK msg;
3539   struct GNUNET_PeerIdentity id;
3540   uint32_t ack;
3541
3542   if (NULL != t->owner)
3543   {
3544     send_client_tunnel_ack (t->owner, t);
3545     return;
3546   }
3547   /* Is it after unicast / multicast retransmission? */
3548   if (GNUNET_MESSAGE_TYPE_MESH_ACK != type)
3549   {
3550     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "ACK via DATA retransmission\n");
3551     if (GNUNET_YES == t->nobuffer)
3552     {
3553       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, nobuffer\n");
3554       return;
3555     }
3556     if (t->queue_max > t->queue_n * 2)
3557     {
3558       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, buffer free\n");
3559       return;
3560     }
3561   }
3562
3563   /* Ok, ACK might be necessary, what PID to ACK? */
3564   ack = tunnel_get_fwd_ack (t);
3565
3566   /* If speed_min and not all children have ack'd, dont send yet */
3567   if (ack == t->last_ack)
3568   {
3569     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, not ready\n");
3570     return;
3571   }
3572
3573   t->last_ack = ack;
3574   msg.pid = htonl (ack);
3575
3576   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
3577
3578   msg.header.size = htons (sizeof (msg));
3579   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_ACK);
3580   msg.tid = htonl (t->id.tid);
3581   GNUNET_PEER_resolve(t->id.oid, &msg.oid);
3582   send_message (&msg.header, &id, t);
3583 }
3584
3585
3586 /**
3587  * Send a message to all peers in this tunnel that the tunnel is no longer
3588  * valid.
3589  *
3590  * @param t The tunnel whose peers to notify.
3591  */
3592 static void
3593 tunnel_send_destroy (struct MeshTunnel *t)
3594 {
3595   struct GNUNET_MESH_TunnelDestroy msg;
3596
3597   msg.header.size = htons (sizeof (msg));
3598   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY);
3599   GNUNET_PEER_resolve (t->id.oid, &msg.oid);
3600   msg.tid = htonl (t->id.tid);
3601   tunnel_send_multicast (t, &msg.header, GNUNET_NO);
3602 }
3603
3604
3605 /**
3606  * Cancel all transmissions towards a neighbor that belong to a certain tunnel.
3607  *
3608  * @param cls Closure (Tunnel which to cancel).
3609  * @param neighbor_id Short ID of the neighbor to whom cancel the transmissions.
3610  */
3611 static void
3612 tunnel_cancel_queues (void *cls, GNUNET_PEER_Id neighbor_id)
3613 {
3614   struct MeshTunnel *t = cls;
3615   struct MeshPeerInfo *peer_info;
3616   struct MeshPeerQueue *pq;
3617   struct MeshPeerQueue *next;
3618
3619   peer_info = peer_info_get_short (neighbor_id);
3620   for (pq = peer_info->queue_head; NULL != pq; pq = next)
3621   {
3622     next = pq->next;
3623     if (pq->tunnel == t)
3624     {
3625       queue_destroy (pq, GNUNET_YES);
3626     }
3627   }
3628   if (NULL == peer_info->queue_head && NULL != peer_info->core_transmit)
3629   {
3630     GNUNET_CORE_notify_transmit_ready_cancel(peer_info->core_transmit);
3631     peer_info->core_transmit = NULL;
3632   }
3633 }
3634
3635 /**
3636  * Destroy the tunnel and free any allocated resources linked to it.
3637  *
3638  * @param t the tunnel to destroy
3639  *
3640  * @return GNUNET_OK on success
3641  */
3642 static int
3643 tunnel_destroy (struct MeshTunnel *t)
3644 {
3645   struct MeshClient *c;
3646   struct GNUNET_HashCode hash;
3647   unsigned int i;
3648   int r;
3649
3650   if (NULL == t)
3651     return GNUNET_OK;
3652
3653   tree_iterate_children (t->tree, &tunnel_cancel_queues, t);
3654
3655   r = GNUNET_OK;
3656   c = t->owner;
3657 #if MESH_DEBUG
3658   {
3659     struct GNUNET_PeerIdentity id;
3660
3661     GNUNET_PEER_resolve (t->id.oid, &id);
3662     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s [%x]\n",
3663                 GNUNET_i2s (&id), t->id.tid);
3664     if (NULL != c)
3665       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
3666   }
3667 #endif
3668
3669   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
3670   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &hash, t))
3671   {
3672     r = GNUNET_SYSERR;
3673   }
3674
3675   GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
3676   if (NULL != c &&
3677       GNUNET_YES !=
3678       GNUNET_CONTAINER_multihashmap_remove (c->own_tunnels, &hash, t))
3679   {
3680     r = GNUNET_SYSERR;
3681   }
3682   GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
3683   for (i = 0; i < t->nclients; i++)
3684   {
3685     c = t->clients[i];
3686     if (GNUNET_YES !=
3687           GNUNET_CONTAINER_multihashmap_remove (c->incoming_tunnels, &hash, t))
3688     {
3689       r = GNUNET_SYSERR;
3690     }
3691   }
3692   for (i = 0; i < t->nignore; i++)
3693   {
3694     c = t->ignore[i];
3695     if (GNUNET_YES !=
3696           GNUNET_CONTAINER_multihashmap_remove (c->ignore_tunnels, &hash, t))
3697     {
3698       r = GNUNET_SYSERR;
3699     }
3700   }
3701   if (t->nclients > 0)
3702   {
3703     if (GNUNET_YES !=
3704         GNUNET_CONTAINER_multihashmap_remove (incoming_tunnels, &hash, t))
3705     {
3706       r = GNUNET_SYSERR;
3707     }
3708     GNUNET_free (t->clients);
3709   }
3710   if (NULL != t->peers)
3711   {
3712     GNUNET_CONTAINER_multihashmap_iterate (t->peers, &peer_info_delete_tunnel,
3713                                            t);
3714     GNUNET_CONTAINER_multihashmap_destroy (t->peers);
3715   }
3716
3717   GNUNET_CONTAINER_multihashmap_iterate (t->children_fc,
3718                                          &tunnel_destroy_child,
3719                                          t);
3720   GNUNET_CONTAINER_multihashmap_destroy (t->children_fc);
3721
3722   tree_destroy (t->tree);
3723
3724   if (NULL != t->regex_ctx)
3725     regex_cancel_search (t->regex_ctx);
3726   if (NULL != t->dht_get_type)
3727     GNUNET_DHT_get_stop (t->dht_get_type);
3728   if (GNUNET_SCHEDULER_NO_TASK != t->timeout_task)
3729     GNUNET_SCHEDULER_cancel (t->timeout_task);
3730   if (GNUNET_SCHEDULER_NO_TASK != t->path_refresh_task)
3731     GNUNET_SCHEDULER_cancel (t->path_refresh_task);
3732
3733   n_tunnels--;
3734   GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
3735   GNUNET_assert (0 <= n_tunnels);
3736   GNUNET_free (t);
3737   return r;
3738 }
3739
3740
3741 /**
3742  * Create a new tunnel
3743  * 
3744  * @param owner Who is the owner of the tunnel (short ID).
3745  * @param tid Tunnel Number of the tunnel.
3746  * @param client Clients that owns the tunnel, NULL for foreign tunnels.
3747  * @param local Tunnel Number for the tunnel, for the client point of view.
3748  * 
3749  * @return A new initialized tunnel. NULL on error.
3750  */
3751 static struct MeshTunnel *
3752 tunnel_new (GNUNET_PEER_Id owner,
3753             MESH_TunnelNumber tid,
3754             struct MeshClient *client,
3755             MESH_TunnelNumber local)
3756 {
3757   struct MeshTunnel *t;
3758   struct GNUNET_HashCode hash;
3759   
3760   if (n_tunnels >= max_tunnels && NULL == client)
3761     return NULL;
3762
3763   t = GNUNET_malloc (sizeof (struct MeshTunnel));
3764   t->id.oid = owner;
3765   t->id.tid = tid;
3766   t->queue_max = (max_msgs_queue / max_tunnels) + 1;
3767   t->tree = tree_new (owner);
3768   t->owner = client;
3769   t->local_tid = local;
3770   t->children_fc = GNUNET_CONTAINER_multihashmap_create (8);
3771   n_tunnels++;
3772   GNUNET_STATISTICS_update (stats, "# tunnels", 1, GNUNET_NO);
3773
3774   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
3775   if (GNUNET_OK !=
3776       GNUNET_CONTAINER_multihashmap_put (tunnels, &hash, t,
3777                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
3778   {
3779     GNUNET_break (0);
3780     tunnel_destroy (t);
3781     if (NULL != client)
3782     {
3783       GNUNET_break (0);
3784       GNUNET_SERVER_receive_done (client->handle, GNUNET_SYSERR);
3785     }
3786     return NULL;
3787   }
3788
3789   if (NULL != client)
3790   {
3791     GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
3792     if (GNUNET_OK !=
3793         GNUNET_CONTAINER_multihashmap_put (client->own_tunnels, &hash, t,
3794                                           GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
3795     {
3796       tunnel_destroy (t);
3797       GNUNET_break (0);
3798       GNUNET_SERVER_receive_done (client->handle, GNUNET_SYSERR);
3799       return NULL;
3800     }
3801   }
3802
3803   return t;
3804 }
3805
3806
3807 /**
3808  * Removes an explicit path from a tunnel, freeing all intermediate nodes
3809  * that are no longer needed, as well as nodes of no longer reachable peers.
3810  * The tunnel itself is also destoyed if results in a remote empty tunnel.
3811  *
3812  * @param t Tunnel from which to remove the path.
3813  * @param peer Short id of the peer which should be removed.
3814  */
3815 static void
3816 tunnel_delete_peer (struct MeshTunnel *t, GNUNET_PEER_Id peer)
3817 {
3818   if (GNUNET_NO == tree_del_peer (t->tree, peer, NULL, NULL))
3819     tunnel_destroy (t);
3820 }
3821
3822
3823 /**
3824  * tunnel_destroy_iterator: iterator for deleting each tunnel that belongs to a
3825  * client when the client disconnects. If the client is not the owner, the
3826  * owner will get notified if no more clients are in the tunnel and the client
3827  * get removed from the tunnel's list.
3828  *
3829  * @param cls closure (client that is disconnecting)
3830  * @param key the hash of the local tunnel id (used to access the hashmap)
3831  * @param value the value stored at the key (tunnel to destroy)
3832  *
3833  * @return GNUNET_OK on success
3834  */
3835 static int
3836 tunnel_destroy_iterator (void *cls, const struct GNUNET_HashCode * key, void *value)
3837 {
3838   struct MeshTunnel *t = value;
3839   struct MeshClient *c = cls;
3840   int r;
3841
3842   send_client_tunnel_disconnect(t, c);
3843   if (c != t->owner)
3844   {
3845     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3846                 "Client %u is destination, keeping the tunnel alive.\n", c->id);
3847     tunnel_delete_client(t, c);
3848     client_delete_tunnel(c, t);
3849     return GNUNET_OK;
3850   }
3851   tunnel_send_destroy(t);
3852   r = tunnel_destroy (t);
3853   return r;
3854 }
3855
3856
3857 /**
3858  * Timeout function, destroys tunnel if called
3859  *
3860  * @param cls Closure (tunnel to destroy).
3861  * @param tc TaskContext
3862  */
3863 static void
3864 tunnel_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3865 {
3866   struct MeshTunnel *t = cls;
3867
3868   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3869     return;
3870   t->timeout_task = GNUNET_SCHEDULER_NO_TASK;
3871   tunnel_destroy (t);
3872 }
3873
3874 /**
3875  * Resets the tunnel timeout. Starts it if no timeout was running.
3876  *
3877  * @param t Tunnel whose timeout to reset.
3878  */
3879 static void
3880 tunnel_reset_timeout (struct MeshTunnel *t)
3881 {
3882   if (GNUNET_SCHEDULER_NO_TASK != t->timeout_task)
3883     GNUNET_SCHEDULER_cancel (t->timeout_task);
3884   t->timeout_task =
3885       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
3886                                     (refresh_path_time, 4), &tunnel_timeout, t);
3887 }
3888
3889
3890 /******************************************************************************/
3891 /****************      MESH NETWORK HANDLER HELPERS     ***********************/
3892 /******************************************************************************/
3893
3894 /**
3895  * Function to send a create path packet to a peer.
3896  *
3897  * @param cls closure
3898  * @param size number of bytes available in buf
3899  * @param buf where the callee should write the message
3900  * @return number of bytes written to buf
3901  */
3902 static size_t
3903 send_core_path_create (void *cls, size_t size, void *buf)
3904 {
3905   struct MeshPathInfo *info = cls;
3906   struct GNUNET_MESH_ManipulatePath *msg;
3907   struct GNUNET_PeerIdentity *peer_ptr;
3908   struct MeshTunnel *t = info->t;
3909   struct MeshPeerPath *p = info->path;
3910   size_t size_needed;
3911   uint32_t opt;
3912   int i;
3913
3914   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATE PATH sending...\n");
3915   size_needed =
3916       sizeof (struct GNUNET_MESH_ManipulatePath) +
3917       p->length * sizeof (struct GNUNET_PeerIdentity);
3918
3919   if (size < size_needed || NULL == buf)
3920   {
3921     GNUNET_break (0);
3922     return 0;
3923   }
3924   msg = (struct GNUNET_MESH_ManipulatePath *) buf;
3925   msg->header.size = htons (size_needed);
3926   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE);
3927   msg->tid = ntohl (t->id.tid);
3928
3929   if (GNUNET_YES == t->speed_min)
3930     opt = MESH_TUNNEL_OPT_SPEED_MIN;
3931   if (GNUNET_YES == t->nobuffer)
3932     opt |= MESH_TUNNEL_OPT_NOBUFFER;
3933   msg->opt = htonl(opt);
3934
3935   peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
3936   for (i = 0; i < p->length; i++)
3937   {
3938     GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
3939   }
3940
3941   path_destroy (p);
3942   GNUNET_free (info);
3943
3944   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3945               "CREATE PATH (%u bytes long) sent!\n", size_needed);
3946   return size_needed;
3947 }
3948
3949
3950 /**
3951  * Fill the core buffer 
3952  *
3953  * @param cls closure (data itself)
3954  * @param size number of bytes available in buf
3955  * @param buf where the callee should write the message
3956  *
3957  * @return number of bytes written to buf
3958  */
3959 static size_t
3960 send_core_data_multicast (void *cls, size_t size, void *buf)
3961 {
3962   struct MeshTransmissionDescriptor *info = cls;
3963   size_t total_size;
3964
3965   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Multicast callback.\n");
3966   GNUNET_assert (NULL != info);
3967   GNUNET_assert (NULL != info->peer);
3968   total_size = info->mesh_data->data_len;
3969   GNUNET_assert (total_size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
3970
3971   if (total_size > size)
3972   {
3973     GNUNET_break (0);
3974     return 0;
3975   }
3976   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " copying data...\n");
3977   memcpy (buf, info->mesh_data->data, total_size);
3978 #if MESH_DEBUG
3979   {
3980     struct GNUNET_MESH_Multicast *mc;
3981     struct GNUNET_MessageHeader *mh;
3982
3983     mh = buf;
3984     if (ntohs (mh->type) == GNUNET_MESSAGE_TYPE_MESH_MULTICAST)
3985     {
3986       mc = (struct GNUNET_MESH_Multicast *) mh;
3987       mh = (struct GNUNET_MessageHeader *) &mc[1];
3988       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3989                   " multicast, payload type %u\n", ntohs (mh->type));
3990       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3991                   " multicast, payload size %u\n", ntohs (mh->size));
3992     }
3993     else
3994     {
3995       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " type %u\n",
3996                   ntohs (mh->type));
3997     }
3998   }
3999 #endif
4000   data_descriptor_decrement_rc (info->mesh_data);
4001   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "freeing info...\n");
4002   GNUNET_free (info);
4003   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "return %u\n", total_size);
4004   return total_size;
4005 }
4006
4007
4008 /**
4009  * Creates a path ack message in buf and frees all unused resources.
4010  *
4011  * @param cls closure (MeshTransmissionDescriptor)
4012  * @param size number of bytes available in buf
4013  * @param buf where the callee should write the message
4014  * @return number of bytes written to buf
4015  */
4016 static size_t
4017 send_core_path_ack (void *cls, size_t size, void *buf)
4018 {
4019   struct MeshTransmissionDescriptor *info = cls;
4020   struct GNUNET_MESH_PathACK *msg = buf;
4021
4022   GNUNET_assert (NULL != info);
4023   if (sizeof (struct GNUNET_MESH_PathACK) > size)
4024   {
4025     GNUNET_break (0);
4026     return 0;
4027   }
4028   msg->header.size = htons (sizeof (struct GNUNET_MESH_PathACK));
4029   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_ACK);
4030   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
4031   msg->tid = htonl (info->origin->tid);
4032   msg->peer_id = my_full_id;
4033
4034   GNUNET_free (info);
4035   /* TODO add signature */
4036
4037   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "PATH ACK sent!\n");
4038   return sizeof (struct GNUNET_MESH_PathACK);
4039 }
4040
4041
4042 /**
4043  * Free a transmission that was already queued with all resources
4044  * associated to the request.
4045  *
4046  * @param queue Queue handler to cancel.
4047  * @param clear_cls Is it necessary to free associated cls?
4048  */
4049 static void
4050 queue_destroy (struct MeshPeerQueue *queue, int clear_cls)
4051 {
4052   struct MeshTransmissionDescriptor *dd;
4053   struct MeshPathInfo *path_info;
4054
4055   if (GNUNET_YES == clear_cls)
4056   {
4057     switch (queue->type)
4058     {
4059     case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4060     case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
4061     case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4062         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   type payload\n");
4063         dd = queue->cls;
4064         data_descriptor_decrement_rc (dd->mesh_data);
4065         break;
4066     case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
4067         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   type create path\n");
4068         path_info = queue->cls;
4069         path_destroy (path_info->path);
4070         break;
4071     default:
4072         GNUNET_break (0);
4073         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   type unknown!\n");
4074     }
4075     GNUNET_free_non_null (queue->cls);
4076   }
4077   GNUNET_CONTAINER_DLL_remove (queue->peer->queue_head,
4078                                queue->peer->queue_tail,
4079                                queue);
4080   GNUNET_free (queue);
4081 }
4082
4083
4084 /**
4085   * Core callback to write a queued packet to core buffer
4086   *
4087   * @param cls Closure (peer info).
4088   * @param size Number of bytes available in buf.
4089   * @param buf Where the to write the message.
4090   *
4091   * @return number of bytes written to buf
4092   */
4093 static size_t
4094 queue_send (void *cls, size_t size, void *buf)
4095 {
4096     struct MeshPeerInfo *peer = cls;
4097     struct GNUNET_MessageHeader *msg;
4098     struct MeshPeerQueue *queue;
4099     struct MeshTunnel *t;
4100     size_t data_size;
4101
4102     peer->core_transmit = NULL;
4103     queue = peer->queue_head;
4104
4105     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "********* Queue send\n");
4106
4107     /* If queue is empty, send should have been cancelled */
4108     if (NULL == queue)
4109     {
4110         GNUNET_break(0);
4111         return 0;
4112     }
4113     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   not empty\n");
4114
4115     /* Check if buffer size is enough for the message */
4116     if (queue->size > size)
4117     {
4118         struct GNUNET_PeerIdentity id;
4119
4120         GNUNET_PEER_resolve (peer->id, &id);
4121         peer->core_transmit =
4122             GNUNET_CORE_notify_transmit_ready(core_handle,
4123                                               0,
4124                                               0,
4125                                               GNUNET_TIME_UNIT_FOREVER_REL,
4126                                               &id,
4127                                               queue->size,
4128                                               &queue_send,
4129                                               peer);
4130         return 0;
4131     }
4132     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   size ok\n");
4133
4134     t = queue->tunnel;
4135     t->queue_n--;
4136
4137     /* Fill buf */
4138     switch (queue->type)
4139     {
4140         case 0:
4141             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   raw\n");
4142             data_size = send_core_data_raw (queue->cls, size, buf);
4143             msg = (struct GNUNET_MessageHeader *) buf;
4144             if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_MESH_UNICAST)
4145               tunnel_send_ack (t, GNUNET_MESSAGE_TYPE_MESH_UNICAST);
4146             break;
4147         case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
4148             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   multicast\n");
4149             data_size = send_core_data_multicast(queue->cls, size, buf);
4150             tunnel_send_ack (t, GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
4151             break;
4152         case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
4153             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path create\n");
4154             data_size = send_core_path_create(queue->cls, size, buf);
4155             break;
4156         case GNUNET_MESSAGE_TYPE_MESH_PATH_ACK:
4157             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path ack\n");
4158             data_size = send_core_path_ack(queue->cls, size, buf);
4159             break;
4160         default:
4161             GNUNET_break (0);
4162             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   type unknown\n");
4163             data_size = 0;
4164     }
4165
4166     /* Free queue, but cls was freed by send_core_* */
4167     queue_destroy (queue, GNUNET_NO);
4168
4169     if (GNUNET_YES == t->destroy && 0 == t->queue_n)
4170     {
4171       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********  destroying tunnel!\n");
4172       tunnel_destroy (t);
4173     }
4174
4175     /* If more data in queue, send next */
4176     if (NULL != peer->queue_head)
4177     {
4178         struct GNUNET_PeerIdentity id;
4179
4180         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   more data!\n");
4181         GNUNET_PEER_resolve (peer->id, &id);
4182         peer->core_transmit =
4183             GNUNET_CORE_notify_transmit_ready(core_handle,
4184                                               0,
4185                                               0,
4186                                               GNUNET_TIME_UNIT_FOREVER_REL,
4187                                               &id,
4188                                               peer->queue_head->size,
4189                                               &queue_send,
4190                                               peer);
4191     }
4192     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   return %d\n", data_size);
4193     return data_size;
4194 }
4195
4196
4197 /**
4198  * Queue and pass message to core when possible.
4199  *
4200  * @param cls Closure (type dependant).
4201  * @param type Type of the message, 0 for a raw message.
4202  * @param size Size of the message.
4203  * @param dst Neighbor to send message to.
4204  * @param t Tunnel this message belongs to.
4205  */
4206 static void
4207 queue_add (void *cls, uint16_t type, size_t size,
4208            struct MeshPeerInfo *dst, struct MeshTunnel *t)
4209 {
4210     struct MeshPeerQueue *queue;
4211
4212     if (t->queue_n >= t->queue_max)
4213     {
4214       if (NULL == t->owner)
4215         GNUNET_break_op(0);       // TODO: kill connection?
4216       else
4217         GNUNET_break(0);
4218       return;                       // Drop message
4219     }
4220     t->queue_n++;
4221     queue = GNUNET_malloc (sizeof (struct MeshPeerQueue));
4222     queue->cls = cls;
4223     queue->type = type;
4224     queue->size = size;
4225     queue->peer = dst;
4226     queue->tunnel = t;
4227     GNUNET_CONTAINER_DLL_insert_tail (dst->queue_head, dst->queue_tail, queue);
4228     if (NULL == dst->core_transmit)
4229     {
4230         struct GNUNET_PeerIdentity id;
4231
4232         GNUNET_PEER_resolve (dst->id, &id);
4233         dst->core_transmit =
4234             GNUNET_CORE_notify_transmit_ready(core_handle,
4235                                               0,
4236                                               0,
4237                                               GNUNET_TIME_UNIT_FOREVER_REL,
4238                                               &id,
4239                                               size,
4240                                               &queue_send,
4241                                               dst);
4242     }
4243 }
4244
4245
4246 /******************************************************************************/
4247 /********************      MESH NETWORK HANDLERS     **************************/
4248 /******************************************************************************/
4249
4250
4251 /**
4252  * Core handler for path creation
4253  *
4254  * @param cls closure
4255  * @param message message
4256  * @param peer peer identity this notification is about
4257  * @param atsi performance data
4258  * @param atsi_count number of records in 'atsi'
4259  *
4260  * @return GNUNET_OK to keep the connection open,
4261  *         GNUNET_SYSERR to close it (signal serious error)
4262  */
4263 static int
4264 handle_mesh_path_create (void *cls, const struct GNUNET_PeerIdentity *peer,
4265                          const struct GNUNET_MessageHeader *message,
4266                          const struct GNUNET_ATS_Information *atsi,
4267                          unsigned int atsi_count)
4268 {
4269   unsigned int own_pos;
4270   uint16_t size;
4271   uint16_t i;
4272   MESH_TunnelNumber tid;
4273   struct GNUNET_MESH_ManipulatePath *msg;
4274   struct GNUNET_PeerIdentity *pi;
4275   struct GNUNET_HashCode hash;
4276   struct MeshPeerPath *path;
4277   struct MeshPeerInfo *dest_peer_info;
4278   struct MeshPeerInfo *orig_peer_info;
4279   struct MeshTunnel *t;
4280
4281   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4282               "Received a path create msg [%s]\n",
4283               GNUNET_i2s (&my_full_id));
4284   size = ntohs (message->size);
4285   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
4286   {
4287     GNUNET_break_op (0);
4288     return GNUNET_OK;
4289   }
4290
4291   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
4292   if (size % sizeof (struct GNUNET_PeerIdentity))
4293   {
4294     GNUNET_break_op (0);
4295     return GNUNET_OK;
4296   }
4297   size /= sizeof (struct GNUNET_PeerIdentity);
4298   if (size < 2)
4299   {
4300     GNUNET_break_op (0);
4301     return GNUNET_OK;
4302   }
4303   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
4304   msg = (struct GNUNET_MESH_ManipulatePath *) message;
4305
4306   tid = ntohl (msg->tid);
4307   pi = (struct GNUNET_PeerIdentity *) &msg[1];
4308   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4309               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi), tid);
4310   t = tunnel_get (pi, tid);
4311   if (NULL == t) // FIXME only for INCOMING tunnels?
4312   {
4313     uint32_t opt;
4314
4315     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating tunnel\n");
4316     t = tunnel_new (GNUNET_PEER_intern (pi), tid, NULL, 0);
4317     if (NULL == t)
4318     {
4319       // FIXME notify failure
4320       return GNUNET_OK;
4321     }
4322     opt = ntohl (msg->opt);
4323     t->speed_min = (0 != (opt & MESH_TUNNEL_OPT_SPEED_MIN)) ?
4324                    GNUNET_YES : GNUNET_NO;
4325     t->nobuffer = (0 != (opt & MESH_TUNNEL_OPT_NOBUFFER)) ?
4326                   GNUNET_YES : GNUNET_NO;
4327
4328     if (GNUNET_YES == t->nobuffer)
4329       t->queue_max = 1;
4330
4331     while (NULL != tunnel_get_incoming (next_local_tid))
4332       next_local_tid = (next_local_tid + 1) | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
4333     t->local_tid_dest = next_local_tid++;
4334     next_local_tid = next_local_tid | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
4335
4336     tunnel_reset_timeout (t);
4337     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
4338     if (GNUNET_OK !=
4339         GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
4340                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
4341     {
4342       tunnel_destroy (t);
4343       GNUNET_break (0);
4344       return GNUNET_OK;
4345     }
4346   }
4347   dest_peer_info =
4348       GNUNET_CONTAINER_multihashmap_get (peers, &pi[size - 1].hashPubKey);
4349   if (NULL == dest_peer_info)
4350   {
4351     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4352                 "  Creating PeerInfo for destination.\n");
4353     dest_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
4354     dest_peer_info->id = GNUNET_PEER_intern (&pi[size - 1]);
4355     GNUNET_CONTAINER_multihashmap_put (peers, &pi[size - 1].hashPubKey,
4356                                        dest_peer_info,
4357                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
4358   }
4359   orig_peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &pi->hashPubKey);
4360   if (NULL == orig_peer_info)
4361   {
4362     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4363                 "  Creating PeerInfo for origin.\n");
4364     orig_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
4365     orig_peer_info->id = GNUNET_PEER_intern (pi);
4366     GNUNET_CONTAINER_multihashmap_put (peers, &pi->hashPubKey, orig_peer_info,
4367                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
4368   }
4369   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
4370   path = path_new (size);
4371   own_pos = 0;
4372   for (i = 0; i < size; i++)
4373   {
4374     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
4375                 GNUNET_i2s (&pi[i]));
4376     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
4377     if (path->peers[i] == myid)
4378       own_pos = i;
4379   }
4380   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
4381   if (own_pos == 0)
4382   {
4383     /* cannot be self, must be 'not found' */
4384     /* create path: self not found in path through self */
4385     GNUNET_break_op (0);
4386     path_destroy (path);
4387     /* FIXME error. destroy tunnel? leave for timeout? */
4388     return 0;
4389   }
4390   path_add_to_peers (path, GNUNET_NO);
4391   tunnel_add_path (t, path, own_pos);
4392   if (own_pos == size - 1)
4393   {
4394     /* It is for us! Send ack. */
4395     struct MeshTransmissionDescriptor *info;
4396
4397     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
4398     peer_info_add_path_to_origin (orig_peer_info, path, GNUNET_NO);
4399     if (NULL == t->peers)
4400     {
4401       /* New tunnel! Notify clients on data. */
4402       t->peers = GNUNET_CONTAINER_multihashmap_create (4);
4403     }
4404     GNUNET_break (GNUNET_SYSERR !=
4405                   GNUNET_CONTAINER_multihashmap_put (t->peers,
4406                                                      &my_full_id.hashPubKey,
4407                                                      peer_info_get
4408                                                      (&my_full_id),
4409                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE));
4410     info = GNUNET_malloc (sizeof (struct MeshTransmissionDescriptor));
4411     info->origin = &t->id;
4412     info->peer = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
4413     GNUNET_assert (NULL != info->peer);
4414     queue_add(info,
4415               GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
4416               sizeof (struct GNUNET_MESH_PathACK),
4417               info->peer,
4418               t);
4419   }
4420   else
4421   {
4422     struct MeshPeerPath *path2;
4423
4424     /* It's for somebody else! Retransmit. */
4425     path2 = path_duplicate (path);
4426     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Retransmitting.\n");
4427     peer_info_add_path (dest_peer_info, path2, GNUNET_NO);
4428     path2 = path_duplicate (path);
4429     peer_info_add_path_to_origin (orig_peer_info, path2, GNUNET_NO);
4430     send_create_path (dest_peer_info, path, t);
4431   }
4432   return GNUNET_OK;
4433 }
4434
4435
4436 /**
4437  * Core handler for path destruction
4438  *
4439  * @param cls closure
4440  * @param message message
4441  * @param peer peer identity this notification is about
4442  * @param atsi performance data
4443  * @param atsi_count number of records in 'atsi'
4444  *
4445  * @return GNUNET_OK to keep the connection open,
4446  *         GNUNET_SYSERR to close it (signal serious error)
4447  */
4448 static int
4449 handle_mesh_path_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
4450                           const struct GNUNET_MessageHeader *message,
4451                           const struct GNUNET_ATS_Information *atsi,
4452                           unsigned int atsi_count)
4453 {
4454   struct GNUNET_MESH_ManipulatePath *msg;
4455   struct GNUNET_PeerIdentity *pi;
4456   struct MeshPeerPath *path;
4457   struct MeshTunnel *t;
4458   unsigned int own_pos;
4459   unsigned int i;
4460   size_t size;
4461
4462   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4463               "Received a PATH DESTROY msg from %s\n", GNUNET_i2s (peer));
4464   size = ntohs (message->size);
4465   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
4466   {
4467     GNUNET_break_op (0);
4468     return GNUNET_OK;
4469   }
4470
4471   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
4472   if (size % sizeof (struct GNUNET_PeerIdentity))
4473   {
4474     GNUNET_break_op (0);
4475     return GNUNET_OK;
4476   }
4477   size /= sizeof (struct GNUNET_PeerIdentity);
4478   if (size < 2)
4479   {
4480     GNUNET_break_op (0);
4481     return GNUNET_OK;
4482   }
4483   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
4484
4485   msg = (struct GNUNET_MESH_ManipulatePath *) message;
4486   pi = (struct GNUNET_PeerIdentity *) &msg[1];
4487   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4488               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi),
4489               msg->tid);
4490   t = tunnel_get (pi, ntohl (msg->tid));
4491   if (NULL == t)
4492   {
4493     /* TODO notify back: we don't know this tunnel */
4494     GNUNET_break_op (0);
4495     return GNUNET_OK;
4496   }
4497   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
4498   path = path_new (size);
4499   own_pos = 0;
4500   for (i = 0; i < size; i++)
4501   {
4502     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
4503                 GNUNET_i2s (&pi[i]));
4504     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
4505     if (path->peers[i] == myid)
4506       own_pos = i;
4507   }
4508   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
4509   if (own_pos < path->length - 1)
4510     send_message (message, &pi[own_pos + 1], t);
4511   else
4512     send_client_tunnel_disconnect(t, NULL);
4513
4514   tunnel_delete_peer (t, path->peers[path->length - 1]);
4515   path_destroy (path);
4516   return GNUNET_OK;
4517 }
4518
4519
4520 /**
4521  * Core handler for notifications of broken paths
4522  *
4523  * @param cls closure
4524  * @param message message
4525  * @param peer peer identity this notification is about
4526  * @param atsi performance data
4527  * @param atsi_count number of records in 'atsi'
4528  *
4529  * @return GNUNET_OK to keep the connection open,
4530  *         GNUNET_SYSERR to close it (signal serious error)
4531  */
4532 static int
4533 handle_mesh_path_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
4534                          const struct GNUNET_MessageHeader *message,
4535                          const struct GNUNET_ATS_Information *atsi,
4536                          unsigned int atsi_count)
4537 {
4538   struct GNUNET_MESH_PathBroken *msg;
4539   struct MeshTunnel *t;
4540
4541   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4542               "Received a PATH BROKEN msg from %s\n", GNUNET_i2s (peer));
4543   msg = (struct GNUNET_MESH_PathBroken *) message;
4544   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
4545               GNUNET_i2s (&msg->peer1));
4546   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
4547               GNUNET_i2s (&msg->peer2));
4548   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4549   if (NULL == t)
4550   {
4551     GNUNET_break_op (0);
4552     return GNUNET_OK;
4553   }
4554   tunnel_notify_connection_broken (t, GNUNET_PEER_search (&msg->peer1),
4555                                    GNUNET_PEER_search (&msg->peer2));
4556   return GNUNET_OK;
4557
4558 }
4559
4560
4561 /**
4562  * Core handler for tunnel destruction
4563  *
4564  * @param cls closure
4565  * @param message message
4566  * @param peer peer identity this notification is about
4567  * @param atsi performance data
4568  * @param atsi_count number of records in 'atsi'
4569  *
4570  * @return GNUNET_OK to keep the connection open,
4571  *         GNUNET_SYSERR to close it (signal serious error)
4572  */
4573 static int
4574 handle_mesh_tunnel_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
4575                             const struct GNUNET_MessageHeader *message,
4576                             const struct GNUNET_ATS_Information *atsi,
4577                             unsigned int atsi_count)
4578 {
4579   struct GNUNET_MESH_TunnelDestroy *msg;
4580   struct MeshTunnel *t;
4581
4582   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4583               "Got a TUNNEL DESTROY packet from %s\n", GNUNET_i2s (peer));
4584   msg = (struct GNUNET_MESH_TunnelDestroy *) message;
4585   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for tunnel %s [%u]\n",
4586               GNUNET_i2s (&msg->oid), ntohl (msg->tid));
4587   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4588   if (NULL == t)
4589   {
4590     /* Probably already got the message from another path,
4591      * destroyed the tunnel and retransmitted to children.
4592      * Safe to ignore.
4593      */
4594     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel", 1, GNUNET_NO);
4595     return GNUNET_OK;
4596   }
4597   if (t->id.oid == myid)
4598   {
4599     GNUNET_break_op (0);
4600     return GNUNET_OK;
4601   }
4602   if (t->local_tid_dest >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
4603   {
4604     /* Tunnel was incoming, notify clients */
4605     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "INCOMING TUNNEL %X %X\n",
4606                 t->local_tid, t->local_tid_dest);
4607     send_clients_tunnel_destroy (t);
4608   }
4609   tunnel_send_destroy (t);
4610   t->destroy = GNUNET_YES;
4611   // TODO: add timeout to destroy the tunnel anyway
4612   return GNUNET_OK;
4613 }
4614
4615
4616 /**
4617  * Core handler for mesh network traffic going from the origin to a peer
4618  *
4619  * @param cls closure
4620  * @param peer peer identity this notification is about
4621  * @param message message
4622  * @param atsi performance data
4623  * @param atsi_count number of records in 'atsi'
4624  * @return GNUNET_OK to keep the connection open,
4625  *         GNUNET_SYSERR to close it (signal serious error)
4626  */
4627 static int
4628 handle_mesh_data_unicast (void *cls, const struct GNUNET_PeerIdentity *peer,
4629                           const struct GNUNET_MessageHeader *message,
4630                           const struct GNUNET_ATS_Information *atsi,
4631                           unsigned int atsi_count)
4632 {
4633   struct GNUNET_MESH_Unicast *msg;
4634   struct GNUNET_PeerIdentity *neighbor;
4635   struct MeshTunnelChildInfo *cinfo;
4636   struct MeshTunnel *t;
4637   GNUNET_PEER_Id dest_id;
4638   uint32_t pid;
4639   uint32_t ttl;
4640   size_t size;
4641
4642   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a unicast packet from %s\n",
4643               GNUNET_i2s (peer));
4644   size = ntohs (message->size);
4645   if (size <
4646       sizeof (struct GNUNET_MESH_Unicast) +
4647       sizeof (struct GNUNET_MessageHeader))
4648   {
4649     GNUNET_break (0);
4650     return GNUNET_OK;
4651   }
4652   msg = (struct GNUNET_MESH_Unicast *) message;
4653   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %u\n",
4654               ntohs (msg[1].header.type));
4655   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4656   if (NULL == t)
4657   {
4658     /* TODO notify back: we don't know this tunnel */
4659     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
4660     GNUNET_break_op (0);
4661     return GNUNET_OK;
4662   }
4663   pid = ntohl (msg->pid);
4664   if (t->pid == pid)
4665   {
4666     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
4667     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4668                 " Already seen pid %u, DROPPING!\n", pid);
4669     return GNUNET_OK;
4670   }
4671   else
4672   {
4673     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4674                 " pid %u not seen yet, forwarding\n", pid);
4675   }
4676   t->skip += (pid - t->pid) - 1;
4677   t->pid = pid;
4678   tunnel_reset_timeout (t);
4679   dest_id = GNUNET_PEER_search (&msg->destination);
4680   if (dest_id == myid)
4681   {
4682     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4683                 "  it's for us! sending to clients...\n");
4684     GNUNET_STATISTICS_update (stats, "# unicast received", 1, GNUNET_NO);
4685     send_subscribed_clients (message, (struct GNUNET_MessageHeader *) &msg[1]);
4686     // FIXME send after client processes the packet
4687     tunnel_send_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
4688     return GNUNET_OK;
4689   }
4690   ttl = ntohl (msg->ttl);
4691   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ttl);
4692   if (ttl == 0)
4693   {
4694     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
4695     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
4696     return GNUNET_OK;
4697   }
4698   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4699               "  not for us, retransmitting...\n");
4700   GNUNET_STATISTICS_update (stats, "# unicast forwarded", 1, GNUNET_NO);
4701
4702   neighbor = tree_get_first_hop (t->tree, dest_id);
4703   cinfo = GNUNET_CONTAINER_multihashmap_get (t->children_fc,
4704                                              &neighbor->hashPubKey);
4705   if (NULL == cinfo)
4706   {
4707     cinfo = GNUNET_malloc (sizeof (struct MeshTunnelChildInfo));
4708     cinfo->id = GNUNET_PEER_intern (neighbor);
4709     cinfo->skip = pid;
4710     cinfo->max_pid = pid + t->queue_max - t->queue_n; // FIXME review
4711
4712     GNUNET_assert (GNUNET_OK ==
4713                    GNUNET_CONTAINER_multihashmap_put (t->children_fc,
4714                        &neighbor->hashPubKey,
4715                        cinfo,
4716                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
4717   }
4718   cinfo->pid = pid;
4719   GNUNET_CONTAINER_multihashmap_iterate (t->children_fc,
4720                                          &tunnel_add_skip,
4721                                          &neighbor);
4722   send_message (message, neighbor, t);
4723   return GNUNET_OK;
4724 }
4725
4726
4727 /**
4728  * Core handler for mesh network traffic going from the origin to all peers
4729  *
4730  * @param cls closure
4731  * @param message message
4732  * @param peer peer identity this notification is about
4733  * @param atsi performance data
4734  * @param atsi_count number of records in 'atsi'
4735  * @return GNUNET_OK to keep the connection open,
4736  *         GNUNET_SYSERR to close it (signal serious error)
4737  *
4738  * TODO: Check who we got this from, to validate route.
4739  */
4740 static int
4741 handle_mesh_data_multicast (void *cls, const struct GNUNET_PeerIdentity *peer,
4742                             const struct GNUNET_MessageHeader *message,
4743                             const struct GNUNET_ATS_Information *atsi,
4744                             unsigned int atsi_count)
4745 {
4746   struct GNUNET_MESH_Multicast *msg;
4747   struct MeshTunnel *t;
4748   size_t size;
4749   uint32_t pid;
4750
4751   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a multicast packet from %s\n",
4752               GNUNET_i2s (peer));
4753   size = ntohs (message->size);
4754   if (sizeof (struct GNUNET_MESH_Multicast) +
4755       sizeof (struct GNUNET_MessageHeader) > size)
4756   {
4757     GNUNET_break_op (0);
4758     return GNUNET_OK;
4759   }
4760   msg = (struct GNUNET_MESH_Multicast *) message;
4761   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4762
4763   if (NULL == t)
4764   {
4765     /* TODO notify that we dont know that tunnel */
4766     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
4767     GNUNET_break_op (0);
4768     return GNUNET_OK;
4769   }
4770   pid = ntohl (msg->pid);
4771   if (t->pid == pid)
4772   {
4773     /* already seen this packet, drop */
4774     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
4775     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4776                 " Already seen pid %u, DROPPING!\n", pid);
4777     return GNUNET_OK;
4778   }
4779   else
4780   {
4781     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4782                 " pid %u not seen yet, forwarding\n", pid);
4783   }
4784   t->skip += (pid - t->pid) - 1;
4785   t->pid = pid;
4786   tunnel_reset_timeout (t);
4787
4788   /* Transmit to locally interested clients */
4789   if (NULL != t->peers &&
4790       GNUNET_CONTAINER_multihashmap_contains (t->peers, &my_full_id.hashPubKey))
4791   {
4792     GNUNET_STATISTICS_update (stats, "# multicast received", 1, GNUNET_NO);
4793     send_subscribed_clients (message, &msg[1].header);
4794   }
4795   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ntohl (msg->ttl));
4796   if (ntohl (msg->ttl) == 0)
4797   {
4798     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
4799     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
4800     return GNUNET_OK;
4801   }
4802   GNUNET_STATISTICS_update (stats, "# multicast forwarded", 1, GNUNET_NO);
4803   tunnel_send_multicast (t, message, GNUNET_NO);
4804   return GNUNET_OK;
4805 }
4806
4807
4808 /**
4809  * Core handler for mesh network traffic toward the owner of a tunnel
4810  *
4811  * @param cls closure
4812  * @param message message
4813  * @param peer peer identity this notification is about
4814  * @param atsi performance data
4815  * @param atsi_count number of records in 'atsi'
4816  *
4817  * @return GNUNET_OK to keep the connection open,
4818  *         GNUNET_SYSERR to close it (signal serious error)
4819  */
4820 static int
4821 handle_mesh_data_to_orig (void *cls, const struct GNUNET_PeerIdentity *peer,
4822                           const struct GNUNET_MessageHeader *message,
4823                           const struct GNUNET_ATS_Information *atsi,
4824                           unsigned int atsi_count)
4825 {
4826   struct GNUNET_MESH_ToOrigin *msg;
4827   struct GNUNET_PeerIdentity id;
4828   struct MeshPeerInfo *peer_info;
4829   struct MeshTunnel *t;
4830   size_t size;
4831
4832   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a ToOrigin packet from %s\n",
4833               GNUNET_i2s (peer));
4834   size = ntohs (message->size);
4835   if (size < sizeof (struct GNUNET_MESH_ToOrigin) +     /* Payload must be */
4836       sizeof (struct GNUNET_MessageHeader))     /* at least a header */
4837   {
4838     GNUNET_break_op (0);
4839     return GNUNET_OK;
4840   }
4841   msg = (struct GNUNET_MESH_ToOrigin *) message;
4842   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %u\n",
4843               ntohs (msg[1].header.type));
4844   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4845
4846   if (NULL == t)
4847   {
4848     /* TODO notify that we dont know this tunnel (whom)? */
4849     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
4850     GNUNET_break_op (0);
4851     return GNUNET_OK;
4852   }
4853
4854   if (t->id.oid == myid)
4855   {
4856     char cbuf[size];
4857     struct GNUNET_MESH_ToOrigin *copy;
4858
4859     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4860                 "  it's for us! sending to clients...\n");
4861     if (NULL == t->owner)
4862     {
4863       /* got data packet for ownerless tunnel */
4864       GNUNET_STATISTICS_update (stats, "# data on ownerless tunnel",
4865                                 1, GNUNET_NO);
4866       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  no clients!\n");
4867       GNUNET_break_op (0);
4868       return GNUNET_OK;
4869     }
4870     /* TODO signature verification */
4871     memcpy (cbuf, message, size);
4872     copy = (struct GNUNET_MESH_ToOrigin *) cbuf;
4873     copy->tid = htonl (t->local_tid);
4874     GNUNET_STATISTICS_update (stats, "# to origin received", 1, GNUNET_NO);
4875     GNUNET_SERVER_notification_context_unicast (nc, t->owner->handle,
4876                                                 &copy->header, GNUNET_NO);
4877     return GNUNET_OK;
4878   }
4879   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4880               "  not for us, retransmitting...\n");
4881
4882   peer_info = peer_info_get (&msg->oid);
4883   if (NULL == peer_info)
4884   {
4885     /* unknown origin of tunnel */
4886     GNUNET_break (0);
4887     return GNUNET_OK;
4888   }
4889   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
4890   send_message (message, &id, t);
4891   GNUNET_STATISTICS_update (stats, "# to origin forwarded", 1, GNUNET_NO);
4892
4893   return GNUNET_OK;
4894 }
4895
4896
4897 /**
4898  * Core handler for mesh network traffic point-to-point acks.
4899  *
4900  * @param cls closure
4901  * @param message message
4902  * @param peer peer identity this notification is about
4903  * @param atsi performance data
4904  * @param atsi_count number of records in 'atsi'
4905  *
4906  * @return GNUNET_OK to keep the connection open,
4907  *         GNUNET_SYSERR to close it (signal serious error)
4908  */
4909 static int
4910 handle_mesh_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
4911                  const struct GNUNET_MessageHeader *message,
4912                  const struct GNUNET_ATS_Information *atsi,
4913                  unsigned int atsi_count)
4914 {
4915   struct GNUNET_MESH_ACK *msg;
4916   struct MeshTunnelChildInfo *cinfo;
4917   struct MeshTunnel *t;
4918   uint32_t ack;
4919
4920   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got an ACK packet from %s\n",
4921               GNUNET_i2s (peer));
4922   msg = (struct GNUNET_MESH_ACK *) message;
4923   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %u\n",
4924               ntohs (msg[1].header.type));
4925   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4926
4927   if (NULL == t)
4928   {
4929     /* TODO notify that we dont know this tunnel (whom)? */
4930     GNUNET_STATISTICS_update (stats, "# ack on unknown tunnel", 1, GNUNET_NO);
4931     GNUNET_break_op (0);
4932     return GNUNET_OK;
4933   }
4934   ack = ntohl (msg->pid);
4935   cinfo = GNUNET_CONTAINER_multihashmap_get (t->children_fc,
4936                                              &peer->hashPubKey);
4937   if (NULL == cinfo)
4938   {
4939     GNUNET_break_op (0);
4940     return GNUNET_OK;
4941   }
4942   cinfo->max_pid = ack;
4943   tunnel_send_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
4944   return GNUNET_OK;
4945 }
4946
4947
4948 /**
4949  * Core handler for path ACKs
4950  *
4951  * @param cls closure
4952  * @param message message
4953  * @param peer peer identity this notification is about
4954  * @param atsi performance data
4955  * @param atsi_count number of records in 'atsi'
4956  *
4957  * @return GNUNET_OK to keep the connection open,
4958  *         GNUNET_SYSERR to close it (signal serious error)
4959  */
4960 static int
4961 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
4962                       const struct GNUNET_MessageHeader *message,
4963                       const struct GNUNET_ATS_Information *atsi,
4964                       unsigned int atsi_count)
4965 {
4966   struct GNUNET_MESH_PathACK *msg;
4967   struct GNUNET_PeerIdentity id;
4968   struct MeshPeerInfo *peer_info;
4969   struct MeshPeerPath *p;
4970   struct MeshTunnel *t;
4971
4972   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a path ACK msg [%s]\n",
4973               GNUNET_i2s (&my_full_id));
4974   msg = (struct GNUNET_MESH_PathACK *) message;
4975   t = tunnel_get (&msg->oid, ntohl(msg->tid));
4976   if (NULL == t)
4977   {
4978     /* TODO notify that we don't know the tunnel */
4979     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel", 1, GNUNET_NO);
4980     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  don't know the tunnel %s [%X]!\n",
4981                 GNUNET_i2s (&msg->oid), ntohl(msg->tid));
4982     return GNUNET_OK;
4983   }
4984   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %s [%X]\n",
4985               GNUNET_i2s (&msg->oid), ntohl(msg->tid));
4986
4987   peer_info = peer_info_get (&msg->peer_id);
4988   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by peer %s\n",
4989               GNUNET_i2s (&msg->peer_id));
4990   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  via peer %s\n",
4991               GNUNET_i2s (peer));
4992
4993   if (NULL != t->regex_ctx && t->regex_ctx->info->peer == peer_info->id)
4994   {
4995     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4996                 "connect_by_string completed, stopping search\n");
4997     regex_cancel_search (t->regex_ctx);
4998     t->regex_ctx = NULL;
4999   }
5000
5001   /* Add paths to peers? */
5002   p = tree_get_path_to_peer (t->tree, peer_info->id);
5003   if (NULL != p)
5004   {
5005     path_add_to_peers (p, GNUNET_YES);
5006     path_destroy (p);
5007   }
5008   else
5009   {
5010     GNUNET_break (0);
5011   }
5012
5013   /* Message for us? */
5014   if (0 == memcmp (&msg->oid, &my_full_id, sizeof (struct GNUNET_PeerIdentity)))
5015   {
5016     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
5017     if (NULL == t->owner)
5018     {
5019       GNUNET_break_op (0);
5020       return GNUNET_OK;
5021     }
5022     if (NULL != t->dht_get_type)
5023     {
5024       GNUNET_DHT_get_stop (t->dht_get_type);
5025       t->dht_get_type = NULL;
5026     }
5027     if (tree_get_status (t->tree, peer_info->id) != MESH_PEER_READY)
5028     {
5029       tree_set_status (t->tree, peer_info->id, MESH_PEER_READY);
5030       send_client_peer_connected (t, peer_info->id);
5031     }
5032     return GNUNET_OK;
5033   }
5034
5035   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5036               "  not for us, retransmitting...\n");
5037   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
5038   peer_info = peer_info_get (&msg->oid);
5039   if (NULL == peer_info)
5040   {
5041     /* If we know the tunnel, we should DEFINITELY know the peer */
5042     GNUNET_break (0);
5043     return GNUNET_OK;
5044   }
5045   send_message (message, &id, t);
5046   return GNUNET_OK;
5047 }
5048
5049
5050 /**
5051  * Functions to handle messages from core
5052  */
5053 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
5054   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
5055   {&handle_mesh_path_destroy, GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY, 0},
5056   {&handle_mesh_path_broken, GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN,
5057    sizeof (struct GNUNET_MESH_PathBroken)},
5058   {&handle_mesh_tunnel_destroy, GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY,
5059    sizeof (struct GNUNET_MESH_TunnelDestroy)},
5060   {&handle_mesh_data_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
5061   {&handle_mesh_data_multicast, GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
5062   {&handle_mesh_data_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
5063   {&handle_mesh_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
5064     sizeof (struct GNUNET_MESH_ACK)},
5065   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
5066    sizeof (struct GNUNET_MESH_PathACK)},
5067   {NULL, 0, 0}
5068 };
5069
5070
5071
5072 /******************************************************************************/
5073 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
5074 /******************************************************************************/
5075
5076 /**
5077  * deregister_app: iterator for removing each application registered by a client
5078  *
5079  * @param cls closure
5080  * @param key the hash of the application id (used to access the hashmap)
5081  * @param value the value stored at the key (client)
5082  *
5083  * @return GNUNET_OK on success
5084  */
5085 static int
5086 deregister_app (void *cls, const struct GNUNET_HashCode * key, void *value)
5087 {
5088   struct GNUNET_CONTAINER_MultiHashMap *h = cls;
5089   GNUNET_break (GNUNET_YES ==
5090                 GNUNET_CONTAINER_multihashmap_remove (h, key, value));
5091   return GNUNET_OK;
5092 }
5093
5094 #if LATER
5095 /**
5096  * notify_client_connection_failure: notify a client that the connection to the
5097  * requested remote peer is not possible (for instance, no route found)
5098  * Function called when the socket is ready to queue more data. "buf" will be
5099  * NULL and "size" zero if the socket was closed for writing in the meantime.
5100  *
5101  * @param cls closure
5102  * @param size number of bytes available in buf
5103  * @param buf where the callee should write the message
5104  * @return number of bytes written to buf
5105  */
5106 static size_t
5107 notify_client_connection_failure (void *cls, size_t size, void *buf)
5108 {
5109   int size_needed;
5110   struct MeshPeerInfo *peer_info;
5111   struct GNUNET_MESH_PeerControl *msg;
5112   struct GNUNET_PeerIdentity id;
5113
5114   if (0 == size && NULL == buf)
5115   {
5116     // TODO retry? cancel?
5117     return 0;
5118   }
5119
5120   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
5121   peer_info = (struct MeshPeerInfo *) cls;
5122   msg = (struct GNUNET_MESH_PeerControl *) buf;
5123   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
5124   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
5125 //     msg->tunnel_id = htonl(peer_info->t->tid);
5126   GNUNET_PEER_resolve (peer_info->id, &id);
5127   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
5128
5129   return size_needed;
5130 }
5131 #endif
5132
5133
5134 /**
5135  * Send keepalive packets for a peer
5136  *
5137  * @param cls Closure (tunnel for which to send the keepalive).
5138  * @param tc Notification context.
5139  *
5140  * TODO: implement explicit multicast keepalive?
5141  */
5142 static void
5143 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
5144 {
5145   struct MeshTunnel *t = cls;
5146   struct GNUNET_MessageHeader *payload;
5147   struct GNUNET_MESH_Multicast *msg;
5148   size_t size =
5149       sizeof (struct GNUNET_MESH_Multicast) +
5150       sizeof (struct GNUNET_MessageHeader);
5151   char cbuf[size];
5152
5153   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
5154   {
5155     return;
5156   }
5157   t->path_refresh_task = GNUNET_SCHEDULER_NO_TASK;
5158
5159   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5160               "sending keepalive for tunnel %d\n", t->id.tid);
5161
5162   msg = (struct GNUNET_MESH_Multicast *) cbuf;
5163   msg->header.size = htons (size);
5164   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
5165   msg->oid = my_full_id;
5166   msg->tid = htonl (t->id.tid);
5167   msg->ttl = htonl (default_ttl);
5168   msg->pid = htonl (t->pid + 1);
5169   t->pid++;
5170   payload = (struct GNUNET_MessageHeader *) &msg[1];
5171   payload->size = htons (sizeof (struct GNUNET_MessageHeader));
5172   payload->type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE);
5173   tunnel_send_multicast (t, &msg->header, GNUNET_YES);
5174
5175   t->path_refresh_task =
5176       GNUNET_SCHEDULER_add_delayed (refresh_path_time, &path_refresh, t);
5177   return;
5178 }
5179
5180
5181 /**
5182  * Function to process paths received for a new peer addition. The recorded
5183  * paths form the initial tunnel, which can be optimized later.
5184  * Called on each result obtained for the DHT search.
5185  *
5186  * @param cls closure
5187  * @param exp when will this value expire
5188  * @param key key of the result
5189  * @param get_path path of the get request
5190  * @param get_path_length lenght of get_path
5191  * @param put_path path of the put request
5192  * @param put_path_length length of the put_path
5193  * @param type type of the result
5194  * @param size number of bytes in data
5195  * @param data pointer to the result data
5196  *
5197  * TODO: re-issue the request after certain time? cancel after X results?
5198  */
5199 static void
5200 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
5201                     const struct GNUNET_HashCode * key,
5202                     const struct GNUNET_PeerIdentity *get_path,
5203                     unsigned int get_path_length,
5204                     const struct GNUNET_PeerIdentity *put_path,
5205                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
5206                     size_t size, const void *data)
5207 {
5208   struct MeshPathInfo *path_info = cls;
5209   struct MeshPeerPath *p;
5210   struct GNUNET_PeerIdentity pi;
5211   int i;
5212
5213   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
5214   GNUNET_PEER_resolve (path_info->peer->id, &pi);
5215   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", GNUNET_i2s (&pi));
5216
5217   p = path_build_from_dht (get_path, get_path_length, put_path,
5218                            put_path_length);
5219   path_add_to_peers (p, GNUNET_NO);
5220   path_destroy(p);
5221   for (i = 0; i < path_info->peer->ntunnels; i++)
5222   {
5223     tunnel_add_peer (path_info->peer->tunnels[i], path_info->peer);
5224     peer_info_connect (path_info->peer, path_info->t);
5225   }
5226
5227   return;
5228 }
5229
5230
5231 /**
5232  * Function to process paths received for a new peer addition. The recorded
5233  * paths form the initial tunnel, which can be optimized later.
5234  * Called on each result obtained for the DHT search.
5235  *
5236  * @param cls closure
5237  * @param exp when will this value expire
5238  * @param key key of the result
5239  * @param get_path path of the get request
5240  * @param get_path_length lenght of get_path
5241  * @param put_path path of the put request
5242  * @param put_path_length length of the put_path
5243  * @param type type of the result
5244  * @param size number of bytes in data
5245  * @param data pointer to the result data
5246  */
5247 static void
5248 dht_get_type_handler (void *cls, struct GNUNET_TIME_Absolute exp,
5249                       const struct GNUNET_HashCode * key,
5250                       const struct GNUNET_PeerIdentity *get_path,
5251                       unsigned int get_path_length,
5252                       const struct GNUNET_PeerIdentity *put_path,
5253                       unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
5254                       size_t size, const void *data)
5255 {
5256   const struct PBlock *pb = data;
5257   const struct GNUNET_PeerIdentity *pi = &pb->id;
5258   struct MeshTunnel *t = cls;
5259   struct MeshPeerInfo *peer_info;
5260   struct MeshPeerPath *p;
5261
5262   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got type DHT result!\n");
5263   if (size != sizeof (struct PBlock))
5264   {
5265     GNUNET_break_op (0);
5266     return;
5267   }
5268   if (ntohl(pb->type) != t->type)
5269   {
5270     GNUNET_break_op (0);
5271     return;
5272   }
5273   GNUNET_assert (NULL != t->owner);
5274   peer_info = peer_info_get (pi);
5275   (void) GNUNET_CONTAINER_multihashmap_put (t->peers, &pi->hashPubKey,
5276                                             peer_info,
5277                                             GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
5278
5279   p = path_build_from_dht (get_path, get_path_length, put_path,
5280                            put_path_length);
5281   path_add_to_peers (p, GNUNET_NO);
5282   path_destroy(p);
5283   tunnel_add_peer (t, peer_info);
5284   peer_info_connect (peer_info, t);
5285 }
5286
5287
5288 /**
5289  * Function to process DHT string to regex matching.
5290  * Called on each result obtained for the DHT search.
5291  *
5292  * @param cls closure (search context)
5293  * @param exp when will this value expire
5294  * @param key key of the result
5295  * @param get_path path of the get request (not used)
5296  * @param get_path_length lenght of get_path (not used)
5297  * @param put_path path of the put request (not used)
5298  * @param put_path_length length of the put_path (not used)
5299  * @param type type of the result
5300  * @param size number of bytes in data
5301  * @param data pointer to the result data
5302  */
5303 static void
5304 dht_get_string_accept_handler (void *cls, struct GNUNET_TIME_Absolute exp,
5305                                const struct GNUNET_HashCode * key,
5306                                const struct GNUNET_PeerIdentity *get_path,
5307                                unsigned int get_path_length,
5308                                const struct GNUNET_PeerIdentity *put_path,
5309                                unsigned int put_path_length,
5310                                enum GNUNET_BLOCK_Type type,
5311                                size_t size, const void *data)
5312 {
5313   const struct MeshRegexAccept *block = data;
5314   struct MeshRegexSearchContext *ctx = cls;
5315   struct MeshRegexSearchInfo *info = ctx->info;
5316   struct MeshPeerPath *p;
5317   struct MeshPeerInfo *peer_info;
5318
5319   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got regex results from DHT!\n");
5320   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", info->description);
5321
5322   peer_info = peer_info_get(&block->id);
5323   p = path_build_from_dht (get_path, get_path_length, put_path,
5324                            put_path_length);
5325   path_add_to_peers (p, GNUNET_NO);
5326   path_destroy(p);
5327
5328   tunnel_add_peer (info->t, peer_info);
5329   peer_info_connect (peer_info, info->t);
5330   if (0 == info->peer)
5331   {
5332     info->peer = peer_info->id;
5333   }
5334   else
5335   {
5336     GNUNET_array_append (info->peers, info->n_peers, peer_info->id);
5337   }
5338
5339   info->timeout = GNUNET_SCHEDULER_add_delayed (connect_timeout,
5340                                                 &regex_connect_timeout,
5341                                                 info);
5342
5343   return;
5344 }
5345
5346
5347 /**
5348  * Function to process DHT string to regex matching.
5349  * Called on each result obtained for the DHT search.
5350  *
5351  * @param cls closure (search context)
5352  * @param exp when will this value expire
5353  * @param key key of the result
5354  * @param get_path path of the get request (not used)
5355  * @param get_path_length lenght of get_path (not used)
5356  * @param put_path path of the put request (not used)
5357  * @param put_path_length length of the put_path (not used)
5358  * @param type type of the result
5359  * @param size number of bytes in data
5360  * @param data pointer to the result data
5361  *
5362  * TODO: re-issue the request after certain time? cancel after X results?
5363  */
5364 static void
5365 dht_get_string_handler (void *cls, struct GNUNET_TIME_Absolute exp,
5366                         const struct GNUNET_HashCode * key,
5367                         const struct GNUNET_PeerIdentity *get_path,
5368                         unsigned int get_path_length,
5369                         const struct GNUNET_PeerIdentity *put_path,
5370                         unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
5371                         size_t size, const void *data)
5372 {
5373   const struct MeshRegexBlock *block = data;
5374   struct MeshRegexSearchContext *ctx = cls;
5375   struct MeshRegexSearchInfo *info = ctx->info;
5376   void *copy;
5377   size_t len;
5378
5379   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5380               "DHT GET STRING RETURNED RESULTS\n");
5381   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5382               "  key: %s\n", GNUNET_h2s (key));
5383
5384   copy = GNUNET_malloc (size);
5385   memcpy (copy, data, size);
5386   GNUNET_break (GNUNET_OK ==
5387                 GNUNET_CONTAINER_multihashmap_put(info->dht_get_results, key, copy,
5388                                                   GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
5389   len = ntohl (block->n_proof);
5390   {
5391     char proof[len + 1];
5392
5393     memcpy (proof, &block[1], len);
5394     proof[len] = '\0';
5395     if (GNUNET_OK != GNUNET_REGEX_check_proof (proof, key))
5396     {
5397       GNUNET_break_op (0);
5398       return;
5399     }
5400   }
5401   len = strlen (info->description);
5402   if (len == ctx->position) // String processed
5403   {
5404     if (GNUNET_YES == ntohl (block->accepting))
5405     {
5406       regex_find_path(key, ctx);
5407     }
5408     else
5409     {
5410       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  block not accepting!\n");
5411       // FIXME REGEX this block not successful, wait for more? start timeout?
5412     }
5413     return;
5414   }
5415   GNUNET_break (GNUNET_OK ==
5416                 GNUNET_MESH_regex_block_iterate (block, size,
5417                                                  &regex_edge_iterator, ctx));
5418   return;
5419 }
5420
5421 /******************************************************************************/
5422 /*********************       MESH LOCAL HANDLES      **************************/
5423 /******************************************************************************/
5424
5425
5426 /**
5427  * Handler for client disconnection
5428  *
5429  * @param cls closure
5430  * @param client identification of the client; NULL
5431  *        for the last call when the server is destroyed
5432  */
5433 static void
5434 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
5435 {
5436   struct MeshClient *c;
5437   struct MeshClient *next;
5438   unsigned int i;
5439
5440   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected\n");
5441   if (client == NULL)
5442   {
5443     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (SERVER DOWN)\n");
5444     return;
5445   }
5446   c = clients;
5447   while (NULL != c)
5448   {
5449     if (c->handle != client)
5450     {
5451       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ... searching\n");
5452       c = c->next;
5453       continue;
5454     }
5455     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u)\n",
5456                 c->id);
5457     GNUNET_SERVER_client_drop (c->handle);
5458     c->shutting_down = GNUNET_YES;
5459     GNUNET_assert (NULL != c->own_tunnels);
5460     GNUNET_assert (NULL != c->incoming_tunnels);
5461     GNUNET_CONTAINER_multihashmap_iterate (c->own_tunnels,
5462                                            &tunnel_destroy_iterator, c);
5463     GNUNET_CONTAINER_multihashmap_iterate (c->incoming_tunnels,
5464                                            &tunnel_destroy_iterator, c);
5465     GNUNET_CONTAINER_multihashmap_iterate (c->ignore_tunnels,
5466                                            &tunnel_destroy_iterator, c);
5467     GNUNET_CONTAINER_multihashmap_destroy (c->own_tunnels);
5468     GNUNET_CONTAINER_multihashmap_destroy (c->incoming_tunnels);
5469     GNUNET_CONTAINER_multihashmap_destroy (c->ignore_tunnels);
5470
5471     /* deregister clients applications */
5472     if (NULL != c->apps)
5473     {
5474       GNUNET_CONTAINER_multihashmap_iterate (c->apps, &deregister_app, c->apps);
5475       GNUNET_CONTAINER_multihashmap_destroy (c->apps);
5476     }
5477     if (0 == GNUNET_CONTAINER_multihashmap_size (applications) &&
5478         GNUNET_SCHEDULER_NO_TASK != announce_applications_task)
5479     {
5480       GNUNET_SCHEDULER_cancel (announce_applications_task);
5481       announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
5482     }
5483     if (NULL != c->types)
5484       GNUNET_CONTAINER_multihashmap_destroy (c->types);
5485     for (i = 0; i < c->n_regex; i++)
5486     {
5487       GNUNET_free (c->regexes[i]);
5488     }
5489     GNUNET_free_non_null (c->regexes);
5490     if (GNUNET_SCHEDULER_NO_TASK != c->regex_announce_task)
5491       GNUNET_SCHEDULER_cancel (c->regex_announce_task);
5492     next = c->next;
5493     GNUNET_CONTAINER_DLL_remove (clients, clients_tail, c);
5494     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT FREE at %p\n", c);
5495     GNUNET_free (c);
5496     GNUNET_STATISTICS_update (stats, "# clients", -1, GNUNET_NO);
5497     c = next;
5498   }
5499   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   done!\n");
5500   return;
5501 }
5502
5503
5504 /**
5505  * Handler for new clients
5506  *
5507  * @param cls closure
5508  * @param client identification of the client
5509  * @param message the actual message, which includes messages the client wants
5510  */
5511 static void
5512 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
5513                          const struct GNUNET_MessageHeader *message)
5514 {
5515   struct GNUNET_MESH_ClientConnect *cc_msg;
5516   struct MeshClient *c;
5517   GNUNET_MESH_ApplicationType *a;
5518   unsigned int size;
5519   uint16_t ntypes;
5520   uint16_t *t;
5521   uint16_t napps;
5522   uint16_t i;
5523
5524   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected\n");
5525   /* Check data sanity */
5526   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
5527   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
5528   ntypes = ntohs (cc_msg->types);
5529   napps = ntohs (cc_msg->applications);
5530   if (size !=
5531       ntypes * sizeof (uint16_t) + napps * sizeof (GNUNET_MESH_ApplicationType))
5532   {
5533     GNUNET_break (0);
5534     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5535     return;
5536   }
5537
5538   /* Create new client structure */
5539   c = GNUNET_malloc (sizeof (struct MeshClient));
5540   c->id = next_client_id++;
5541   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT NEW %u\n", c->id);
5542   c->handle = client;
5543   GNUNET_SERVER_client_keep (client);
5544   a = (GNUNET_MESH_ApplicationType *) &cc_msg[1];
5545   if (napps > 0)
5546   {
5547     GNUNET_MESH_ApplicationType at;
5548     struct GNUNET_HashCode hc;
5549
5550     c->apps = GNUNET_CONTAINER_multihashmap_create (napps);
5551     for (i = 0; i < napps; i++)
5552     {
5553       at = ntohl (a[i]);
5554       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  app type: %u\n", at);
5555       GNUNET_CRYPTO_hash (&at, sizeof (at), &hc);
5556       /* store in clients hashmap */
5557       GNUNET_CONTAINER_multihashmap_put (c->apps, &hc, (void *) (long) at,
5558                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
5559       /* store in global hashmap, for announcements */
5560       GNUNET_CONTAINER_multihashmap_put (applications, &hc, c,
5561                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
5562     }
5563     if (GNUNET_SCHEDULER_NO_TASK == announce_applications_task)
5564       announce_applications_task =
5565           GNUNET_SCHEDULER_add_now (&announce_applications, NULL);
5566
5567   }
5568   if (ntypes > 0)
5569   {
5570     uint16_t u16;
5571     struct GNUNET_HashCode hc;
5572
5573     t = (uint16_t *) & a[napps];
5574     c->types = GNUNET_CONTAINER_multihashmap_create (ntypes);
5575     for (i = 0; i < ntypes; i++)
5576     {
5577       u16 = ntohs (t[i]);
5578       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  msg type: %u\n", u16);
5579       GNUNET_CRYPTO_hash (&u16, sizeof (u16), &hc);
5580
5581       /* store in clients hashmap */
5582       GNUNET_CONTAINER_multihashmap_put (c->types, &hc, c,
5583                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
5584       /* store in global hashmap */
5585       GNUNET_CONTAINER_multihashmap_put (types, &hc, c,
5586                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
5587     }
5588   }
5589   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5590               " client has %u+%u subscriptions\n", napps, ntypes);
5591
5592   GNUNET_CONTAINER_DLL_insert (clients, clients_tail, c);
5593   c->own_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
5594   c->incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
5595   c->ignore_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
5596   GNUNET_SERVER_notification_context_add (nc, client);
5597   GNUNET_STATISTICS_update (stats, "# clients", 1, GNUNET_NO);
5598
5599   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5600   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
5601 }
5602
5603
5604 /**
5605  * Handler for clients announcing available services by a regular expression.
5606  *
5607  * @param cls closure
5608  * @param client identification of the client
5609  * @param message the actual message, which includes messages the client wants
5610  */
5611 static void
5612 handle_local_announce_regex (void *cls, struct GNUNET_SERVER_Client *client,
5613                              const struct GNUNET_MessageHeader *message)
5614 {
5615   struct MeshClient *c;
5616   char *regex;
5617   size_t len;
5618
5619   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "announce regex started\n");
5620
5621   /* Sanity check for client registration */
5622   if (NULL == (c = client_get (client)))
5623   {
5624     GNUNET_break (0);
5625     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5626     return;
5627   }
5628   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
5629
5630   len = ntohs (message->size) - sizeof(struct GNUNET_MessageHeader);
5631   regex = GNUNET_malloc (len + 1);
5632   memcpy (regex, &message[1], len);
5633   regex[len] = '\0';
5634   GNUNET_array_append (c->regexes, c->n_regex, regex);
5635   if (GNUNET_SCHEDULER_NO_TASK == c->regex_announce_task)
5636   {
5637     c->regex_announce_task = GNUNET_SCHEDULER_add_now(&announce_regex, c);
5638   }
5639   else
5640   {
5641     regex_put(regex);
5642   }
5643   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5644   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "announce regex processed\n");
5645 }
5646
5647
5648 /**
5649  * Handler for requests of new tunnels
5650  *
5651  * @param cls closure
5652  * @param client identification of the client
5653  * @param message the actual message
5654  */
5655 static void
5656 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
5657                             const struct GNUNET_MessageHeader *message)
5658 {
5659   struct GNUNET_MESH_TunnelMessage *t_msg;
5660   struct MeshTunnel *t;
5661   struct MeshClient *c;
5662
5663   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel requested\n");
5664
5665   /* Sanity check for client registration */
5666   if (NULL == (c = client_get (client)))
5667   {
5668     GNUNET_break (0);
5669     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5670     return;
5671   }
5672   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
5673
5674   /* Message sanity check */
5675   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
5676   {
5677     GNUNET_break (0);
5678     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5679     return;
5680   }
5681
5682   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
5683   /* Sanity check for tunnel numbering */
5684   if (0 == (ntohl (t_msg->tunnel_id) & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
5685   {
5686     GNUNET_break (0);
5687     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5688     return;
5689   }
5690   /* Sanity check for duplicate tunnel IDs */
5691   if (NULL != tunnel_get_by_local_id (c, ntohl (t_msg->tunnel_id)))
5692   {
5693     GNUNET_break (0);
5694     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5695     return;
5696   }
5697
5698   while (NULL != tunnel_get_by_pi (myid, next_tid))
5699     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
5700   t = tunnel_new (myid, next_tid++, c, ntohl (t_msg->tunnel_id));
5701   if (NULL == t)
5702   {
5703     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Tunnel creation failed.\n");
5704     GNUNET_break (0);
5705     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5706     return;
5707   }
5708   next_tid = next_tid & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
5709   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED TUNNEL %s [%x] (%x)\n",
5710               GNUNET_i2s (&my_full_id), t->id.tid, t->local_tid);
5711   t->peers = GNUNET_CONTAINER_multihashmap_create (32);
5712
5713   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel created\n");
5714   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5715   return;
5716 }
5717
5718
5719 /**
5720  * Handler for requests of deleting tunnels
5721  *
5722  * @param cls closure
5723  * @param client identification of the client
5724  * @param message the actual message
5725  */
5726 static void
5727 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
5728                              const struct GNUNET_MessageHeader *message)
5729 {
5730   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
5731   struct MeshClient *c;
5732   struct MeshTunnel *t;
5733   MESH_TunnelNumber tid;
5734
5735   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5736               "Got a DESTROY TUNNEL from client!\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   /* Message sanity check */
5746   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
5747   {
5748     GNUNET_break (0);
5749     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5750     return;
5751   }
5752   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
5753   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
5754
5755   /* Retrieve tunnel */
5756   tid = ntohl (tunnel_msg->tunnel_id);
5757   t = tunnel_get_by_local_id(c, tid);
5758   if (NULL == t)
5759   {
5760     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
5761     GNUNET_break (0);
5762     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5763     return;
5764   }
5765   if (c != t->owner || tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
5766   {
5767     client_ignore_tunnel (c, t);
5768 #if 0
5769     // TODO: when to destroy incoming tunnel?
5770     if (t->nclients == 0)
5771     {
5772       GNUNET_assert (GNUNET_YES ==
5773                      GNUNET_CONTAINER_multihashmap_remove (incoming_tunnels,
5774                                                            &hash, t));
5775       GNUNET_assert (GNUNET_YES ==
5776                      GNUNET_CONTAINER_multihashmap_remove (t->peers,
5777                                                            &my_full_id.hashPubKey,
5778                                                            t));
5779     }
5780 #endif
5781     GNUNET_SERVER_receive_done (client, GNUNET_OK);
5782     return;
5783   }
5784   send_client_tunnel_disconnect(t, c);
5785   client_delete_tunnel(c, t);
5786
5787   /* Don't try to ACK the client about the tunnel_destroy multicast packet */
5788   t->owner = NULL;
5789   tunnel_send_destroy (t);
5790   t->destroy = GNUNET_YES;
5791   // The tunnel will be destroyed when the last message is transmitted.
5792   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5793   return;
5794 }
5795
5796
5797 /**
5798  * Handler for requests of seeting tunnel's speed.
5799  *
5800  * @param cls Closure (unused).
5801  * @param client Identification of the client.
5802  * @param message The actual message.
5803  */
5804 static void
5805 handle_local_tunnel_speed (void *cls, struct GNUNET_SERVER_Client *client,
5806                            const struct GNUNET_MessageHeader *message)
5807 {
5808   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
5809   struct MeshClient *c;
5810   struct MeshTunnel *t;
5811   MESH_TunnelNumber tid;
5812
5813   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5814               "Got a SPEED request from client!\n");
5815
5816   /* Sanity check for client registration */
5817   if (NULL == (c = client_get (client)))
5818   {
5819     GNUNET_break (0);
5820     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5821     return;
5822   }
5823
5824   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
5825   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
5826
5827   /* Retrieve tunnel */
5828   tid = ntohl (tunnel_msg->tunnel_id);
5829   t = tunnel_get_by_local_id(c, tid);
5830   if (NULL == t)
5831   {
5832     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  tunnel %X not found\n", tid);
5833     GNUNET_break (0);
5834     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5835     return;
5836   }
5837
5838   switch (ntohs(message->type))
5839   {
5840       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MIN:
5841           t->speed_min = GNUNET_YES;
5842           break;
5843       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MAX:
5844           t->speed_min = GNUNET_NO;
5845           break;
5846       default:
5847           GNUNET_break (0);
5848   }
5849   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5850 }
5851
5852
5853 /**
5854  * Handler for requests of seeting tunnel's buffering policy.
5855  *
5856  * @param cls Closure (unused).
5857  * @param client Identification of the client.
5858  * @param message The actual message.
5859  */
5860 static void
5861 handle_local_tunnel_buffer (void *cls, struct GNUNET_SERVER_Client *client,
5862                             const struct GNUNET_MessageHeader *message)
5863 {
5864   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
5865   struct MeshClient *c;
5866   struct MeshTunnel *t;
5867   MESH_TunnelNumber tid;
5868
5869   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5870               "Got a BUFFER request from client!\n");
5871
5872   /* Sanity check for client registration */
5873   if (NULL == (c = client_get (client)))
5874   {
5875     GNUNET_break (0);
5876     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5877     return;
5878   }
5879
5880   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
5881   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
5882
5883   /* Retrieve tunnel */
5884   tid = ntohl (tunnel_msg->tunnel_id);
5885   t = tunnel_get_by_local_id(c, tid);
5886   if (NULL == t)
5887   {
5888     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
5889     GNUNET_break (0);
5890     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5891     return;
5892   }
5893
5894   switch (ntohs(message->type))
5895   {
5896       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER:
5897           t->nobuffer = GNUNET_NO;
5898           break;
5899       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER:
5900           t->nobuffer = GNUNET_YES;
5901           break;
5902       default:
5903           GNUNET_break (0);
5904   }
5905
5906   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5907 }
5908
5909
5910 /**
5911  * Handler for connection requests to new peers
5912  *
5913  * @param cls closure
5914  * @param client identification of the client
5915  * @param message the actual message (PeerControl)
5916  */
5917 static void
5918 handle_local_connect_add (void *cls, struct GNUNET_SERVER_Client *client,
5919                           const struct GNUNET_MessageHeader *message)
5920 {
5921   struct GNUNET_MESH_PeerControl *peer_msg;
5922   struct MeshPeerInfo *peer_info;
5923   struct MeshClient *c;
5924   struct MeshTunnel *t;
5925   MESH_TunnelNumber tid;
5926
5927   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got connection request\n");
5928   /* Sanity check for client registration */
5929   if (NULL == (c = client_get (client)))
5930   {
5931     GNUNET_break (0);
5932     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5933     return;
5934   }
5935
5936   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
5937   /* Sanity check for message size */
5938   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
5939   {
5940     GNUNET_break (0);
5941     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5942     return;
5943   }
5944
5945   /* Tunnel exists? */
5946   tid = ntohl (peer_msg->tunnel_id);
5947   t = tunnel_get_by_local_id (c, tid);
5948   if (NULL == t)
5949   {
5950     GNUNET_break (0);
5951     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5952     return;
5953   }
5954
5955   /* Does client own tunnel? */
5956   if (t->owner->handle != client)
5957   {
5958     GNUNET_break (0);
5959     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5960     return;
5961   }
5962   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "     for %s\n",
5963               GNUNET_i2s (&peer_msg->peer));
5964   peer_info = peer_info_get (&peer_msg->peer);
5965
5966   tunnel_add_peer (t, peer_info);
5967   peer_info_connect (peer_info, t);
5968
5969   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5970   return;
5971 }
5972
5973
5974 /**
5975  * Handler for disconnection requests of peers in a tunnel
5976  *
5977  * @param cls closure
5978  * @param client identification of the client
5979  * @param message the actual message (PeerControl)
5980  */
5981 static void
5982 handle_local_connect_del (void *cls, struct GNUNET_SERVER_Client *client,
5983                           const struct GNUNET_MessageHeader *message)
5984 {
5985   struct GNUNET_MESH_PeerControl *peer_msg;
5986   struct MeshPeerInfo *peer_info;
5987   struct MeshClient *c;
5988   struct MeshTunnel *t;
5989   MESH_TunnelNumber tid;
5990
5991   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER DEL request\n");
5992   /* Sanity check for client registration */
5993   if (NULL == (c = client_get (client)))
5994   {
5995     GNUNET_break (0);
5996     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5997     return;
5998   }
5999   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6000   /* Sanity check for message size */
6001   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6002   {
6003     GNUNET_break (0);
6004     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6005     return;
6006   }
6007
6008   /* Tunnel exists? */
6009   tid = ntohl (peer_msg->tunnel_id);
6010   t = tunnel_get_by_local_id (c, tid);
6011   if (NULL == t)
6012   {
6013     GNUNET_break (0);
6014     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6015     return;
6016   }
6017   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
6018
6019   /* Does client own tunnel? */
6020   if (t->owner->handle != client)
6021   {
6022     GNUNET_break (0);
6023     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6024     return;
6025   }
6026
6027   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for peer %s\n",
6028               GNUNET_i2s (&peer_msg->peer));
6029   /* Is the peer in the tunnel? */
6030   peer_info =
6031       GNUNET_CONTAINER_multihashmap_get (t->peers, &peer_msg->peer.hashPubKey);
6032   if (NULL == peer_info)
6033   {
6034     GNUNET_break (0);
6035     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6036     return;
6037   }
6038
6039   /* Ok, delete peer from tunnel */
6040   GNUNET_CONTAINER_multihashmap_remove_all (t->peers,
6041                                             &peer_msg->peer.hashPubKey);
6042
6043   send_destroy_path (t, peer_info->id);
6044   tunnel_delete_peer (t, peer_info->id);
6045   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6046   return;
6047 }
6048
6049 /**
6050  * Handler for blacklist requests of peers in a tunnel
6051  *
6052  * @param cls closure
6053  * @param client identification of the client
6054  * @param message the actual message (PeerControl)
6055  */
6056 static void
6057 handle_local_blacklist (void *cls, struct GNUNET_SERVER_Client *client,
6058                           const struct GNUNET_MessageHeader *message)
6059 {
6060   struct GNUNET_MESH_PeerControl *peer_msg;
6061   struct MeshClient *c;
6062   struct MeshTunnel *t;
6063   MESH_TunnelNumber tid;
6064
6065   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER BLACKLIST request\n");
6066   /* Sanity check for client registration */
6067   if (NULL == (c = client_get (client)))
6068   {
6069     GNUNET_break (0);
6070     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6071     return;
6072   }
6073   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6074
6075   /* Sanity check for message size */
6076   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6077   {
6078     GNUNET_break (0);
6079     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6080     return;
6081   }
6082
6083   /* Tunnel exists? */
6084   tid = ntohl (peer_msg->tunnel_id);
6085   t = tunnel_get_by_local_id (c, tid);
6086   if (NULL == t)
6087   {
6088     GNUNET_break (0);
6089     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6090     return;
6091   }
6092   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
6093
6094   GNUNET_array_append(t->blacklisted, t->nblacklisted,
6095                       GNUNET_PEER_intern(&peer_msg->peer));
6096 }
6097
6098
6099 /**
6100  * Handler for unblacklist requests of peers in a tunnel
6101  *
6102  * @param cls closure
6103  * @param client identification of the client
6104  * @param message the actual message (PeerControl)
6105  */
6106 static void
6107 handle_local_unblacklist (void *cls, struct GNUNET_SERVER_Client *client,
6108                           const struct GNUNET_MessageHeader *message)
6109 {
6110   struct GNUNET_MESH_PeerControl *peer_msg;
6111   struct MeshClient *c;
6112   struct MeshTunnel *t;
6113   MESH_TunnelNumber tid;
6114   GNUNET_PEER_Id pid;
6115   unsigned int i;
6116
6117   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER UNBLACKLIST request\n");
6118   /* Sanity check for client registration */
6119   if (NULL == (c = client_get (client)))
6120   {
6121     GNUNET_break (0);
6122     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6123     return;
6124   }
6125   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6126
6127   /* Sanity check for message size */
6128   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6129   {
6130     GNUNET_break (0);
6131     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6132     return;
6133   }
6134
6135   /* Tunnel exists? */
6136   tid = ntohl (peer_msg->tunnel_id);
6137   t = tunnel_get_by_local_id (c, tid);
6138   if (NULL == t)
6139   {
6140     GNUNET_break (0);
6141     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6142     return;
6143   }
6144   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
6145
6146   /* if peer is not known, complain */
6147   pid = GNUNET_PEER_search (&peer_msg->peer);
6148   if (0 == pid)
6149   {
6150     GNUNET_break (0);
6151     return;
6152   }
6153
6154   /* search and remove from list */
6155   for (i = 0; i < t->nblacklisted; i++)
6156   {
6157     if (t->blacklisted[i] == pid)
6158     {
6159       t->blacklisted[i] = t->blacklisted[t->nblacklisted - 1];
6160       GNUNET_array_grow (t->blacklisted, t->nblacklisted, t->nblacklisted - 1);
6161       return;
6162     }
6163   }
6164
6165   /* if peer hasn't been blacklisted, complain */
6166   GNUNET_break (0);
6167 }
6168
6169
6170 /**
6171  * Handler for connection requests to new peers by type
6172  *
6173  * @param cls closure
6174  * @param client identification of the client
6175  * @param message the actual message (ConnectPeerByType)
6176  */
6177 static void
6178 handle_local_connect_by_type (void *cls, struct GNUNET_SERVER_Client *client,
6179                               const struct GNUNET_MessageHeader *message)
6180 {
6181   struct GNUNET_MESH_ConnectPeerByType *connect_msg;
6182   struct MeshClient *c;
6183   struct MeshTunnel *t;
6184   struct GNUNET_HashCode hash;
6185   MESH_TunnelNumber tid;
6186
6187   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got connect by type request\n");
6188   /* Sanity check for client registration */
6189   if (NULL == (c = client_get (client)))
6190   {
6191     GNUNET_break (0);
6192     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6193     return;
6194   }
6195
6196   connect_msg = (struct GNUNET_MESH_ConnectPeerByType *) message;
6197   /* Sanity check for message size */
6198   if (sizeof (struct GNUNET_MESH_ConnectPeerByType) !=
6199       ntohs (connect_msg->header.size))
6200   {
6201     GNUNET_break (0);
6202     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6203     return;
6204   }
6205
6206   /* Tunnel exists? */
6207   tid = ntohl (connect_msg->tunnel_id);
6208   t = tunnel_get_by_local_id (c, tid);
6209   if (NULL == t)
6210   {
6211     GNUNET_break (0);
6212     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6213     return;
6214   }
6215
6216   /* Does client own tunnel? */
6217   if (t->owner->handle != client)
6218   {
6219     GNUNET_break (0);
6220     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6221     return;
6222   }
6223
6224   /* Do WE have the service? */
6225   t->type = ntohl (connect_msg->type);
6226   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " type requested: %u\n", t->type);
6227   GNUNET_CRYPTO_hash (&t->type, sizeof (GNUNET_MESH_ApplicationType), &hash);
6228   if (GNUNET_CONTAINER_multihashmap_contains (applications, &hash) ==
6229       GNUNET_YES)
6230   {
6231     /* Yes! Fast forward, add ourselves to the tunnel and send the
6232      * good news to the client, and alert the destination client of
6233      * an incoming tunnel.
6234      *
6235      * FIXME send a path create to self, avoid code duplication
6236      */
6237     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " available locally\n");
6238     GNUNET_CONTAINER_multihashmap_put (t->peers, &my_full_id.hashPubKey,
6239                                        peer_info_get (&my_full_id),
6240                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
6241
6242     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " notifying client\n");
6243     send_client_peer_connected (t, myid);
6244     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Done\n");
6245     GNUNET_SERVER_receive_done (client, GNUNET_OK);
6246
6247     t->local_tid_dest = next_local_tid++;
6248     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
6249     GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
6250                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
6251
6252     return;
6253   }
6254   /* Ok, lets find a peer offering the service */
6255   if (NULL != t->dht_get_type)
6256   {
6257     GNUNET_DHT_get_stop (t->dht_get_type);
6258   }
6259   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " looking in DHT for %s\n",
6260               GNUNET_h2s (&hash));
6261   t->dht_get_type =
6262       GNUNET_DHT_get_start (dht_handle, 
6263                             GNUNET_BLOCK_TYPE_MESH_PEER_BY_TYPE,
6264                             &hash,
6265                             dht_replication_level,
6266                             GNUNET_DHT_RO_RECORD_ROUTE |
6267                             GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
6268                             NULL, 0,
6269                             &dht_get_type_handler, t);
6270
6271   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6272   return;
6273 }
6274
6275
6276 /**
6277  * Handler for connection requests to new peers by a string service description.
6278  *
6279  * @param cls closure
6280  * @param client identification of the client
6281  * @param message the actual message, which includes messages the client wants
6282  */
6283 static void
6284 handle_local_connect_by_string (void *cls, struct GNUNET_SERVER_Client *client,
6285                                 const struct GNUNET_MessageHeader *message)
6286 {
6287   struct GNUNET_MESH_ConnectPeerByString *msg;
6288   struct MeshRegexSearchContext *ctx;
6289   struct MeshRegexSearchInfo *info;
6290   struct GNUNET_DHT_GetHandle *get_h;
6291   struct GNUNET_HashCode key;
6292   struct MeshTunnel *t;
6293   struct MeshClient *c;
6294   MESH_TunnelNumber tid;
6295   const char *string;
6296   size_t size;
6297   size_t len;
6298   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6299               "Connect by string started\n");
6300   msg = (struct GNUNET_MESH_ConnectPeerByString *) message;
6301   size = htons (message->size);
6302
6303   /* Sanity check for client registration */
6304   if (NULL == (c = client_get (client)))
6305   {
6306     GNUNET_break (0);
6307     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6308     return;
6309   }
6310
6311   /* Message size sanity check */
6312   if (sizeof(struct GNUNET_MESH_ConnectPeerByString) >= size)
6313   {
6314     GNUNET_break (0);
6315     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6316     return;
6317   }
6318
6319   /* Tunnel exists? */
6320   tid = ntohl (msg->tunnel_id);
6321   t = tunnel_get_by_local_id (c, tid);
6322   if (NULL == t)
6323   {
6324     GNUNET_break (0);
6325     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6326     return;
6327   }
6328
6329   /* Does client own tunnel? */
6330   if (t->owner->handle != client)
6331   {
6332     GNUNET_break (0);
6333     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6334     return;
6335   }
6336
6337   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6338               "  on tunnel %s [%u]\n",
6339               GNUNET_i2s(&my_full_id),
6340               t->id.tid);
6341
6342   /* Only one connect_by_string allowed at the same time! */
6343   /* FIXME: allow more, return handle at api level to cancel, document */
6344   if (NULL != t->regex_ctx)
6345   {
6346     GNUNET_break (0);
6347     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6348     return;
6349   }
6350
6351   /* Find string itself */
6352   len = size - sizeof(struct GNUNET_MESH_ConnectPeerByString);
6353   string = (const char *) &msg[1];
6354
6355   /* Initialize context */
6356   size = GNUNET_REGEX_get_first_key(string, len, &key);
6357   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6358               "  consumed %u bits out of %u\n", size, len);
6359   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6360               "  looking for %s\n", GNUNET_h2s (&key));
6361
6362   info = GNUNET_malloc (sizeof (struct MeshRegexSearchInfo));
6363   info->t = t;
6364   info->description = GNUNET_malloc (len + 1);
6365   memcpy (info->description, string, len);
6366   info->description[len] = '\0';
6367   info->dht_get_handles = GNUNET_CONTAINER_multihashmap_create(32);
6368   info->dht_get_results = GNUNET_CONTAINER_multihashmap_create(32);
6369   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   string: %s\n", info->description);
6370
6371   ctx = GNUNET_malloc (sizeof (struct MeshRegexSearchContext));
6372   ctx->position = size;
6373   ctx->info = info;
6374   t->regex_ctx = ctx;
6375
6376   GNUNET_array_append (info->contexts, info->n_contexts, ctx);
6377
6378   /* Start search in DHT */
6379   get_h = GNUNET_DHT_get_start (dht_handle,    /* handle */
6380                                 GNUNET_BLOCK_TYPE_MESH_REGEX, /* type */
6381                                 &key,     /* key to search */
6382                                 dht_replication_level, /* replication level */
6383                                 GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
6384                                 NULL,       /* xquery */ // FIXME BLOOMFILTER
6385                                 0,     /* xquery bits */ // FIXME BLOOMFILTER SIZE
6386                                 &dht_get_string_handler, ctx);
6387
6388   GNUNET_break (GNUNET_OK ==
6389                 GNUNET_CONTAINER_multihashmap_put(info->dht_get_handles,
6390                                                   &key,
6391                                                   get_h,
6392                                                   GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
6393
6394   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6395   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "connect by string processed\n");
6396 }
6397
6398
6399 /**
6400  * Handler for client traffic directed to one peer
6401  *
6402  * @param cls closure
6403  * @param client identification of the client
6404  * @param message the actual message
6405  */
6406 static void
6407 handle_local_unicast (void *cls, struct GNUNET_SERVER_Client *client,
6408                       const struct GNUNET_MessageHeader *message)
6409 {
6410   struct MeshClient *c;
6411   struct MeshTunnel *t;
6412   struct MeshPeerInfo *pi;
6413   struct GNUNET_MESH_Unicast *data_msg;
6414   MESH_TunnelNumber tid;
6415   size_t size;
6416
6417   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6418               "Got a unicast request from a client!\n");
6419
6420   /* Sanity check for client registration */
6421   if (NULL == (c = client_get (client)))
6422   {
6423     GNUNET_break (0);
6424     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6425     return;
6426   }
6427   data_msg = (struct GNUNET_MESH_Unicast *) message;
6428   /* Sanity check for message size */
6429   size = ntohs (message->size);
6430   if (sizeof (struct GNUNET_MESH_Unicast) +
6431       sizeof (struct GNUNET_MessageHeader) > size)
6432   {
6433     GNUNET_break (0);
6434     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6435     return;
6436   }
6437
6438   /* Tunnel exists? */
6439   tid = ntohl (data_msg->tid);
6440   t = tunnel_get_by_local_id (c, tid);
6441   if (NULL == t)
6442   {
6443     GNUNET_break (0);
6444     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6445     return;
6446   }
6447
6448   /*  Is it a local tunnel? Then, does client own the tunnel? */
6449   if (t->owner->handle != client)
6450   {
6451     GNUNET_break (0);
6452     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6453     return;
6454   }
6455
6456   pi = GNUNET_CONTAINER_multihashmap_get (t->peers,
6457                                           &data_msg->destination.hashPubKey);
6458   /* Is the selected peer in the tunnel? */
6459   if (NULL == pi)
6460   {
6461     GNUNET_break (0);
6462     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6463     return;
6464   }
6465
6466   /* Ok, everything is correct, send the message
6467    * (pretend we got it from a mesh peer)
6468    */
6469   {
6470     char buf[ntohs (message->size)] GNUNET_ALIGN;
6471     struct GNUNET_MESH_Unicast *copy;
6472
6473     /* Work around const limitation */
6474     copy = (struct GNUNET_MESH_Unicast *) buf;
6475     memcpy (buf, data_msg, size);
6476     copy->oid = my_full_id;
6477     copy->tid = htonl (t->id.tid);
6478     copy->ttl = htonl (default_ttl);
6479     copy->pid = htonl (t->pid + 1);
6480     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6481                 "  calling generic handler...\n");
6482     handle_mesh_data_unicast (NULL, &my_full_id, &copy->header, NULL, 0);
6483   }
6484   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "receive done OK\n");
6485   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6486   return;
6487 }
6488
6489
6490 /**
6491  * Handler for client traffic directed to the origin
6492  *
6493  * @param cls closure
6494  * @param client identification of the client
6495  * @param message the actual message
6496  */
6497 static void
6498 handle_local_to_origin (void *cls, struct GNUNET_SERVER_Client *client,
6499                         const struct GNUNET_MessageHeader *message)
6500 {
6501   struct GNUNET_MESH_ToOrigin *data_msg;
6502   struct GNUNET_PeerIdentity id;
6503   struct MeshClient *c;
6504   struct MeshTunnel *t;
6505   MESH_TunnelNumber tid;
6506   size_t size;
6507
6508   /* Sanity check for client registration */
6509   if (NULL == (c = client_get (client)))
6510   {
6511     GNUNET_break (0);
6512     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6513     return;
6514   }
6515   data_msg = (struct GNUNET_MESH_ToOrigin *) message;
6516   /* Sanity check for message size */
6517   size = ntohs (message->size);
6518   if (sizeof (struct GNUNET_MESH_ToOrigin) +
6519       sizeof (struct GNUNET_MessageHeader) > size)
6520   {
6521     GNUNET_break (0);
6522     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6523     return;
6524   }
6525
6526   /* Tunnel exists? */
6527   tid = ntohl (data_msg->tid);
6528   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6529               "Got a ToOrigin request from a client! Tunnel %X\n", tid);
6530   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
6531   {
6532     GNUNET_break (0);
6533     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6534     return;
6535   }
6536   t = tunnel_get_by_local_id (c, tid);
6537   if (NULL == t)
6538   {
6539     GNUNET_break (0);
6540     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6541     return;
6542   }
6543
6544   /*  It should be sent by someone who has this as incoming tunnel. */
6545   if (-1 == client_knows_tunnel (c, t))
6546   {
6547     GNUNET_break (0);
6548     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6549     return;
6550   }
6551   GNUNET_PEER_resolve (t->id.oid, &id);
6552
6553   /* Ok, everything is correct, send the message
6554    * (pretend we got it from a mesh peer)
6555    */
6556   {
6557     char buf[ntohs (message->size)] GNUNET_ALIGN;
6558     struct GNUNET_MESH_ToOrigin *copy;
6559
6560     /* Work around const limitation */
6561     copy = (struct GNUNET_MESH_ToOrigin *) buf;
6562     memcpy (buf, data_msg, size);
6563     copy->oid = id;
6564     copy->tid = htonl (t->id.tid);
6565     copy->sender = my_full_id;
6566     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6567                 "  calling generic handler...\n");
6568     handle_mesh_data_to_orig (NULL, &my_full_id, &copy->header, NULL, 0);
6569   }
6570   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6571   return;
6572 }
6573
6574
6575 /**
6576  * Handler for client traffic directed to all peers in a tunnel
6577  *
6578  * @param cls closure
6579  * @param client identification of the client
6580  * @param message the actual message
6581  */
6582 static void
6583 handle_local_multicast (void *cls, struct GNUNET_SERVER_Client *client,
6584                         const struct GNUNET_MessageHeader *message)
6585 {
6586   struct MeshClient *c;
6587   struct MeshTunnel *t;
6588   struct GNUNET_MESH_Multicast *data_msg;
6589   MESH_TunnelNumber tid;
6590
6591   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6592               "Got a multicast request from a client!\n");
6593
6594   /* Sanity check for client registration */
6595   if (NULL == (c = client_get (client)))
6596   {
6597     GNUNET_break (0);
6598     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6599     return;
6600   }
6601   data_msg = (struct GNUNET_MESH_Multicast *) message;
6602   /* Sanity check for message size */
6603   if (sizeof (struct GNUNET_MESH_Multicast) +
6604       sizeof (struct GNUNET_MessageHeader) > ntohs (data_msg->header.size))
6605   {
6606     GNUNET_break (0);
6607     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6608     return;
6609   }
6610
6611   /* Tunnel exists? */
6612   tid = ntohl (data_msg->tid);
6613   t = tunnel_get_by_local_id (c, tid);
6614   if (NULL == t)
6615   {
6616     GNUNET_break (0);
6617     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6618     return;
6619   }
6620
6621   /* Does client own tunnel? */
6622   if (t->owner->handle != client)
6623   {
6624     GNUNET_break (0);
6625     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6626     return;
6627   }
6628
6629   {
6630     char buf[ntohs (message->size)] GNUNET_ALIGN;
6631     struct GNUNET_MESH_Multicast *copy;
6632
6633     copy = (struct GNUNET_MESH_Multicast *) buf;
6634     memcpy (buf, message, ntohs (message->size));
6635     copy->oid = my_full_id;
6636     copy->tid = htonl (t->id.tid);
6637     copy->ttl = htonl (default_ttl);
6638     copy->pid = htonl (t->pid + 1);
6639     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6640                 "  calling generic handler...\n");
6641     handle_mesh_data_multicast (client, &my_full_id, &copy->header, NULL, 0);
6642   }
6643
6644   /* receive done gets called when last copy is sent to a neighbor */
6645   return;
6646 }
6647
6648
6649 /**
6650  * Handler for client ACKs for payload traffic.
6651  *
6652  * @param cls Closure (unused).
6653  * @param client Identification of the client.
6654  * @param message The actual message.
6655  */
6656 static void
6657 handle_local_ack (void *cls, struct GNUNET_SERVER_Client *client,
6658                   const struct GNUNET_MessageHeader *message)
6659 {
6660   struct GNUNET_MESH_LocalAck *msg;
6661   struct MeshTunnel *t;
6662   struct MeshClient *c;
6663   MESH_TunnelNumber tid;
6664
6665   /* Sanity check for client registration */
6666   if (NULL == (c = client_get (client)))
6667   {
6668     GNUNET_break (0);
6669     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6670     return;
6671   }
6672
6673   msg = (struct GNUNET_MESH_LocalAck *) message;
6674   /* Tunnel exists? */
6675   tid = ntohl (msg->tunnel_id);
6676   t = tunnel_get_by_local_id (c, tid);
6677   if (NULL == t)
6678   {
6679     GNUNET_break (0);
6680     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6681     return;
6682   }
6683
6684   /* Does client own tunnel? */
6685   if (NULL != t->owner && t->owner->handle == client)
6686   {
6687     GNUNET_break (0);
6688     // FIXME TODO
6689   }
6690   else
6691   {
6692     tunnel_set_client_ack (t, c, ntohl (msg->max_pid));
6693   }
6694
6695   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6696   return;
6697 }
6698
6699
6700 /**
6701  * Functions to handle messages from clients
6702  */
6703 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
6704   {&handle_local_new_client, NULL,
6705    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
6706   {&handle_local_announce_regex, NULL,
6707    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ANNOUNCE_REGEX, 0},
6708   {&handle_local_tunnel_create, NULL,
6709    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
6710    sizeof (struct GNUNET_MESH_TunnelMessage)},
6711   {&handle_local_tunnel_destroy, NULL,
6712    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
6713    sizeof (struct GNUNET_MESH_TunnelMessage)},
6714   {&handle_local_tunnel_speed, NULL,
6715    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MIN,
6716    sizeof (struct GNUNET_MESH_TunnelMessage)},
6717   {&handle_local_tunnel_speed, NULL,
6718    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MAX,
6719    sizeof (struct GNUNET_MESH_TunnelMessage)},
6720   {&handle_local_tunnel_buffer, NULL,
6721    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER,
6722    sizeof (struct GNUNET_MESH_TunnelMessage)},
6723   {&handle_local_tunnel_buffer, NULL,
6724    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER,
6725    sizeof (struct GNUNET_MESH_TunnelMessage)},
6726   {&handle_local_connect_add, NULL,
6727    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD,
6728    sizeof (struct GNUNET_MESH_PeerControl)},
6729   {&handle_local_connect_del, NULL,
6730    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL,
6731    sizeof (struct GNUNET_MESH_PeerControl)},
6732   {&handle_local_blacklist, NULL,
6733    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_BLACKLIST,
6734    sizeof (struct GNUNET_MESH_PeerControl)},
6735   {&handle_local_unblacklist, NULL,
6736    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_UNBLACKLIST,
6737    sizeof (struct GNUNET_MESH_PeerControl)},
6738   {&handle_local_connect_by_type, NULL,
6739    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE,
6740    sizeof (struct GNUNET_MESH_ConnectPeerByType)},
6741   {&handle_local_connect_by_string, NULL,
6742    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_STRING, 0},
6743   {&handle_local_unicast, NULL,
6744    GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
6745   {&handle_local_to_origin, NULL,
6746    GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
6747   {&handle_local_multicast, NULL,
6748    GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
6749   {&handle_local_ack, NULL,
6750    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK,
6751    sizeof (struct GNUNET_MESH_LocalAck)},
6752   {NULL, NULL, 0, 0}
6753 };
6754
6755
6756 /**
6757  * To be called on core init/fail.
6758  *
6759  * @param cls service closure
6760  * @param server handle to the server for this service
6761  * @param identity the public identity of this peer
6762  */
6763 static void
6764 core_init (void *cls, struct GNUNET_CORE_Handle *server,
6765            const struct GNUNET_PeerIdentity *identity)
6766 {
6767   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
6768   core_handle = server;
6769   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)) ||
6770       NULL == server)
6771   {
6772     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
6773     GNUNET_SCHEDULER_shutdown ();
6774   }
6775   return;
6776 }
6777
6778
6779 /**
6780  * Method called whenever a given peer connects.
6781  *
6782  * @param cls closure
6783  * @param peer peer identity this notification is about
6784  * @param atsi performance data for the connection
6785  * @param atsi_count number of records in 'atsi'
6786  */
6787 static void
6788 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
6789               const struct GNUNET_ATS_Information *atsi,
6790               unsigned int atsi_count)
6791 {
6792   struct MeshPeerInfo *peer_info;
6793   struct MeshPeerPath *path;
6794
6795   DEBUG_CONN ("Peer connected\n");
6796   DEBUG_CONN ("     %s\n", GNUNET_i2s (&my_full_id));
6797   peer_info = peer_info_get (peer);
6798   if (myid == peer_info->id)
6799   {
6800     DEBUG_CONN ("     (self)\n");
6801     return;
6802   }
6803   else
6804   {
6805     DEBUG_CONN ("     %s\n", GNUNET_i2s (peer));
6806   }
6807   path = path_new (2);
6808   path->peers[0] = myid;
6809   path->peers[1] = peer_info->id;
6810   GNUNET_PEER_change_rc (myid, 1);
6811   GNUNET_PEER_change_rc (peer_info->id, 1);
6812   peer_info_add_path (peer_info, path, GNUNET_YES);
6813   GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
6814   return;
6815 }
6816
6817
6818 /**
6819  * Method called whenever a peer disconnects.
6820  *
6821  * @param cls closure
6822  * @param peer peer identity this notification is about
6823  */
6824 static void
6825 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
6826 {
6827   struct MeshPeerInfo *pi;
6828   struct MeshPeerQueue *q;
6829   struct MeshPeerQueue *n;
6830
6831   DEBUG_CONN ("Peer disconnected\n");
6832   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
6833   if (NULL == pi)
6834   {
6835     GNUNET_break (0);
6836     return;
6837   }
6838   q = pi->queue_head;
6839   while (NULL != q)
6840   {
6841       n = q->next;
6842       if (q->peer == pi)
6843       {
6844         /* try to reroute this traffic instead */
6845         queue_destroy(q, GNUNET_YES);
6846       }
6847       q = n;
6848   }
6849   peer_info_remove_path (pi, pi->id, myid);
6850   if (myid == pi->id)
6851   {
6852     DEBUG_CONN ("     (self)\n");
6853   }
6854   GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
6855   return;
6856 }
6857
6858
6859 /******************************************************************************/
6860 /************************      MAIN FUNCTIONS      ****************************/
6861 /******************************************************************************/
6862
6863 /**
6864  * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
6865  *
6866  * @param cls closure
6867  * @param key current key code
6868  * @param value value in the hash map
6869  * @return GNUNET_YES if we should continue to iterate,
6870  *         GNUNET_NO if not.
6871  */
6872 static int
6873 shutdown_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
6874 {
6875   struct MeshTunnel *t = value;
6876
6877   tunnel_destroy (t);
6878   return GNUNET_YES;
6879 }
6880
6881 /**
6882  * Iterator over peer hash map entries to destroy the tunnel during shutdown.
6883  *
6884  * @param cls closure
6885  * @param key current key code
6886  * @param value value in the hash map
6887  * @return GNUNET_YES if we should continue to iterate,
6888  *         GNUNET_NO if not.
6889  */
6890 static int
6891 shutdown_peer (void *cls, const struct GNUNET_HashCode * key, void *value)
6892 {
6893   struct MeshPeerInfo *p = value;
6894   struct MeshPeerQueue *q;
6895   struct MeshPeerQueue *n;
6896
6897   q = p->queue_head;
6898   while (NULL != q)
6899   {
6900       n = q->next;
6901       if (q->peer == p)
6902       {
6903         queue_destroy(q, GNUNET_YES);
6904       }
6905       q = n;
6906   }
6907   peer_info_destroy (p);
6908   return GNUNET_YES;
6909 }
6910
6911 /**
6912  * Task run during shutdown.
6913  *
6914  * @param cls unused
6915  * @param tc unused
6916  */
6917 static void
6918 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
6919 {
6920   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
6921
6922   if (core_handle != NULL)
6923   {
6924     GNUNET_CORE_disconnect (core_handle);
6925     core_handle = NULL;
6926   }
6927   GNUNET_CONTAINER_multihashmap_iterate (tunnels, &shutdown_tunnel, NULL);
6928   GNUNET_CONTAINER_multihashmap_iterate (peers, &shutdown_peer, NULL);
6929   if (dht_handle != NULL)
6930   {
6931     GNUNET_DHT_disconnect (dht_handle);
6932     dht_handle = NULL;
6933   }
6934   if (nc != NULL)
6935   {
6936     GNUNET_SERVER_notification_context_destroy (nc);
6937     nc = NULL;
6938   }
6939   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
6940   {
6941     GNUNET_SCHEDULER_cancel (announce_id_task);
6942     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
6943   }
6944   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
6945 }
6946
6947 /**
6948  * Process mesh requests.
6949  *
6950  * @param cls closure
6951  * @param server the initialized server
6952  * @param c configuration to use
6953  */
6954 static void
6955 run (void *cls, struct GNUNET_SERVER_Handle *server,
6956      const struct GNUNET_CONFIGURATION_Handle *c)
6957 {
6958   struct MeshPeerInfo *peer;
6959   struct MeshPeerPath *p;
6960   char *keyfile;
6961
6962   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
6963   server_handle = server;
6964   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
6965                                      NULL,      /* Closure passed to MESH functions */
6966                                      &core_init,        /* Call core_init once connected */
6967                                      &core_connect,     /* Handle connects */
6968                                      &core_disconnect,  /* remove peers on disconnects */
6969                                      NULL,      /* Don't notify about all incoming messages */
6970                                      GNUNET_NO, /* For header only in notification */
6971                                      NULL,      /* Don't notify about all outbound messages */
6972                                      GNUNET_NO, /* For header-only out notification */
6973                                      core_handlers);    /* Register these handlers */
6974
6975   if (core_handle == NULL)
6976   {
6977     GNUNET_break (0);
6978     GNUNET_SCHEDULER_shutdown ();
6979     return;
6980   }
6981
6982   if (GNUNET_OK !=
6983       GNUNET_CONFIGURATION_get_value_filename (c, "GNUNETD", "HOSTKEY",
6984                                                &keyfile))
6985   {
6986     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6987                 _
6988                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
6989                 "hostkey");
6990     GNUNET_SCHEDULER_shutdown ();
6991     return;
6992   }
6993
6994   if (GNUNET_OK !=
6995       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_PATH_TIME",
6996                                            &refresh_path_time))
6997   {
6998     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6999                 _
7000                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7001                 "refresh path time");
7002     GNUNET_SCHEDULER_shutdown ();
7003     return;
7004   }
7005
7006   if (GNUNET_OK !=
7007       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "APP_ANNOUNCE_TIME",
7008                                            &app_announce_time))
7009   {
7010     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7011                 _
7012                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7013                 "app announce time");
7014     GNUNET_SCHEDULER_shutdown ();
7015     return;
7016   }
7017
7018   if (GNUNET_OK !=
7019       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "ID_ANNOUNCE_TIME",
7020                                            &id_announce_time))
7021   {
7022     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7023                 _
7024                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7025                 "id announce time");
7026     GNUNET_SCHEDULER_shutdown ();
7027     return;
7028   }
7029
7030   if (GNUNET_OK !=
7031       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "UNACKNOWLEDGED_WAIT",
7032                                            &unacknowledged_wait_time))
7033   {
7034     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7035                 _
7036                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7037                 "unacknowledged wait time");
7038     GNUNET_SCHEDULER_shutdown ();
7039     return;
7040   }
7041
7042   if (GNUNET_OK !=
7043       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "CONNECT_TIMEOUT",
7044                                            &connect_timeout))
7045   {
7046     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7047                 _
7048                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7049                 "connect timeout");
7050     GNUNET_SCHEDULER_shutdown ();
7051     return;
7052   }
7053
7054   if (GNUNET_OK !=
7055       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
7056                                              &max_msgs_queue))
7057   {
7058     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7059                 _
7060                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7061                 "max msgs queue");
7062     GNUNET_SCHEDULER_shutdown ();
7063     return;
7064   }
7065
7066   if (GNUNET_OK !=
7067       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_TUNNELS",
7068                                              &max_tunnels))
7069   {
7070     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7071                 _
7072                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7073                 "max tunnels");
7074     GNUNET_SCHEDULER_shutdown ();
7075     return;
7076   }
7077
7078   if (GNUNET_OK !=
7079       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
7080                                              &default_ttl))
7081   {
7082     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7083                 _
7084                 ("Mesh service is lacking key configuration settings (%s). Using default (%u).\n"),
7085                 "default ttl", 64);
7086     default_ttl = 64;
7087   }
7088
7089   if (GNUNET_OK !=
7090       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DHT_REPLICATION_LEVEL",
7091                                              &dht_replication_level))
7092   {
7093     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7094                 _
7095                 ("Mesh service is lacking key configuration settings (%s). Using default (%u).\n"),
7096                 "dht replication level", 10);
7097     dht_replication_level = 10;
7098   }
7099
7100   
7101   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
7102   GNUNET_free (keyfile);
7103   if (my_private_key == NULL)
7104   {
7105     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7106                 _("Mesh service could not access hostkey.  Exiting.\n"));
7107     GNUNET_SCHEDULER_shutdown ();
7108     return;
7109   }
7110   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
7111   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
7112                       &my_full_id.hashPubKey);
7113   myid = GNUNET_PEER_intern (&my_full_id);
7114
7115 //   transport_handle = GNUNET_TRANSPORT_connect(c,
7116 //                                               &my_full_id,
7117 //                                               NULL,
7118 //                                               NULL,
7119 //                                               NULL,
7120 //                                               NULL);
7121
7122   dht_handle = GNUNET_DHT_connect (c, 64);
7123   if (dht_handle == NULL)
7124   {
7125     GNUNET_break (0);
7126   }
7127
7128   stats = GNUNET_STATISTICS_create ("mesh", c);
7129
7130
7131   next_tid = 0;
7132   next_local_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
7133
7134   tunnels = GNUNET_CONTAINER_multihashmap_create (32);
7135   incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
7136   peers = GNUNET_CONTAINER_multihashmap_create (32);
7137   applications = GNUNET_CONTAINER_multihashmap_create (32);
7138   types = GNUNET_CONTAINER_multihashmap_create (32);
7139
7140   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
7141   nc = GNUNET_SERVER_notification_context_create (server_handle, 1);
7142   GNUNET_SERVER_disconnect_notify (server_handle,
7143                                    &handle_local_client_disconnect, NULL);
7144
7145
7146   clients = NULL;
7147   clients_tail = NULL;
7148   next_client_id = 0;
7149
7150   announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
7151   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
7152
7153   /* Create a peer_info for the local peer */
7154   peer = peer_info_get (&my_full_id);
7155   p = path_new (1);
7156   p->peers[0] = myid;
7157   GNUNET_PEER_change_rc (myid, 1);
7158   peer_info_add_path (peer, p, GNUNET_YES);
7159
7160   /* Scheduled the task to clean up when shutdown is called */
7161   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
7162                                 NULL);
7163
7164   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "end of run()\n");
7165 }
7166
7167 /**
7168  * The main function for the mesh service.
7169  *
7170  * @param argc number of arguments from the command line
7171  * @param argv command line arguments
7172  * @return 0 ok, 1 on error
7173  */
7174 int
7175 main (int argc, char *const *argv)
7176 {
7177   int ret;
7178
7179   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
7180   ret =
7181       (GNUNET_OK ==
7182        GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
7183                            NULL)) ? 0 : 1;
7184   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");
7185
7186   return ret;
7187 }