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