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