9db69f2f5cd53d2398afcb32b91362716188ea60
[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_log (GNUNET_ERROR_TYPE_DEBUG,
3350               "  no one to send data to\n");
3351     GNUNET_free (mdata->data);
3352     GNUNET_free (mdata->reference_counter);
3353     if (NULL != mdata->task)
3354     {
3355       GNUNET_SCHEDULER_cancel(*(mdata->task));
3356       GNUNET_free (mdata->task);
3357       GNUNET_SERVER_receive_done (t->owner->handle, GNUNET_OK);
3358     }
3359     GNUNET_free (mdata);
3360     t->fwd_queue_n--;
3361   }
3362   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3363               " sending a multicast packet done\n");
3364   return;
3365 }
3366
3367
3368 /**
3369  * Increase the SKIP value of all peers that
3370  * have not received a unicast message.
3371  *
3372  * @param cls Closure (ID of the peer that HAS received the message).
3373  * @param key ID of the neighbor.
3374  * @param value Information about the neighbor.
3375  *
3376  * @return GNUNET_YES to keep iterating.
3377  */
3378 static int
3379 tunnel_add_skip (void *cls,
3380                  const struct GNUNET_HashCode * key,
3381                  void *value)
3382 {
3383   struct GNUNET_PeerIdentity *neighbor = cls;
3384   struct MeshTunnelChildInfo *cinfo = value;
3385
3386   /* TODO compare only pointers? key == neighbor? */
3387   if (0 == memcmp (&neighbor->hashPubKey, key, sizeof (struct GNUNET_HashCode)))
3388   {
3389     return GNUNET_YES;
3390   }
3391   cinfo->skip++;
3392   return GNUNET_YES;
3393 }
3394
3395
3396 /**
3397  * @brief Get neighbor's Flow Control information.
3398  *
3399  * Retrieves the MeshTunnelChildInfo containing Flow Control data about a direct
3400  * descendant of the local node in a certain tunnel.
3401  * If the info is not yet there (recently created path), creates the data struct
3402  * and inserts it into the tunnel info, initialized to the current tunnel ACK
3403  * values.
3404  *
3405  * @param t Tunnel related.
3406  * @param peer Neighbor whose Flow Control info is needed.
3407  *
3408  * @return Neighbor's Flow Control info.
3409  */
3410 static struct MeshTunnelChildInfo *
3411 tunnel_get_neighbor_fc (const struct MeshTunnel *t,
3412                         const struct GNUNET_PeerIdentity *peer)
3413 {
3414   struct MeshTunnelChildInfo *cinfo;
3415   cinfo = GNUNET_CONTAINER_multihashmap_get (t->children_fc,
3416                                              &peer->hashPubKey);
3417   if (NULL == cinfo)
3418   {
3419     uint32_t delta;
3420
3421     cinfo = GNUNET_malloc (sizeof (struct MeshTunnelChildInfo));
3422     cinfo->id = GNUNET_PEER_intern (peer);
3423     cinfo->skip = t->fwd_pid;
3424
3425     delta = t->nobuffer ? 1 : INITIAL_WINDOW_SIZE - 1;
3426     cinfo->fwd_ack = t->fwd_pid + delta;
3427     cinfo->bck_ack = delta;
3428
3429     GNUNET_assert (GNUNET_OK ==
3430       GNUNET_CONTAINER_multihashmap_put (t->children_fc,
3431                                          &peer->hashPubKey,
3432                                          cinfo,
3433                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
3434   }
3435   return cinfo;
3436 }
3437
3438
3439 /**
3440  * Get the Flow Control info of a client.
3441  * 
3442  * @param t Tunnel on which to look.
3443  * @param c Client whose ACK to get.
3444  * 
3445  * @return ACK value.
3446  */
3447 static struct MeshTunnelClientInfo *
3448 tunnel_get_client_fc (struct MeshTunnel *t,
3449                       struct MeshClient *c)
3450 {
3451   unsigned int i;
3452
3453   for (i = 0; i < t->nclients; i++)
3454   {
3455     if (t->clients[i] != c)
3456       continue;
3457     return &t->clients_fc[i];
3458   }
3459   GNUNET_assert (0);
3460   return NULL; // avoid compiler / coverity complaints
3461 }
3462
3463
3464 /**
3465  * Iterator to get the appropiate ACK value from all children nodes.
3466  *
3467  * @param cls Closue (tunnel).
3468  * @param id Id of the child node.
3469  */
3470 static void
3471 tunnel_get_child_fwd_ack (void *cls,
3472                           GNUNET_PEER_Id id)
3473 {
3474   struct GNUNET_PeerIdentity peer_id;
3475   struct MeshTunnelChildInfo *cinfo;
3476   struct MeshTunnelChildIteratorContext *ctx = cls;
3477   struct MeshTunnel *t = ctx->t;
3478   uint32_t ack;
3479
3480   GNUNET_PEER_resolve (id, &peer_id);
3481   cinfo = tunnel_get_neighbor_fc (t, &peer_id);
3482   ack = cinfo->fwd_ack;
3483
3484   ctx->nchildren++;
3485   if (GNUNET_NO == ctx->init)
3486   {
3487     ctx->max_child_ack = ack;
3488     ctx->init = GNUNET_YES;
3489   }
3490
3491   if (GNUNET_YES == t->speed_min)
3492   {
3493     ctx->max_child_ack = ctx->max_child_ack > ack ? ack : ctx->max_child_ack;
3494   }
3495   else
3496   {
3497     ctx->max_child_ack = ctx->max_child_ack > ack ? ctx->max_child_ack : ack;
3498   }
3499
3500 }
3501
3502
3503 /**
3504  * Get the maximum PID allowed to transmit to any
3505  * tunnel child of the local peer, depending on the tunnel
3506  * buffering/speed settings.
3507  *
3508  * @param t Tunnel.
3509  *
3510  * @return Maximum PID allowed (uint32 MAX), -1 if node has no children.
3511  */
3512 static int64_t
3513 tunnel_get_children_fwd_ack (struct MeshTunnel *t)
3514 {
3515   struct MeshTunnelChildIteratorContext ctx;
3516   ctx.t = t;
3517   ctx.max_child_ack = 0;
3518   ctx.nchildren = 0;
3519   tree_iterate_children (t->tree, tunnel_get_child_fwd_ack, &ctx);
3520
3521   if (0 == ctx.nchildren)
3522   {
3523     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3524             "  tunnel has no children, no FWD ACK\n");
3525     return -1LL;
3526   }
3527
3528   if (GNUNET_YES == t->nobuffer && GMC_is_pid_bigger(ctx.max_child_ack, t->fwd_pid))
3529     ctx.max_child_ack = t->fwd_pid + 1; // Might overflow, it's ok.
3530
3531   return (int64_t) ctx.max_child_ack;
3532 }
3533
3534
3535 /**
3536  * Set the FWD ACK value of a client in a particular tunnel.
3537  * 
3538  * @param t Tunnel affected.
3539  * @param c Client whose ACK to set.
3540  * @param ack ACK value.
3541  */
3542 static void
3543 tunnel_set_client_fwd_ack (struct MeshTunnel *t,
3544                            struct MeshClient *c, 
3545                            uint32_t ack)
3546 {
3547   unsigned int i;
3548
3549   for (i = 0; i < t->nclients; i++)
3550   {
3551     if (t->clients[i] != c)
3552       continue;
3553     t->clients_fc[i].fwd_ack = ack;
3554     return;
3555   }
3556   GNUNET_break (0);
3557 }
3558
3559
3560 /**
3561  * Get the highest ACK value of all clients in a particular tunnel,
3562  * according to the buffering/speed settings.
3563  * 
3564  * @param t Tunnel on which to look.
3565  * 
3566  * @return Corresponding ACK value (max uint32_t).
3567  *         If no clients are suscribed, -1.
3568  */
3569 static int64_t
3570 tunnel_get_clients_fwd_ack (struct MeshTunnel *t)
3571 {
3572   unsigned int i;
3573   int64_t ack;
3574
3575   if (0 == t->nclients)
3576   {
3577     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3578                 "  tunnel has no clients, no FWD ACK\n");
3579     return -1LL;
3580   }
3581
3582   for (ack = -1, i = 0; i < t->nclients; i++)
3583   {
3584     if (-1 == ack ||
3585         (GNUNET_YES == t->speed_min &&
3586          GNUNET_YES == GMC_is_pid_bigger (ack, t->clients_fc[i].fwd_ack)) ||
3587         (GNUNET_NO == t->speed_min &&
3588          GNUNET_YES == GMC_is_pid_bigger (t->clients_fc[i].fwd_ack, ack)))
3589     {
3590       ack = t->clients_fc[i].fwd_ack;
3591     }
3592   }
3593
3594   if (GNUNET_YES == t->nobuffer && GMC_is_pid_bigger(ack, t->fwd_pid))
3595     ack = (uint32_t) t->fwd_pid + 1; // Might overflow, it's ok.
3596
3597   return (uint32_t) ack;
3598 }
3599
3600
3601 /**
3602  * Get the current fwd ack value for a tunnel, taking in account the tunnel
3603  * mode and the status of all children nodes.
3604  *
3605  * @param t Tunnel.
3606  *
3607  * @return Maximum PID allowed.
3608  */
3609 static uint32_t
3610 tunnel_get_fwd_ack (struct MeshTunnel *t)
3611 {
3612   uint32_t count;
3613   uint32_t buffer_free;
3614   int64_t child_ack;
3615   int64_t client_ack;
3616   uint32_t ack;
3617
3618   count = t->fwd_pid - t->skip;
3619   buffer_free = t->fwd_queue_max - t->fwd_queue_n;
3620   ack = count + buffer_free; // Might overflow 32 bits, it's ok!
3621   child_ack = tunnel_get_children_fwd_ack (t);
3622   client_ack = tunnel_get_clients_fwd_ack (t);
3623   if (-1 == child_ack)
3624   {
3625     // Node has no children, child_ack AND core buffer are irrelevant.
3626     GNUNET_break (-1 != client_ack); // No children AND no clients? Not good! // FIXME fc
3627     return (uint32_t) client_ack;
3628   }
3629
3630   if (GNUNET_YES == t->speed_min)
3631   {
3632     ack = GMC_min_pid ((uint32_t) child_ack, ack);
3633     ack = GMC_min_pid ((uint32_t) client_ack, ack);
3634   }
3635   else
3636   {
3637     ack = GMC_max_pid ((uint32_t) child_ack, ack);
3638     ack = GMC_max_pid ((uint32_t) client_ack, ack);
3639   }
3640   if (GNUNET_YES == t->nobuffer && GMC_is_pid_bigger(ack, t->fwd_pid))
3641     ack = t->fwd_pid + 1; // Might overflow 32 bits, it's ok!
3642   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "c %u, bf %u, ch %u, cl %u, ACK: %u\n",
3643               count, buffer_free, child_ack, client_ack, ack);
3644   return ack;
3645 }
3646
3647
3648 /**
3649  * Build a local ACK message and send it to a local client.
3650  * 
3651  * @param t Tunnel on which to send the ACK.
3652  * @param c Client to whom send the ACK.
3653  * @param ack Value of the ACK.
3654  */
3655 static void
3656 send_local_ack (struct MeshTunnel *t, struct MeshClient *c, uint32_t ack)
3657 {
3658   struct GNUNET_MESH_LocalAck msg;
3659
3660   msg.header.size = htons (sizeof (msg));
3661   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
3662   msg.tunnel_id = htonl (t->owner == c ? t->local_tid : t->local_tid_dest);
3663   msg.max_pid = htonl (ack); 
3664   GNUNET_SERVER_notification_context_unicast(nc,
3665                                               c->handle,
3666                                               &msg.header,
3667                                               GNUNET_NO);
3668 }
3669
3670 /**
3671  * Build an ACK message and queue it to send to the given peer.
3672  * 
3673  * @param t Tunnel on which to send the ACK.
3674  * @param peer Peer to whom send the ACK.
3675  * @param ack Value of the ACK.
3676  */
3677 static void
3678 send_ack (struct MeshTunnel *t, struct GNUNET_PeerIdentity *peer,  uint32_t ack)
3679 {
3680   struct GNUNET_MESH_ACK msg;
3681
3682   GNUNET_PEER_resolve (t->id.oid, &msg.oid);
3683   msg.header.size = htons (sizeof (msg));
3684   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_ACK);
3685   msg.pid = htonl (ack);
3686   msg.tid = htonl (t->id.tid);
3687
3688   send_message (&msg.header, peer, t);
3689 }
3690
3691
3692 /**
3693  * Notify a the owner of a tunnel about how many more
3694  * payload packages will we accept on a given tunnel.
3695  *
3696  * @param t Tunnel on which to send the ACK.
3697  */
3698 static void
3699 tunnel_send_client_fwd_ack (struct MeshTunnel *t)
3700 {
3701   uint32_t ack;
3702
3703   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3704               "Sending client FWD ACK on tunnel %X\n",
3705               t->local_tid);
3706
3707   ack = tunnel_get_fwd_ack (t);
3708
3709   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ack %u\n", ack);
3710   if (t->last_fwd_ack == ack)
3711     return;
3712
3713   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " sending!\n");
3714   t->last_fwd_ack = ack;
3715   send_local_ack (t, t->owner, ack);
3716 }
3717
3718
3719 /**
3720  * Send an ACK informing the predecessor about the available buffer space.
3721  * In case there is no predecessor, inform the owning client.
3722  * If buffering is off, send only on behalf of children or self if endpoint.
3723  * If buffering is on, send when sent to children and buffer space is free.
3724  * Note that although the name is fwd_ack, the FWD mean forward *traffic*,
3725  * the ACK itself goes "back" (towards root).
3726  * 
3727  * @param t Tunnel on which to send the ACK.
3728  * @param type Type of message that triggered the ACK transmission.
3729  */
3730 static void
3731 tunnel_send_fwd_ack (struct MeshTunnel *t, uint16_t type)
3732 {
3733   struct GNUNET_PeerIdentity id;
3734   uint32_t ack;
3735
3736   if (NULL != t->owner)
3737   {
3738     tunnel_send_client_fwd_ack (t);
3739     return;
3740   }
3741   /* Is it after unicast / multicast retransmission? */
3742   switch (type)
3743   {
3744     case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
3745     case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
3746       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3747                   "ACK due to FWD DATA retransmission\n");
3748       if (GNUNET_YES == t->nobuffer)
3749       {
3750         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, nobuffer\n");
3751         return;
3752       }
3753       if (t->fwd_queue_max > t->fwd_queue_n * 2 &&
3754           GMC_is_pid_bigger(t->last_fwd_ack, t->fwd_pid))
3755       {
3756         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, buffer free\n");
3757         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3758                     "  t->qmax: %u, t->qn: %u\n",
3759                     t->fwd_queue_max, t->fwd_queue_n);
3760         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3761                     "  t->pid: %u, t->ack: %u\n",
3762                     t->fwd_pid, t->last_fwd_ack);
3763         return;
3764       }
3765       break;
3766     case GNUNET_MESSAGE_TYPE_MESH_ACK:
3767     case GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK:
3768       break;
3769     default:
3770       GNUNET_break (0);
3771   }
3772
3773   /* Ok, ACK might be necessary, what PID to ACK? */
3774   ack = tunnel_get_fwd_ack (t);
3775
3776   /* If speed_min and not all children have ack'd, dont send yet */
3777   if (ack == t->last_fwd_ack)
3778   {
3779     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending FWD ACK, not ready\n");
3780     return;
3781   }
3782
3783   t->last_fwd_ack = ack;
3784   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
3785   send_ack (t, &id, ack);
3786 }
3787
3788
3789 /**
3790  * Iterator to send a child node a BCK ACK to allow him to send more
3791  * to_origin data.
3792  *
3793  * @param cls Closure (tunnel).
3794  * @param id Id of the child node.
3795  */
3796 static void
3797 tunnel_send_child_bck_ack (void *cls,
3798                            GNUNET_PEER_Id id)
3799 {
3800   struct MeshTunnel *t = cls;
3801   struct MeshTunnelChildInfo *cinfo;
3802   struct GNUNET_PeerIdentity peer;
3803
3804   GNUNET_PEER_resolve (id, &peer);
3805   cinfo = tunnel_get_neighbor_fc (t, &peer);
3806
3807   if (cinfo->bck_ack != cinfo->pid &&
3808       GNUNET_NO == GMC_is_pid_bigger (cinfo->bck_ack, cinfo->pid))
3809     return;
3810
3811   cinfo->bck_ack++;
3812   send_ack (t, &peer, cinfo->bck_ack);
3813 }
3814
3815
3816 /**
3817  * @brief Send BCK ACKs to clients to allow them more to_origin traffic
3818  * 
3819  * Iterates over all clients and sends BCK ACKs to the ones that need it.
3820  * 
3821  * @param t Tunnel on which to send the BCK ACKs.
3822  */
3823 static void
3824 tunnel_send_clients_bck_ack (struct MeshTunnel *t)
3825 {
3826   unsigned int i;
3827   unsigned int tunnel_delta;
3828
3829   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Sending BCK ACK to clients\n");
3830
3831   tunnel_delta = t->bck_ack - t->bck_pid;
3832   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   tunnel delta: %u\n", tunnel_delta);
3833
3834   /* Find client whom to allow to send to origin (with lowest buffer space) */
3835   for (i = 0; i < t->nclients; i++)
3836   {
3837     struct MeshTunnelClientInfo *clinfo;
3838     unsigned int delta;
3839
3840     clinfo = &t->clients_fc[i];
3841     delta = clinfo->bck_ack - clinfo->bck_pid;
3842     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    client %u delta: %u\n",
3843          t->clients[i]->id, delta);
3844
3845     if ((GNUNET_NO == t->nobuffer && tunnel_delta > delta) ||
3846         (GNUNET_YES == t->nobuffer && 0 == delta))
3847     {
3848       uint32_t ack;
3849
3850       ack = clinfo->bck_pid;
3851       ack += t->nobuffer ? 1 : tunnel_delta;
3852       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3853                   "    sending ack to client %u: %u\n",
3854                   t->clients[i]->id, ack);
3855       send_local_ack (t, t->clients[i], ack);
3856       clinfo->bck_ack = ack;
3857     }
3858   }
3859 }
3860
3861
3862 /**
3863  * Send an ACK informing the children nodes and destination clients about
3864  * the available buffer space.
3865  * If buffering is off, send only on behalf of root (can be self).
3866  * If buffering is on, send when sent to predecessor and buffer space is free.
3867  * Note that although the name is bck_ack, the BCK mean backwards *traffic*,
3868  * the ACK itself goes "forward" (towards children/clients).
3869  * 
3870  * @param t Tunnel on which to send the ACK.
3871  * @param type Type of message that triggered the ACK transmission.
3872  */
3873 static void
3874 tunnel_send_bck_ack (struct MeshTunnel *t, uint16_t type)
3875 {
3876   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3877               "Sending BCK ACK on tunnel %u [%u] due to %s\n",
3878               t->id.oid, t->id.tid, GNUNET_MESH_DEBUG_M2S(type));
3879   /* Is it after data to_origin retransmission? */
3880   switch (type)
3881   {
3882     case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
3883       if (GNUNET_YES == t->nobuffer)
3884       {
3885         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3886                     "    Not sending ACK, nobuffer\n");
3887         return;
3888       }
3889       break;
3890     case GNUNET_MESSAGE_TYPE_MESH_ACK:
3891     case GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK:
3892       break;
3893     default:
3894       GNUNET_break (0);
3895   }
3896
3897   tunnel_send_clients_bck_ack (t);
3898   tree_iterate_children (t->tree, &tunnel_send_child_bck_ack, t);
3899 }
3900
3901
3902 /**
3903  * @brief Re-initiate traffic to this peer if necessary.
3904  *
3905  * Check if there is traffic queued towards this peer
3906  * and the core transmit handle is NULL (traffic was stalled).
3907  * If so, call core tmt rdy.
3908  *
3909  * @param cls Closure (unused)
3910  * @param peer_id Short ID of peer to which initiate traffic.
3911  */
3912 static void
3913 peer_unlock_queue(void *cls, GNUNET_PEER_Id peer_id)
3914 {
3915   struct MeshPeerInfo *peer;
3916   struct GNUNET_PeerIdentity id;
3917   struct MeshPeerQueue *q;
3918   size_t size;
3919
3920   peer = peer_info_get_short(peer_id);
3921   if (NULL != peer->core_transmit)
3922     return;
3923
3924   q = queue_get_next(peer);
3925   if (NULL == q)
3926   {
3927     /* Might br multicast traffic already sent to this particular peer but
3928      * not to other children in this tunnel.
3929      * This way t->queue_n would be > 0 but the queue of this particular peer
3930      * would be empty.
3931      */
3932     return;
3933   }
3934   size = q->size;
3935   GNUNET_PEER_resolve (peer->id, &id);
3936   peer->core_transmit =
3937         GNUNET_CORE_notify_transmit_ready(core_handle,
3938                                           0,
3939                                           0,
3940                                           GNUNET_TIME_UNIT_FOREVER_REL,
3941                                           &id,
3942                                           size,
3943                                           &queue_send,
3944                                           peer);
3945         return;
3946 }
3947
3948
3949 /**
3950  * @brief Allow transmission of FWD traffic on this tunnel
3951  *
3952  * Check if there is traffic queued towards any children
3953  * and the core transmit handle is NULL, and if so, call core tmt rdy.
3954  *
3955  * @param t Tunnel on which to unlock FWD traffic.
3956  */
3957 static void
3958 tunnel_unlock_fwd_queues (struct MeshTunnel *t)
3959 {
3960   if (0 == t->fwd_queue_n)
3961     return;
3962
3963   tree_iterate_children (t->tree, &peer_unlock_queue, NULL);
3964 }
3965
3966
3967 /**
3968  * @brief Allow transmission of BCK traffic on this tunnel
3969  *
3970  * Check if there is traffic queued towards the root of the tree
3971  * and the core transmit handle is NULL, and if so, call core tmt rdy.
3972  *
3973  * @param t Tunnel on which to unlock BCK traffic.
3974  */
3975 static void
3976 tunnel_unlock_bck_queue (struct MeshTunnel *t)
3977 {
3978   if (0 == t->bck_queue_n)
3979     return;
3980
3981   peer_unlock_queue(NULL, tree_get_predecessor(t->tree));
3982 }
3983
3984
3985 /**
3986  * Send a message to all peers in this tunnel that the tunnel is no longer
3987  * valid.
3988  *
3989  * @param t The tunnel whose peers to notify.
3990  */
3991 static void
3992 tunnel_send_destroy (struct MeshTunnel *t)
3993 {
3994   struct GNUNET_MESH_TunnelDestroy msg;
3995
3996   msg.header.size = htons (sizeof (msg));
3997   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY);
3998   GNUNET_PEER_resolve (t->id.oid, &msg.oid);
3999   msg.tid = htonl (t->id.tid);
4000   tunnel_send_multicast (t, &msg.header, GNUNET_NO);
4001 }
4002
4003
4004 /**
4005  * Cancel all transmissions towards a neighbor that belong to a certain tunnel.
4006  *
4007  * @param cls Closure (Tunnel which to cancel).
4008  * @param neighbor_id Short ID of the neighbor to whom cancel the transmissions.
4009  */
4010 static void
4011 tunnel_cancel_queues (void *cls, GNUNET_PEER_Id neighbor_id)
4012 {
4013   struct MeshTunnel *t = cls;
4014   struct MeshPeerInfo *peer_info;
4015   struct MeshPeerQueue *pq;
4016   struct MeshPeerQueue *next;
4017
4018   peer_info = peer_info_get_short (neighbor_id);
4019   for (pq = peer_info->queue_head; NULL != pq; pq = next)
4020   {
4021     next = pq->next;
4022     if (pq->tunnel == t)
4023     {
4024       queue_destroy (pq, GNUNET_YES);
4025     }
4026   }
4027   if (NULL == peer_info->queue_head && NULL != peer_info->core_transmit)
4028   {
4029     GNUNET_CORE_notify_transmit_ready_cancel(peer_info->core_transmit);
4030     peer_info->core_transmit = NULL;
4031   }
4032 }
4033
4034 /**
4035  * Destroy the tunnel and free any allocated resources linked to it.
4036  *
4037  * @param t the tunnel to destroy
4038  *
4039  * @return GNUNET_OK on success
4040  */
4041 static int
4042 tunnel_destroy (struct MeshTunnel *t)
4043 {
4044   struct MeshClient *c;
4045   struct GNUNET_HashCode hash;
4046   unsigned int i;
4047   int r;
4048
4049   if (NULL == t)
4050     return GNUNET_OK;
4051
4052   tree_iterate_children (t->tree, &tunnel_cancel_queues, t);
4053
4054   r = GNUNET_OK;
4055   c = t->owner;
4056 #if MESH_DEBUG
4057   {
4058     struct GNUNET_PeerIdentity id;
4059
4060     GNUNET_PEER_resolve (t->id.oid, &id);
4061     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s [%x]\n",
4062                 GNUNET_i2s (&id), t->id.tid);
4063     if (NULL != c)
4064       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
4065   }
4066 #endif
4067
4068   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
4069   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &hash, t))
4070   {
4071     r = GNUNET_SYSERR;
4072   }
4073
4074   GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
4075   if (NULL != c &&
4076       GNUNET_YES !=
4077       GNUNET_CONTAINER_multihashmap_remove (c->own_tunnels, &hash, t))
4078   {
4079     r = GNUNET_SYSERR;
4080   }
4081   GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
4082   for (i = 0; i < t->nclients; i++)
4083   {
4084     c = t->clients[i];
4085     if (GNUNET_YES !=
4086           GNUNET_CONTAINER_multihashmap_remove (c->incoming_tunnels, &hash, t))
4087     {
4088       r = GNUNET_SYSERR;
4089     }
4090   }
4091   for (i = 0; i < t->nignore; i++)
4092   {
4093     c = t->ignore[i];
4094     if (GNUNET_YES !=
4095           GNUNET_CONTAINER_multihashmap_remove (c->ignore_tunnels, &hash, t))
4096     {
4097       r = GNUNET_SYSERR;
4098     }
4099   }
4100   if (t->nclients > 0)
4101   {
4102     if (GNUNET_YES !=
4103         GNUNET_CONTAINER_multihashmap_remove (incoming_tunnels, &hash, t))
4104     {
4105       r = GNUNET_SYSERR;
4106     }
4107     GNUNET_free (t->clients);
4108   }
4109   if (NULL != t->peers)
4110   {
4111     GNUNET_CONTAINER_multihashmap_iterate (t->peers, &peer_info_delete_tunnel,
4112                                            t);
4113     GNUNET_CONTAINER_multihashmap_destroy (t->peers);
4114   }
4115
4116   GNUNET_CONTAINER_multihashmap_iterate (t->children_fc,
4117                                          &tunnel_destroy_child,
4118                                          t);
4119   GNUNET_CONTAINER_multihashmap_destroy (t->children_fc);
4120
4121   tree_destroy (t->tree);
4122
4123   if (NULL != t->regex_ctx)
4124     regex_cancel_search (t->regex_ctx);
4125   if (NULL != t->dht_get_type)
4126     GNUNET_DHT_get_stop (t->dht_get_type);
4127   if (GNUNET_SCHEDULER_NO_TASK != t->timeout_task)
4128     GNUNET_SCHEDULER_cancel (t->timeout_task);
4129   if (GNUNET_SCHEDULER_NO_TASK != t->path_refresh_task)
4130     GNUNET_SCHEDULER_cancel (t->path_refresh_task);
4131
4132   n_tunnels--;
4133   GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
4134   GNUNET_assert (0 <= n_tunnels);
4135   GNUNET_free (t);
4136   return r;
4137 }
4138
4139
4140 /**
4141  * Create a new tunnel
4142  * 
4143  * @param owner Who is the owner of the tunnel (short ID).
4144  * @param tid Tunnel Number of the tunnel.
4145  * @param client Clients that owns the tunnel, NULL for foreign tunnels.
4146  * @param local Tunnel Number for the tunnel, for the client point of view.
4147  * 
4148  * @return A new initialized tunnel. NULL on error.
4149  */
4150 static struct MeshTunnel *
4151 tunnel_new (GNUNET_PEER_Id owner,
4152             MESH_TunnelNumber tid,
4153             struct MeshClient *client,
4154             MESH_TunnelNumber local)
4155 {
4156   struct MeshTunnel *t;
4157   struct GNUNET_HashCode hash;
4158
4159   if (n_tunnels >= max_tunnels && NULL == client)
4160     return NULL;
4161
4162   t = GNUNET_malloc (sizeof (struct MeshTunnel));
4163   t->id.oid = owner;
4164   t->id.tid = tid;
4165   t->fwd_queue_max = (max_msgs_queue / max_tunnels) + 1;
4166   t->bck_queue_max = t->fwd_queue_max;
4167   t->tree = tree_new (owner);
4168   t->owner = client;
4169   t->fwd_pid = (uint32_t) -1; // Next (expected) = 0
4170   t->bck_pid = (uint32_t) -1; // Next (expected) = 0
4171   t->bck_ack = INITIAL_WINDOW_SIZE - 1;
4172   t->last_fwd_ack = INITIAL_WINDOW_SIZE - 1;
4173   t->local_tid = local;
4174   t->children_fc = GNUNET_CONTAINER_multihashmap_create (8);
4175   n_tunnels++;
4176   GNUNET_STATISTICS_update (stats, "# tunnels", 1, GNUNET_NO);
4177
4178   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
4179   if (GNUNET_OK !=
4180       GNUNET_CONTAINER_multihashmap_put (tunnels, &hash, t,
4181                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
4182   {
4183     GNUNET_break (0);
4184     tunnel_destroy (t);
4185     if (NULL != client)
4186     {
4187       GNUNET_break (0);
4188       GNUNET_SERVER_receive_done (client->handle, GNUNET_SYSERR);
4189     }
4190     return NULL;
4191   }
4192
4193   if (NULL != client)
4194   {
4195     GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
4196     if (GNUNET_OK !=
4197         GNUNET_CONTAINER_multihashmap_put (client->own_tunnels, &hash, t,
4198                                           GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
4199     {
4200       tunnel_destroy (t);
4201       GNUNET_break (0);
4202       GNUNET_SERVER_receive_done (client->handle, GNUNET_SYSERR);
4203       return NULL;
4204     }
4205   }
4206
4207   return t;
4208 }
4209
4210
4211 /**
4212  * Removes an explicit path from a tunnel, freeing all intermediate nodes
4213  * that are no longer needed, as well as nodes of no longer reachable peers.
4214  * The tunnel itself is also destoyed if results in a remote empty tunnel.
4215  *
4216  * @param t Tunnel from which to remove the path.
4217  * @param peer Short id of the peer which should be removed.
4218  */
4219 static void
4220 tunnel_delete_peer (struct MeshTunnel *t, GNUNET_PEER_Id peer)
4221 {
4222   if (GNUNET_NO == tree_del_peer (t->tree, peer, NULL, NULL))
4223     tunnel_destroy (t);
4224 }
4225
4226
4227 /**
4228  * tunnel_destroy_iterator: iterator for deleting each tunnel that belongs to a
4229  * client when the client disconnects. If the client is not the owner, the
4230  * owner will get notified if no more clients are in the tunnel and the client
4231  * get removed from the tunnel's list.
4232  *
4233  * @param cls closure (client that is disconnecting)
4234  * @param key the hash of the local tunnel id (used to access the hashmap)
4235  * @param value the value stored at the key (tunnel to destroy)
4236  *
4237  * @return GNUNET_OK on success
4238  */
4239 static int
4240 tunnel_destroy_iterator (void *cls, const struct GNUNET_HashCode * key, void *value)
4241 {
4242   struct MeshTunnel *t = value;
4243   struct MeshClient *c = cls;
4244   int r;
4245
4246   send_client_tunnel_disconnect(t, c);
4247   if (c != t->owner)
4248   {
4249     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4250                 "Client %u is destination, keeping the tunnel alive.\n", c->id);
4251     tunnel_delete_client(t, c);
4252     client_delete_tunnel(c, t);
4253     return GNUNET_OK;
4254   }
4255   tunnel_send_destroy(t);
4256   r = tunnel_destroy (t);
4257   return r;
4258 }
4259
4260
4261 /**
4262  * Timeout function, destroys tunnel if called
4263  *
4264  * @param cls Closure (tunnel to destroy).
4265  * @param tc TaskContext
4266  */
4267 static void
4268 tunnel_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4269 {
4270   struct MeshTunnel *t = cls;
4271
4272   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4273     return;
4274   t->timeout_task = GNUNET_SCHEDULER_NO_TASK;
4275   tunnel_destroy (t);
4276 }
4277
4278 /**
4279  * Resets the tunnel timeout. Starts it if no timeout was running.
4280  *
4281  * @param t Tunnel whose timeout to reset.
4282  *
4283  * TODO use heap to improve efficiency of scheduler.
4284  */
4285 static void
4286 tunnel_reset_timeout (struct MeshTunnel *t)
4287 {
4288   if (GNUNET_SCHEDULER_NO_TASK != t->timeout_task)
4289     GNUNET_SCHEDULER_cancel (t->timeout_task);
4290   t->timeout_task =
4291       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
4292                                     (refresh_path_time, 4), &tunnel_timeout, t);
4293 }
4294
4295
4296 /******************************************************************************/
4297 /****************      MESH NETWORK HANDLER HELPERS     ***********************/
4298 /******************************************************************************/
4299
4300 /**
4301  * Function to send a create path packet to a peer.
4302  *
4303  * @param cls closure
4304  * @param size number of bytes available in buf
4305  * @param buf where the callee should write the message
4306  * @return number of bytes written to buf
4307  */
4308 static size_t
4309 send_core_path_create (void *cls, size_t size, void *buf)
4310 {
4311   struct MeshPathInfo *info = cls;
4312   struct GNUNET_MESH_ManipulatePath *msg;
4313   struct GNUNET_PeerIdentity *peer_ptr;
4314   struct MeshTunnel *t = info->t;
4315   struct MeshPeerPath *p = info->path;
4316   size_t size_needed;
4317   uint32_t opt;
4318   int i;
4319
4320   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATE PATH sending...\n");
4321   size_needed =
4322       sizeof (struct GNUNET_MESH_ManipulatePath) +
4323       p->length * sizeof (struct GNUNET_PeerIdentity);
4324
4325   if (size < size_needed || NULL == buf)
4326   {
4327     GNUNET_break (0);
4328     return 0;
4329   }
4330   msg = (struct GNUNET_MESH_ManipulatePath *) buf;
4331   msg->header.size = htons (size_needed);
4332   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE);
4333   msg->tid = ntohl (t->id.tid);
4334
4335   if (GNUNET_YES == t->speed_min)
4336     opt = MESH_TUNNEL_OPT_SPEED_MIN;
4337   if (GNUNET_YES == t->nobuffer)
4338     opt |= MESH_TUNNEL_OPT_NOBUFFER;
4339   msg->opt = htonl(opt);
4340
4341   peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
4342   for (i = 0; i < p->length; i++)
4343   {
4344     GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
4345   }
4346
4347   path_destroy (p);
4348   GNUNET_free (info);
4349
4350   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4351               "CREATE PATH (%u bytes long) sent!\n", size_needed);
4352   return size_needed;
4353 }
4354
4355
4356 /**
4357  * Fill the core buffer 
4358  *
4359  * @param cls closure (data itself)
4360  * @param size number of bytes available in buf
4361  * @param buf where the callee should write the message
4362  *
4363  * @return number of bytes written to buf
4364  */
4365 static size_t
4366 send_core_data_multicast (void *cls, size_t size, void *buf)
4367 {
4368   struct MeshTransmissionDescriptor *info = cls;
4369   size_t total_size;
4370
4371   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Multicast callback.\n");
4372   GNUNET_assert (NULL != info);
4373   GNUNET_assert (NULL != info->peer);
4374   total_size = info->mesh_data->data_len;
4375   GNUNET_assert (total_size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
4376
4377   if (total_size > size)
4378   {
4379     GNUNET_break (0);
4380     return 0;
4381   }
4382   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " copying data...\n");
4383   memcpy (buf, info->mesh_data->data, total_size);
4384 #if MESH_DEBUG
4385   {
4386     struct GNUNET_MESH_Multicast *mc;
4387     struct GNUNET_MessageHeader *mh;
4388
4389     mh = buf;
4390     if (ntohs (mh->type) == GNUNET_MESSAGE_TYPE_MESH_MULTICAST)
4391     {
4392       mc = (struct GNUNET_MESH_Multicast *) mh;
4393       mh = (struct GNUNET_MessageHeader *) &mc[1];
4394       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4395                   " multicast, payload type %s\n",
4396                   GNUNET_MESH_DEBUG_M2S (ntohs (mh->type)));
4397       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4398                   " multicast, payload size %u\n", ntohs (mh->size));
4399     }
4400     else
4401     {
4402       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " type %s\n",
4403                   GNUNET_MESH_DEBUG_M2S (ntohs (mh->type)));
4404     }
4405   }
4406 #endif
4407   data_descriptor_decrement_rc (info->mesh_data);
4408   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "freeing info...\n");
4409   GNUNET_free (info);
4410   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "return %u\n", total_size);
4411   return total_size;
4412 }
4413
4414
4415 /**
4416  * Creates a path ack message in buf and frees all unused resources.
4417  *
4418  * @param cls closure (MeshTransmissionDescriptor)
4419  * @param size number of bytes available in buf
4420  * @param buf where the callee should write the message
4421  * @return number of bytes written to buf
4422  */
4423 static size_t
4424 send_core_path_ack (void *cls, size_t size, void *buf)
4425 {
4426   struct MeshTransmissionDescriptor *info = cls;
4427   struct GNUNET_MESH_PathACK *msg = buf;
4428
4429   GNUNET_assert (NULL != info);
4430   if (sizeof (struct GNUNET_MESH_PathACK) > size)
4431   {
4432     GNUNET_break (0);
4433     return 0;
4434   }
4435   msg->header.size = htons (sizeof (struct GNUNET_MESH_PathACK));
4436   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_ACK);
4437   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
4438   msg->tid = htonl (info->origin->tid);
4439   msg->peer_id = my_full_id;
4440
4441   GNUNET_free (info);
4442   /* TODO add signature */
4443
4444   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "PATH ACK sent!\n");
4445   return sizeof (struct GNUNET_MESH_PathACK);
4446 }
4447
4448
4449 /**
4450  * Free a transmission that was already queued with all resources
4451  * associated to the request.
4452  *
4453  * @param queue Queue handler to cancel.
4454  * @param clear_cls Is it necessary to free associated cls?
4455  */
4456 static void
4457 queue_destroy (struct MeshPeerQueue *queue, int clear_cls)
4458 {
4459   struct MeshTransmissionDescriptor *dd;
4460   struct MeshPathInfo *path_info;
4461
4462   if (GNUNET_YES == clear_cls)
4463   {
4464     switch (queue->type)
4465     {
4466     case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4467     case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
4468     case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4469         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   type payload\n");
4470         dd = queue->cls;
4471         data_descriptor_decrement_rc (dd->mesh_data);
4472         break;
4473     case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
4474         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   type create path\n");
4475         path_info = queue->cls;
4476         path_destroy (path_info->path);
4477         break;
4478     default:
4479         GNUNET_break (0);
4480         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   type unknown!\n");
4481     }
4482     GNUNET_free_non_null (queue->cls);
4483   }
4484   GNUNET_CONTAINER_DLL_remove (queue->peer->queue_head,
4485                                queue->peer->queue_tail,
4486                                queue);
4487   GNUNET_free (queue);
4488 }
4489
4490
4491 /**
4492  * @brief Get the next transmittable message from the queue.
4493  *
4494  * This will be the head, except in the case of being a data packet
4495  * not allowed by the destination peer.
4496  *
4497  * @param peer Destination peer.
4498  *
4499  * @return The next viable MeshPeerQueue element to send to that peer.
4500  *         NULL when there are no transmittable messages.
4501  */
4502 struct MeshPeerQueue *
4503 queue_get_next (const struct MeshPeerInfo *peer)
4504 {
4505   struct MeshPeerQueue *q;
4506   struct MeshTunnel *t;
4507   struct MeshTransmissionDescriptor *info;
4508   struct MeshTunnelChildInfo *cinfo;
4509   struct GNUNET_MESH_Unicast *ucast;
4510   struct GNUNET_MESH_ToOrigin *to_orig;
4511   struct GNUNET_MESH_Multicast *mcast;
4512   struct GNUNET_PeerIdentity id;
4513   uint32_t pid;
4514   uint32_t ack;
4515
4516   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   selecting message\n");
4517   for (q = peer->queue_head; NULL != q; q = q->next)
4518   {
4519     t = q->tunnel;
4520     info = q->cls;
4521     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4522                 "*********     %s\n",
4523                 GNUNET_MESH_DEBUG_M2S(q->type));
4524     switch (q->type)
4525     {
4526       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4527         ucast = (struct GNUNET_MESH_Unicast *) info->mesh_data->data;
4528         pid = ntohl (ucast->pid);
4529         GNUNET_PEER_resolve (info->peer->id, &id);
4530         cinfo = tunnel_get_neighbor_fc(t, &id);
4531         ack = cinfo->fwd_ack;
4532         break;
4533       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4534         to_orig = (struct GNUNET_MESH_ToOrigin *) info->mesh_data->data;
4535         pid = ntohl (to_orig->pid);
4536         ack = t->bck_ack;
4537         break;
4538       case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
4539         mcast = (struct GNUNET_MESH_Multicast *) info->mesh_data->data;
4540         pid = ntohl (mcast->pid);
4541         GNUNET_PEER_resolve (info->peer->id, &id);
4542         cinfo = tunnel_get_neighbor_fc(t, &id);
4543         ack = cinfo->fwd_ack;
4544         break;
4545       default:
4546         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4547                     "*********   OK!\n");
4548         return q;
4549     }
4550         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4551                     "*********     ACK: %u, PID: %u\n",
4552                     ack, pid);
4553     if (GNUNET_NO == GMC_is_pid_bigger(pid, ack))
4554     {
4555       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4556                   "*********   OK!\n");
4557       return q;
4558     }
4559     else
4560     {
4561       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4562                   "*********     NEXT!\n");
4563     }
4564   }
4565   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4566                 "*********   nothing found\n");
4567   return NULL;
4568 }
4569
4570
4571 /**
4572   * Core callback to write a queued packet to core buffer
4573   *
4574   * @param cls Closure (peer info).
4575   * @param size Number of bytes available in buf.
4576   * @param buf Where the to write the message.
4577   *
4578   * @return number of bytes written to buf
4579   */
4580 static size_t
4581 queue_send (void *cls, size_t size, void *buf)
4582 {
4583     struct MeshPeerInfo *peer = cls;
4584     struct GNUNET_MessageHeader *msg;
4585     struct MeshPeerQueue *queue;
4586     struct MeshTunnel *t;
4587     size_t data_size;
4588
4589     peer->core_transmit = NULL;
4590     
4591     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "********* Queue send\n");
4592     queue = queue_get_next(peer);
4593
4594     /* Queue has no internal mesh traffic not sendable payload */
4595     if (NULL == queue)
4596     {
4597       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   not ready, return\n");
4598       if (NULL == peer->queue_head)
4599         GNUNET_break(0); // Should've been canceled
4600       return 0;
4601     }
4602     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   not empty\n");
4603
4604     /* Check if buffer size is enough for the message */
4605     if (queue->size > size)
4606     {
4607         struct GNUNET_PeerIdentity id;
4608
4609         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4610                     "*********   not enough room, reissue\n");
4611         GNUNET_PEER_resolve (peer->id, &id);
4612         peer->core_transmit =
4613             GNUNET_CORE_notify_transmit_ready(core_handle,
4614                                               0,
4615                                               0,
4616                                               GNUNET_TIME_UNIT_FOREVER_REL,
4617                                               &id,
4618                                               queue->size,
4619                                               &queue_send,
4620                                               peer);
4621         return 0;
4622     }
4623     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   size ok\n");
4624
4625     t = queue->tunnel;
4626     if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == queue->type)
4627     {
4628       t->fwd_queue_n--;
4629       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4630                   "*********   unicast: t->q (%u/%u)\n",
4631                   t->fwd_queue_n, t->fwd_queue_max);
4632     }
4633     else if (GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == queue->type)
4634     {
4635       t->bck_queue_n--;
4636       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   to origin\n");
4637     }
4638
4639     /* Fill buf */
4640     switch (queue->type)
4641     {
4642       case 0:
4643       case GNUNET_MESSAGE_TYPE_MESH_ACK:
4644       case GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN:
4645       case GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY:
4646         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4647                     "*********   raw: %s\n",
4648                     GNUNET_MESH_DEBUG_M2S (queue->type));
4649         /* Fall through */
4650       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4651       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4652         data_size = send_core_data_raw (queue->cls, size, buf);
4653         msg = (struct GNUNET_MessageHeader *) buf;
4654         switch (ntohs (msg->type)) // Type of preconstructed message
4655         {
4656           case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4657             tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_UNICAST);
4658             break;
4659           case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4660             tunnel_send_bck_ack(t, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
4661             break;
4662           default:
4663               break;
4664         }
4665         break;
4666       case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
4667         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   multicast\n");
4668         data_size = send_core_data_multicast(queue->cls, size, buf);
4669         // FIXME fc substract when? depending on the tunnel conf.
4670         // t->fwd_queue_n--;
4671         tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
4672         break;
4673       case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
4674         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path create\n");
4675         data_size = send_core_path_create(queue->cls, size, buf);
4676         break;
4677       case GNUNET_MESSAGE_TYPE_MESH_PATH_ACK:
4678         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path ack\n");
4679         data_size = send_core_path_ack(queue->cls, size, buf);
4680         break;
4681       default:
4682         GNUNET_break (0);
4683         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4684                     "*********   type unknown: %u\n",
4685                     queue->type);
4686         data_size = 0;
4687     }
4688
4689     /* Free queue, but cls was freed by send_core_* */
4690     queue_destroy (queue, GNUNET_NO);
4691
4692     if (GNUNET_YES == t->destroy && 0 == t->fwd_queue_n)
4693     {
4694       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********  destroying tunnel!\n");
4695       tunnel_destroy (t);
4696     }
4697
4698     /* If more data in queue, send next */
4699     if (NULL != peer->queue_head)
4700     {
4701         struct GNUNET_PeerIdentity id;
4702
4703         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   more data!\n");
4704         GNUNET_PEER_resolve (peer->id, &id);
4705         peer->core_transmit =
4706             GNUNET_CORE_notify_transmit_ready(core_handle,
4707                                               0,
4708                                               0,
4709                                               GNUNET_TIME_UNIT_FOREVER_REL,
4710                                               &id,
4711                                               peer->queue_head->size,
4712                                               &queue_send,
4713                                               peer);
4714     }
4715     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   return %d\n", data_size);
4716     return data_size;
4717 }
4718
4719
4720 /**
4721  * Queue and pass message to core when possible.
4722  *
4723  * @param cls Closure (type dependant).
4724  * @param type Type of the message, 0 for a raw message.
4725  * @param size Size of the message.
4726  * @param dst Neighbor to send message to.
4727  * @param t Tunnel this message belongs to.
4728  */
4729 static void
4730 queue_add (void *cls, uint16_t type, size_t size,
4731            struct MeshPeerInfo *dst, struct MeshTunnel *t)
4732 {
4733   struct MeshPeerQueue *queue;
4734   unsigned int *max;
4735   unsigned int *n;
4736
4737   n = NULL;
4738   if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == type ||
4739       GNUNET_MESSAGE_TYPE_MESH_MULTICAST == type)
4740   {
4741     n = &t->fwd_queue_n;
4742     max = &t->fwd_queue_max;
4743   }
4744   else if (GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == type)
4745   {
4746     n = &t->bck_queue_n;
4747     max = &t->bck_queue_max;
4748   }
4749   if (NULL != n) {
4750     if (*n >= *max)
4751     {
4752       if (NULL == t->owner)
4753         GNUNET_break_op(0);       // TODO: kill connection?
4754       else
4755         GNUNET_break(0);
4756       return;                       // Drop message
4757     }
4758     (*n)++;
4759   }
4760   queue = GNUNET_malloc (sizeof (struct MeshPeerQueue));
4761   queue->cls = cls;
4762   queue->type = type;
4763   queue->size = size;
4764   queue->peer = dst;
4765   queue->tunnel = t;
4766   GNUNET_CONTAINER_DLL_insert_tail (dst->queue_head, dst->queue_tail, queue);
4767   if (NULL == dst->core_transmit)
4768   {
4769       struct GNUNET_PeerIdentity id;
4770
4771       GNUNET_PEER_resolve (dst->id, &id);
4772       dst->core_transmit =
4773           GNUNET_CORE_notify_transmit_ready(core_handle,
4774                                             0,
4775                                             0,
4776                                             GNUNET_TIME_UNIT_FOREVER_REL,
4777                                             &id,
4778                                             size,
4779                                             &queue_send,
4780                                             dst);
4781   }
4782 }
4783
4784
4785 /******************************************************************************/
4786 /********************      MESH NETWORK HANDLERS     **************************/
4787 /******************************************************************************/
4788
4789
4790 /**
4791  * Core handler for path creation
4792  *
4793  * @param cls closure
4794  * @param message message
4795  * @param peer peer identity this notification is about
4796  * @param atsi performance data
4797  * @param atsi_count number of records in 'atsi'
4798  *
4799  * @return GNUNET_OK to keep the connection open,
4800  *         GNUNET_SYSERR to close it (signal serious error)
4801  */
4802 static int
4803 handle_mesh_path_create (void *cls, const struct GNUNET_PeerIdentity *peer,
4804                          const struct GNUNET_MessageHeader *message,
4805                          const struct GNUNET_ATS_Information *atsi,
4806                          unsigned int atsi_count)
4807 {
4808   unsigned int own_pos;
4809   uint16_t size;
4810   uint16_t i;
4811   MESH_TunnelNumber tid;
4812   struct GNUNET_MESH_ManipulatePath *msg;
4813   struct GNUNET_PeerIdentity *pi;
4814   struct GNUNET_HashCode hash;
4815   struct MeshPeerPath *path;
4816   struct MeshPeerInfo *dest_peer_info;
4817   struct MeshPeerInfo *orig_peer_info;
4818   struct MeshTunnel *t;
4819
4820   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4821               "Received a path create msg [%s]\n",
4822               GNUNET_i2s (&my_full_id));
4823   size = ntohs (message->size);
4824   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
4825   {
4826     GNUNET_break_op (0);
4827     return GNUNET_OK;
4828   }
4829
4830   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
4831   if (size % sizeof (struct GNUNET_PeerIdentity))
4832   {
4833     GNUNET_break_op (0);
4834     return GNUNET_OK;
4835   }
4836   size /= sizeof (struct GNUNET_PeerIdentity);
4837   if (size < 2)
4838   {
4839     GNUNET_break_op (0);
4840     return GNUNET_OK;
4841   }
4842   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
4843   msg = (struct GNUNET_MESH_ManipulatePath *) message;
4844
4845   tid = ntohl (msg->tid);
4846   pi = (struct GNUNET_PeerIdentity *) &msg[1];
4847   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4848               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi), tid);
4849   t = tunnel_get (pi, tid);
4850   if (NULL == t) // FIXME only for INCOMING tunnels?
4851   {
4852     uint32_t opt;
4853
4854     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating tunnel\n");
4855     t = tunnel_new (GNUNET_PEER_intern (pi), tid, NULL, 0);
4856     if (NULL == t)
4857     {
4858       // FIXME notify failure
4859       return GNUNET_OK;
4860     }
4861     opt = ntohl (msg->opt);
4862     t->speed_min = (0 != (opt & MESH_TUNNEL_OPT_SPEED_MIN)) ?
4863                    GNUNET_YES : GNUNET_NO;
4864     t->nobuffer = (0 != (opt & MESH_TUNNEL_OPT_NOBUFFER)) ?
4865                   GNUNET_YES : GNUNET_NO;
4866
4867     if (GNUNET_YES == t->nobuffer)
4868     {
4869       t->bck_queue_max = 1;
4870       t->fwd_queue_max = 1;
4871     }
4872
4873     // FIXME only assign a local tid if a local client is interested (on demand)
4874     while (NULL != tunnel_get_incoming (next_local_tid))
4875       next_local_tid = (next_local_tid + 1) | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
4876     t->local_tid_dest = next_local_tid++;
4877     next_local_tid = next_local_tid | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
4878     // FIXME end
4879
4880     tunnel_reset_timeout (t);
4881     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
4882     if (GNUNET_OK !=
4883         GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
4884                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
4885     {
4886       tunnel_destroy (t);
4887       GNUNET_break (0);
4888       return GNUNET_OK;
4889     }
4890   }
4891   dest_peer_info =
4892       GNUNET_CONTAINER_multihashmap_get (peers, &pi[size - 1].hashPubKey);
4893   if (NULL == dest_peer_info)
4894   {
4895     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4896                 "  Creating PeerInfo for destination.\n");
4897     dest_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
4898     dest_peer_info->id = GNUNET_PEER_intern (&pi[size - 1]);
4899     GNUNET_CONTAINER_multihashmap_put (peers, &pi[size - 1].hashPubKey,
4900                                        dest_peer_info,
4901                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
4902   }
4903   orig_peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &pi->hashPubKey);
4904   if (NULL == orig_peer_info)
4905   {
4906     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4907                 "  Creating PeerInfo for origin.\n");
4908     orig_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
4909     orig_peer_info->id = GNUNET_PEER_intern (pi);
4910     GNUNET_CONTAINER_multihashmap_put (peers, &pi->hashPubKey, orig_peer_info,
4911                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
4912   }
4913   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
4914   path = path_new (size);
4915   own_pos = 0;
4916   for (i = 0; i < size; i++)
4917   {
4918     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
4919                 GNUNET_i2s (&pi[i]));
4920     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
4921     if (path->peers[i] == myid)
4922       own_pos = i;
4923   }
4924   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
4925   if (own_pos == 0)
4926   {
4927     /* cannot be self, must be 'not found' */
4928     /* create path: self not found in path through self */
4929     GNUNET_break_op (0);
4930     path_destroy (path);
4931     tunnel_destroy (t);
4932     return GNUNET_OK;
4933   }
4934   path_add_to_peers (path, GNUNET_NO);
4935   tunnel_add_path (t, path, own_pos);
4936   if (own_pos == size - 1)
4937   {
4938     /* It is for us! Send ack. */
4939     struct MeshTransmissionDescriptor *info;
4940
4941     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
4942     peer_info_add_path_to_origin (orig_peer_info, path, GNUNET_NO);
4943     if (NULL == t->peers)
4944     {
4945       /* New tunnel! Notify clients on data. */
4946       t->peers = GNUNET_CONTAINER_multihashmap_create (4);
4947     }
4948     GNUNET_break (GNUNET_SYSERR !=
4949                   GNUNET_CONTAINER_multihashmap_put (t->peers,
4950                                                      &my_full_id.hashPubKey,
4951                                                      peer_info_get
4952                                                      (&my_full_id),
4953                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE));
4954     info = GNUNET_malloc (sizeof (struct MeshTransmissionDescriptor));
4955     info->origin = &t->id;
4956     info->peer = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
4957     GNUNET_assert (NULL != info->peer);
4958     queue_add(info,
4959               GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
4960               sizeof (struct GNUNET_MESH_PathACK),
4961               info->peer,
4962               t);
4963   }
4964   else
4965   {
4966     struct MeshPeerPath *path2;
4967
4968     /* It's for somebody else! Retransmit. */
4969     path2 = path_duplicate (path);
4970     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Retransmitting.\n");
4971     peer_info_add_path (dest_peer_info, path2, GNUNET_NO);
4972     path2 = path_duplicate (path);
4973     peer_info_add_path_to_origin (orig_peer_info, path2, GNUNET_NO);
4974     send_create_path (dest_peer_info, path, t);
4975   }
4976   return GNUNET_OK;
4977 }
4978
4979
4980 /**
4981  * Core handler for path destruction
4982  *
4983  * @param cls closure
4984  * @param message message
4985  * @param peer peer identity this notification is about
4986  * @param atsi performance data
4987  * @param atsi_count number of records in 'atsi'
4988  *
4989  * @return GNUNET_OK to keep the connection open,
4990  *         GNUNET_SYSERR to close it (signal serious error)
4991  */
4992 static int
4993 handle_mesh_path_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
4994                           const struct GNUNET_MessageHeader *message,
4995                           const struct GNUNET_ATS_Information *atsi,
4996                           unsigned int atsi_count)
4997 {
4998   struct GNUNET_MESH_ManipulatePath *msg;
4999   struct GNUNET_PeerIdentity *pi;
5000   struct MeshPeerPath *path;
5001   struct MeshTunnel *t;
5002   unsigned int own_pos;
5003   unsigned int i;
5004   size_t size;
5005
5006   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5007               "Received a PATH DESTROY msg from %s\n", GNUNET_i2s (peer));
5008   size = ntohs (message->size);
5009   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
5010   {
5011     GNUNET_break_op (0);
5012     return GNUNET_OK;
5013   }
5014
5015   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
5016   if (size % sizeof (struct GNUNET_PeerIdentity))
5017   {
5018     GNUNET_break_op (0);
5019     return GNUNET_OK;
5020   }
5021   size /= sizeof (struct GNUNET_PeerIdentity);
5022   if (size < 2)
5023   {
5024     GNUNET_break_op (0);
5025     return GNUNET_OK;
5026   }
5027   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
5028
5029   msg = (struct GNUNET_MESH_ManipulatePath *) message;
5030   pi = (struct GNUNET_PeerIdentity *) &msg[1];
5031   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5032               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi),
5033               msg->tid);
5034   t = tunnel_get (pi, ntohl (msg->tid));
5035   if (NULL == t)
5036   {
5037     /* TODO notify back: we don't know this tunnel */
5038     GNUNET_break_op (0);
5039     return GNUNET_OK;
5040   }
5041   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
5042   path = path_new (size);
5043   own_pos = 0;
5044   for (i = 0; i < size; i++)
5045   {
5046     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
5047                 GNUNET_i2s (&pi[i]));
5048     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
5049     if (path->peers[i] == myid)
5050       own_pos = i;
5051   }
5052   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
5053   if (own_pos < path->length - 1)
5054     send_message (message, &pi[own_pos + 1], t);
5055   else
5056     send_client_tunnel_disconnect(t, NULL);
5057
5058   tunnel_delete_peer (t, path->peers[path->length - 1]);
5059   path_destroy (path);
5060   return GNUNET_OK;
5061 }
5062
5063
5064 /**
5065  * Core handler for notifications of broken paths
5066  *
5067  * @param cls closure
5068  * @param message message
5069  * @param peer peer identity this notification is about
5070  * @param atsi performance data
5071  * @param atsi_count number of records in 'atsi'
5072  *
5073  * @return GNUNET_OK to keep the connection open,
5074  *         GNUNET_SYSERR to close it (signal serious error)
5075  */
5076 static int
5077 handle_mesh_path_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
5078                          const struct GNUNET_MessageHeader *message,
5079                          const struct GNUNET_ATS_Information *atsi,
5080                          unsigned int atsi_count)
5081 {
5082   struct GNUNET_MESH_PathBroken *msg;
5083   struct MeshTunnel *t;
5084
5085   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5086               "Received a PATH BROKEN msg from %s\n", GNUNET_i2s (peer));
5087   msg = (struct GNUNET_MESH_PathBroken *) message;
5088   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
5089               GNUNET_i2s (&msg->peer1));
5090   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
5091               GNUNET_i2s (&msg->peer2));
5092   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5093   if (NULL == t)
5094   {
5095     GNUNET_break_op (0);
5096     return GNUNET_OK;
5097   }
5098   tunnel_notify_connection_broken (t, GNUNET_PEER_search (&msg->peer1),
5099                                    GNUNET_PEER_search (&msg->peer2));
5100   return GNUNET_OK;
5101
5102 }
5103
5104
5105 /**
5106  * Core handler for tunnel destruction
5107  *
5108  * @param cls closure
5109  * @param message message
5110  * @param peer peer identity this notification is about
5111  * @param atsi performance data
5112  * @param atsi_count number of records in 'atsi'
5113  *
5114  * @return GNUNET_OK to keep the connection open,
5115  *         GNUNET_SYSERR to close it (signal serious error)
5116  */
5117 static int
5118 handle_mesh_tunnel_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
5119                             const struct GNUNET_MessageHeader *message,
5120                             const struct GNUNET_ATS_Information *atsi,
5121                             unsigned int atsi_count)
5122 {
5123   struct GNUNET_MESH_TunnelDestroy *msg;
5124   struct MeshTunnel *t;
5125
5126   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5127               "Got a TUNNEL DESTROY packet from %s\n", GNUNET_i2s (peer));
5128   msg = (struct GNUNET_MESH_TunnelDestroy *) message;
5129   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for tunnel %s [%u]\n",
5130               GNUNET_i2s (&msg->oid), ntohl (msg->tid));
5131   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5132   if (NULL == t)
5133   {
5134     /* Probably already got the message from another path,
5135      * destroyed the tunnel and retransmitted to children.
5136      * Safe to ignore.
5137      */
5138     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel", 1, GNUNET_NO);
5139     return GNUNET_OK;
5140   }
5141   if (t->id.oid == myid)
5142   {
5143     GNUNET_break_op (0);
5144     return GNUNET_OK;
5145   }
5146   if (t->local_tid_dest >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
5147   {
5148     /* Tunnel was incoming, notify clients */
5149     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "INCOMING TUNNEL %X %X\n",
5150                 t->local_tid, t->local_tid_dest);
5151     send_clients_tunnel_destroy (t);
5152   }
5153   tunnel_send_destroy (t);
5154   t->destroy = GNUNET_YES;
5155   // TODO: add timeout to destroy the tunnel anyway
5156   return GNUNET_OK;
5157 }
5158
5159
5160 /**
5161  * Core handler for mesh network traffic going from the origin to a peer
5162  *
5163  * @param cls closure
5164  * @param peer peer identity this notification is about
5165  * @param message message
5166  * @param atsi performance data
5167  * @param atsi_count number of records in 'atsi'
5168  * @return GNUNET_OK to keep the connection open,
5169  *         GNUNET_SYSERR to close it (signal serious error)
5170  */
5171 static int
5172 handle_mesh_data_unicast (void *cls, const struct GNUNET_PeerIdentity *peer,
5173                           const struct GNUNET_MessageHeader *message,
5174                           const struct GNUNET_ATS_Information *atsi,
5175                           unsigned int atsi_count)
5176 {
5177   struct GNUNET_MESH_Unicast *msg;
5178   struct GNUNET_PeerIdentity *neighbor;
5179   struct MeshTunnelChildInfo *cinfo;
5180   struct MeshTunnel *t;
5181   GNUNET_PEER_Id dest_id;
5182   uint32_t pid;
5183   uint32_t ttl;
5184   size_t size;
5185
5186   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a unicast packet from %s\n",
5187               GNUNET_i2s (peer));
5188   /* Check size */
5189   size = ntohs (message->size);
5190   if (size <
5191       sizeof (struct GNUNET_MESH_Unicast) +
5192       sizeof (struct GNUNET_MessageHeader))
5193   {
5194     GNUNET_break (0);
5195     return GNUNET_OK;
5196   }
5197   msg = (struct GNUNET_MESH_Unicast *) message;
5198   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %s\n",
5199               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
5200   /* Check tunnel */
5201   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5202   if (NULL == t)
5203   {
5204     /* TODO notify back: we don't know this tunnel */
5205     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
5206     GNUNET_break_op (0);
5207     return GNUNET_OK;
5208   }
5209   pid = ntohl (msg->pid);
5210   if (t->fwd_pid == pid)
5211   {
5212     GNUNET_STATISTICS_update (stats, "# duplicate PID drops", 1, GNUNET_NO);
5213     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5214                 " Already seen pid %u, DROPPING!\n", pid);
5215     return GNUNET_OK;
5216   }
5217   else
5218   {
5219     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5220                 " pid %u not seen yet, forwarding\n", pid);
5221   }
5222
5223   t->skip += (pid - t->fwd_pid) - 1;
5224   t->fwd_pid = pid;
5225
5226   if (GMC_is_pid_bigger (pid, t->last_fwd_ack))
5227   {
5228     GNUNET_STATISTICS_update (stats, "# unsolicited unicast", 1, GNUNET_NO);
5229     GNUNET_break_op (0);
5230     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5231                 "Received PID %u, ACK %u\n",
5232                 pid, t->last_fwd_ack);
5233     return GNUNET_OK;
5234   }
5235
5236   tunnel_reset_timeout (t);
5237   dest_id = GNUNET_PEER_search (&msg->destination);
5238   if (dest_id == myid)
5239   {
5240     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5241                 "  it's for us! sending to clients...\n");
5242     GNUNET_STATISTICS_update (stats, "# unicast received", 1, GNUNET_NO);
5243     send_subscribed_clients (message, &msg[1].header, t);
5244     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_UNICAST);
5245     return GNUNET_OK;
5246   }
5247   ttl = ntohl (msg->ttl);
5248   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ttl);
5249   if (ttl == 0)
5250   {
5251     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
5252     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
5253     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5254     return GNUNET_OK;
5255   }
5256   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5257               "  not for us, retransmitting...\n");
5258
5259   neighbor = tree_get_first_hop (t->tree, dest_id);
5260   cinfo = tunnel_get_neighbor_fc (t, neighbor);
5261   cinfo->pid = pid;
5262   GNUNET_CONTAINER_multihashmap_iterate (t->children_fc,
5263                                          &tunnel_add_skip,
5264                                          &neighbor);
5265   if (GNUNET_YES == t->nobuffer &&
5266       GNUNET_YES == GMC_is_pid_bigger (pid, cinfo->fwd_ack))
5267   {
5268     GNUNET_STATISTICS_update (stats, "# unsolicited unicast", 1, GNUNET_NO);
5269     GNUNET_break_op (0);
5270     return GNUNET_OK;
5271   }
5272   send_message (message, neighbor, t);
5273   GNUNET_STATISTICS_update (stats, "# unicast forwarded", 1, GNUNET_NO);
5274   return GNUNET_OK;
5275 }
5276
5277
5278 /**
5279  * Core handler for mesh network traffic going from the origin to all peers
5280  *
5281  * @param cls closure
5282  * @param message message
5283  * @param peer peer identity this notification is about
5284  * @param atsi performance data
5285  * @param atsi_count number of records in 'atsi'
5286  * @return GNUNET_OK to keep the connection open,
5287  *         GNUNET_SYSERR to close it (signal serious error)
5288  *
5289  * TODO: Check who we got this from, to validate route.
5290  */
5291 static int
5292 handle_mesh_data_multicast (void *cls, const struct GNUNET_PeerIdentity *peer,
5293                             const struct GNUNET_MessageHeader *message,
5294                             const struct GNUNET_ATS_Information *atsi,
5295                             unsigned int atsi_count)
5296 {
5297   struct GNUNET_MESH_Multicast *msg;
5298   struct MeshTunnel *t;
5299   size_t size;
5300   uint32_t pid;
5301
5302   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a multicast packet from %s\n",
5303               GNUNET_i2s (peer));
5304   size = ntohs (message->size);
5305   if (sizeof (struct GNUNET_MESH_Multicast) +
5306       sizeof (struct GNUNET_MessageHeader) > size)
5307   {
5308     GNUNET_break_op (0);
5309     return GNUNET_OK;
5310   }
5311   msg = (struct GNUNET_MESH_Multicast *) message;
5312   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5313
5314   if (NULL == t)
5315   {
5316     /* TODO notify that we dont know that tunnel */
5317     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
5318     GNUNET_break_op (0);
5319     return GNUNET_OK;
5320   }
5321   pid = ntohl (msg->pid);
5322   if (t->fwd_pid == pid)
5323   {
5324     /* already seen this packet, drop */
5325     GNUNET_STATISTICS_update (stats, "# duplicate PID drops", 1, GNUNET_NO);
5326     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5327                 " Already seen pid %u, DROPPING!\n", pid);
5328     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5329     return GNUNET_OK;
5330   }
5331   else
5332   {
5333     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5334                 " pid %u not seen yet, forwarding\n", pid);
5335   }
5336   t->skip += (pid - t->fwd_pid) - 1;
5337   t->fwd_pid = pid;
5338   tunnel_reset_timeout (t);
5339
5340   /* Transmit to locally interested clients */
5341   if (NULL != t->peers &&
5342       GNUNET_CONTAINER_multihashmap_contains (t->peers, &my_full_id.hashPubKey))
5343   {
5344     GNUNET_STATISTICS_update (stats, "# multicast received", 1, GNUNET_NO);
5345     send_subscribed_clients (message, &msg[1].header, t);
5346     tunnel_send_fwd_ack(t, GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
5347   }
5348   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ntohl (msg->ttl));
5349   if (ntohl (msg->ttl) == 0)
5350   {
5351     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
5352     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
5353     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5354     return GNUNET_OK;
5355   }
5356   GNUNET_STATISTICS_update (stats, "# multicast forwarded", 1, GNUNET_NO);
5357   tunnel_send_multicast (t, message, GNUNET_NO);
5358   return GNUNET_OK;
5359 }
5360
5361
5362 /**
5363  * Core handler for mesh network traffic toward the owner of a tunnel
5364  *
5365  * @param cls closure
5366  * @param message message
5367  * @param peer peer identity this notification is about
5368  * @param atsi performance data
5369  * @param atsi_count number of records in 'atsi'
5370  *
5371  * @return GNUNET_OK to keep the connection open,
5372  *         GNUNET_SYSERR to close it (signal serious error)
5373  */
5374 static int
5375 handle_mesh_data_to_orig (void *cls, const struct GNUNET_PeerIdentity *peer,
5376                           const struct GNUNET_MessageHeader *message,
5377                           const struct GNUNET_ATS_Information *atsi,
5378                           unsigned int atsi_count)
5379 {
5380   struct GNUNET_MESH_ToOrigin *msg;
5381   struct GNUNET_PeerIdentity id;
5382   struct MeshPeerInfo *peer_info;
5383   struct MeshTunnel *t;
5384   size_t size;
5385
5386
5387   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a ToOrigin packet from %s\n",
5388               GNUNET_i2s (peer));
5389   size = ntohs (message->size);
5390   if (size < sizeof (struct GNUNET_MESH_ToOrigin) +     /* Payload must be */
5391       sizeof (struct GNUNET_MessageHeader))     /* at least a header */
5392   {
5393     GNUNET_break_op (0);
5394     return GNUNET_OK;
5395   }
5396   msg = (struct GNUNET_MESH_ToOrigin *) message;
5397   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %s\n",
5398               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
5399   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5400
5401   if (NULL == t)
5402   {
5403     /* TODO notify that we dont know this tunnel (whom)? */
5404     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
5405     GNUNET_break_op (0);
5406     return GNUNET_OK;
5407   }
5408
5409   if (NULL != t->owner)
5410   {
5411     char cbuf[size];
5412     struct GNUNET_MESH_ToOrigin *copy;
5413
5414     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5415                 "  it's for us! sending to clients...\n");
5416     /* TODO signature verification */
5417     memcpy (cbuf, message, size);
5418     copy = (struct GNUNET_MESH_ToOrigin *) cbuf;
5419     copy->tid = htonl (t->local_tid);
5420     GNUNET_STATISTICS_update (stats, "# to origin received", 1, GNUNET_NO);
5421     GNUNET_SERVER_notification_context_unicast (nc, t->owner->handle,
5422                                                 &copy->header, GNUNET_NO);
5423     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
5424     return GNUNET_OK;
5425   }
5426   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5427               "  not for us, retransmitting...\n");
5428
5429   peer_info = peer_info_get (&msg->oid);
5430   if (NULL == peer_info)
5431   {
5432     /* unknown origin of tunnel */
5433     GNUNET_break (0);
5434     return GNUNET_OK;
5435   }
5436   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
5437   send_message (message, &id, t);
5438   GNUNET_STATISTICS_update (stats, "# to origin forwarded", 1, GNUNET_NO);
5439
5440   return GNUNET_OK;
5441 }
5442
5443
5444 /**
5445  * Core handler for mesh network traffic point-to-point acks.
5446  *
5447  * @param cls closure
5448  * @param message message
5449  * @param peer peer identity this notification is about
5450  * @param atsi performance data
5451  * @param atsi_count number of records in 'atsi'
5452  *
5453  * @return GNUNET_OK to keep the connection open,
5454  *         GNUNET_SYSERR to close it (signal serious error)
5455  */
5456 static int
5457 handle_mesh_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5458                  const struct GNUNET_MessageHeader *message,
5459                  const struct GNUNET_ATS_Information *atsi,
5460                  unsigned int atsi_count)
5461 {
5462   struct GNUNET_MESH_ACK *msg;
5463   struct MeshTunnel *t;
5464   uint32_t ack;
5465
5466   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK packet from %s!\n",
5467               GNUNET_i2s (peer));
5468   msg = (struct GNUNET_MESH_ACK *) message;
5469
5470   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5471
5472   if (NULL == t)
5473   {
5474     /* TODO notify that we dont know this tunnel (whom)? */
5475     GNUNET_STATISTICS_update (stats, "# ack on unknown tunnel", 1, GNUNET_NO);
5476     GNUNET_break_op (0);
5477     return GNUNET_OK;
5478   }
5479   ack = ntohl (msg->pid);
5480
5481   /* Is this a forward or backward ACK? */
5482   if (tree_get_predecessor(t->tree) != GNUNET_PEER_search(peer))
5483   {
5484     struct MeshTunnelChildInfo *cinfo;
5485
5486     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
5487     cinfo = tunnel_get_neighbor_fc (t, peer);
5488     cinfo->fwd_ack = ack;
5489     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5490     tunnel_unlock_fwd_queues (t);
5491   }
5492   else
5493   {
5494     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
5495     t->bck_ack = ack;
5496     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5497     tunnel_unlock_bck_queue (t);
5498   }
5499   return GNUNET_OK;
5500 }
5501
5502
5503 /**
5504  * Core handler for path ACKs
5505  *
5506  * @param cls closure
5507  * @param message message
5508  * @param peer peer identity this notification is about
5509  * @param atsi performance data
5510  * @param atsi_count number of records in 'atsi'
5511  *
5512  * @return GNUNET_OK to keep the connection open,
5513  *         GNUNET_SYSERR to close it (signal serious error)
5514  */
5515 static int
5516 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5517                       const struct GNUNET_MessageHeader *message,
5518                       const struct GNUNET_ATS_Information *atsi,
5519                       unsigned int atsi_count)
5520 {
5521   struct GNUNET_MESH_PathACK *msg;
5522   struct GNUNET_PeerIdentity id;
5523   struct MeshPeerInfo *peer_info;
5524   struct MeshPeerPath *p;
5525   struct MeshTunnel *t;
5526
5527   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a path ACK msg [%s]\n",
5528               GNUNET_i2s (&my_full_id));
5529   msg = (struct GNUNET_MESH_PathACK *) message;
5530   t = tunnel_get (&msg->oid, ntohl(msg->tid));
5531   if (NULL == t)
5532   {
5533     /* TODO notify that we don't know the tunnel */
5534     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel", 1, GNUNET_NO);
5535     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  don't know the tunnel %s [%X]!\n",
5536                 GNUNET_i2s (&msg->oid), ntohl(msg->tid));
5537     return GNUNET_OK;
5538   }
5539   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %s [%X]\n",
5540               GNUNET_i2s (&msg->oid), ntohl(msg->tid));
5541
5542   peer_info = peer_info_get (&msg->peer_id);
5543   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by peer %s\n",
5544               GNUNET_i2s (&msg->peer_id));
5545   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  via peer %s\n",
5546               GNUNET_i2s (peer));
5547
5548   if (NULL != t->regex_ctx && t->regex_ctx->info->peer == peer_info->id)
5549   {
5550     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5551                 "connect_by_string completed, stopping search\n");
5552     regex_cancel_search (t->regex_ctx);
5553     t->regex_ctx = NULL;
5554   }
5555
5556   /* Add paths to peers? */
5557   p = tree_get_path_to_peer (t->tree, peer_info->id);
5558   if (NULL != p)
5559   {
5560     path_add_to_peers (p, GNUNET_YES);
5561     path_destroy (p);
5562   }
5563   else
5564   {
5565     GNUNET_break (0);
5566   }
5567
5568   /* Message for us? */
5569   if (0 == memcmp (&msg->oid, &my_full_id, sizeof (struct GNUNET_PeerIdentity)))
5570   {
5571     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
5572     if (NULL == t->owner)
5573     {
5574       GNUNET_break_op (0);
5575       return GNUNET_OK;
5576     }
5577     if (NULL != t->dht_get_type)
5578     {
5579       GNUNET_DHT_get_stop (t->dht_get_type);
5580       t->dht_get_type = NULL;
5581     }
5582     if (tree_get_status (t->tree, peer_info->id) != MESH_PEER_READY)
5583     {
5584       tree_set_status (t->tree, peer_info->id, MESH_PEER_READY);
5585       send_client_peer_connected (t, peer_info->id);
5586     }
5587     return GNUNET_OK;
5588   }
5589
5590   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5591               "  not for us, retransmitting...\n");
5592   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
5593   peer_info = peer_info_get (&msg->oid);
5594   if (NULL == peer_info)
5595   {
5596     /* If we know the tunnel, we should DEFINITELY know the peer */
5597     GNUNET_break (0);
5598     return GNUNET_OK;
5599   }
5600   send_message (message, &id, t);
5601   return GNUNET_OK;
5602 }
5603
5604
5605 /**
5606  * Functions to handle messages from core
5607  */
5608 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
5609   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
5610   {&handle_mesh_path_destroy, GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY, 0},
5611   {&handle_mesh_path_broken, GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN,
5612    sizeof (struct GNUNET_MESH_PathBroken)},
5613   {&handle_mesh_tunnel_destroy, GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY,
5614    sizeof (struct GNUNET_MESH_TunnelDestroy)},
5615   {&handle_mesh_data_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
5616   {&handle_mesh_data_multicast, GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
5617   {&handle_mesh_data_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
5618   {&handle_mesh_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
5619     sizeof (struct GNUNET_MESH_ACK)},
5620   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
5621    sizeof (struct GNUNET_MESH_PathACK)},
5622   {NULL, 0, 0}
5623 };
5624
5625
5626
5627 /******************************************************************************/
5628 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
5629 /******************************************************************************/
5630
5631 /**
5632  * deregister_app: iterator for removing each application registered by a client
5633  *
5634  * @param cls closure
5635  * @param key the hash of the application id (used to access the hashmap)
5636  * @param value the value stored at the key (client)
5637  *
5638  * @return GNUNET_OK on success
5639  */
5640 static int
5641 deregister_app (void *cls, const struct GNUNET_HashCode * key, void *value)
5642 {
5643   struct GNUNET_CONTAINER_MultiHashMap *h = cls;
5644   GNUNET_break (GNUNET_YES ==
5645                 GNUNET_CONTAINER_multihashmap_remove (h, key, value));
5646   return GNUNET_OK;
5647 }
5648
5649 #if LATER
5650 /**
5651  * notify_client_connection_failure: notify a client that the connection to the
5652  * requested remote peer is not possible (for instance, no route found)
5653  * Function called when the socket is ready to queue more data. "buf" will be
5654  * NULL and "size" zero if the socket was closed for writing in the meantime.
5655  *
5656  * @param cls closure
5657  * @param size number of bytes available in buf
5658  * @param buf where the callee should write the message
5659  * @return number of bytes written to buf
5660  */
5661 static size_t
5662 notify_client_connection_failure (void *cls, size_t size, void *buf)
5663 {
5664   int size_needed;
5665   struct MeshPeerInfo *peer_info;
5666   struct GNUNET_MESH_PeerControl *msg;
5667   struct GNUNET_PeerIdentity id;
5668
5669   if (0 == size && NULL == buf)
5670   {
5671     // TODO retry? cancel?
5672     return 0;
5673   }
5674
5675   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
5676   peer_info = (struct MeshPeerInfo *) cls;
5677   msg = (struct GNUNET_MESH_PeerControl *) buf;
5678   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
5679   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
5680 //     msg->tunnel_id = htonl(peer_info->t->tid);
5681   GNUNET_PEER_resolve (peer_info->id, &id);
5682   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
5683
5684   return size_needed;
5685 }
5686 #endif
5687
5688
5689 /**
5690  * Send keepalive packets for a peer
5691  *
5692  * @param cls Closure (tunnel for which to send the keepalive).
5693  * @param tc Notification context.
5694  *
5695  * TODO: implement explicit multicast keepalive?
5696  */
5697 static void
5698 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
5699 {
5700   struct MeshTunnel *t = cls;
5701   struct GNUNET_MessageHeader *payload;
5702   struct GNUNET_MESH_Multicast *msg;
5703   size_t size =
5704       sizeof (struct GNUNET_MESH_Multicast) +
5705       sizeof (struct GNUNET_MessageHeader);
5706   char cbuf[size];
5707
5708   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
5709   {
5710     return;
5711   }
5712   t->path_refresh_task = GNUNET_SCHEDULER_NO_TASK;
5713
5714   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5715               "sending keepalive for tunnel %d\n", t->id.tid);
5716
5717   msg = (struct GNUNET_MESH_Multicast *) cbuf;
5718   msg->header.size = htons (size);
5719   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
5720   // FIXME: change type to != MULTICAST
5721   msg->oid = my_full_id;
5722   msg->tid = htonl (t->id.tid);
5723   msg->ttl = htonl (default_ttl);
5724   msg->pid = htonl (t->fwd_pid + 1);
5725   t->fwd_pid++;
5726   payload = (struct GNUNET_MessageHeader *) &msg[1];
5727   payload->size = htons (sizeof (struct GNUNET_MessageHeader));
5728   payload->type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE);
5729   tunnel_send_multicast (t, &msg->header, GNUNET_YES);
5730
5731   t->path_refresh_task =
5732       GNUNET_SCHEDULER_add_delayed (refresh_path_time, &path_refresh, t);
5733   return;
5734 }
5735
5736
5737 /**
5738  * Function to process paths received for a new peer addition. The recorded
5739  * paths form the initial tunnel, which can be optimized later.
5740  * Called on each result obtained for the DHT search.
5741  *
5742  * @param cls closure
5743  * @param exp when will this value expire
5744  * @param key key of the result
5745  * @param get_path path of the get request
5746  * @param get_path_length lenght of get_path
5747  * @param put_path path of the put request
5748  * @param put_path_length length of the put_path
5749  * @param type type of the result
5750  * @param size number of bytes in data
5751  * @param data pointer to the result data
5752  *
5753  * TODO: re-issue the request after certain time? cancel after X results?
5754  */
5755 static void
5756 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
5757                     const struct GNUNET_HashCode * key,
5758                     const struct GNUNET_PeerIdentity *get_path,
5759                     unsigned int get_path_length,
5760                     const struct GNUNET_PeerIdentity *put_path,
5761                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
5762                     size_t size, const void *data)
5763 {
5764   struct MeshPathInfo *path_info = cls;
5765   struct MeshPeerPath *p;
5766   struct GNUNET_PeerIdentity pi;
5767   int i;
5768
5769   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
5770   GNUNET_PEER_resolve (path_info->peer->id, &pi);
5771   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", GNUNET_i2s (&pi));
5772
5773   p = path_build_from_dht (get_path, get_path_length, put_path,
5774                            put_path_length);
5775   path_add_to_peers (p, GNUNET_NO);
5776   path_destroy(p);
5777   for (i = 0; i < path_info->peer->ntunnels; i++)
5778   {
5779     tunnel_add_peer (path_info->peer->tunnels[i], path_info->peer);
5780     peer_info_connect (path_info->peer, path_info->t);
5781   }
5782
5783   return;
5784 }
5785
5786
5787 /**
5788  * Function to process paths received for a new peer addition. The recorded
5789  * paths form the initial tunnel, which can be optimized later.
5790  * Called on each result obtained for the DHT search.
5791  *
5792  * @param cls closure
5793  * @param exp when will this value expire
5794  * @param key key of the result
5795  * @param get_path path of the get request
5796  * @param get_path_length lenght of get_path
5797  * @param put_path path of the put request
5798  * @param put_path_length length of the put_path
5799  * @param type type of the result
5800  * @param size number of bytes in data
5801  * @param data pointer to the result data
5802  */
5803 static void
5804 dht_get_type_handler (void *cls, struct GNUNET_TIME_Absolute exp,
5805                       const struct GNUNET_HashCode * key,
5806                       const struct GNUNET_PeerIdentity *get_path,
5807                       unsigned int get_path_length,
5808                       const struct GNUNET_PeerIdentity *put_path,
5809                       unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
5810                       size_t size, const void *data)
5811 {
5812   const struct PBlock *pb = data;
5813   const struct GNUNET_PeerIdentity *pi = &pb->id;
5814   struct MeshTunnel *t = cls;
5815   struct MeshPeerInfo *peer_info;
5816   struct MeshPeerPath *p;
5817
5818   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got type DHT result!\n");
5819   if (size != sizeof (struct PBlock))
5820   {
5821     GNUNET_break_op (0);
5822     return;
5823   }
5824   if (ntohl(pb->type) != t->type)
5825   {
5826     GNUNET_break_op (0);
5827     return;
5828   }
5829   GNUNET_assert (NULL != t->owner);
5830   peer_info = peer_info_get (pi);
5831   (void) GNUNET_CONTAINER_multihashmap_put (t->peers, &pi->hashPubKey,
5832                                             peer_info,
5833                                             GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
5834
5835   p = path_build_from_dht (get_path, get_path_length, put_path,
5836                            put_path_length);
5837   path_add_to_peers (p, GNUNET_NO);
5838   path_destroy(p);
5839   tunnel_add_peer (t, peer_info);
5840   peer_info_connect (peer_info, t);
5841 }
5842
5843
5844 /**
5845  * Function to process DHT string to regex matching.
5846  * Called on each result obtained for the DHT search.
5847  *
5848  * @param cls closure (search context)
5849  * @param exp when will this value expire
5850  * @param key key of the result
5851  * @param get_path path of the get request (not used)
5852  * @param get_path_length lenght of get_path (not used)
5853  * @param put_path path of the put request (not used)
5854  * @param put_path_length length of the put_path (not used)
5855  * @param type type of the result
5856  * @param size number of bytes in data
5857  * @param data pointer to the result data
5858  */
5859 static void
5860 dht_get_string_accept_handler (void *cls, struct GNUNET_TIME_Absolute exp,
5861                                const struct GNUNET_HashCode * key,
5862                                const struct GNUNET_PeerIdentity *get_path,
5863                                unsigned int get_path_length,
5864                                const struct GNUNET_PeerIdentity *put_path,
5865                                unsigned int put_path_length,
5866                                enum GNUNET_BLOCK_Type type,
5867                                size_t size, const void *data)
5868 {
5869   const struct MeshRegexAccept *block = data;
5870   struct MeshRegexSearchContext *ctx = cls;
5871   struct MeshRegexSearchInfo *info = ctx->info;
5872   struct MeshPeerPath *p;
5873   struct MeshPeerInfo *peer_info;
5874
5875   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got regex results from DHT!\n");
5876   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", info->description);
5877
5878   peer_info = peer_info_get(&block->id);
5879   p = path_build_from_dht (get_path, get_path_length, put_path,
5880                            put_path_length);
5881   path_add_to_peers (p, GNUNET_NO);
5882   path_destroy(p);
5883
5884   tunnel_add_peer (info->t, peer_info);
5885   peer_info_connect (peer_info, info->t);
5886   if (0 == info->peer)
5887   {
5888     info->peer = peer_info->id;
5889   }
5890   else
5891   {
5892     GNUNET_array_append (info->peers, info->n_peers, peer_info->id);
5893   }
5894
5895   info->timeout = GNUNET_SCHEDULER_add_delayed (connect_timeout,
5896                                                 &regex_connect_timeout,
5897                                                 info);
5898
5899   return;
5900 }
5901
5902
5903 /**
5904  * Function to process DHT string to regex matching.
5905  * Called on each result obtained for the DHT search.
5906  *
5907  * @param cls closure (search context)
5908  * @param exp when will this value expire
5909  * @param key key of the result
5910  * @param get_path path of the get request (not used)
5911  * @param get_path_length lenght of get_path (not used)
5912  * @param put_path path of the put request (not used)
5913  * @param put_path_length length of the put_path (not used)
5914  * @param type type of the result
5915  * @param size number of bytes in data
5916  * @param data pointer to the result data
5917  *
5918  * TODO: re-issue the request after certain time? cancel after X results?
5919  */
5920 static void
5921 dht_get_string_handler (void *cls, struct GNUNET_TIME_Absolute exp,
5922                         const struct GNUNET_HashCode * key,
5923                         const struct GNUNET_PeerIdentity *get_path,
5924                         unsigned int get_path_length,
5925                         const struct GNUNET_PeerIdentity *put_path,
5926                         unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
5927                         size_t size, const void *data)
5928 {
5929   const struct MeshRegexBlock *block = data;
5930   struct MeshRegexSearchContext *ctx = cls;
5931   struct MeshRegexSearchInfo *info = ctx->info;
5932   void *copy;
5933   size_t len;
5934
5935   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5936               "DHT GET STRING RETURNED RESULTS\n");
5937   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5938               "  key: %s\n", GNUNET_h2s (key));
5939
5940   copy = GNUNET_malloc (size);
5941   memcpy (copy, data, size);
5942   GNUNET_break (GNUNET_OK ==
5943                 GNUNET_CONTAINER_multihashmap_put(info->dht_get_results, key, copy,
5944                                                   GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
5945   len = ntohl (block->n_proof);
5946   {
5947     char proof[len + 1];
5948
5949     memcpy (proof, &block[1], len);
5950     proof[len] = '\0';
5951     if (GNUNET_OK != GNUNET_REGEX_check_proof (proof, key))
5952     {
5953       GNUNET_break_op (0);
5954       return;
5955     }
5956   }
5957   len = strlen (info->description);
5958   if (len == ctx->position) // String processed
5959   {
5960     if (GNUNET_YES == ntohl (block->accepting))
5961     {
5962       regex_find_path(key, ctx);
5963     }
5964     else
5965     {
5966       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  block not accepting!\n");
5967       // FIXME REGEX this block not successful, wait for more? start timeout?
5968     }
5969     return;
5970   }
5971   GNUNET_break (GNUNET_OK ==
5972                 GNUNET_MESH_regex_block_iterate (block, size,
5973                                                  &regex_edge_iterator, ctx));
5974   return;
5975 }
5976
5977 /******************************************************************************/
5978 /*********************       MESH LOCAL HANDLES      **************************/
5979 /******************************************************************************/
5980
5981
5982 /**
5983  * Handler for client disconnection
5984  *
5985  * @param cls closure
5986  * @param client identification of the client; NULL
5987  *        for the last call when the server is destroyed
5988  */
5989 static void
5990 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
5991 {
5992   struct MeshClient *c;
5993   struct MeshClient *next;
5994   unsigned int i;
5995
5996   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected\n");
5997   if (client == NULL)
5998   {
5999     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (SERVER DOWN)\n");
6000     return;
6001   }
6002   c = clients;
6003   while (NULL != c)
6004   {
6005     if (c->handle != client)
6006     {
6007       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ... searching\n");
6008       c = c->next;
6009       continue;
6010     }
6011     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u)\n",
6012                 c->id);
6013     GNUNET_SERVER_client_drop (c->handle);
6014     c->shutting_down = GNUNET_YES;
6015     GNUNET_assert (NULL != c->own_tunnels);
6016     GNUNET_assert (NULL != c->incoming_tunnels);
6017     GNUNET_CONTAINER_multihashmap_iterate (c->own_tunnels,
6018                                            &tunnel_destroy_iterator, c);
6019     GNUNET_CONTAINER_multihashmap_iterate (c->incoming_tunnels,
6020                                            &tunnel_destroy_iterator, c);
6021     GNUNET_CONTAINER_multihashmap_iterate (c->ignore_tunnels,
6022                                            &tunnel_destroy_iterator, c);
6023     GNUNET_CONTAINER_multihashmap_destroy (c->own_tunnels);
6024     GNUNET_CONTAINER_multihashmap_destroy (c->incoming_tunnels);
6025     GNUNET_CONTAINER_multihashmap_destroy (c->ignore_tunnels);
6026
6027     /* deregister clients applications */
6028     if (NULL != c->apps)
6029     {
6030       GNUNET_CONTAINER_multihashmap_iterate (c->apps, &deregister_app, c->apps);
6031       GNUNET_CONTAINER_multihashmap_destroy (c->apps);
6032     }
6033     if (0 == GNUNET_CONTAINER_multihashmap_size (applications) &&
6034         GNUNET_SCHEDULER_NO_TASK != announce_applications_task)
6035     {
6036       GNUNET_SCHEDULER_cancel (announce_applications_task);
6037       announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
6038     }
6039     if (NULL != c->types)
6040       GNUNET_CONTAINER_multihashmap_destroy (c->types);
6041     for (i = 0; i < c->n_regex; i++)
6042     {
6043       GNUNET_free (c->regexes[i]);
6044     }
6045     GNUNET_free_non_null (c->regexes);
6046     if (GNUNET_SCHEDULER_NO_TASK != c->regex_announce_task)
6047       GNUNET_SCHEDULER_cancel (c->regex_announce_task);
6048     next = c->next;
6049     GNUNET_CONTAINER_DLL_remove (clients, clients_tail, c);
6050     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT FREE at %p\n", c);
6051     GNUNET_free (c);
6052     GNUNET_STATISTICS_update (stats, "# clients", -1, GNUNET_NO);
6053     c = next;
6054   }
6055   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   done!\n");
6056   return;
6057 }
6058
6059
6060 /**
6061  * Handler for new clients
6062  *
6063  * @param cls closure
6064  * @param client identification of the client
6065  * @param message the actual message, which includes messages the client wants
6066  */
6067 static void
6068 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
6069                          const struct GNUNET_MessageHeader *message)
6070 {
6071   struct GNUNET_MESH_ClientConnect *cc_msg;
6072   struct MeshClient *c;
6073   GNUNET_MESH_ApplicationType *a;
6074   unsigned int size;
6075   uint16_t ntypes;
6076   uint16_t *t;
6077   uint16_t napps;
6078   uint16_t i;
6079
6080   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected\n");
6081   /* Check data sanity */
6082   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
6083   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
6084   ntypes = ntohs (cc_msg->types);
6085   napps = ntohs (cc_msg->applications);
6086   if (size !=
6087       ntypes * sizeof (uint16_t) + napps * sizeof (GNUNET_MESH_ApplicationType))
6088   {
6089     GNUNET_break (0);
6090     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6091     return;
6092   }
6093
6094   /* Create new client structure */
6095   c = GNUNET_malloc (sizeof (struct MeshClient));
6096   c->id = next_client_id++;
6097   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT NEW %u\n", c->id);
6098   c->handle = client;
6099   GNUNET_SERVER_client_keep (client);
6100   a = (GNUNET_MESH_ApplicationType *) &cc_msg[1];
6101   if (napps > 0)
6102   {
6103     GNUNET_MESH_ApplicationType at;
6104     struct GNUNET_HashCode hc;
6105
6106     c->apps = GNUNET_CONTAINER_multihashmap_create (napps);
6107     for (i = 0; i < napps; i++)
6108     {
6109       at = ntohl (a[i]);
6110       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  app type: %u\n", at);
6111       GNUNET_CRYPTO_hash (&at, sizeof (at), &hc);
6112       /* store in clients hashmap */
6113       GNUNET_CONTAINER_multihashmap_put (c->apps, &hc, (void *) (long) at,
6114                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6115       /* store in global hashmap, for announcements */
6116       GNUNET_CONTAINER_multihashmap_put (applications, &hc, c,
6117                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6118     }
6119     if (GNUNET_SCHEDULER_NO_TASK == announce_applications_task)
6120       announce_applications_task =
6121           GNUNET_SCHEDULER_add_now (&announce_applications, NULL);
6122
6123   }
6124   if (ntypes > 0)
6125   {
6126     uint16_t u16;
6127     struct GNUNET_HashCode hc;
6128
6129     t = (uint16_t *) & a[napps];
6130     c->types = GNUNET_CONTAINER_multihashmap_create (ntypes);
6131     for (i = 0; i < ntypes; i++)
6132     {
6133       u16 = ntohs (t[i]);
6134       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  msg type: %u\n", u16);
6135       GNUNET_CRYPTO_hash (&u16, sizeof (u16), &hc);
6136
6137       /* store in clients hashmap */
6138       GNUNET_CONTAINER_multihashmap_put (c->types, &hc, c,
6139                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6140       /* store in global hashmap */
6141       GNUNET_CONTAINER_multihashmap_put (types, &hc, c,
6142                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6143     }
6144   }
6145   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6146               " client has %u+%u subscriptions\n", napps, ntypes);
6147
6148   GNUNET_CONTAINER_DLL_insert (clients, clients_tail, c);
6149   c->own_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
6150   c->incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
6151   c->ignore_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
6152   GNUNET_SERVER_notification_context_add (nc, client);
6153   GNUNET_STATISTICS_update (stats, "# clients", 1, GNUNET_NO);
6154
6155   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6156   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
6157 }
6158
6159
6160 /**
6161  * Handler for clients announcing available services by a regular expression.
6162  *
6163  * @param cls closure
6164  * @param client identification of the client
6165  * @param message the actual message, which includes messages the client wants
6166  */
6167 static void
6168 handle_local_announce_regex (void *cls, struct GNUNET_SERVER_Client *client,
6169                              const struct GNUNET_MessageHeader *message)
6170 {
6171   struct MeshClient *c;
6172   char *regex;
6173   size_t len;
6174
6175   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "announce regex started\n");
6176
6177   /* Sanity check for client registration */
6178   if (NULL == (c = client_get (client)))
6179   {
6180     GNUNET_break (0);
6181     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6182     return;
6183   }
6184   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6185
6186   len = ntohs (message->size) - sizeof(struct GNUNET_MessageHeader);
6187   regex = GNUNET_malloc (len + 1);
6188   memcpy (regex, &message[1], len);
6189   regex[len] = '\0';
6190   GNUNET_array_append (c->regexes, c->n_regex, regex);
6191   if (GNUNET_SCHEDULER_NO_TASK == c->regex_announce_task)
6192   {
6193     c->regex_announce_task = GNUNET_SCHEDULER_add_now(&announce_regex, c);
6194   }
6195   else
6196   {
6197     regex_put(regex);
6198   }
6199   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6200   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "announce regex processed\n");
6201 }
6202
6203
6204 /**
6205  * Handler for requests of new tunnels
6206  *
6207  * @param cls closure
6208  * @param client identification of the client
6209  * @param message the actual message
6210  */
6211 static void
6212 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
6213                             const struct GNUNET_MessageHeader *message)
6214 {
6215   struct GNUNET_MESH_TunnelMessage *t_msg;
6216   struct MeshTunnel *t;
6217   struct MeshClient *c;
6218   MESH_TunnelNumber tid;
6219
6220   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel requested\n");
6221
6222   /* Sanity check for client registration */
6223   if (NULL == (c = client_get (client)))
6224   {
6225     GNUNET_break (0);
6226     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6227     return;
6228   }
6229   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6230
6231   /* Message sanity check */
6232   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
6233   {
6234     GNUNET_break (0);
6235     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6236     return;
6237   }
6238
6239   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6240   /* Sanity check for tunnel numbering */
6241   tid = ntohl (t_msg->tunnel_id);
6242   if (0 == (tid & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
6243   {
6244     GNUNET_break (0);
6245     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6246     return;
6247   }
6248   /* Sanity check for duplicate tunnel IDs */
6249   if (NULL != tunnel_get_by_local_id (c, tid))
6250   {
6251     GNUNET_break (0);
6252     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6253     return;
6254   }
6255
6256   while (NULL != tunnel_get_by_pi (myid, next_tid))
6257     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
6258   t = tunnel_new (myid, next_tid++, c, tid);
6259   if (NULL == t)
6260   {
6261     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Tunnel creation failed.\n");
6262     GNUNET_break (0);
6263     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6264     return;
6265   }
6266   next_tid = next_tid & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
6267   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED TUNNEL %s [%x] (%x)\n",
6268               GNUNET_i2s (&my_full_id), t->id.tid, t->local_tid);
6269   t->peers = GNUNET_CONTAINER_multihashmap_create (32);
6270
6271   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel created\n");
6272   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6273   return;
6274 }
6275
6276
6277 /**
6278  * Handler for requests of deleting tunnels
6279  *
6280  * @param cls closure
6281  * @param client identification of the client
6282  * @param message the actual message
6283  */
6284 static void
6285 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
6286                              const struct GNUNET_MessageHeader *message)
6287 {
6288   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
6289   struct MeshClient *c;
6290   struct MeshTunnel *t;
6291   MESH_TunnelNumber tid;
6292
6293   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6294               "Got a DESTROY TUNNEL from client!\n");
6295
6296   /* Sanity check for client registration */
6297   if (NULL == (c = client_get (client)))
6298   {
6299     GNUNET_break (0);
6300     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6301     return;
6302   }
6303   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6304
6305   /* Message sanity check */
6306   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
6307   {
6308     GNUNET_break (0);
6309     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6310     return;
6311   }
6312
6313   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6314
6315   /* Retrieve tunnel */
6316   tid = ntohl (tunnel_msg->tunnel_id);
6317   t = tunnel_get_by_local_id(c, tid);
6318   if (NULL == t)
6319   {
6320     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
6321     GNUNET_break (0);
6322     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6323     return;
6324   }
6325   if (c != t->owner || tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
6326   {
6327     client_ignore_tunnel (c, t);
6328 #if 0
6329     // TODO: when to destroy incoming tunnel?
6330     if (t->nclients == 0)
6331     {
6332       GNUNET_assert (GNUNET_YES ==
6333                      GNUNET_CONTAINER_multihashmap_remove (incoming_tunnels,
6334                                                            &hash, t));
6335       GNUNET_assert (GNUNET_YES ==
6336                      GNUNET_CONTAINER_multihashmap_remove (t->peers,
6337                                                            &my_full_id.hashPubKey,
6338                                                            t));
6339     }
6340 #endif
6341     GNUNET_SERVER_receive_done (client, GNUNET_OK);
6342     return;
6343   }
6344   send_client_tunnel_disconnect(t, c);
6345   client_delete_tunnel(c, t);
6346
6347   /* Don't try to ACK the client about the tunnel_destroy multicast packet */
6348   t->owner = NULL;
6349   tunnel_send_destroy (t);
6350   t->destroy = GNUNET_YES;
6351   // The tunnel will be destroyed when the last message is transmitted.
6352   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6353   return;
6354 }
6355
6356
6357 /**
6358  * Handler for requests of seeting tunnel's speed.
6359  *
6360  * @param cls Closure (unused).
6361  * @param client Identification of the client.
6362  * @param message The actual message.
6363  */
6364 static void
6365 handle_local_tunnel_speed (void *cls, struct GNUNET_SERVER_Client *client,
6366                            const struct GNUNET_MessageHeader *message)
6367 {
6368   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
6369   struct MeshClient *c;
6370   struct MeshTunnel *t;
6371   MESH_TunnelNumber tid;
6372
6373   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6374               "Got a SPEED request from client!\n");
6375
6376   /* Sanity check for client registration */
6377   if (NULL == (c = client_get (client)))
6378   {
6379     GNUNET_break (0);
6380     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6381     return;
6382   }
6383
6384   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6385
6386   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6387
6388   /* Retrieve tunnel */
6389   tid = ntohl (tunnel_msg->tunnel_id);
6390   t = tunnel_get_by_local_id(c, tid);
6391   if (NULL == t)
6392   {
6393     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  tunnel %X not found\n", tid);
6394     GNUNET_break (0);
6395     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6396     return;
6397   }
6398
6399   switch (ntohs(message->type))
6400   {
6401       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MIN:
6402           t->speed_min = GNUNET_YES;
6403           break;
6404       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MAX:
6405           t->speed_min = GNUNET_NO;
6406           break;
6407       default:
6408           GNUNET_break (0);
6409   }
6410   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6411 }
6412
6413
6414 /**
6415  * Handler for requests of seeting tunnel's buffering policy.
6416  *
6417  * @param cls Closure (unused).
6418  * @param client Identification of the client.
6419  * @param message The actual message.
6420  */
6421 static void
6422 handle_local_tunnel_buffer (void *cls, struct GNUNET_SERVER_Client *client,
6423                             const struct GNUNET_MessageHeader *message)
6424 {
6425   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
6426   struct MeshClient *c;
6427   struct MeshTunnel *t;
6428   MESH_TunnelNumber tid;
6429
6430   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6431               "Got a BUFFER request from client!\n");
6432
6433   /* Sanity check for client registration */
6434   if (NULL == (c = client_get (client)))
6435   {
6436     GNUNET_break (0);
6437     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6438     return;
6439   }
6440   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6441
6442   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6443
6444   /* Retrieve tunnel */
6445   tid = ntohl (tunnel_msg->tunnel_id);
6446   t = tunnel_get_by_local_id(c, tid);
6447   if (NULL == t)
6448   {
6449     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
6450     GNUNET_break (0);
6451     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6452     return;
6453   }
6454
6455   switch (ntohs(message->type))
6456   {
6457       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER:
6458           t->nobuffer = GNUNET_NO;
6459           break;
6460       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER:
6461           t->nobuffer = GNUNET_YES;
6462           break;
6463       default:
6464           GNUNET_break (0);
6465   }
6466
6467   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6468 }
6469
6470
6471 /**
6472  * Handler for connection requests to new peers
6473  *
6474  * @param cls closure
6475  * @param client identification of the client
6476  * @param message the actual message (PeerControl)
6477  */
6478 static void
6479 handle_local_connect_add (void *cls, struct GNUNET_SERVER_Client *client,
6480                           const struct GNUNET_MessageHeader *message)
6481 {
6482   struct GNUNET_MESH_PeerControl *peer_msg;
6483   struct MeshPeerInfo *peer_info;
6484   struct MeshClient *c;
6485   struct MeshTunnel *t;
6486   MESH_TunnelNumber tid;
6487
6488   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got connection request\n");
6489   /* Sanity check for client registration */
6490   if (NULL == (c = client_get (client)))
6491   {
6492     GNUNET_break (0);
6493     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6494     return;
6495   }
6496   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6497
6498   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6499
6500   /* Sanity check for message size */
6501   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6502   {
6503     GNUNET_break (0);
6504     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6505     return;
6506   }
6507
6508   /* Tunnel exists? */
6509   tid = ntohl (peer_msg->tunnel_id);
6510   t = tunnel_get_by_local_id (c, tid);
6511   if (NULL == t)
6512   {
6513     GNUNET_break (0);
6514     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6515     return;
6516   }
6517
6518   /* Does client own tunnel? */
6519   if (t->owner->handle != client)
6520   {
6521     GNUNET_break (0);
6522     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6523     return;
6524   }
6525   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "     for %s\n",
6526               GNUNET_i2s (&peer_msg->peer));
6527   peer_info = peer_info_get (&peer_msg->peer);
6528
6529   tunnel_add_peer (t, peer_info);
6530   peer_info_connect (peer_info, t);
6531
6532   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6533   return;
6534 }
6535
6536
6537 /**
6538  * Handler for disconnection requests of peers in a tunnel
6539  *
6540  * @param cls closure
6541  * @param client identification of the client
6542  * @param message the actual message (PeerControl)
6543  */
6544 static void
6545 handle_local_connect_del (void *cls, struct GNUNET_SERVER_Client *client,
6546                           const struct GNUNET_MessageHeader *message)
6547 {
6548   struct GNUNET_MESH_PeerControl *peer_msg;
6549   struct MeshPeerInfo *peer_info;
6550   struct MeshClient *c;
6551   struct MeshTunnel *t;
6552   MESH_TunnelNumber tid;
6553
6554   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER DEL request\n");
6555   /* Sanity check for client registration */
6556   if (NULL == (c = client_get (client)))
6557   {
6558     GNUNET_break (0);
6559     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6560     return;
6561   }
6562   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6563
6564   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6565
6566   /* Sanity check for message size */
6567   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6568   {
6569     GNUNET_break (0);
6570     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6571     return;
6572   }
6573
6574   /* Tunnel exists? */
6575   tid = ntohl (peer_msg->tunnel_id);
6576   t = tunnel_get_by_local_id (c, tid);
6577   if (NULL == t)
6578   {
6579     GNUNET_break (0);
6580     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6581     return;
6582   }
6583   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
6584
6585   /* Does client own tunnel? */
6586   if (t->owner->handle != client)
6587   {
6588     GNUNET_break (0);
6589     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6590     return;
6591   }
6592
6593   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for peer %s\n",
6594               GNUNET_i2s (&peer_msg->peer));
6595   /* Is the peer in the tunnel? */
6596   peer_info =
6597       GNUNET_CONTAINER_multihashmap_get (t->peers, &peer_msg->peer.hashPubKey);
6598   if (NULL == peer_info)
6599   {
6600     GNUNET_break (0);
6601     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6602     return;
6603   }
6604
6605   /* Ok, delete peer from tunnel */
6606   GNUNET_CONTAINER_multihashmap_remove_all (t->peers,
6607                                             &peer_msg->peer.hashPubKey);
6608
6609   send_destroy_path (t, peer_info->id);
6610   tunnel_delete_peer (t, peer_info->id);
6611   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6612   return;
6613 }
6614
6615 /**
6616  * Handler for blacklist requests of peers in a tunnel
6617  *
6618  * @param cls closure
6619  * @param client identification of the client
6620  * @param message the actual message (PeerControl)
6621  * 
6622  * FIXME implement DHT block bloomfilter
6623  */
6624 static void
6625 handle_local_blacklist (void *cls, struct GNUNET_SERVER_Client *client,
6626                           const struct GNUNET_MessageHeader *message)
6627 {
6628   struct GNUNET_MESH_PeerControl *peer_msg;
6629   struct MeshClient *c;
6630   struct MeshTunnel *t;
6631   MESH_TunnelNumber tid;
6632
6633   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER BLACKLIST request\n");
6634   /* Sanity check for client registration */
6635   if (NULL == (c = client_get (client)))
6636   {
6637     GNUNET_break (0);
6638     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6639     return;
6640   }
6641   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6642
6643   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6644
6645   /* Sanity check for message size */
6646   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6647   {
6648     GNUNET_break (0);
6649     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6650     return;
6651   }
6652
6653   /* Tunnel exists? */
6654   tid = ntohl (peer_msg->tunnel_id);
6655   t = tunnel_get_by_local_id (c, tid);
6656   if (NULL == t)
6657   {
6658     GNUNET_break (0);
6659     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6660     return;
6661   }
6662   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
6663
6664   GNUNET_array_append(t->blacklisted, t->nblacklisted,
6665                       GNUNET_PEER_intern(&peer_msg->peer));
6666 }
6667
6668
6669 /**
6670  * Handler for unblacklist requests of peers in a tunnel
6671  *
6672  * @param cls closure
6673  * @param client identification of the client
6674  * @param message the actual message (PeerControl)
6675  */
6676 static void
6677 handle_local_unblacklist (void *cls, struct GNUNET_SERVER_Client *client,
6678                           const struct GNUNET_MessageHeader *message)
6679 {
6680   struct GNUNET_MESH_PeerControl *peer_msg;
6681   struct MeshClient *c;
6682   struct MeshTunnel *t;
6683   MESH_TunnelNumber tid;
6684   GNUNET_PEER_Id pid;
6685   unsigned int i;
6686
6687   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER UNBLACKLIST request\n");
6688   /* Sanity check for client registration */
6689   if (NULL == (c = client_get (client)))
6690   {
6691     GNUNET_break (0);
6692     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6693     return;
6694   }
6695   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6696
6697   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6698
6699   /* Sanity check for message size */
6700   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6701   {
6702     GNUNET_break (0);
6703     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6704     return;
6705   }
6706
6707   /* Tunnel exists? */
6708   tid = ntohl (peer_msg->tunnel_id);
6709   t = tunnel_get_by_local_id (c, tid);
6710   if (NULL == t)
6711   {
6712     GNUNET_break (0);
6713     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6714     return;
6715   }
6716   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
6717
6718   /* if peer is not known, complain */
6719   pid = GNUNET_PEER_search (&peer_msg->peer);
6720   if (0 == pid)
6721   {
6722     GNUNET_break (0);
6723     return;
6724   }
6725
6726   /* search and remove from list */
6727   for (i = 0; i < t->nblacklisted; i++)
6728   {
6729     if (t->blacklisted[i] == pid)
6730     {
6731       t->blacklisted[i] = t->blacklisted[t->nblacklisted - 1];
6732       GNUNET_array_grow (t->blacklisted, t->nblacklisted, t->nblacklisted - 1);
6733       return;
6734     }
6735   }
6736
6737   /* if peer hasn't been blacklisted, complain */
6738   GNUNET_break (0);
6739 }
6740
6741
6742 /**
6743  * Handler for connection requests to new peers by type
6744  *
6745  * @param cls closure
6746  * @param client identification of the client
6747  * @param message the actual message (ConnectPeerByType)
6748  */
6749 static void
6750 handle_local_connect_by_type (void *cls, struct GNUNET_SERVER_Client *client,
6751                               const struct GNUNET_MessageHeader *message)
6752 {
6753   struct GNUNET_MESH_ConnectPeerByType *connect_msg;
6754   struct MeshClient *c;
6755   struct MeshTunnel *t;
6756   struct GNUNET_HashCode hash;
6757   MESH_TunnelNumber tid;
6758
6759   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got connect by type request\n");
6760   /* Sanity check for client registration */
6761   if (NULL == (c = client_get (client)))
6762   {
6763     GNUNET_break (0);
6764     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6765     return;
6766   }
6767   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6768
6769   connect_msg = (struct GNUNET_MESH_ConnectPeerByType *) message;
6770
6771   /* Sanity check for message size */
6772   if (sizeof (struct GNUNET_MESH_ConnectPeerByType) !=
6773       ntohs (connect_msg->header.size))
6774   {
6775     GNUNET_break (0);
6776     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6777     return;
6778   }
6779
6780   /* Tunnel exists? */
6781   tid = ntohl (connect_msg->tunnel_id);
6782   t = tunnel_get_by_local_id (c, tid);
6783   if (NULL == t)
6784   {
6785     GNUNET_break (0);
6786     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6787     return;
6788   }
6789
6790   /* Does client own tunnel? */
6791   if (t->owner->handle != client)
6792   {
6793     GNUNET_break (0);
6794     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6795     return;
6796   }
6797
6798   /* Do WE have the service? */
6799   t->type = ntohl (connect_msg->type);
6800   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " type requested: %u\n", t->type);
6801   GNUNET_CRYPTO_hash (&t->type, sizeof (GNUNET_MESH_ApplicationType), &hash);
6802   if (GNUNET_CONTAINER_multihashmap_contains (applications, &hash) ==
6803       GNUNET_YES)
6804   {
6805     /* Yes! Fast forward, add ourselves to the tunnel and send the
6806      * good news to the client, and alert the destination client of
6807      * an incoming tunnel.
6808      *
6809      * FIXME send a path create to self, avoid code duplication
6810      */
6811     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " available locally\n");
6812     GNUNET_CONTAINER_multihashmap_put (t->peers, &my_full_id.hashPubKey,
6813                                        peer_info_get (&my_full_id),
6814                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
6815
6816     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " notifying client\n");
6817     send_client_peer_connected (t, myid);
6818     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Done\n");
6819     GNUNET_SERVER_receive_done (client, GNUNET_OK);
6820
6821     t->local_tid_dest = next_local_tid++;
6822     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
6823     GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
6824                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
6825
6826     return;
6827   }
6828   /* Ok, lets find a peer offering the service */
6829   if (NULL != t->dht_get_type)
6830   {
6831     GNUNET_DHT_get_stop (t->dht_get_type);
6832   }
6833   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " looking in DHT for %s\n",
6834               GNUNET_h2s (&hash));
6835   t->dht_get_type =
6836       GNUNET_DHT_get_start (dht_handle, 
6837                             GNUNET_BLOCK_TYPE_MESH_PEER_BY_TYPE,
6838                             &hash,
6839                             dht_replication_level,
6840                             GNUNET_DHT_RO_RECORD_ROUTE |
6841                             GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
6842                             NULL, 0,
6843                             &dht_get_type_handler, t);
6844
6845   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6846   return;
6847 }
6848
6849
6850 /**
6851  * Handler for connection requests to new peers by a string service description.
6852  *
6853  * @param cls closure
6854  * @param client identification of the client
6855  * @param message the actual message, which includes messages the client wants
6856  */
6857 static void
6858 handle_local_connect_by_string (void *cls, struct GNUNET_SERVER_Client *client,
6859                                 const struct GNUNET_MessageHeader *message)
6860 {
6861   struct GNUNET_MESH_ConnectPeerByString *msg;
6862   struct MeshRegexSearchContext *ctx;
6863   struct MeshRegexSearchInfo *info;
6864   struct GNUNET_DHT_GetHandle *get_h;
6865   struct GNUNET_HashCode key;
6866   struct MeshTunnel *t;
6867   struct MeshClient *c;
6868   MESH_TunnelNumber tid;
6869   const char *string;
6870   size_t size;
6871   size_t len;
6872   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6873               "Connect by string started\n");
6874   msg = (struct GNUNET_MESH_ConnectPeerByString *) message;
6875   size = htons (message->size);
6876
6877   /* Sanity check for client registration */
6878   if (NULL == (c = client_get (client)))
6879   {
6880     GNUNET_break (0);
6881     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6882     return;
6883   }
6884   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6885
6886   /* Message size sanity check */
6887   if (sizeof(struct GNUNET_MESH_ConnectPeerByString) >= size)
6888   {
6889     GNUNET_break (0);
6890     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6891     return;
6892   }
6893
6894   /* Tunnel exists? */
6895   tid = ntohl (msg->tunnel_id);
6896   t = tunnel_get_by_local_id (c, tid);
6897   if (NULL == t)
6898   {
6899     GNUNET_break (0);
6900     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6901     return;
6902   }
6903
6904   /* Does client own tunnel? */
6905   if (t->owner->handle != client)
6906   {
6907     GNUNET_break (0);
6908     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6909     return;
6910   }
6911
6912   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6913               "  on tunnel %s [%u]\n",
6914               GNUNET_i2s(&my_full_id),
6915               t->id.tid);
6916
6917   /* Only one connect_by_string allowed at the same time! */
6918   /* FIXME: allow more, return handle at api level to cancel, document */
6919   if (NULL != t->regex_ctx)
6920   {
6921     GNUNET_break (0);
6922     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6923     return;
6924   }
6925
6926   /* Find string itself */
6927   len = size - sizeof(struct GNUNET_MESH_ConnectPeerByString);
6928   string = (const char *) &msg[1];
6929
6930   /* Initialize context */
6931   size = GNUNET_REGEX_get_first_key(string, len, &key);
6932   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6933               "  consumed %u bits out of %u\n", size, len);
6934   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6935               "  looking for %s\n", GNUNET_h2s (&key));
6936
6937   info = GNUNET_malloc (sizeof (struct MeshRegexSearchInfo));
6938   info->t = t;
6939   info->description = GNUNET_malloc (len + 1);
6940   memcpy (info->description, string, len);
6941   info->description[len] = '\0';
6942   info->dht_get_handles = GNUNET_CONTAINER_multihashmap_create(32);
6943   info->dht_get_results = GNUNET_CONTAINER_multihashmap_create(32);
6944   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   string: %s\n", info->description);
6945
6946   ctx = GNUNET_malloc (sizeof (struct MeshRegexSearchContext));
6947   ctx->position = size;
6948   ctx->info = info;
6949   t->regex_ctx = ctx;
6950
6951   GNUNET_array_append (info->contexts, info->n_contexts, ctx);
6952
6953   /* Start search in DHT */
6954   get_h = GNUNET_DHT_get_start (dht_handle,    /* handle */
6955                                 GNUNET_BLOCK_TYPE_MESH_REGEX, /* type */
6956                                 &key,     /* key to search */
6957                                 dht_replication_level, /* replication level */
6958                                 GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
6959                                 NULL,       /* xquery */ // FIXME BLOOMFILTER
6960                                 0,     /* xquery bits */ // FIXME BLOOMFILTER SIZE
6961                                 &dht_get_string_handler, ctx);
6962
6963   GNUNET_break (GNUNET_OK ==
6964                 GNUNET_CONTAINER_multihashmap_put(info->dht_get_handles,
6965                                                   &key,
6966                                                   get_h,
6967                                                   GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
6968
6969   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6970   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "connect by string processed\n");
6971 }
6972
6973
6974 /**
6975  * Handler for client traffic directed to one peer
6976  *
6977  * @param cls closure
6978  * @param client identification of the client
6979  * @param message the actual message
6980  */
6981 static void
6982 handle_local_unicast (void *cls, struct GNUNET_SERVER_Client *client,
6983                       const struct GNUNET_MessageHeader *message)
6984 {
6985   struct MeshClient *c;
6986   struct MeshTunnel *t;
6987   struct MeshPeerInfo *pi;
6988   struct GNUNET_MESH_Unicast *data_msg;
6989   MESH_TunnelNumber tid;
6990   size_t size;
6991
6992   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6993               "Got a unicast request from a client!\n");
6994
6995   /* Sanity check for client registration */
6996   if (NULL == (c = client_get (client)))
6997   {
6998     GNUNET_break (0);
6999     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7000     return;
7001   }
7002   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7003
7004   data_msg = (struct GNUNET_MESH_Unicast *) message;
7005
7006   /* Sanity check for message size */
7007   size = ntohs (message->size);
7008   if (sizeof (struct GNUNET_MESH_Unicast) +
7009       sizeof (struct GNUNET_MessageHeader) > size)
7010   {
7011     GNUNET_break (0);
7012     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7013     return;
7014   }
7015
7016   /* Tunnel exists? */
7017   tid = ntohl (data_msg->tid);
7018   t = tunnel_get_by_local_id (c, tid);
7019   if (NULL == t)
7020   {
7021     GNUNET_break (0);
7022     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7023     return;
7024   }
7025
7026   /*  Is it a local tunnel? Then, does client own the tunnel? */
7027   if (t->owner->handle != client)
7028   {
7029     GNUNET_break (0);
7030     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7031     return;
7032   }
7033
7034   pi = GNUNET_CONTAINER_multihashmap_get (t->peers,
7035                                           &data_msg->destination.hashPubKey);
7036   /* Is the selected peer in the tunnel? */
7037   if (NULL == pi)
7038   {
7039     GNUNET_break (0);
7040     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7041     return;
7042   }
7043
7044   /* PID should be as expected */
7045   if (ntohl (data_msg->pid) != t->fwd_pid + 1)
7046   {
7047     GNUNET_break (0);
7048     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7049               "Unicast PID, expected %u, got %u\n",
7050               t->fwd_pid + 1, ntohl (data_msg->pid));
7051     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7052     return;
7053   }
7054
7055   /* Ok, everything is correct, send the message
7056    * (pretend we got it from a mesh peer)
7057    */
7058   {
7059     /* Work around const limitation */
7060     char buf[ntohs (message->size)] GNUNET_ALIGN;
7061     struct GNUNET_MESH_Unicast *copy;
7062
7063     copy = (struct GNUNET_MESH_Unicast *) buf;
7064     memcpy (buf, data_msg, size);
7065     copy->oid = my_full_id;
7066     copy->tid = htonl (t->id.tid);
7067     copy->ttl = htonl (default_ttl);
7068     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7069                 "  calling generic handler...\n");
7070     handle_mesh_data_unicast (NULL, &my_full_id, &copy->header, NULL, 0);
7071   }
7072   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "receive done OK\n");
7073   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7074
7075   return;
7076 }
7077
7078
7079 /**
7080  * Handler for client traffic directed to the origin
7081  *
7082  * @param cls closure
7083  * @param client identification of the client
7084  * @param message the actual message
7085  */
7086 static void
7087 handle_local_to_origin (void *cls, struct GNUNET_SERVER_Client *client,
7088                         const struct GNUNET_MessageHeader *message)
7089 {
7090   struct GNUNET_MESH_ToOrigin *data_msg;
7091   struct MeshTunnelClientInfo *clinfo;
7092   struct MeshClient *c;
7093   struct MeshTunnel *t;
7094   MESH_TunnelNumber tid;
7095   size_t size;
7096
7097   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7098               "Got a ToOrigin request from a client!\n");
7099   /* Sanity check for client registration */
7100   if (NULL == (c = client_get (client)))
7101   {
7102     GNUNET_break (0);
7103     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7104     return;
7105   }
7106   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7107
7108   data_msg = (struct GNUNET_MESH_ToOrigin *) message;
7109
7110   /* Sanity check for message size */
7111   size = ntohs (message->size);
7112   if (sizeof (struct GNUNET_MESH_ToOrigin) +
7113       sizeof (struct GNUNET_MessageHeader) > size)
7114   {
7115     GNUNET_break (0);
7116     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7117     return;
7118   }
7119
7120   /* Tunnel exists? */
7121   tid = ntohl (data_msg->tid);
7122   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
7123   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
7124   {
7125     GNUNET_break (0);
7126     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7127     return;
7128   }
7129   t = tunnel_get_by_local_id (c, tid);
7130   if (NULL == t)
7131   {
7132     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
7133     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
7134     GNUNET_break (0);
7135     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7136     return;
7137   }
7138
7139   /*  It should be sent by someone who has this as incoming tunnel. */
7140   if (GNUNET_NO == client_knows_tunnel (c, t))
7141   {
7142     GNUNET_break (0);
7143     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7144     return;
7145   }
7146
7147   /* PID should be as expected */
7148   clinfo = tunnel_get_client_fc (t, c);
7149   if (ntohl (data_msg->pid) != clinfo->bck_pid + 1)
7150   {
7151     GNUNET_break (0);
7152     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7153                 "To Origin PID, expected %u, got %u\n",
7154                 clinfo->bck_pid + 1,
7155                 ntohl (data_msg->pid));
7156     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7157     return;
7158   }
7159
7160   /* Ok, everything is correct, send the message
7161    * (pretend we got it from a mesh peer)
7162    */
7163   clinfo->bck_pid++;
7164   {
7165     char buf[ntohs (message->size)] GNUNET_ALIGN;
7166     struct GNUNET_MESH_ToOrigin *copy;
7167
7168     /* Work around const limitation */
7169     copy = (struct GNUNET_MESH_ToOrigin *) buf;
7170     memcpy (buf, data_msg, size);
7171     GNUNET_PEER_resolve (t->id.oid, &copy->oid);
7172     copy->tid = htonl (t->id.tid);
7173     copy->ttl = htonl (default_ttl);
7174     if (ntohl (copy->pid) != (t->bck_pid + 1))
7175     {
7176       GNUNET_break (0);
7177       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7178                   "To Origin PID, expected %u, got %u\n",
7179                   t->bck_pid + 1,
7180                   ntohl (copy->pid));
7181       return;
7182     }
7183     t->bck_pid++;
7184     copy->sender = my_full_id;
7185     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7186                 "  calling generic handler...\n");
7187     handle_mesh_data_to_orig (NULL, &my_full_id, &copy->header, NULL, 0);
7188   }
7189   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7190
7191   return;
7192 }
7193
7194
7195 /**
7196  * Handler for client traffic directed to all peers in a tunnel
7197  *
7198  * @param cls closure
7199  * @param client identification of the client
7200  * @param message the actual message
7201  */
7202 static void
7203 handle_local_multicast (void *cls, struct GNUNET_SERVER_Client *client,
7204                         const struct GNUNET_MessageHeader *message)
7205 {
7206   struct MeshClient *c;
7207   struct MeshTunnel *t;
7208   struct GNUNET_MESH_Multicast *data_msg;
7209   MESH_TunnelNumber tid;
7210
7211   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7212               "Got a multicast request from a client!\n");
7213
7214   /* Sanity check for client registration */
7215   if (NULL == (c = client_get (client)))
7216   {
7217     GNUNET_break (0);
7218     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7219     return;
7220   }
7221   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7222
7223   data_msg = (struct GNUNET_MESH_Multicast *) message;
7224
7225   /* Sanity check for message size */
7226   if (sizeof (struct GNUNET_MESH_Multicast) +
7227       sizeof (struct GNUNET_MessageHeader) > ntohs (data_msg->header.size))
7228   {
7229     GNUNET_break (0);
7230     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7231     return;
7232   }
7233
7234   /* Tunnel exists? */
7235   tid = ntohl (data_msg->tid);
7236   t = tunnel_get_by_local_id (c, tid);
7237   if (NULL == t)
7238   {
7239     GNUNET_break (0);
7240     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
7241     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
7242     GNUNET_break (0);
7243     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7244     return;
7245   }
7246
7247   /* Does client own tunnel? */
7248   if (t->owner->handle != client)
7249   {
7250     GNUNET_break (0);
7251     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7252     return;
7253   }
7254
7255   /* PID should be as expected */
7256   if (ntohl (data_msg->pid) != t->fwd_pid + 1)
7257   {
7258     GNUNET_break (0);
7259     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7260               "Multicast PID, expected %u, got %u\n",
7261               t->fwd_pid + 1, ntohl (data_msg->pid));
7262     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7263     return;
7264   }
7265
7266   {
7267     char buf[ntohs (message->size)] GNUNET_ALIGN;
7268     struct GNUNET_MESH_Multicast *copy;
7269
7270     copy = (struct GNUNET_MESH_Multicast *) buf;
7271     memcpy (buf, message, ntohs (message->size));
7272     copy->oid = my_full_id;
7273     copy->tid = htonl (t->id.tid);
7274     copy->ttl = htonl (default_ttl);
7275     GNUNET_assert (ntohl (copy->pid) == (t->fwd_pid + 1));
7276     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7277                 "  calling generic handler...\n");
7278     handle_mesh_data_multicast (client, &my_full_id, &copy->header, NULL, 0);
7279   }
7280
7281   /* receive done gets called when last copy is sent to a neighbor */
7282   return;
7283 }
7284
7285
7286 /**
7287  * Handler for client's ACKs for payload traffic.
7288  *
7289  * @param cls Closure (unused).
7290  * @param client Identification of the client.
7291  * @param message The actual message.
7292  */
7293 static void
7294 handle_local_ack (void *cls, struct GNUNET_SERVER_Client *client,
7295                   const struct GNUNET_MessageHeader *message)
7296 {
7297   struct GNUNET_MESH_LocalAck *msg;
7298   struct MeshTunnel *t;
7299   struct MeshClient *c;
7300   MESH_TunnelNumber tid;
7301   uint32_t ack;
7302
7303   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a local ACK\n");
7304   /* Sanity check for client registration */
7305   if (NULL == (c = client_get (client)))
7306   {
7307     GNUNET_break (0);
7308     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7309     return;
7310   }
7311   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7312
7313   msg = (struct GNUNET_MESH_LocalAck *) message;
7314
7315   /* Tunnel exists? */
7316   tid = ntohl (msg->tunnel_id);
7317   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
7318   t = tunnel_get_by_local_id (c, tid);
7319   if (NULL == t)
7320   {
7321     GNUNET_break (0); // FIXME fc
7322     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
7323     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
7324     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7325     return;
7326   }
7327
7328   ack = ntohl (msg->max_pid);
7329   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ack %u\n", ack);
7330
7331   /* Does client own tunnel? I.E: Is this and ACK for BCK traffic? */
7332   if (NULL != t->owner && t->owner->handle == client)
7333   {
7334     /* The client owns the tunnel, ACK is for data to_origin, send BCK ACK. */
7335     t->bck_ack = ack;
7336     tunnel_send_bck_ack(t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
7337   }
7338   else
7339   {
7340     /* The client doesn't own the tunnel, this ACK is for FWD traffic. */
7341     tunnel_set_client_fwd_ack (t, c, ack);
7342     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
7343   }
7344
7345   GNUNET_SERVER_receive_done (client, GNUNET_OK);  
7346
7347   return;
7348 }
7349
7350
7351 /**
7352  * Functions to handle messages from clients
7353  */
7354 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
7355   {&handle_local_new_client, NULL,
7356    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
7357   {&handle_local_announce_regex, NULL,
7358    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ANNOUNCE_REGEX, 0},
7359   {&handle_local_tunnel_create, NULL,
7360    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
7361    sizeof (struct GNUNET_MESH_TunnelMessage)},
7362   {&handle_local_tunnel_destroy, NULL,
7363    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
7364    sizeof (struct GNUNET_MESH_TunnelMessage)},
7365   {&handle_local_tunnel_speed, NULL,
7366    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MIN,
7367    sizeof (struct GNUNET_MESH_TunnelMessage)},
7368   {&handle_local_tunnel_speed, NULL,
7369    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MAX,
7370    sizeof (struct GNUNET_MESH_TunnelMessage)},
7371   {&handle_local_tunnel_buffer, NULL,
7372    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER,
7373    sizeof (struct GNUNET_MESH_TunnelMessage)},
7374   {&handle_local_tunnel_buffer, NULL,
7375    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER,
7376    sizeof (struct GNUNET_MESH_TunnelMessage)},
7377   {&handle_local_connect_add, NULL,
7378    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD,
7379    sizeof (struct GNUNET_MESH_PeerControl)},
7380   {&handle_local_connect_del, NULL,
7381    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL,
7382    sizeof (struct GNUNET_MESH_PeerControl)},
7383   {&handle_local_blacklist, NULL,
7384    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_BLACKLIST,
7385    sizeof (struct GNUNET_MESH_PeerControl)},
7386   {&handle_local_unblacklist, NULL,
7387    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_UNBLACKLIST,
7388    sizeof (struct GNUNET_MESH_PeerControl)},
7389   {&handle_local_connect_by_type, NULL,
7390    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE,
7391    sizeof (struct GNUNET_MESH_ConnectPeerByType)},
7392   {&handle_local_connect_by_string, NULL,
7393    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_STRING, 0},
7394   {&handle_local_unicast, NULL,
7395    GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
7396   {&handle_local_to_origin, NULL,
7397    GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
7398   {&handle_local_multicast, NULL,
7399    GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
7400   {&handle_local_ack, NULL,
7401    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK,
7402    sizeof (struct GNUNET_MESH_LocalAck)},
7403   {NULL, NULL, 0, 0}
7404 };
7405
7406
7407 /**
7408  * To be called on core init/fail.
7409  *
7410  * @param cls service closure
7411  * @param server handle to the server for this service
7412  * @param identity the public identity of this peer
7413  */
7414 static void
7415 core_init (void *cls, struct GNUNET_CORE_Handle *server,
7416            const struct GNUNET_PeerIdentity *identity)
7417 {
7418   static int i = 0;
7419   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
7420   core_handle = server;
7421   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)) ||
7422       NULL == server)
7423   {
7424     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
7425     GNUNET_SCHEDULER_shutdown (); // Try gracefully
7426     if (10 < i++)
7427       GNUNET_abort(); // Try harder
7428   }
7429   return;
7430 }
7431
7432
7433 /**
7434  * Method called whenever a given peer connects.
7435  *
7436  * @param cls closure
7437  * @param peer peer identity this notification is about
7438  * @param atsi performance data for the connection
7439  * @param atsi_count number of records in 'atsi'
7440  */
7441 static void
7442 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
7443               const struct GNUNET_ATS_Information *atsi,
7444               unsigned int atsi_count)
7445 {
7446   struct MeshPeerInfo *peer_info;
7447   struct MeshPeerPath *path;
7448
7449   DEBUG_CONN ("Peer connected\n");
7450   DEBUG_CONN ("     %s\n", GNUNET_i2s (&my_full_id));
7451   peer_info = peer_info_get (peer);
7452   if (myid == peer_info->id)
7453   {
7454     DEBUG_CONN ("     (self)\n");
7455     return;
7456   }
7457   else
7458   {
7459     DEBUG_CONN ("     %s\n", GNUNET_i2s (peer));
7460   }
7461   path = path_new (2);
7462   path->peers[0] = myid;
7463   path->peers[1] = peer_info->id;
7464   GNUNET_PEER_change_rc (myid, 1);
7465   GNUNET_PEER_change_rc (peer_info->id, 1);
7466   peer_info_add_path (peer_info, path, GNUNET_YES);
7467   GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
7468   return;
7469 }
7470
7471
7472 /**
7473  * Method called whenever a peer disconnects.
7474  *
7475  * @param cls closure
7476  * @param peer peer identity this notification is about
7477  */
7478 static void
7479 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
7480 {
7481   struct MeshPeerInfo *pi;
7482   struct MeshPeerQueue *q;
7483   struct MeshPeerQueue *n;
7484
7485   DEBUG_CONN ("Peer disconnected\n");
7486   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
7487   if (NULL == pi)
7488   {
7489     GNUNET_break (0);
7490     return;
7491   }
7492   q = pi->queue_head;
7493   while (NULL != q)
7494   {
7495       n = q->next;
7496       if (q->peer == pi)
7497       {
7498         /* try to reroute this traffic instead */
7499         queue_destroy(q, GNUNET_YES);
7500       }
7501       q = n;
7502   }
7503   peer_info_remove_path (pi, pi->id, myid);
7504   if (myid == pi->id)
7505   {
7506     DEBUG_CONN ("     (self)\n");
7507   }
7508   GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
7509   return;
7510 }
7511
7512
7513 /******************************************************************************/
7514 /************************      MAIN FUNCTIONS      ****************************/
7515 /******************************************************************************/
7516
7517 /**
7518  * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
7519  *
7520  * @param cls closure
7521  * @param key current key code
7522  * @param value value in the hash map
7523  * @return GNUNET_YES if we should continue to iterate,
7524  *         GNUNET_NO if not.
7525  */
7526 static int
7527 shutdown_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
7528 {
7529   struct MeshTunnel *t = value;
7530
7531   tunnel_destroy (t);
7532   return GNUNET_YES;
7533 }
7534
7535 /**
7536  * Iterator over peer hash map entries to destroy the tunnel during shutdown.
7537  *
7538  * @param cls closure
7539  * @param key current key code
7540  * @param value value in the hash map
7541  * @return GNUNET_YES if we should continue to iterate,
7542  *         GNUNET_NO if not.
7543  */
7544 static int
7545 shutdown_peer (void *cls, const struct GNUNET_HashCode * key, void *value)
7546 {
7547   struct MeshPeerInfo *p = value;
7548   struct MeshPeerQueue *q;
7549   struct MeshPeerQueue *n;
7550
7551   q = p->queue_head;
7552   while (NULL != q)
7553   {
7554       n = q->next;
7555       if (q->peer == p)
7556       {
7557         queue_destroy(q, GNUNET_YES);
7558       }
7559       q = n;
7560   }
7561   peer_info_destroy (p);
7562   return GNUNET_YES;
7563 }
7564
7565 /**
7566  * Task run during shutdown.
7567  *
7568  * @param cls unused
7569  * @param tc unused
7570  */
7571 static void
7572 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
7573 {
7574   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
7575
7576   if (core_handle != NULL)
7577   {
7578     GNUNET_CORE_disconnect (core_handle);
7579     core_handle = NULL;
7580   }
7581   GNUNET_CONTAINER_multihashmap_iterate (tunnels, &shutdown_tunnel, NULL);
7582   GNUNET_CONTAINER_multihashmap_iterate (peers, &shutdown_peer, NULL);
7583   if (dht_handle != NULL)
7584   {
7585     GNUNET_DHT_disconnect (dht_handle);
7586     dht_handle = NULL;
7587   }
7588   if (nc != NULL)
7589   {
7590     GNUNET_SERVER_notification_context_destroy (nc);
7591     nc = NULL;
7592   }
7593   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
7594   {
7595     GNUNET_SCHEDULER_cancel (announce_id_task);
7596     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
7597   }
7598   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
7599 }
7600
7601 /**
7602  * Process mesh requests.
7603  *
7604  * @param cls closure
7605  * @param server the initialized server
7606  * @param c configuration to use
7607  */
7608 static void
7609 run (void *cls, struct GNUNET_SERVER_Handle *server,
7610      const struct GNUNET_CONFIGURATION_Handle *c)
7611 {
7612   struct MeshPeerInfo *peer;
7613   struct MeshPeerPath *p;
7614   char *keyfile;
7615
7616   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
7617   server_handle = server;
7618   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
7619                                      NULL,      /* Closure passed to MESH functions */
7620                                      &core_init,        /* Call core_init once connected */
7621                                      &core_connect,     /* Handle connects */
7622                                      &core_disconnect,  /* remove peers on disconnects */
7623                                      NULL,      /* Don't notify about all incoming messages */
7624                                      GNUNET_NO, /* For header only in notification */
7625                                      NULL,      /* Don't notify about all outbound messages */
7626                                      GNUNET_NO, /* For header-only out notification */
7627                                      core_handlers);    /* Register these handlers */
7628
7629   if (core_handle == NULL)
7630   {
7631     GNUNET_break (0);
7632     GNUNET_SCHEDULER_shutdown ();
7633     return;
7634   }
7635
7636   if (GNUNET_OK !=
7637       GNUNET_CONFIGURATION_get_value_filename (c, "GNUNETD", "HOSTKEY",
7638                                                &keyfile))
7639   {
7640     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7641                 _
7642                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7643                 "hostkey");
7644     GNUNET_SCHEDULER_shutdown ();
7645     return;
7646   }
7647
7648   if (GNUNET_OK !=
7649       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_PATH_TIME",
7650                                            &refresh_path_time))
7651   {
7652     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7653                 _
7654                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7655                 "refresh path time");
7656     GNUNET_SCHEDULER_shutdown ();
7657     return;
7658   }
7659
7660   if (GNUNET_OK !=
7661       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "APP_ANNOUNCE_TIME",
7662                                            &app_announce_time))
7663   {
7664     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7665                 _
7666                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7667                 "app announce time");
7668     GNUNET_SCHEDULER_shutdown ();
7669     return;
7670   }
7671
7672   if (GNUNET_OK !=
7673       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "ID_ANNOUNCE_TIME",
7674                                            &id_announce_time))
7675   {
7676     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7677                 _
7678                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7679                 "id announce time");
7680     GNUNET_SCHEDULER_shutdown ();
7681     return;
7682   }
7683
7684   if (GNUNET_OK !=
7685       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "UNACKNOWLEDGED_WAIT",
7686                                            &unacknowledged_wait_time))
7687   {
7688     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7689                 _
7690                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7691                 "unacknowledged wait time");
7692     GNUNET_SCHEDULER_shutdown ();
7693     return;
7694   }
7695
7696   if (GNUNET_OK !=
7697       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "CONNECT_TIMEOUT",
7698                                            &connect_timeout))
7699   {
7700     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7701                 _
7702                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7703                 "connect timeout");
7704     GNUNET_SCHEDULER_shutdown ();
7705     return;
7706   }
7707
7708   if (GNUNET_OK !=
7709       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
7710                                              &max_msgs_queue))
7711   {
7712     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7713                 _
7714                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7715                 "max msgs queue");
7716     GNUNET_SCHEDULER_shutdown ();
7717     return;
7718   }
7719
7720   if (GNUNET_OK !=
7721       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_TUNNELS",
7722                                              &max_tunnels))
7723   {
7724     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7725                 _
7726                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7727                 "max tunnels");
7728     GNUNET_SCHEDULER_shutdown ();
7729     return;
7730   }
7731
7732   if (GNUNET_OK !=
7733       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
7734                                              &default_ttl))
7735   {
7736     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7737                 _
7738                 ("Mesh service is lacking key configuration settings (%s). Using default (%u).\n"),
7739                 "default ttl", 64);
7740     default_ttl = 64;
7741   }
7742
7743   if (GNUNET_OK !=
7744       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DHT_REPLICATION_LEVEL",
7745                                              &dht_replication_level))
7746   {
7747     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7748                 _
7749                 ("Mesh service is lacking key configuration settings (%s). Using default (%u).\n"),
7750                 "dht replication level", 10);
7751     dht_replication_level = 10;
7752   }
7753
7754   
7755   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
7756   GNUNET_free (keyfile);
7757   if (my_private_key == NULL)
7758   {
7759     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7760                 _("Mesh service could not access hostkey.  Exiting.\n"));
7761     GNUNET_SCHEDULER_shutdown ();
7762     return;
7763   }
7764   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
7765   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
7766                       &my_full_id.hashPubKey);
7767   myid = GNUNET_PEER_intern (&my_full_id);
7768   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
7769               "Mesh for peer [%s] starting\n",
7770               GNUNET_i2s(&my_full_id));
7771
7772 //   transport_handle = GNUNET_TRANSPORT_connect(c,
7773 //                                               &my_full_id,
7774 //                                               NULL,
7775 //                                               NULL,
7776 //                                               NULL,
7777 //                                               NULL);
7778
7779   dht_handle = GNUNET_DHT_connect (c, 64);
7780   if (dht_handle == NULL)
7781   {
7782     GNUNET_break (0);
7783   }
7784
7785   stats = GNUNET_STATISTICS_create ("mesh", c);
7786
7787
7788   next_tid = 0;
7789   next_local_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
7790
7791   tunnels = GNUNET_CONTAINER_multihashmap_create (32);
7792   incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
7793   peers = GNUNET_CONTAINER_multihashmap_create (32);
7794   applications = GNUNET_CONTAINER_multihashmap_create (32);
7795   types = GNUNET_CONTAINER_multihashmap_create (32);
7796
7797   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
7798   nc = GNUNET_SERVER_notification_context_create (server_handle, 1);
7799   GNUNET_SERVER_disconnect_notify (server_handle,
7800                                    &handle_local_client_disconnect, NULL);
7801
7802
7803   clients = NULL;
7804   clients_tail = NULL;
7805   next_client_id = 0;
7806
7807   announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
7808   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
7809
7810   /* Create a peer_info for the local peer */
7811   peer = peer_info_get (&my_full_id);
7812   p = path_new (1);
7813   p->peers[0] = myid;
7814   GNUNET_PEER_change_rc (myid, 1);
7815   peer_info_add_path (peer, p, GNUNET_YES);
7816
7817   /* Scheduled the task to clean up when shutdown is called */
7818   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
7819                                 NULL);
7820
7821   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "end of run()\n");
7822 }
7823
7824 /**
7825  * The main function for the mesh service.
7826  *
7827  * @param argc number of arguments from the command line
7828  * @param argv command line arguments
7829  * @return 0 ok, 1 on error
7830  */
7831 int
7832 main (int argc, char *const *argv)
7833 {
7834   int ret;
7835
7836   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
7837   ret =
7838       (GNUNET_OK ==
7839        GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
7840                            NULL)) ? 0 : 1;
7841   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");
7842
7843   INTERVAL_SHOW;
7844
7845   return ret;
7846 }