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