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