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