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