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