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