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