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