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