55be9ea443306e8027b9a9632d1eef227f382d41
[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         if (GNUNET_MESSAGE_TYPE_MESH_MULTICAST != ntohs(mcast->header.type)) 
4541         {
4542           // Not a multicast payload: multicast control traffic (destroy, etc)
4543           return q;
4544         }
4545         pid = ntohl (mcast->pid);
4546         GNUNET_PEER_resolve (info->peer->id, &id);
4547         cinfo = tunnel_get_neighbor_fc(t, &id);
4548         ack = cinfo->fwd_ack;
4549         break;
4550       default:
4551         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4552                     "*********   OK!\n");
4553         return q;
4554     }
4555         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4556                     "*********     ACK: %u, PID: %u\n",
4557                     ack, pid);
4558     if (GNUNET_NO == GMC_is_pid_bigger(pid, ack))
4559     {
4560       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4561                   "*********   OK!\n");
4562       return q;
4563     }
4564     else
4565     {
4566       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4567                   "*********     NEXT!\n");
4568     }
4569   }
4570   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4571                 "*********   nothing found\n");
4572   return NULL;
4573 }
4574
4575
4576 /**
4577   * Core callback to write a queued packet to core buffer
4578   *
4579   * @param cls Closure (peer info).
4580   * @param size Number of bytes available in buf.
4581   * @param buf Where the to write the message.
4582   *
4583   * @return number of bytes written to buf
4584   */
4585 static size_t
4586 queue_send (void *cls, size_t size, void *buf)
4587 {
4588     struct MeshPeerInfo *peer = cls;
4589     struct GNUNET_MessageHeader *msg;
4590     struct MeshPeerQueue *queue;
4591     struct MeshTunnel *t;
4592     size_t data_size;
4593
4594     peer->core_transmit = NULL;
4595     
4596     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "********* Queue send\n");
4597     queue = queue_get_next(peer);
4598
4599     /* Queue has no internal mesh traffic not sendable payload */
4600     if (NULL == queue)
4601     {
4602       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   not ready, return\n");
4603       if (NULL == peer->queue_head)
4604         GNUNET_break(0); // Should've been canceled
4605       return 0;
4606     }
4607     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   not empty\n");
4608
4609     /* Check if buffer size is enough for the message */
4610     if (queue->size > size)
4611     {
4612         struct GNUNET_PeerIdentity id;
4613
4614         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4615                     "*********   not enough room, reissue\n");
4616         GNUNET_PEER_resolve (peer->id, &id);
4617         peer->core_transmit =
4618             GNUNET_CORE_notify_transmit_ready(core_handle,
4619                                               0,
4620                                               0,
4621                                               GNUNET_TIME_UNIT_FOREVER_REL,
4622                                               &id,
4623                                               queue->size,
4624                                               &queue_send,
4625                                               peer);
4626         return 0;
4627     }
4628     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   size ok\n");
4629
4630     t = queue->tunnel;
4631     if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == queue->type)
4632     {
4633       t->fwd_queue_n--;
4634       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4635                   "*********   unicast: t->q (%u/%u)\n",
4636                   t->fwd_queue_n, t->fwd_queue_max);
4637     }
4638     else if (GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == queue->type)
4639     {
4640       t->bck_queue_n--;
4641       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   to origin\n");
4642     }
4643
4644     /* Fill buf */
4645     switch (queue->type)
4646     {
4647       case 0:
4648       case GNUNET_MESSAGE_TYPE_MESH_ACK:
4649       case GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN:
4650       case GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY:
4651         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4652                     "*********   raw: %s\n",
4653                     GNUNET_MESH_DEBUG_M2S (queue->type));
4654         /* Fall through */
4655       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4656       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4657         data_size = send_core_data_raw (queue->cls, size, buf);
4658         msg = (struct GNUNET_MessageHeader *) buf;
4659         switch (ntohs (msg->type)) // Type of preconstructed message
4660         {
4661           case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4662             tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_UNICAST);
4663             break;
4664           case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4665             tunnel_send_bck_ack(t, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
4666             break;
4667           default:
4668               break;
4669         }
4670         break;
4671       case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
4672         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   multicast\n");
4673         data_size = send_core_data_multicast(queue->cls, size, buf);
4674         // FIXME fc substract when? depending on the tunnel conf.
4675         // t->fwd_queue_n--;
4676         tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
4677         break;
4678       case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
4679         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path create\n");
4680         data_size = send_core_path_create(queue->cls, size, buf);
4681         break;
4682       case GNUNET_MESSAGE_TYPE_MESH_PATH_ACK:
4683         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path ack\n");
4684         data_size = send_core_path_ack(queue->cls, size, buf);
4685         break;
4686       default:
4687         GNUNET_break (0);
4688         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4689                     "*********   type unknown: %u\n",
4690                     queue->type);
4691         data_size = 0;
4692     }
4693
4694     /* Free queue, but cls was freed by send_core_* */
4695     queue_destroy (queue, GNUNET_NO);
4696
4697     if (GNUNET_YES == t->destroy && 0 == t->fwd_queue_n)
4698     {
4699       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********  destroying tunnel!\n");
4700       tunnel_destroy (t);
4701     }
4702
4703     /* If more data in queue, send next */
4704     if (NULL != peer->queue_head)
4705     {
4706         struct GNUNET_PeerIdentity id;
4707
4708         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   more data!\n");
4709         GNUNET_PEER_resolve (peer->id, &id);
4710         peer->core_transmit =
4711             GNUNET_CORE_notify_transmit_ready(core_handle,
4712                                               0,
4713                                               0,
4714                                               GNUNET_TIME_UNIT_FOREVER_REL,
4715                                               &id,
4716                                               peer->queue_head->size,
4717                                               &queue_send,
4718                                               peer);
4719     }
4720     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   return %d\n", data_size);
4721     return data_size;
4722 }
4723
4724
4725 /**
4726  * Queue and pass message to core when possible.
4727  *
4728  * @param cls Closure (type dependant).
4729  * @param type Type of the message, 0 for a raw message.
4730  * @param size Size of the message.
4731  * @param dst Neighbor to send message to.
4732  * @param t Tunnel this message belongs to.
4733  */
4734 static void
4735 queue_add (void *cls, uint16_t type, size_t size,
4736            struct MeshPeerInfo *dst, struct MeshTunnel *t)
4737 {
4738   struct MeshPeerQueue *queue;
4739   unsigned int *max;
4740   unsigned int *n;
4741
4742   n = NULL;
4743   if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == type ||
4744       GNUNET_MESSAGE_TYPE_MESH_MULTICAST == type)
4745   {
4746     n = &t->fwd_queue_n;
4747     max = &t->fwd_queue_max;
4748   }
4749   else if (GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == type)
4750   {
4751     n = &t->bck_queue_n;
4752     max = &t->bck_queue_max;
4753   }
4754   if (NULL != n) {
4755     if (*n >= *max)
4756     {
4757       if (NULL == t->owner)
4758         GNUNET_break_op(0);       // TODO: kill connection?
4759       else
4760         GNUNET_break(0);
4761       return;                       // Drop message
4762     }
4763     (*n)++;
4764   }
4765   queue = GNUNET_malloc (sizeof (struct MeshPeerQueue));
4766   queue->cls = cls;
4767   queue->type = type;
4768   queue->size = size;
4769   queue->peer = dst;
4770   queue->tunnel = t;
4771   GNUNET_CONTAINER_DLL_insert_tail (dst->queue_head, dst->queue_tail, queue);
4772   if (NULL == dst->core_transmit)
4773   {
4774       struct GNUNET_PeerIdentity id;
4775
4776       GNUNET_PEER_resolve (dst->id, &id);
4777       dst->core_transmit =
4778           GNUNET_CORE_notify_transmit_ready(core_handle,
4779                                             0,
4780                                             0,
4781                                             GNUNET_TIME_UNIT_FOREVER_REL,
4782                                             &id,
4783                                             size,
4784                                             &queue_send,
4785                                             dst);
4786   }
4787 }
4788
4789
4790 /******************************************************************************/
4791 /********************      MESH NETWORK HANDLERS     **************************/
4792 /******************************************************************************/
4793
4794
4795 /**
4796  * Core handler for path creation
4797  *
4798  * @param cls closure
4799  * @param message message
4800  * @param peer peer identity this notification is about
4801  * @param atsi performance data
4802  * @param atsi_count number of records in 'atsi'
4803  *
4804  * @return GNUNET_OK to keep the connection open,
4805  *         GNUNET_SYSERR to close it (signal serious error)
4806  */
4807 static int
4808 handle_mesh_path_create (void *cls, const struct GNUNET_PeerIdentity *peer,
4809                          const struct GNUNET_MessageHeader *message,
4810                          const struct GNUNET_ATS_Information *atsi,
4811                          unsigned int atsi_count)
4812 {
4813   unsigned int own_pos;
4814   uint16_t size;
4815   uint16_t i;
4816   MESH_TunnelNumber tid;
4817   struct GNUNET_MESH_ManipulatePath *msg;
4818   struct GNUNET_PeerIdentity *pi;
4819   struct GNUNET_HashCode hash;
4820   struct MeshPeerPath *path;
4821   struct MeshPeerInfo *dest_peer_info;
4822   struct MeshPeerInfo *orig_peer_info;
4823   struct MeshTunnel *t;
4824
4825   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4826               "Received a path create msg [%s]\n",
4827               GNUNET_i2s (&my_full_id));
4828   size = ntohs (message->size);
4829   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
4830   {
4831     GNUNET_break_op (0);
4832     return GNUNET_OK;
4833   }
4834
4835   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
4836   if (size % sizeof (struct GNUNET_PeerIdentity))
4837   {
4838     GNUNET_break_op (0);
4839     return GNUNET_OK;
4840   }
4841   size /= sizeof (struct GNUNET_PeerIdentity);
4842   if (size < 2)
4843   {
4844     GNUNET_break_op (0);
4845     return GNUNET_OK;
4846   }
4847   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
4848   msg = (struct GNUNET_MESH_ManipulatePath *) message;
4849
4850   tid = ntohl (msg->tid);
4851   pi = (struct GNUNET_PeerIdentity *) &msg[1];
4852   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4853               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi), tid);
4854   t = tunnel_get (pi, tid);
4855   if (NULL == t) // FIXME only for INCOMING tunnels?
4856   {
4857     uint32_t opt;
4858
4859     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating tunnel\n");
4860     t = tunnel_new (GNUNET_PEER_intern (pi), tid, NULL, 0);
4861     if (NULL == t)
4862     {
4863       // FIXME notify failure
4864       return GNUNET_OK;
4865     }
4866     opt = ntohl (msg->opt);
4867     t->speed_min = (0 != (opt & MESH_TUNNEL_OPT_SPEED_MIN)) ?
4868                    GNUNET_YES : GNUNET_NO;
4869     t->nobuffer = (0 != (opt & MESH_TUNNEL_OPT_NOBUFFER)) ?
4870                   GNUNET_YES : GNUNET_NO;
4871
4872     if (GNUNET_YES == t->nobuffer)
4873     {
4874       t->bck_queue_max = 1;
4875       t->fwd_queue_max = 1;
4876     }
4877
4878     // FIXME only assign a local tid if a local client is interested (on demand)
4879     while (NULL != tunnel_get_incoming (next_local_tid))
4880       next_local_tid = (next_local_tid + 1) | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
4881     t->local_tid_dest = next_local_tid++;
4882     next_local_tid = next_local_tid | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
4883     // FIXME end
4884
4885     tunnel_reset_timeout (t);
4886     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
4887     if (GNUNET_OK !=
4888         GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
4889                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
4890     {
4891       tunnel_destroy (t);
4892       GNUNET_break (0);
4893       return GNUNET_OK;
4894     }
4895   }
4896   dest_peer_info =
4897       GNUNET_CONTAINER_multihashmap_get (peers, &pi[size - 1].hashPubKey);
4898   if (NULL == dest_peer_info)
4899   {
4900     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4901                 "  Creating PeerInfo for destination.\n");
4902     dest_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
4903     dest_peer_info->id = GNUNET_PEER_intern (&pi[size - 1]);
4904     GNUNET_CONTAINER_multihashmap_put (peers, &pi[size - 1].hashPubKey,
4905                                        dest_peer_info,
4906                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
4907   }
4908   orig_peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &pi->hashPubKey);
4909   if (NULL == orig_peer_info)
4910   {
4911     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4912                 "  Creating PeerInfo for origin.\n");
4913     orig_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
4914     orig_peer_info->id = GNUNET_PEER_intern (pi);
4915     GNUNET_CONTAINER_multihashmap_put (peers, &pi->hashPubKey, orig_peer_info,
4916                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
4917   }
4918   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
4919   path = path_new (size);
4920   own_pos = 0;
4921   for (i = 0; i < size; i++)
4922   {
4923     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
4924                 GNUNET_i2s (&pi[i]));
4925     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
4926     if (path->peers[i] == myid)
4927       own_pos = i;
4928   }
4929   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
4930   if (own_pos == 0)
4931   {
4932     /* cannot be self, must be 'not found' */
4933     /* create path: self not found in path through self */
4934     GNUNET_break_op (0);
4935     path_destroy (path);
4936     tunnel_destroy (t);
4937     return GNUNET_OK;
4938   }
4939   path_add_to_peers (path, GNUNET_NO);
4940   tunnel_add_path (t, path, own_pos);
4941   if (own_pos == size - 1)
4942   {
4943     /* It is for us! Send ack. */
4944     struct MeshTransmissionDescriptor *info;
4945
4946     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
4947     peer_info_add_path_to_origin (orig_peer_info, path, GNUNET_NO);
4948     if (NULL == t->peers)
4949     {
4950       /* New tunnel! Notify clients on data. */
4951       t->peers = GNUNET_CONTAINER_multihashmap_create (4);
4952     }
4953     GNUNET_break (GNUNET_SYSERR !=
4954                   GNUNET_CONTAINER_multihashmap_put (t->peers,
4955                                                      &my_full_id.hashPubKey,
4956                                                      peer_info_get
4957                                                      (&my_full_id),
4958                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE));
4959     info = GNUNET_malloc (sizeof (struct MeshTransmissionDescriptor));
4960     info->origin = &t->id;
4961     info->peer = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
4962     GNUNET_assert (NULL != info->peer);
4963     queue_add(info,
4964               GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
4965               sizeof (struct GNUNET_MESH_PathACK),
4966               info->peer,
4967               t);
4968   }
4969   else
4970   {
4971     struct MeshPeerPath *path2;
4972
4973     /* It's for somebody else! Retransmit. */
4974     path2 = path_duplicate (path);
4975     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Retransmitting.\n");
4976     peer_info_add_path (dest_peer_info, path2, GNUNET_NO);
4977     path2 = path_duplicate (path);
4978     peer_info_add_path_to_origin (orig_peer_info, path2, GNUNET_NO);
4979     send_create_path (dest_peer_info, path, t);
4980   }
4981   return GNUNET_OK;
4982 }
4983
4984
4985 /**
4986  * Core handler for path destruction
4987  *
4988  * @param cls closure
4989  * @param message message
4990  * @param peer peer identity this notification is about
4991  * @param atsi performance data
4992  * @param atsi_count number of records in 'atsi'
4993  *
4994  * @return GNUNET_OK to keep the connection open,
4995  *         GNUNET_SYSERR to close it (signal serious error)
4996  */
4997 static int
4998 handle_mesh_path_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
4999                           const struct GNUNET_MessageHeader *message,
5000                           const struct GNUNET_ATS_Information *atsi,
5001                           unsigned int atsi_count)
5002 {
5003   struct GNUNET_MESH_ManipulatePath *msg;
5004   struct GNUNET_PeerIdentity *pi;
5005   struct MeshPeerPath *path;
5006   struct MeshTunnel *t;
5007   unsigned int own_pos;
5008   unsigned int i;
5009   size_t size;
5010
5011   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5012               "Received a PATH DESTROY msg from %s\n", GNUNET_i2s (peer));
5013   size = ntohs (message->size);
5014   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
5015   {
5016     GNUNET_break_op (0);
5017     return GNUNET_OK;
5018   }
5019
5020   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
5021   if (size % sizeof (struct GNUNET_PeerIdentity))
5022   {
5023     GNUNET_break_op (0);
5024     return GNUNET_OK;
5025   }
5026   size /= sizeof (struct GNUNET_PeerIdentity);
5027   if (size < 2)
5028   {
5029     GNUNET_break_op (0);
5030     return GNUNET_OK;
5031   }
5032   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
5033
5034   msg = (struct GNUNET_MESH_ManipulatePath *) message;
5035   pi = (struct GNUNET_PeerIdentity *) &msg[1];
5036   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5037               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi),
5038               msg->tid);
5039   t = tunnel_get (pi, ntohl (msg->tid));
5040   if (NULL == t)
5041   {
5042     /* TODO notify back: we don't know this tunnel */
5043     GNUNET_break_op (0);
5044     return GNUNET_OK;
5045   }
5046   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
5047   path = path_new (size);
5048   own_pos = 0;
5049   for (i = 0; i < size; i++)
5050   {
5051     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
5052                 GNUNET_i2s (&pi[i]));
5053     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
5054     if (path->peers[i] == myid)
5055       own_pos = i;
5056   }
5057   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
5058   if (own_pos < path->length - 1)
5059     send_message (message, &pi[own_pos + 1], t);
5060   else
5061     send_client_tunnel_disconnect(t, NULL);
5062
5063   tunnel_delete_peer (t, path->peers[path->length - 1]);
5064   path_destroy (path);
5065   return GNUNET_OK;
5066 }
5067
5068
5069 /**
5070  * Core handler for notifications of broken paths
5071  *
5072  * @param cls closure
5073  * @param message message
5074  * @param peer peer identity this notification is about
5075  * @param atsi performance data
5076  * @param atsi_count number of records in 'atsi'
5077  *
5078  * @return GNUNET_OK to keep the connection open,
5079  *         GNUNET_SYSERR to close it (signal serious error)
5080  */
5081 static int
5082 handle_mesh_path_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
5083                          const struct GNUNET_MessageHeader *message,
5084                          const struct GNUNET_ATS_Information *atsi,
5085                          unsigned int atsi_count)
5086 {
5087   struct GNUNET_MESH_PathBroken *msg;
5088   struct MeshTunnel *t;
5089
5090   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5091               "Received a PATH BROKEN msg from %s\n", GNUNET_i2s (peer));
5092   msg = (struct GNUNET_MESH_PathBroken *) message;
5093   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
5094               GNUNET_i2s (&msg->peer1));
5095   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
5096               GNUNET_i2s (&msg->peer2));
5097   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5098   if (NULL == t)
5099   {
5100     GNUNET_break_op (0);
5101     return GNUNET_OK;
5102   }
5103   tunnel_notify_connection_broken (t, GNUNET_PEER_search (&msg->peer1),
5104                                    GNUNET_PEER_search (&msg->peer2));
5105   return GNUNET_OK;
5106
5107 }
5108
5109
5110 /**
5111  * Core handler for tunnel destruction
5112  *
5113  * @param cls closure
5114  * @param message message
5115  * @param peer peer identity this notification is about
5116  * @param atsi performance data
5117  * @param atsi_count number of records in 'atsi'
5118  *
5119  * @return GNUNET_OK to keep the connection open,
5120  *         GNUNET_SYSERR to close it (signal serious error)
5121  */
5122 static int
5123 handle_mesh_tunnel_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
5124                             const struct GNUNET_MessageHeader *message,
5125                             const struct GNUNET_ATS_Information *atsi,
5126                             unsigned int atsi_count)
5127 {
5128   struct GNUNET_MESH_TunnelDestroy *msg;
5129   struct MeshTunnel *t;
5130
5131   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5132               "Got a TUNNEL DESTROY packet from %s\n", GNUNET_i2s (peer));
5133   msg = (struct GNUNET_MESH_TunnelDestroy *) message;
5134   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for tunnel %s [%u]\n",
5135               GNUNET_i2s (&msg->oid), ntohl (msg->tid));
5136   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5137   if (NULL == t)
5138   {
5139     /* Probably already got the message from another path,
5140      * destroyed the tunnel and retransmitted to children.
5141      * Safe to ignore.
5142      */
5143     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel", 1, GNUNET_NO);
5144     return GNUNET_OK;
5145   }
5146   if (t->id.oid == myid)
5147   {
5148     GNUNET_break_op (0);
5149     return GNUNET_OK;
5150   }
5151   if (t->local_tid_dest >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
5152   {
5153     /* Tunnel was incoming, notify clients */
5154     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "INCOMING TUNNEL %X %X\n",
5155                 t->local_tid, t->local_tid_dest);
5156     send_clients_tunnel_destroy (t);
5157   }
5158   tunnel_send_destroy (t);
5159   t->destroy = GNUNET_YES;
5160   // TODO: add timeout to destroy the tunnel anyway
5161   return GNUNET_OK;
5162 }
5163
5164
5165 /**
5166  * Core handler for mesh network traffic going from the origin to a peer
5167  *
5168  * @param cls closure
5169  * @param peer peer identity this notification is about
5170  * @param message message
5171  * @param atsi performance data
5172  * @param atsi_count number of records in 'atsi'
5173  * @return GNUNET_OK to keep the connection open,
5174  *         GNUNET_SYSERR to close it (signal serious error)
5175  */
5176 static int
5177 handle_mesh_data_unicast (void *cls, const struct GNUNET_PeerIdentity *peer,
5178                           const struct GNUNET_MessageHeader *message,
5179                           const struct GNUNET_ATS_Information *atsi,
5180                           unsigned int atsi_count)
5181 {
5182   struct GNUNET_MESH_Unicast *msg;
5183   struct GNUNET_PeerIdentity *neighbor;
5184   struct MeshTunnelChildInfo *cinfo;
5185   struct MeshTunnel *t;
5186   GNUNET_PEER_Id dest_id;
5187   uint32_t pid;
5188   uint32_t ttl;
5189   size_t size;
5190
5191   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a unicast packet from %s\n",
5192               GNUNET_i2s (peer));
5193   /* Check size */
5194   size = ntohs (message->size);
5195   if (size <
5196       sizeof (struct GNUNET_MESH_Unicast) +
5197       sizeof (struct GNUNET_MessageHeader))
5198   {
5199     GNUNET_break (0);
5200     return GNUNET_OK;
5201   }
5202   msg = (struct GNUNET_MESH_Unicast *) message;
5203   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %s\n",
5204               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
5205   /* Check tunnel */
5206   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5207   if (NULL == t)
5208   {
5209     /* TODO notify back: we don't know this tunnel */
5210     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
5211     GNUNET_break_op (0);
5212     return GNUNET_OK;
5213   }
5214   pid = ntohl (msg->pid);
5215   if (t->fwd_pid == pid)
5216   {
5217     GNUNET_STATISTICS_update (stats, "# duplicate PID drops", 1, GNUNET_NO);
5218     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5219                 " Already seen pid %u, DROPPING!\n", pid);
5220     return GNUNET_OK;
5221   }
5222   else
5223   {
5224     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5225                 " pid %u not seen yet, forwarding\n", pid);
5226   }
5227
5228   t->skip += (pid - t->fwd_pid) - 1;
5229   t->fwd_pid = pid;
5230
5231   if (GMC_is_pid_bigger (pid, t->last_fwd_ack))
5232   {
5233     GNUNET_STATISTICS_update (stats, "# unsolicited unicast", 1, GNUNET_NO);
5234     GNUNET_break_op (0);
5235     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5236                 "Received PID %u, ACK %u\n",
5237                 pid, t->last_fwd_ack);
5238     return GNUNET_OK;
5239   }
5240
5241   tunnel_reset_timeout (t);
5242   dest_id = GNUNET_PEER_search (&msg->destination);
5243   if (dest_id == myid)
5244   {
5245     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5246                 "  it's for us! sending to clients...\n");
5247     GNUNET_STATISTICS_update (stats, "# unicast received", 1, GNUNET_NO);
5248     send_subscribed_clients (message, &msg[1].header, t);
5249     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_UNICAST);
5250     return GNUNET_OK;
5251   }
5252   ttl = ntohl (msg->ttl);
5253   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ttl);
5254   if (ttl == 0)
5255   {
5256     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
5257     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
5258     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5259     return GNUNET_OK;
5260   }
5261   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5262               "  not for us, retransmitting...\n");
5263
5264   neighbor = tree_get_first_hop (t->tree, dest_id);
5265   cinfo = tunnel_get_neighbor_fc (t, neighbor);
5266   cinfo->pid = pid;
5267   GNUNET_CONTAINER_multihashmap_iterate (t->children_fc,
5268                                          &tunnel_add_skip,
5269                                          &neighbor);
5270   if (GNUNET_YES == t->nobuffer &&
5271       GNUNET_YES == GMC_is_pid_bigger (pid, cinfo->fwd_ack))
5272   {
5273     GNUNET_STATISTICS_update (stats, "# unsolicited unicast", 1, GNUNET_NO);
5274     GNUNET_break_op (0);
5275     return GNUNET_OK;
5276   }
5277   send_message (message, neighbor, t);
5278   GNUNET_STATISTICS_update (stats, "# unicast forwarded", 1, GNUNET_NO);
5279   return GNUNET_OK;
5280 }
5281
5282
5283 /**
5284  * Core handler for mesh network traffic going from the origin to all peers
5285  *
5286  * @param cls closure
5287  * @param message message
5288  * @param peer peer identity this notification is about
5289  * @param atsi performance data
5290  * @param atsi_count number of records in 'atsi'
5291  * @return GNUNET_OK to keep the connection open,
5292  *         GNUNET_SYSERR to close it (signal serious error)
5293  *
5294  * TODO: Check who we got this from, to validate route.
5295  */
5296 static int
5297 handle_mesh_data_multicast (void *cls, const struct GNUNET_PeerIdentity *peer,
5298                             const struct GNUNET_MessageHeader *message,
5299                             const struct GNUNET_ATS_Information *atsi,
5300                             unsigned int atsi_count)
5301 {
5302   struct GNUNET_MESH_Multicast *msg;
5303   struct MeshTunnel *t;
5304   size_t size;
5305   uint32_t pid;
5306
5307   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a multicast packet from %s\n",
5308               GNUNET_i2s (peer));
5309   size = ntohs (message->size);
5310   if (sizeof (struct GNUNET_MESH_Multicast) +
5311       sizeof (struct GNUNET_MessageHeader) > size)
5312   {
5313     GNUNET_break_op (0);
5314     return GNUNET_OK;
5315   }
5316   msg = (struct GNUNET_MESH_Multicast *) message;
5317   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5318
5319   if (NULL == t)
5320   {
5321     /* TODO notify that we dont know that tunnel */
5322     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
5323     GNUNET_break_op (0);
5324     return GNUNET_OK;
5325   }
5326   pid = ntohl (msg->pid);
5327   if (t->fwd_pid == pid)
5328   {
5329     /* already seen this packet, drop */
5330     GNUNET_STATISTICS_update (stats, "# duplicate PID drops", 1, GNUNET_NO);
5331     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5332                 " Already seen pid %u, DROPPING!\n", pid);
5333     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5334     return GNUNET_OK;
5335   }
5336   else
5337   {
5338     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5339                 " pid %u not seen yet, forwarding\n", pid);
5340   }
5341   t->skip += (pid - t->fwd_pid) - 1;
5342   t->fwd_pid = pid;
5343   tunnel_reset_timeout (t);
5344
5345   /* Transmit to locally interested clients */
5346   if (NULL != t->peers &&
5347       GNUNET_CONTAINER_multihashmap_contains (t->peers, &my_full_id.hashPubKey))
5348   {
5349     GNUNET_STATISTICS_update (stats, "# multicast received", 1, GNUNET_NO);
5350     send_subscribed_clients (message, &msg[1].header, t);
5351     tunnel_send_fwd_ack(t, GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
5352   }
5353   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ntohl (msg->ttl));
5354   if (ntohl (msg->ttl) == 0)
5355   {
5356     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
5357     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
5358     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5359     return GNUNET_OK;
5360   }
5361   GNUNET_STATISTICS_update (stats, "# multicast forwarded", 1, GNUNET_NO);
5362   tunnel_send_multicast (t, message, GNUNET_NO);
5363   return GNUNET_OK;
5364 }
5365
5366
5367 /**
5368  * Core handler for mesh network traffic toward the owner of a tunnel
5369  *
5370  * @param cls closure
5371  * @param message message
5372  * @param peer peer identity this notification is about
5373  * @param atsi performance data
5374  * @param atsi_count number of records in 'atsi'
5375  *
5376  * @return GNUNET_OK to keep the connection open,
5377  *         GNUNET_SYSERR to close it (signal serious error)
5378  */
5379 static int
5380 handle_mesh_data_to_orig (void *cls, const struct GNUNET_PeerIdentity *peer,
5381                           const struct GNUNET_MessageHeader *message,
5382                           const struct GNUNET_ATS_Information *atsi,
5383                           unsigned int atsi_count)
5384 {
5385   struct GNUNET_MESH_ToOrigin *msg;
5386   struct GNUNET_PeerIdentity id;
5387   struct MeshPeerInfo *peer_info;
5388   struct MeshTunnel *t;
5389   size_t size;
5390
5391
5392   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a ToOrigin packet from %s\n",
5393               GNUNET_i2s (peer));
5394   size = ntohs (message->size);
5395   if (size < sizeof (struct GNUNET_MESH_ToOrigin) +     /* Payload must be */
5396       sizeof (struct GNUNET_MessageHeader))     /* at least a header */
5397   {
5398     GNUNET_break_op (0);
5399     return GNUNET_OK;
5400   }
5401   msg = (struct GNUNET_MESH_ToOrigin *) message;
5402   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %s\n",
5403               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
5404   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5405
5406   if (NULL == t)
5407   {
5408     /* TODO notify that we dont know this tunnel (whom)? */
5409     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
5410     GNUNET_break_op (0);
5411     return GNUNET_OK;
5412   }
5413
5414   if (NULL != t->owner)
5415   {
5416     char cbuf[size];
5417     struct GNUNET_MESH_ToOrigin *copy;
5418
5419     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5420                 "  it's for us! sending to clients...\n");
5421     /* TODO signature verification */
5422     memcpy (cbuf, message, size);
5423     copy = (struct GNUNET_MESH_ToOrigin *) cbuf;
5424     copy->tid = htonl (t->local_tid);
5425     GNUNET_STATISTICS_update (stats, "# to origin received", 1, GNUNET_NO);
5426     GNUNET_SERVER_notification_context_unicast (nc, t->owner->handle,
5427                                                 &copy->header, GNUNET_NO);
5428     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
5429     return GNUNET_OK;
5430   }
5431   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5432               "  not for us, retransmitting...\n");
5433
5434   peer_info = peer_info_get (&msg->oid);
5435   if (NULL == peer_info)
5436   {
5437     /* unknown origin of tunnel */
5438     GNUNET_break (0);
5439     return GNUNET_OK;
5440   }
5441   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
5442   send_message (message, &id, t);
5443   GNUNET_STATISTICS_update (stats, "# to origin forwarded", 1, GNUNET_NO);
5444
5445   return GNUNET_OK;
5446 }
5447
5448
5449 /**
5450  * Core handler for mesh network traffic point-to-point acks.
5451  *
5452  * @param cls closure
5453  * @param message message
5454  * @param peer peer identity this notification is about
5455  * @param atsi performance data
5456  * @param atsi_count number of records in 'atsi'
5457  *
5458  * @return GNUNET_OK to keep the connection open,
5459  *         GNUNET_SYSERR to close it (signal serious error)
5460  */
5461 static int
5462 handle_mesh_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5463                  const struct GNUNET_MessageHeader *message,
5464                  const struct GNUNET_ATS_Information *atsi,
5465                  unsigned int atsi_count)
5466 {
5467   struct GNUNET_MESH_ACK *msg;
5468   struct MeshTunnel *t;
5469   uint32_t ack;
5470
5471   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK packet from %s!\n",
5472               GNUNET_i2s (peer));
5473   msg = (struct GNUNET_MESH_ACK *) message;
5474
5475   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5476
5477   if (NULL == t)
5478   {
5479     /* TODO notify that we dont know this tunnel (whom)? */
5480     GNUNET_STATISTICS_update (stats, "# ack on unknown tunnel", 1, GNUNET_NO);
5481     GNUNET_break_op (0);
5482     return GNUNET_OK;
5483   }
5484   ack = ntohl (msg->pid);
5485
5486   /* Is this a forward or backward ACK? */
5487   if (tree_get_predecessor(t->tree) != GNUNET_PEER_search(peer))
5488   {
5489     struct MeshTunnelChildInfo *cinfo;
5490
5491     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
5492     cinfo = tunnel_get_neighbor_fc (t, peer);
5493     cinfo->fwd_ack = ack;
5494     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5495     tunnel_unlock_fwd_queues (t);
5496   }
5497   else
5498   {
5499     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
5500     t->bck_ack = ack;
5501     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5502     tunnel_unlock_bck_queue (t);
5503   }
5504   return GNUNET_OK;
5505 }
5506
5507
5508 /**
5509  * Core handler for path ACKs
5510  *
5511  * @param cls closure
5512  * @param message message
5513  * @param peer peer identity this notification is about
5514  * @param atsi performance data
5515  * @param atsi_count number of records in 'atsi'
5516  *
5517  * @return GNUNET_OK to keep the connection open,
5518  *         GNUNET_SYSERR to close it (signal serious error)
5519  */
5520 static int
5521 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5522                       const struct GNUNET_MessageHeader *message,
5523                       const struct GNUNET_ATS_Information *atsi,
5524                       unsigned int atsi_count)
5525 {
5526   struct GNUNET_MESH_PathACK *msg;
5527   struct GNUNET_PeerIdentity id;
5528   struct MeshPeerInfo *peer_info;
5529   struct MeshPeerPath *p;
5530   struct MeshTunnel *t;
5531
5532   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a path ACK msg [%s]\n",
5533               GNUNET_i2s (&my_full_id));
5534   msg = (struct GNUNET_MESH_PathACK *) message;
5535   t = tunnel_get (&msg->oid, ntohl(msg->tid));
5536   if (NULL == t)
5537   {
5538     /* TODO notify that we don't know the tunnel */
5539     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel", 1, GNUNET_NO);
5540     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  don't know the tunnel %s [%X]!\n",
5541                 GNUNET_i2s (&msg->oid), ntohl(msg->tid));
5542     return GNUNET_OK;
5543   }
5544   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %s [%X]\n",
5545               GNUNET_i2s (&msg->oid), ntohl(msg->tid));
5546
5547   peer_info = peer_info_get (&msg->peer_id);
5548   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by peer %s\n",
5549               GNUNET_i2s (&msg->peer_id));
5550   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  via peer %s\n",
5551               GNUNET_i2s (peer));
5552
5553   if (NULL != t->regex_ctx && t->regex_ctx->info->peer == peer_info->id)
5554   {
5555     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5556                 "connect_by_string completed, stopping search\n");
5557     regex_cancel_search (t->regex_ctx);
5558     t->regex_ctx = NULL;
5559   }
5560
5561   /* Add paths to peers? */
5562   p = tree_get_path_to_peer (t->tree, peer_info->id);
5563   if (NULL != p)
5564   {
5565     path_add_to_peers (p, GNUNET_YES);
5566     path_destroy (p);
5567   }
5568   else
5569   {
5570     GNUNET_break (0);
5571   }
5572
5573   /* Message for us? */
5574   if (0 == memcmp (&msg->oid, &my_full_id, sizeof (struct GNUNET_PeerIdentity)))
5575   {
5576     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
5577     if (NULL == t->owner)
5578     {
5579       GNUNET_break_op (0);
5580       return GNUNET_OK;
5581     }
5582     if (NULL != t->dht_get_type)
5583     {
5584       GNUNET_DHT_get_stop (t->dht_get_type);
5585       t->dht_get_type = NULL;
5586     }
5587     if (tree_get_status (t->tree, peer_info->id) != MESH_PEER_READY)
5588     {
5589       tree_set_status (t->tree, peer_info->id, MESH_PEER_READY);
5590       send_client_peer_connected (t, peer_info->id);
5591     }
5592     return GNUNET_OK;
5593   }
5594
5595   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5596               "  not for us, retransmitting...\n");
5597   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
5598   peer_info = peer_info_get (&msg->oid);
5599   if (NULL == peer_info)
5600   {
5601     /* If we know the tunnel, we should DEFINITELY know the peer */
5602     GNUNET_break (0);
5603     return GNUNET_OK;
5604   }
5605   send_message (message, &id, t);
5606   return GNUNET_OK;
5607 }
5608
5609
5610 /**
5611  * Functions to handle messages from core
5612  */
5613 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
5614   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
5615   {&handle_mesh_path_destroy, GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY, 0},
5616   {&handle_mesh_path_broken, GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN,
5617    sizeof (struct GNUNET_MESH_PathBroken)},
5618   {&handle_mesh_tunnel_destroy, GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY,
5619    sizeof (struct GNUNET_MESH_TunnelDestroy)},
5620   {&handle_mesh_data_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
5621   {&handle_mesh_data_multicast, GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
5622   {&handle_mesh_data_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
5623   {&handle_mesh_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
5624     sizeof (struct GNUNET_MESH_ACK)},
5625   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
5626    sizeof (struct GNUNET_MESH_PathACK)},
5627   {NULL, 0, 0}
5628 };
5629
5630
5631
5632 /******************************************************************************/
5633 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
5634 /******************************************************************************/
5635
5636 /**
5637  * deregister_app: iterator for removing each application registered by a client
5638  *
5639  * @param cls closure
5640  * @param key the hash of the application id (used to access the hashmap)
5641  * @param value the value stored at the key (client)
5642  *
5643  * @return GNUNET_OK on success
5644  */
5645 static int
5646 deregister_app (void *cls, const struct GNUNET_HashCode * key, void *value)
5647 {
5648   struct GNUNET_CONTAINER_MultiHashMap *h = cls;
5649   GNUNET_break (GNUNET_YES ==
5650                 GNUNET_CONTAINER_multihashmap_remove (h, key, value));
5651   return GNUNET_OK;
5652 }
5653
5654 #if LATER
5655 /**
5656  * notify_client_connection_failure: notify a client that the connection to the
5657  * requested remote peer is not possible (for instance, no route found)
5658  * Function called when the socket is ready to queue more data. "buf" will be
5659  * NULL and "size" zero if the socket was closed for writing in the meantime.
5660  *
5661  * @param cls closure
5662  * @param size number of bytes available in buf
5663  * @param buf where the callee should write the message
5664  * @return number of bytes written to buf
5665  */
5666 static size_t
5667 notify_client_connection_failure (void *cls, size_t size, void *buf)
5668 {
5669   int size_needed;
5670   struct MeshPeerInfo *peer_info;
5671   struct GNUNET_MESH_PeerControl *msg;
5672   struct GNUNET_PeerIdentity id;
5673
5674   if (0 == size && NULL == buf)
5675   {
5676     // TODO retry? cancel?
5677     return 0;
5678   }
5679
5680   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
5681   peer_info = (struct MeshPeerInfo *) cls;
5682   msg = (struct GNUNET_MESH_PeerControl *) buf;
5683   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
5684   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
5685 //     msg->tunnel_id = htonl(peer_info->t->tid);
5686   GNUNET_PEER_resolve (peer_info->id, &id);
5687   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
5688
5689   return size_needed;
5690 }
5691 #endif
5692
5693
5694 /**
5695  * Send keepalive packets for a peer
5696  *
5697  * @param cls Closure (tunnel for which to send the keepalive).
5698  * @param tc Notification context.
5699  *
5700  * TODO: implement explicit multicast keepalive?
5701  */
5702 static void
5703 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
5704 {
5705   struct MeshTunnel *t = cls;
5706   struct GNUNET_MessageHeader *payload;
5707   struct GNUNET_MESH_Multicast *msg;
5708   size_t size =
5709       sizeof (struct GNUNET_MESH_Multicast) +
5710       sizeof (struct GNUNET_MessageHeader);
5711   char cbuf[size];
5712
5713   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
5714   {
5715     return;
5716   }
5717   t->path_refresh_task = GNUNET_SCHEDULER_NO_TASK;
5718
5719   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5720               "sending keepalive for tunnel %d\n", t->id.tid);
5721
5722   msg = (struct GNUNET_MESH_Multicast *) cbuf;
5723   msg->header.size = htons (size);
5724   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
5725   // FIXME: change type to != MULTICAST
5726   msg->oid = my_full_id;
5727   msg->tid = htonl (t->id.tid);
5728   msg->ttl = htonl (default_ttl);
5729   msg->pid = htonl (t->fwd_pid + 1);
5730   t->fwd_pid++;
5731   payload = (struct GNUNET_MessageHeader *) &msg[1];
5732   payload->size = htons (sizeof (struct GNUNET_MessageHeader));
5733   payload->type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE);
5734   tunnel_send_multicast (t, &msg->header, GNUNET_YES);
5735
5736   t->path_refresh_task =
5737       GNUNET_SCHEDULER_add_delayed (refresh_path_time, &path_refresh, t);
5738   return;
5739 }
5740
5741
5742 /**
5743  * Function to process paths received for a new peer addition. The recorded
5744  * paths form the initial tunnel, which can be optimized later.
5745  * Called on each result obtained for the DHT search.
5746  *
5747  * @param cls closure
5748  * @param exp when will this value expire
5749  * @param key key of the result
5750  * @param get_path path of the get request
5751  * @param get_path_length lenght of get_path
5752  * @param put_path path of the put request
5753  * @param put_path_length length of the put_path
5754  * @param type type of the result
5755  * @param size number of bytes in data
5756  * @param data pointer to the result data
5757  *
5758  * TODO: re-issue the request after certain time? cancel after X results?
5759  */
5760 static void
5761 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
5762                     const struct GNUNET_HashCode * key,
5763                     const struct GNUNET_PeerIdentity *get_path,
5764                     unsigned int get_path_length,
5765                     const struct GNUNET_PeerIdentity *put_path,
5766                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
5767                     size_t size, const void *data)
5768 {
5769   struct MeshPathInfo *path_info = cls;
5770   struct MeshPeerPath *p;
5771   struct GNUNET_PeerIdentity pi;
5772   int i;
5773
5774   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
5775   GNUNET_PEER_resolve (path_info->peer->id, &pi);
5776   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", GNUNET_i2s (&pi));
5777
5778   p = path_build_from_dht (get_path, get_path_length, put_path,
5779                            put_path_length);
5780   path_add_to_peers (p, GNUNET_NO);
5781   path_destroy(p);
5782   for (i = 0; i < path_info->peer->ntunnels; i++)
5783   {
5784     tunnel_add_peer (path_info->peer->tunnels[i], path_info->peer);
5785     peer_info_connect (path_info->peer, path_info->t);
5786   }
5787
5788   return;
5789 }
5790
5791
5792 /**
5793  * Function to process paths received for a new peer addition. The recorded
5794  * paths form the initial tunnel, which can be optimized later.
5795  * Called on each result obtained for the DHT search.
5796  *
5797  * @param cls closure
5798  * @param exp when will this value expire
5799  * @param key key of the result
5800  * @param get_path path of the get request
5801  * @param get_path_length lenght of get_path
5802  * @param put_path path of the put request
5803  * @param put_path_length length of the put_path
5804  * @param type type of the result
5805  * @param size number of bytes in data
5806  * @param data pointer to the result data
5807  */
5808 static void
5809 dht_get_type_handler (void *cls, struct GNUNET_TIME_Absolute exp,
5810                       const struct GNUNET_HashCode * key,
5811                       const struct GNUNET_PeerIdentity *get_path,
5812                       unsigned int get_path_length,
5813                       const struct GNUNET_PeerIdentity *put_path,
5814                       unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
5815                       size_t size, const void *data)
5816 {
5817   const struct PBlock *pb = data;
5818   const struct GNUNET_PeerIdentity *pi = &pb->id;
5819   struct MeshTunnel *t = cls;
5820   struct MeshPeerInfo *peer_info;
5821   struct MeshPeerPath *p;
5822
5823   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got type DHT result!\n");
5824   if (size != sizeof (struct PBlock))
5825   {
5826     GNUNET_break_op (0);
5827     return;
5828   }
5829   if (ntohl(pb->type) != t->type)
5830   {
5831     GNUNET_break_op (0);
5832     return;
5833   }
5834   GNUNET_assert (NULL != t->owner);
5835   peer_info = peer_info_get (pi);
5836   (void) GNUNET_CONTAINER_multihashmap_put (t->peers, &pi->hashPubKey,
5837                                             peer_info,
5838                                             GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
5839
5840   p = path_build_from_dht (get_path, get_path_length, put_path,
5841                            put_path_length);
5842   path_add_to_peers (p, GNUNET_NO);
5843   path_destroy(p);
5844   tunnel_add_peer (t, peer_info);
5845   peer_info_connect (peer_info, t);
5846 }
5847
5848
5849 /**
5850  * Function to process DHT string to regex matching.
5851  * Called on each result obtained for the DHT search.
5852  *
5853  * @param cls closure (search context)
5854  * @param exp when will this value expire
5855  * @param key key of the result
5856  * @param get_path path of the get request (not used)
5857  * @param get_path_length lenght of get_path (not used)
5858  * @param put_path path of the put request (not used)
5859  * @param put_path_length length of the put_path (not used)
5860  * @param type type of the result
5861  * @param size number of bytes in data
5862  * @param data pointer to the result data
5863  */
5864 static void
5865 dht_get_string_accept_handler (void *cls, struct GNUNET_TIME_Absolute exp,
5866                                const struct GNUNET_HashCode * key,
5867                                const struct GNUNET_PeerIdentity *get_path,
5868                                unsigned int get_path_length,
5869                                const struct GNUNET_PeerIdentity *put_path,
5870                                unsigned int put_path_length,
5871                                enum GNUNET_BLOCK_Type type,
5872                                size_t size, const void *data)
5873 {
5874   const struct MeshRegexAccept *block = data;
5875   struct MeshRegexSearchContext *ctx = cls;
5876   struct MeshRegexSearchInfo *info = ctx->info;
5877   struct MeshPeerPath *p;
5878   struct MeshPeerInfo *peer_info;
5879
5880   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got regex results from DHT!\n");
5881   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", info->description);
5882
5883   peer_info = peer_info_get(&block->id);
5884   p = path_build_from_dht (get_path, get_path_length, put_path,
5885                            put_path_length);
5886   path_add_to_peers (p, GNUNET_NO);
5887   path_destroy(p);
5888
5889   tunnel_add_peer (info->t, peer_info);
5890   peer_info_connect (peer_info, info->t);
5891   if (0 == info->peer)
5892   {
5893     info->peer = peer_info->id;
5894   }
5895   else
5896   {
5897     GNUNET_array_append (info->peers, info->n_peers, peer_info->id);
5898   }
5899
5900   info->timeout = GNUNET_SCHEDULER_add_delayed (connect_timeout,
5901                                                 &regex_connect_timeout,
5902                                                 info);
5903
5904   return;
5905 }
5906
5907
5908 /**
5909  * Function to process DHT string to regex matching.
5910  * Called on each result obtained for the DHT search.
5911  *
5912  * @param cls closure (search context)
5913  * @param exp when will this value expire
5914  * @param key key of the result
5915  * @param get_path path of the get request (not used)
5916  * @param get_path_length lenght of get_path (not used)
5917  * @param put_path path of the put request (not used)
5918  * @param put_path_length length of the put_path (not used)
5919  * @param type type of the result
5920  * @param size number of bytes in data
5921  * @param data pointer to the result data
5922  *
5923  * TODO: re-issue the request after certain time? cancel after X results?
5924  */
5925 static void
5926 dht_get_string_handler (void *cls, struct GNUNET_TIME_Absolute exp,
5927                         const struct GNUNET_HashCode * key,
5928                         const struct GNUNET_PeerIdentity *get_path,
5929                         unsigned int get_path_length,
5930                         const struct GNUNET_PeerIdentity *put_path,
5931                         unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
5932                         size_t size, const void *data)
5933 {
5934   const struct MeshRegexBlock *block = data;
5935   struct MeshRegexSearchContext *ctx = cls;
5936   struct MeshRegexSearchInfo *info = ctx->info;
5937   void *copy;
5938   size_t len;
5939
5940   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5941               "DHT GET STRING RETURNED RESULTS\n");
5942   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5943               "  key: %s\n", GNUNET_h2s (key));
5944
5945   copy = GNUNET_malloc (size);
5946   memcpy (copy, data, size);
5947   GNUNET_break (GNUNET_OK ==
5948                 GNUNET_CONTAINER_multihashmap_put(info->dht_get_results, key, copy,
5949                                                   GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
5950   len = ntohl (block->n_proof);
5951   {
5952     char proof[len + 1];
5953
5954     memcpy (proof, &block[1], len);
5955     proof[len] = '\0';
5956     if (GNUNET_OK != GNUNET_REGEX_check_proof (proof, key))
5957     {
5958       GNUNET_break_op (0);
5959       return;
5960     }
5961   }
5962   len = strlen (info->description);
5963   if (len == ctx->position) // String processed
5964   {
5965     if (GNUNET_YES == ntohl (block->accepting))
5966     {
5967       regex_find_path(key, ctx);
5968     }
5969     else
5970     {
5971       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  block not accepting!\n");
5972       // FIXME REGEX this block not successful, wait for more? start timeout?
5973     }
5974     return;
5975   }
5976   GNUNET_break (GNUNET_OK ==
5977                 GNUNET_MESH_regex_block_iterate (block, size,
5978                                                  &regex_edge_iterator, ctx));
5979   return;
5980 }
5981
5982 /******************************************************************************/
5983 /*********************       MESH LOCAL HANDLES      **************************/
5984 /******************************************************************************/
5985
5986
5987 /**
5988  * Handler for client disconnection
5989  *
5990  * @param cls closure
5991  * @param client identification of the client; NULL
5992  *        for the last call when the server is destroyed
5993  */
5994 static void
5995 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
5996 {
5997   struct MeshClient *c;
5998   struct MeshClient *next;
5999   unsigned int i;
6000
6001   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected\n");
6002   if (client == NULL)
6003   {
6004     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (SERVER DOWN)\n");
6005     return;
6006   }
6007   c = clients;
6008   while (NULL != c)
6009   {
6010     if (c->handle != client)
6011     {
6012       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ... searching\n");
6013       c = c->next;
6014       continue;
6015     }
6016     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u)\n",
6017                 c->id);
6018     GNUNET_SERVER_client_drop (c->handle);
6019     c->shutting_down = GNUNET_YES;
6020     GNUNET_assert (NULL != c->own_tunnels);
6021     GNUNET_assert (NULL != c->incoming_tunnels);
6022     GNUNET_CONTAINER_multihashmap_iterate (c->own_tunnels,
6023                                            &tunnel_destroy_iterator, c);
6024     GNUNET_CONTAINER_multihashmap_iterate (c->incoming_tunnels,
6025                                            &tunnel_destroy_iterator, c);
6026     GNUNET_CONTAINER_multihashmap_iterate (c->ignore_tunnels,
6027                                            &tunnel_destroy_iterator, c);
6028     GNUNET_CONTAINER_multihashmap_destroy (c->own_tunnels);
6029     GNUNET_CONTAINER_multihashmap_destroy (c->incoming_tunnels);
6030     GNUNET_CONTAINER_multihashmap_destroy (c->ignore_tunnels);
6031
6032     /* deregister clients applications */
6033     if (NULL != c->apps)
6034     {
6035       GNUNET_CONTAINER_multihashmap_iterate (c->apps, &deregister_app, c->apps);
6036       GNUNET_CONTAINER_multihashmap_destroy (c->apps);
6037     }
6038     if (0 == GNUNET_CONTAINER_multihashmap_size (applications) &&
6039         GNUNET_SCHEDULER_NO_TASK != announce_applications_task)
6040     {
6041       GNUNET_SCHEDULER_cancel (announce_applications_task);
6042       announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
6043     }
6044     if (NULL != c->types)
6045       GNUNET_CONTAINER_multihashmap_destroy (c->types);
6046     for (i = 0; i < c->n_regex; i++)
6047     {
6048       GNUNET_free (c->regexes[i]);
6049     }
6050     GNUNET_free_non_null (c->regexes);
6051     if (GNUNET_SCHEDULER_NO_TASK != c->regex_announce_task)
6052       GNUNET_SCHEDULER_cancel (c->regex_announce_task);
6053     next = c->next;
6054     GNUNET_CONTAINER_DLL_remove (clients, clients_tail, c);
6055     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT FREE at %p\n", c);
6056     GNUNET_free (c);
6057     GNUNET_STATISTICS_update (stats, "# clients", -1, GNUNET_NO);
6058     c = next;
6059   }
6060   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   done!\n");
6061   return;
6062 }
6063
6064
6065 /**
6066  * Handler for new clients
6067  *
6068  * @param cls closure
6069  * @param client identification of the client
6070  * @param message the actual message, which includes messages the client wants
6071  */
6072 static void
6073 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
6074                          const struct GNUNET_MessageHeader *message)
6075 {
6076   struct GNUNET_MESH_ClientConnect *cc_msg;
6077   struct MeshClient *c;
6078   GNUNET_MESH_ApplicationType *a;
6079   unsigned int size;
6080   uint16_t ntypes;
6081   uint16_t *t;
6082   uint16_t napps;
6083   uint16_t i;
6084
6085   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected\n");
6086   /* Check data sanity */
6087   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
6088   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
6089   ntypes = ntohs (cc_msg->types);
6090   napps = ntohs (cc_msg->applications);
6091   if (size !=
6092       ntypes * sizeof (uint16_t) + napps * sizeof (GNUNET_MESH_ApplicationType))
6093   {
6094     GNUNET_break (0);
6095     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6096     return;
6097   }
6098
6099   /* Create new client structure */
6100   c = GNUNET_malloc (sizeof (struct MeshClient));
6101   c->id = next_client_id++;
6102   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT NEW %u\n", c->id);
6103   c->handle = client;
6104   GNUNET_SERVER_client_keep (client);
6105   a = (GNUNET_MESH_ApplicationType *) &cc_msg[1];
6106   if (napps > 0)
6107   {
6108     GNUNET_MESH_ApplicationType at;
6109     struct GNUNET_HashCode hc;
6110
6111     c->apps = GNUNET_CONTAINER_multihashmap_create (napps);
6112     for (i = 0; i < napps; i++)
6113     {
6114       at = ntohl (a[i]);
6115       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  app type: %u\n", at);
6116       GNUNET_CRYPTO_hash (&at, sizeof (at), &hc);
6117       /* store in clients hashmap */
6118       GNUNET_CONTAINER_multihashmap_put (c->apps, &hc, (void *) (long) at,
6119                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6120       /* store in global hashmap, for announcements */
6121       GNUNET_CONTAINER_multihashmap_put (applications, &hc, c,
6122                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6123     }
6124     if (GNUNET_SCHEDULER_NO_TASK == announce_applications_task)
6125       announce_applications_task =
6126           GNUNET_SCHEDULER_add_now (&announce_applications, NULL);
6127
6128   }
6129   if (ntypes > 0)
6130   {
6131     uint16_t u16;
6132     struct GNUNET_HashCode hc;
6133
6134     t = (uint16_t *) & a[napps];
6135     c->types = GNUNET_CONTAINER_multihashmap_create (ntypes);
6136     for (i = 0; i < ntypes; i++)
6137     {
6138       u16 = ntohs (t[i]);
6139       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  msg type: %u\n", u16);
6140       GNUNET_CRYPTO_hash (&u16, sizeof (u16), &hc);
6141
6142       /* store in clients hashmap */
6143       GNUNET_CONTAINER_multihashmap_put (c->types, &hc, c,
6144                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6145       /* store in global hashmap */
6146       GNUNET_CONTAINER_multihashmap_put (types, &hc, c,
6147                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6148     }
6149   }
6150   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6151               " client has %u+%u subscriptions\n", napps, ntypes);
6152
6153   GNUNET_CONTAINER_DLL_insert (clients, clients_tail, c);
6154   c->own_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
6155   c->incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
6156   c->ignore_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
6157   GNUNET_SERVER_notification_context_add (nc, client);
6158   GNUNET_STATISTICS_update (stats, "# clients", 1, GNUNET_NO);
6159
6160   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6161   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
6162 }
6163
6164
6165 /**
6166  * Handler for clients announcing available services by a regular expression.
6167  *
6168  * @param cls closure
6169  * @param client identification of the client
6170  * @param message the actual message, which includes messages the client wants
6171  */
6172 static void
6173 handle_local_announce_regex (void *cls, struct GNUNET_SERVER_Client *client,
6174                              const struct GNUNET_MessageHeader *message)
6175 {
6176   struct MeshClient *c;
6177   char *regex;
6178   size_t len;
6179
6180   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "announce regex started\n");
6181
6182   /* Sanity check for client registration */
6183   if (NULL == (c = client_get (client)))
6184   {
6185     GNUNET_break (0);
6186     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6187     return;
6188   }
6189   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6190
6191   len = ntohs (message->size) - sizeof(struct GNUNET_MessageHeader);
6192   regex = GNUNET_malloc (len + 1);
6193   memcpy (regex, &message[1], len);
6194   regex[len] = '\0';
6195   GNUNET_array_append (c->regexes, c->n_regex, regex);
6196   if (GNUNET_SCHEDULER_NO_TASK == c->regex_announce_task)
6197   {
6198     c->regex_announce_task = GNUNET_SCHEDULER_add_now(&announce_regex, c);
6199   }
6200   else
6201   {
6202     regex_put(regex);
6203   }
6204   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6205   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "announce regex processed\n");
6206 }
6207
6208
6209 /**
6210  * Handler for requests of new tunnels
6211  *
6212  * @param cls closure
6213  * @param client identification of the client
6214  * @param message the actual message
6215  */
6216 static void
6217 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
6218                             const struct GNUNET_MessageHeader *message)
6219 {
6220   struct GNUNET_MESH_TunnelMessage *t_msg;
6221   struct MeshTunnel *t;
6222   struct MeshClient *c;
6223   MESH_TunnelNumber tid;
6224
6225   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel requested\n");
6226
6227   /* Sanity check for client registration */
6228   if (NULL == (c = client_get (client)))
6229   {
6230     GNUNET_break (0);
6231     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6232     return;
6233   }
6234   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6235
6236   /* Message sanity check */
6237   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
6238   {
6239     GNUNET_break (0);
6240     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6241     return;
6242   }
6243
6244   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6245   /* Sanity check for tunnel numbering */
6246   tid = ntohl (t_msg->tunnel_id);
6247   if (0 == (tid & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
6248   {
6249     GNUNET_break (0);
6250     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6251     return;
6252   }
6253   /* Sanity check for duplicate tunnel IDs */
6254   if (NULL != tunnel_get_by_local_id (c, tid))
6255   {
6256     GNUNET_break (0);
6257     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6258     return;
6259   }
6260
6261   while (NULL != tunnel_get_by_pi (myid, next_tid))
6262     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
6263   t = tunnel_new (myid, next_tid++, c, tid);
6264   if (NULL == t)
6265   {
6266     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Tunnel creation failed.\n");
6267     GNUNET_break (0);
6268     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6269     return;
6270   }
6271   next_tid = next_tid & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
6272   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED TUNNEL %s [%x] (%x)\n",
6273               GNUNET_i2s (&my_full_id), t->id.tid, t->local_tid);
6274   t->peers = GNUNET_CONTAINER_multihashmap_create (32);
6275
6276   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel created\n");
6277   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6278   return;
6279 }
6280
6281
6282 /**
6283  * Handler for requests of deleting tunnels
6284  *
6285  * @param cls closure
6286  * @param client identification of the client
6287  * @param message the actual message
6288  */
6289 static void
6290 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
6291                              const struct GNUNET_MessageHeader *message)
6292 {
6293   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
6294   struct MeshClient *c;
6295   struct MeshTunnel *t;
6296   MESH_TunnelNumber tid;
6297
6298   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6299               "Got a DESTROY TUNNEL from client!\n");
6300
6301   /* Sanity check for client registration */
6302   if (NULL == (c = client_get (client)))
6303   {
6304     GNUNET_break (0);
6305     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6306     return;
6307   }
6308   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6309
6310   /* Message sanity check */
6311   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
6312   {
6313     GNUNET_break (0);
6314     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6315     return;
6316   }
6317
6318   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6319
6320   /* Retrieve tunnel */
6321   tid = ntohl (tunnel_msg->tunnel_id);
6322   t = tunnel_get_by_local_id(c, tid);
6323   if (NULL == t)
6324   {
6325     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
6326     GNUNET_break (0);
6327     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6328     return;
6329   }
6330   if (c != t->owner || tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
6331   {
6332     client_ignore_tunnel (c, t);
6333 #if 0
6334     // TODO: when to destroy incoming tunnel?
6335     if (t->nclients == 0)
6336     {
6337       GNUNET_assert (GNUNET_YES ==
6338                      GNUNET_CONTAINER_multihashmap_remove (incoming_tunnels,
6339                                                            &hash, t));
6340       GNUNET_assert (GNUNET_YES ==
6341                      GNUNET_CONTAINER_multihashmap_remove (t->peers,
6342                                                            &my_full_id.hashPubKey,
6343                                                            t));
6344     }
6345 #endif
6346     GNUNET_SERVER_receive_done (client, GNUNET_OK);
6347     return;
6348   }
6349   send_client_tunnel_disconnect(t, c);
6350   client_delete_tunnel(c, t);
6351
6352   /* Don't try to ACK the client about the tunnel_destroy multicast packet */
6353   t->owner = NULL;
6354   tunnel_send_destroy (t);
6355   t->destroy = GNUNET_YES;
6356   // The tunnel will be destroyed when the last message is transmitted.
6357   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6358   return;
6359 }
6360
6361
6362 /**
6363  * Handler for requests of seeting tunnel's speed.
6364  *
6365  * @param cls Closure (unused).
6366  * @param client Identification of the client.
6367  * @param message The actual message.
6368  */
6369 static void
6370 handle_local_tunnel_speed (void *cls, struct GNUNET_SERVER_Client *client,
6371                            const struct GNUNET_MessageHeader *message)
6372 {
6373   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
6374   struct MeshClient *c;
6375   struct MeshTunnel *t;
6376   MESH_TunnelNumber tid;
6377
6378   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6379               "Got a SPEED request from client!\n");
6380
6381   /* Sanity check for client registration */
6382   if (NULL == (c = client_get (client)))
6383   {
6384     GNUNET_break (0);
6385     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6386     return;
6387   }
6388
6389   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6390
6391   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6392
6393   /* Retrieve tunnel */
6394   tid = ntohl (tunnel_msg->tunnel_id);
6395   t = tunnel_get_by_local_id(c, tid);
6396   if (NULL == t)
6397   {
6398     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  tunnel %X not found\n", tid);
6399     GNUNET_break (0);
6400     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6401     return;
6402   }
6403
6404   switch (ntohs(message->type))
6405   {
6406       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MIN:
6407           t->speed_min = GNUNET_YES;
6408           break;
6409       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MAX:
6410           t->speed_min = GNUNET_NO;
6411           break;
6412       default:
6413           GNUNET_break (0);
6414   }
6415   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6416 }
6417
6418
6419 /**
6420  * Handler for requests of seeting tunnel's buffering policy.
6421  *
6422  * @param cls Closure (unused).
6423  * @param client Identification of the client.
6424  * @param message The actual message.
6425  */
6426 static void
6427 handle_local_tunnel_buffer (void *cls, struct GNUNET_SERVER_Client *client,
6428                             const struct GNUNET_MessageHeader *message)
6429 {
6430   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
6431   struct MeshClient *c;
6432   struct MeshTunnel *t;
6433   MESH_TunnelNumber tid;
6434
6435   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6436               "Got a BUFFER request from client!\n");
6437
6438   /* Sanity check for client registration */
6439   if (NULL == (c = client_get (client)))
6440   {
6441     GNUNET_break (0);
6442     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6443     return;
6444   }
6445   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6446
6447   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6448
6449   /* Retrieve tunnel */
6450   tid = ntohl (tunnel_msg->tunnel_id);
6451   t = tunnel_get_by_local_id(c, tid);
6452   if (NULL == t)
6453   {
6454     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
6455     GNUNET_break (0);
6456     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6457     return;
6458   }
6459
6460   switch (ntohs(message->type))
6461   {
6462       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER:
6463           t->nobuffer = GNUNET_NO;
6464           break;
6465       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER:
6466           t->nobuffer = GNUNET_YES;
6467           break;
6468       default:
6469           GNUNET_break (0);
6470   }
6471
6472   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6473 }
6474
6475
6476 /**
6477  * Handler for connection requests to new peers
6478  *
6479  * @param cls closure
6480  * @param client identification of the client
6481  * @param message the actual message (PeerControl)
6482  */
6483 static void
6484 handle_local_connect_add (void *cls, struct GNUNET_SERVER_Client *client,
6485                           const struct GNUNET_MessageHeader *message)
6486 {
6487   struct GNUNET_MESH_PeerControl *peer_msg;
6488   struct MeshPeerInfo *peer_info;
6489   struct MeshClient *c;
6490   struct MeshTunnel *t;
6491   MESH_TunnelNumber tid;
6492
6493   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got connection request\n");
6494   /* Sanity check for client registration */
6495   if (NULL == (c = client_get (client)))
6496   {
6497     GNUNET_break (0);
6498     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6499     return;
6500   }
6501   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6502
6503   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6504
6505   /* Sanity check for message size */
6506   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6507   {
6508     GNUNET_break (0);
6509     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6510     return;
6511   }
6512
6513   /* Tunnel exists? */
6514   tid = ntohl (peer_msg->tunnel_id);
6515   t = tunnel_get_by_local_id (c, tid);
6516   if (NULL == t)
6517   {
6518     GNUNET_break (0);
6519     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6520     return;
6521   }
6522
6523   /* Does client own tunnel? */
6524   if (t->owner->handle != client)
6525   {
6526     GNUNET_break (0);
6527     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6528     return;
6529   }
6530   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "     for %s\n",
6531               GNUNET_i2s (&peer_msg->peer));
6532   peer_info = peer_info_get (&peer_msg->peer);
6533
6534   tunnel_add_peer (t, peer_info);
6535   peer_info_connect (peer_info, t);
6536
6537   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6538   return;
6539 }
6540
6541
6542 /**
6543  * Handler for disconnection requests of peers in a tunnel
6544  *
6545  * @param cls closure
6546  * @param client identification of the client
6547  * @param message the actual message (PeerControl)
6548  */
6549 static void
6550 handle_local_connect_del (void *cls, struct GNUNET_SERVER_Client *client,
6551                           const struct GNUNET_MessageHeader *message)
6552 {
6553   struct GNUNET_MESH_PeerControl *peer_msg;
6554   struct MeshPeerInfo *peer_info;
6555   struct MeshClient *c;
6556   struct MeshTunnel *t;
6557   MESH_TunnelNumber tid;
6558
6559   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER DEL request\n");
6560   /* Sanity check for client registration */
6561   if (NULL == (c = client_get (client)))
6562   {
6563     GNUNET_break (0);
6564     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6565     return;
6566   }
6567   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6568
6569   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6570
6571   /* Sanity check for message size */
6572   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6573   {
6574     GNUNET_break (0);
6575     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6576     return;
6577   }
6578
6579   /* Tunnel exists? */
6580   tid = ntohl (peer_msg->tunnel_id);
6581   t = tunnel_get_by_local_id (c, tid);
6582   if (NULL == t)
6583   {
6584     GNUNET_break (0);
6585     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6586     return;
6587   }
6588   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
6589
6590   /* Does client own tunnel? */
6591   if (t->owner->handle != client)
6592   {
6593     GNUNET_break (0);
6594     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6595     return;
6596   }
6597
6598   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for peer %s\n",
6599               GNUNET_i2s (&peer_msg->peer));
6600   /* Is the peer in the tunnel? */
6601   peer_info =
6602       GNUNET_CONTAINER_multihashmap_get (t->peers, &peer_msg->peer.hashPubKey);
6603   if (NULL == peer_info)
6604   {
6605     GNUNET_break (0);
6606     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6607     return;
6608   }
6609
6610   /* Ok, delete peer from tunnel */
6611   GNUNET_CONTAINER_multihashmap_remove_all (t->peers,
6612                                             &peer_msg->peer.hashPubKey);
6613
6614   send_destroy_path (t, peer_info->id);
6615   tunnel_delete_peer (t, peer_info->id);
6616   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6617   return;
6618 }
6619
6620 /**
6621  * Handler for blacklist requests of peers in a tunnel
6622  *
6623  * @param cls closure
6624  * @param client identification of the client
6625  * @param message the actual message (PeerControl)
6626  * 
6627  * FIXME implement DHT block bloomfilter
6628  */
6629 static void
6630 handle_local_blacklist (void *cls, struct GNUNET_SERVER_Client *client,
6631                           const struct GNUNET_MessageHeader *message)
6632 {
6633   struct GNUNET_MESH_PeerControl *peer_msg;
6634   struct MeshClient *c;
6635   struct MeshTunnel *t;
6636   MESH_TunnelNumber tid;
6637
6638   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER BLACKLIST request\n");
6639   /* Sanity check for client registration */
6640   if (NULL == (c = client_get (client)))
6641   {
6642     GNUNET_break (0);
6643     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6644     return;
6645   }
6646   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6647
6648   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6649
6650   /* Sanity check for message size */
6651   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6652   {
6653     GNUNET_break (0);
6654     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6655     return;
6656   }
6657
6658   /* Tunnel exists? */
6659   tid = ntohl (peer_msg->tunnel_id);
6660   t = tunnel_get_by_local_id (c, tid);
6661   if (NULL == t)
6662   {
6663     GNUNET_break (0);
6664     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6665     return;
6666   }
6667   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
6668
6669   GNUNET_array_append(t->blacklisted, t->nblacklisted,
6670                       GNUNET_PEER_intern(&peer_msg->peer));
6671 }
6672
6673
6674 /**
6675  * Handler for unblacklist requests of peers in a tunnel
6676  *
6677  * @param cls closure
6678  * @param client identification of the client
6679  * @param message the actual message (PeerControl)
6680  */
6681 static void
6682 handle_local_unblacklist (void *cls, struct GNUNET_SERVER_Client *client,
6683                           const struct GNUNET_MessageHeader *message)
6684 {
6685   struct GNUNET_MESH_PeerControl *peer_msg;
6686   struct MeshClient *c;
6687   struct MeshTunnel *t;
6688   MESH_TunnelNumber tid;
6689   GNUNET_PEER_Id pid;
6690   unsigned int i;
6691
6692   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER UNBLACKLIST request\n");
6693   /* Sanity check for client registration */
6694   if (NULL == (c = client_get (client)))
6695   {
6696     GNUNET_break (0);
6697     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6698     return;
6699   }
6700   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6701
6702   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6703
6704   /* Sanity check for message size */
6705   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6706   {
6707     GNUNET_break (0);
6708     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6709     return;
6710   }
6711
6712   /* Tunnel exists? */
6713   tid = ntohl (peer_msg->tunnel_id);
6714   t = tunnel_get_by_local_id (c, tid);
6715   if (NULL == t)
6716   {
6717     GNUNET_break (0);
6718     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6719     return;
6720   }
6721   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
6722
6723   /* if peer is not known, complain */
6724   pid = GNUNET_PEER_search (&peer_msg->peer);
6725   if (0 == pid)
6726   {
6727     GNUNET_break (0);
6728     return;
6729   }
6730
6731   /* search and remove from list */
6732   for (i = 0; i < t->nblacklisted; i++)
6733   {
6734     if (t->blacklisted[i] == pid)
6735     {
6736       t->blacklisted[i] = t->blacklisted[t->nblacklisted - 1];
6737       GNUNET_array_grow (t->blacklisted, t->nblacklisted, t->nblacklisted - 1);
6738       return;
6739     }
6740   }
6741
6742   /* if peer hasn't been blacklisted, complain */
6743   GNUNET_break (0);
6744 }
6745
6746
6747 /**
6748  * Handler for connection requests to new peers by type
6749  *
6750  * @param cls closure
6751  * @param client identification of the client
6752  * @param message the actual message (ConnectPeerByType)
6753  */
6754 static void
6755 handle_local_connect_by_type (void *cls, struct GNUNET_SERVER_Client *client,
6756                               const struct GNUNET_MessageHeader *message)
6757 {
6758   struct GNUNET_MESH_ConnectPeerByType *connect_msg;
6759   struct MeshClient *c;
6760   struct MeshTunnel *t;
6761   struct GNUNET_HashCode hash;
6762   MESH_TunnelNumber tid;
6763
6764   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got connect by type request\n");
6765   /* Sanity check for client registration */
6766   if (NULL == (c = client_get (client)))
6767   {
6768     GNUNET_break (0);
6769     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6770     return;
6771   }
6772   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6773
6774   connect_msg = (struct GNUNET_MESH_ConnectPeerByType *) message;
6775
6776   /* Sanity check for message size */
6777   if (sizeof (struct GNUNET_MESH_ConnectPeerByType) !=
6778       ntohs (connect_msg->header.size))
6779   {
6780     GNUNET_break (0);
6781     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6782     return;
6783   }
6784
6785   /* Tunnel exists? */
6786   tid = ntohl (connect_msg->tunnel_id);
6787   t = tunnel_get_by_local_id (c, tid);
6788   if (NULL == t)
6789   {
6790     GNUNET_break (0);
6791     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6792     return;
6793   }
6794
6795   /* Does client own tunnel? */
6796   if (t->owner->handle != client)
6797   {
6798     GNUNET_break (0);
6799     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6800     return;
6801   }
6802
6803   /* Do WE have the service? */
6804   t->type = ntohl (connect_msg->type);
6805   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " type requested: %u\n", t->type);
6806   GNUNET_CRYPTO_hash (&t->type, sizeof (GNUNET_MESH_ApplicationType), &hash);
6807   if (GNUNET_CONTAINER_multihashmap_contains (applications, &hash) ==
6808       GNUNET_YES)
6809   {
6810     /* Yes! Fast forward, add ourselves to the tunnel and send the
6811      * good news to the client, and alert the destination client of
6812      * an incoming tunnel.
6813      *
6814      * FIXME send a path create to self, avoid code duplication
6815      */
6816     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " available locally\n");
6817     GNUNET_CONTAINER_multihashmap_put (t->peers, &my_full_id.hashPubKey,
6818                                        peer_info_get (&my_full_id),
6819                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
6820
6821     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " notifying client\n");
6822     send_client_peer_connected (t, myid);
6823     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Done\n");
6824     GNUNET_SERVER_receive_done (client, GNUNET_OK);
6825
6826     t->local_tid_dest = next_local_tid++;
6827     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
6828     GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
6829                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
6830
6831     return;
6832   }
6833   /* Ok, lets find a peer offering the service */
6834   if (NULL != t->dht_get_type)
6835   {
6836     GNUNET_DHT_get_stop (t->dht_get_type);
6837   }
6838   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " looking in DHT for %s\n",
6839               GNUNET_h2s (&hash));
6840   t->dht_get_type =
6841       GNUNET_DHT_get_start (dht_handle, 
6842                             GNUNET_BLOCK_TYPE_MESH_PEER_BY_TYPE,
6843                             &hash,
6844                             dht_replication_level,
6845                             GNUNET_DHT_RO_RECORD_ROUTE |
6846                             GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
6847                             NULL, 0,
6848                             &dht_get_type_handler, t);
6849
6850   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6851   return;
6852 }
6853
6854
6855 /**
6856  * Handler for connection requests to new peers by a string service description.
6857  *
6858  * @param cls closure
6859  * @param client identification of the client
6860  * @param message the actual message, which includes messages the client wants
6861  */
6862 static void
6863 handle_local_connect_by_string (void *cls, struct GNUNET_SERVER_Client *client,
6864                                 const struct GNUNET_MessageHeader *message)
6865 {
6866   struct GNUNET_MESH_ConnectPeerByString *msg;
6867   struct MeshRegexSearchContext *ctx;
6868   struct MeshRegexSearchInfo *info;
6869   struct GNUNET_DHT_GetHandle *get_h;
6870   struct GNUNET_HashCode key;
6871   struct MeshTunnel *t;
6872   struct MeshClient *c;
6873   MESH_TunnelNumber tid;
6874   const char *string;
6875   size_t size;
6876   size_t len;
6877   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6878               "Connect by string started\n");
6879   msg = (struct GNUNET_MESH_ConnectPeerByString *) message;
6880   size = htons (message->size);
6881
6882   /* Sanity check for client registration */
6883   if (NULL == (c = client_get (client)))
6884   {
6885     GNUNET_break (0);
6886     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6887     return;
6888   }
6889   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6890
6891   /* Message size sanity check */
6892   if (sizeof(struct GNUNET_MESH_ConnectPeerByString) >= size)
6893   {
6894     GNUNET_break (0);
6895     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6896     return;
6897   }
6898
6899   /* Tunnel exists? */
6900   tid = ntohl (msg->tunnel_id);
6901   t = tunnel_get_by_local_id (c, tid);
6902   if (NULL == t)
6903   {
6904     GNUNET_break (0);
6905     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6906     return;
6907   }
6908
6909   /* Does client own tunnel? */
6910   if (t->owner->handle != client)
6911   {
6912     GNUNET_break (0);
6913     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6914     return;
6915   }
6916
6917   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6918               "  on tunnel %s [%u]\n",
6919               GNUNET_i2s(&my_full_id),
6920               t->id.tid);
6921
6922   /* Only one connect_by_string allowed at the same time! */
6923   /* FIXME: allow more, return handle at api level to cancel, document */
6924   if (NULL != t->regex_ctx)
6925   {
6926     GNUNET_break (0);
6927     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6928     return;
6929   }
6930
6931   /* Find string itself */
6932   len = size - sizeof(struct GNUNET_MESH_ConnectPeerByString);
6933   string = (const char *) &msg[1];
6934
6935   /* Initialize context */
6936   size = GNUNET_REGEX_get_first_key(string, len, &key);
6937   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6938               "  consumed %u bits out of %u\n", size, len);
6939   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6940               "  looking for %s\n", GNUNET_h2s (&key));
6941
6942   info = GNUNET_malloc (sizeof (struct MeshRegexSearchInfo));
6943   info->t = t;
6944   info->description = GNUNET_malloc (len + 1);
6945   memcpy (info->description, string, len);
6946   info->description[len] = '\0';
6947   info->dht_get_handles = GNUNET_CONTAINER_multihashmap_create(32);
6948   info->dht_get_results = GNUNET_CONTAINER_multihashmap_create(32);
6949   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   string: %s\n", info->description);
6950
6951   ctx = GNUNET_malloc (sizeof (struct MeshRegexSearchContext));
6952   ctx->position = size;
6953   ctx->info = info;
6954   t->regex_ctx = ctx;
6955
6956   GNUNET_array_append (info->contexts, info->n_contexts, ctx);
6957
6958   /* Start search in DHT */
6959   get_h = GNUNET_DHT_get_start (dht_handle,    /* handle */
6960                                 GNUNET_BLOCK_TYPE_MESH_REGEX, /* type */
6961                                 &key,     /* key to search */
6962                                 dht_replication_level, /* replication level */
6963                                 GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
6964                                 NULL,       /* xquery */ // FIXME BLOOMFILTER
6965                                 0,     /* xquery bits */ // FIXME BLOOMFILTER SIZE
6966                                 &dht_get_string_handler, ctx);
6967
6968   GNUNET_break (GNUNET_OK ==
6969                 GNUNET_CONTAINER_multihashmap_put(info->dht_get_handles,
6970                                                   &key,
6971                                                   get_h,
6972                                                   GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
6973
6974   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6975   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "connect by string processed\n");
6976 }
6977
6978
6979 /**
6980  * Handler for client traffic directed to one peer
6981  *
6982  * @param cls closure
6983  * @param client identification of the client
6984  * @param message the actual message
6985  */
6986 static void
6987 handle_local_unicast (void *cls, struct GNUNET_SERVER_Client *client,
6988                       const struct GNUNET_MessageHeader *message)
6989 {
6990   struct MeshClient *c;
6991   struct MeshTunnel *t;
6992   struct MeshPeerInfo *pi;
6993   struct GNUNET_MESH_Unicast *data_msg;
6994   MESH_TunnelNumber tid;
6995   size_t size;
6996
6997   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6998               "Got a unicast request from a client!\n");
6999
7000   /* Sanity check for client registration */
7001   if (NULL == (c = client_get (client)))
7002   {
7003     GNUNET_break (0);
7004     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7005     return;
7006   }
7007   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7008
7009   data_msg = (struct GNUNET_MESH_Unicast *) message;
7010
7011   /* Sanity check for message size */
7012   size = ntohs (message->size);
7013   if (sizeof (struct GNUNET_MESH_Unicast) +
7014       sizeof (struct GNUNET_MessageHeader) > size)
7015   {
7016     GNUNET_break (0);
7017     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7018     return;
7019   }
7020
7021   /* Tunnel exists? */
7022   tid = ntohl (data_msg->tid);
7023   t = tunnel_get_by_local_id (c, tid);
7024   if (NULL == t)
7025   {
7026     GNUNET_break (0);
7027     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7028     return;
7029   }
7030
7031   /*  Is it a local tunnel? Then, does client own the tunnel? */
7032   if (t->owner->handle != client)
7033   {
7034     GNUNET_break (0);
7035     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7036     return;
7037   }
7038
7039   pi = GNUNET_CONTAINER_multihashmap_get (t->peers,
7040                                           &data_msg->destination.hashPubKey);
7041   /* Is the selected peer in the tunnel? */
7042   if (NULL == pi)
7043   {
7044     GNUNET_break (0);
7045     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7046     return;
7047   }
7048
7049   /* PID should be as expected */
7050   if (ntohl (data_msg->pid) != t->fwd_pid + 1)
7051   {
7052     GNUNET_break (0);
7053     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7054               "Unicast PID, expected %u, got %u\n",
7055               t->fwd_pid + 1, ntohl (data_msg->pid));
7056     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7057     return;
7058   }
7059
7060   /* Ok, everything is correct, send the message
7061    * (pretend we got it from a mesh peer)
7062    */
7063   {
7064     /* Work around const limitation */
7065     char buf[ntohs (message->size)] GNUNET_ALIGN;
7066     struct GNUNET_MESH_Unicast *copy;
7067
7068     copy = (struct GNUNET_MESH_Unicast *) buf;
7069     memcpy (buf, data_msg, size);
7070     copy->oid = my_full_id;
7071     copy->tid = htonl (t->id.tid);
7072     copy->ttl = htonl (default_ttl);
7073     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7074                 "  calling generic handler...\n");
7075     handle_mesh_data_unicast (NULL, &my_full_id, &copy->header, NULL, 0);
7076   }
7077   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "receive done OK\n");
7078   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7079
7080   return;
7081 }
7082
7083
7084 /**
7085  * Handler for client traffic directed to the origin
7086  *
7087  * @param cls closure
7088  * @param client identification of the client
7089  * @param message the actual message
7090  */
7091 static void
7092 handle_local_to_origin (void *cls, struct GNUNET_SERVER_Client *client,
7093                         const struct GNUNET_MessageHeader *message)
7094 {
7095   struct GNUNET_MESH_ToOrigin *data_msg;
7096   struct MeshTunnelClientInfo *clinfo;
7097   struct MeshClient *c;
7098   struct MeshTunnel *t;
7099   MESH_TunnelNumber tid;
7100   size_t size;
7101
7102   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7103               "Got a ToOrigin request from a client!\n");
7104   /* Sanity check for client registration */
7105   if (NULL == (c = client_get (client)))
7106   {
7107     GNUNET_break (0);
7108     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7109     return;
7110   }
7111   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7112
7113   data_msg = (struct GNUNET_MESH_ToOrigin *) message;
7114
7115   /* Sanity check for message size */
7116   size = ntohs (message->size);
7117   if (sizeof (struct GNUNET_MESH_ToOrigin) +
7118       sizeof (struct GNUNET_MessageHeader) > size)
7119   {
7120     GNUNET_break (0);
7121     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7122     return;
7123   }
7124
7125   /* Tunnel exists? */
7126   tid = ntohl (data_msg->tid);
7127   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
7128   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
7129   {
7130     GNUNET_break (0);
7131     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7132     return;
7133   }
7134   t = tunnel_get_by_local_id (c, tid);
7135   if (NULL == t)
7136   {
7137     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
7138     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
7139     GNUNET_break (0);
7140     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7141     return;
7142   }
7143
7144   /*  It should be sent by someone who has this as incoming tunnel. */
7145   if (GNUNET_NO == client_knows_tunnel (c, t))
7146   {
7147     GNUNET_break (0);
7148     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7149     return;
7150   }
7151
7152   /* PID should be as expected */
7153   clinfo = tunnel_get_client_fc (t, c);
7154   if (ntohl (data_msg->pid) != clinfo->bck_pid + 1)
7155   {
7156     GNUNET_break (0);
7157     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7158                 "To Origin PID, expected %u, got %u\n",
7159                 clinfo->bck_pid + 1,
7160                 ntohl (data_msg->pid));
7161     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7162     return;
7163   }
7164
7165   /* Ok, everything is correct, send the message
7166    * (pretend we got it from a mesh peer)
7167    */
7168   clinfo->bck_pid++;
7169   {
7170     char buf[ntohs (message->size)] GNUNET_ALIGN;
7171     struct GNUNET_MESH_ToOrigin *copy;
7172
7173     /* Work around const limitation */
7174     copy = (struct GNUNET_MESH_ToOrigin *) buf;
7175     memcpy (buf, data_msg, size);
7176     GNUNET_PEER_resolve (t->id.oid, &copy->oid);
7177     copy->tid = htonl (t->id.tid);
7178     copy->ttl = htonl (default_ttl);
7179     if (ntohl (copy->pid) != (t->bck_pid + 1))
7180     {
7181       GNUNET_break (0);
7182       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7183                   "To Origin PID, expected %u, got %u\n",
7184                   t->bck_pid + 1,
7185                   ntohl (copy->pid));
7186       return;
7187     }
7188     t->bck_pid++;
7189     copy->sender = my_full_id;
7190     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7191                 "  calling generic handler...\n");
7192     handle_mesh_data_to_orig (NULL, &my_full_id, &copy->header, NULL, 0);
7193   }
7194   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7195
7196   return;
7197 }
7198
7199
7200 /**
7201  * Handler for client traffic directed to all peers in a tunnel
7202  *
7203  * @param cls closure
7204  * @param client identification of the client
7205  * @param message the actual message
7206  */
7207 static void
7208 handle_local_multicast (void *cls, struct GNUNET_SERVER_Client *client,
7209                         const struct GNUNET_MessageHeader *message)
7210 {
7211   struct MeshClient *c;
7212   struct MeshTunnel *t;
7213   struct GNUNET_MESH_Multicast *data_msg;
7214   MESH_TunnelNumber tid;
7215
7216   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7217               "Got a multicast request from a client!\n");
7218
7219   /* Sanity check for client registration */
7220   if (NULL == (c = client_get (client)))
7221   {
7222     GNUNET_break (0);
7223     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7224     return;
7225   }
7226   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7227
7228   data_msg = (struct GNUNET_MESH_Multicast *) message;
7229
7230   /* Sanity check for message size */
7231   if (sizeof (struct GNUNET_MESH_Multicast) +
7232       sizeof (struct GNUNET_MessageHeader) > ntohs (data_msg->header.size))
7233   {
7234     GNUNET_break (0);
7235     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7236     return;
7237   }
7238
7239   /* Tunnel exists? */
7240   tid = ntohl (data_msg->tid);
7241   t = tunnel_get_by_local_id (c, tid);
7242   if (NULL == t)
7243   {
7244     GNUNET_break (0);
7245     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
7246     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
7247     GNUNET_break (0);
7248     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7249     return;
7250   }
7251
7252   /* Does client own tunnel? */
7253   if (t->owner->handle != client)
7254   {
7255     GNUNET_break (0);
7256     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7257     return;
7258   }
7259
7260   /* PID should be as expected */
7261   if (ntohl (data_msg->pid) != t->fwd_pid + 1)
7262   {
7263     GNUNET_break (0);
7264     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7265               "Multicast PID, expected %u, got %u\n",
7266               t->fwd_pid + 1, ntohl (data_msg->pid));
7267     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7268     return;
7269   }
7270
7271   {
7272     char buf[ntohs (message->size)] GNUNET_ALIGN;
7273     struct GNUNET_MESH_Multicast *copy;
7274
7275     copy = (struct GNUNET_MESH_Multicast *) buf;
7276     memcpy (buf, message, ntohs (message->size));
7277     copy->oid = my_full_id;
7278     copy->tid = htonl (t->id.tid);
7279     copy->ttl = htonl (default_ttl);
7280     GNUNET_assert (ntohl (copy->pid) == (t->fwd_pid + 1));
7281     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7282                 "  calling generic handler...\n");
7283     handle_mesh_data_multicast (client, &my_full_id, &copy->header, NULL, 0);
7284   }
7285
7286   /* receive done gets called when last copy is sent to a neighbor */
7287   return;
7288 }
7289
7290
7291 /**
7292  * Handler for client's ACKs for payload traffic.
7293  *
7294  * @param cls Closure (unused).
7295  * @param client Identification of the client.
7296  * @param message The actual message.
7297  */
7298 static void
7299 handle_local_ack (void *cls, struct GNUNET_SERVER_Client *client,
7300                   const struct GNUNET_MessageHeader *message)
7301 {
7302   struct GNUNET_MESH_LocalAck *msg;
7303   struct MeshTunnel *t;
7304   struct MeshClient *c;
7305   MESH_TunnelNumber tid;
7306   uint32_t ack;
7307
7308   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a local ACK\n");
7309   /* Sanity check for client registration */
7310   if (NULL == (c = client_get (client)))
7311   {
7312     GNUNET_break (0);
7313     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7314     return;
7315   }
7316   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7317
7318   msg = (struct GNUNET_MESH_LocalAck *) message;
7319
7320   /* Tunnel exists? */
7321   tid = ntohl (msg->tunnel_id);
7322   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
7323   t = tunnel_get_by_local_id (c, tid);
7324   if (NULL == t)
7325   {
7326     GNUNET_break (0); // FIXME fc
7327     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
7328     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
7329     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7330     return;
7331   }
7332
7333   ack = ntohl (msg->max_pid);
7334   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ack %u\n", ack);
7335
7336   /* Does client own tunnel? I.E: Is this and ACK for BCK traffic? */
7337   if (NULL != t->owner && t->owner->handle == client)
7338   {
7339     /* The client owns the tunnel, ACK is for data to_origin, send BCK ACK. */
7340     t->bck_ack = ack;
7341     tunnel_send_bck_ack(t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
7342   }
7343   else
7344   {
7345     /* The client doesn't own the tunnel, this ACK is for FWD traffic. */
7346     tunnel_set_client_fwd_ack (t, c, ack);
7347     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
7348   }
7349
7350   GNUNET_SERVER_receive_done (client, GNUNET_OK);  
7351
7352   return;
7353 }
7354
7355
7356 /**
7357  * Functions to handle messages from clients
7358  */
7359 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
7360   {&handle_local_new_client, NULL,
7361    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
7362   {&handle_local_announce_regex, NULL,
7363    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ANNOUNCE_REGEX, 0},
7364   {&handle_local_tunnel_create, NULL,
7365    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
7366    sizeof (struct GNUNET_MESH_TunnelMessage)},
7367   {&handle_local_tunnel_destroy, NULL,
7368    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
7369    sizeof (struct GNUNET_MESH_TunnelMessage)},
7370   {&handle_local_tunnel_speed, NULL,
7371    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MIN,
7372    sizeof (struct GNUNET_MESH_TunnelMessage)},
7373   {&handle_local_tunnel_speed, NULL,
7374    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MAX,
7375    sizeof (struct GNUNET_MESH_TunnelMessage)},
7376   {&handle_local_tunnel_buffer, NULL,
7377    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER,
7378    sizeof (struct GNUNET_MESH_TunnelMessage)},
7379   {&handle_local_tunnel_buffer, NULL,
7380    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER,
7381    sizeof (struct GNUNET_MESH_TunnelMessage)},
7382   {&handle_local_connect_add, NULL,
7383    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD,
7384    sizeof (struct GNUNET_MESH_PeerControl)},
7385   {&handle_local_connect_del, NULL,
7386    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL,
7387    sizeof (struct GNUNET_MESH_PeerControl)},
7388   {&handle_local_blacklist, NULL,
7389    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_BLACKLIST,
7390    sizeof (struct GNUNET_MESH_PeerControl)},
7391   {&handle_local_unblacklist, NULL,
7392    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_UNBLACKLIST,
7393    sizeof (struct GNUNET_MESH_PeerControl)},
7394   {&handle_local_connect_by_type, NULL,
7395    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE,
7396    sizeof (struct GNUNET_MESH_ConnectPeerByType)},
7397   {&handle_local_connect_by_string, NULL,
7398    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_STRING, 0},
7399   {&handle_local_unicast, NULL,
7400    GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
7401   {&handle_local_to_origin, NULL,
7402    GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
7403   {&handle_local_multicast, NULL,
7404    GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
7405   {&handle_local_ack, NULL,
7406    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK,
7407    sizeof (struct GNUNET_MESH_LocalAck)},
7408   {NULL, NULL, 0, 0}
7409 };
7410
7411
7412 /**
7413  * To be called on core init/fail.
7414  *
7415  * @param cls service closure
7416  * @param server handle to the server for this service
7417  * @param identity the public identity of this peer
7418  */
7419 static void
7420 core_init (void *cls, struct GNUNET_CORE_Handle *server,
7421            const struct GNUNET_PeerIdentity *identity)
7422 {
7423   static int i = 0;
7424   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
7425   core_handle = server;
7426   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)) ||
7427       NULL == server)
7428   {
7429     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
7430     GNUNET_SCHEDULER_shutdown (); // Try gracefully
7431     if (10 < i++)
7432       GNUNET_abort(); // Try harder
7433   }
7434   return;
7435 }
7436
7437
7438 /**
7439  * Method called whenever a given peer connects.
7440  *
7441  * @param cls closure
7442  * @param peer peer identity this notification is about
7443  * @param atsi performance data for the connection
7444  * @param atsi_count number of records in 'atsi'
7445  */
7446 static void
7447 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
7448               const struct GNUNET_ATS_Information *atsi,
7449               unsigned int atsi_count)
7450 {
7451   struct MeshPeerInfo *peer_info;
7452   struct MeshPeerPath *path;
7453
7454   DEBUG_CONN ("Peer connected\n");
7455   DEBUG_CONN ("     %s\n", GNUNET_i2s (&my_full_id));
7456   peer_info = peer_info_get (peer);
7457   if (myid == peer_info->id)
7458   {
7459     DEBUG_CONN ("     (self)\n");
7460     return;
7461   }
7462   else
7463   {
7464     DEBUG_CONN ("     %s\n", GNUNET_i2s (peer));
7465   }
7466   path = path_new (2);
7467   path->peers[0] = myid;
7468   path->peers[1] = peer_info->id;
7469   GNUNET_PEER_change_rc (myid, 1);
7470   GNUNET_PEER_change_rc (peer_info->id, 1);
7471   peer_info_add_path (peer_info, path, GNUNET_YES);
7472   GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
7473   return;
7474 }
7475
7476
7477 /**
7478  * Method called whenever a peer disconnects.
7479  *
7480  * @param cls closure
7481  * @param peer peer identity this notification is about
7482  */
7483 static void
7484 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
7485 {
7486   struct MeshPeerInfo *pi;
7487   struct MeshPeerQueue *q;
7488   struct MeshPeerQueue *n;
7489
7490   DEBUG_CONN ("Peer disconnected\n");
7491   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
7492   if (NULL == pi)
7493   {
7494     GNUNET_break (0);
7495     return;
7496   }
7497   q = pi->queue_head;
7498   while (NULL != q)
7499   {
7500       n = q->next;
7501       if (q->peer == pi)
7502       {
7503         /* try to reroute this traffic instead */
7504         queue_destroy(q, GNUNET_YES);
7505       }
7506       q = n;
7507   }
7508   peer_info_remove_path (pi, pi->id, myid);
7509   if (myid == pi->id)
7510   {
7511     DEBUG_CONN ("     (self)\n");
7512   }
7513   GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
7514   return;
7515 }
7516
7517
7518 /******************************************************************************/
7519 /************************      MAIN FUNCTIONS      ****************************/
7520 /******************************************************************************/
7521
7522 /**
7523  * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
7524  *
7525  * @param cls closure
7526  * @param key current key code
7527  * @param value value in the hash map
7528  * @return GNUNET_YES if we should continue to iterate,
7529  *         GNUNET_NO if not.
7530  */
7531 static int
7532 shutdown_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
7533 {
7534   struct MeshTunnel *t = value;
7535
7536   tunnel_destroy (t);
7537   return GNUNET_YES;
7538 }
7539
7540 /**
7541  * Iterator over peer hash map entries to destroy the tunnel during shutdown.
7542  *
7543  * @param cls closure
7544  * @param key current key code
7545  * @param value value in the hash map
7546  * @return GNUNET_YES if we should continue to iterate,
7547  *         GNUNET_NO if not.
7548  */
7549 static int
7550 shutdown_peer (void *cls, const struct GNUNET_HashCode * key, void *value)
7551 {
7552   struct MeshPeerInfo *p = value;
7553   struct MeshPeerQueue *q;
7554   struct MeshPeerQueue *n;
7555
7556   q = p->queue_head;
7557   while (NULL != q)
7558   {
7559       n = q->next;
7560       if (q->peer == p)
7561       {
7562         queue_destroy(q, GNUNET_YES);
7563       }
7564       q = n;
7565   }
7566   peer_info_destroy (p);
7567   return GNUNET_YES;
7568 }
7569
7570 /**
7571  * Task run during shutdown.
7572  *
7573  * @param cls unused
7574  * @param tc unused
7575  */
7576 static void
7577 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
7578 {
7579   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
7580
7581   if (core_handle != NULL)
7582   {
7583     GNUNET_CORE_disconnect (core_handle);
7584     core_handle = NULL;
7585   }
7586   GNUNET_CONTAINER_multihashmap_iterate (tunnels, &shutdown_tunnel, NULL);
7587   GNUNET_CONTAINER_multihashmap_iterate (peers, &shutdown_peer, NULL);
7588   if (dht_handle != NULL)
7589   {
7590     GNUNET_DHT_disconnect (dht_handle);
7591     dht_handle = NULL;
7592   }
7593   if (nc != NULL)
7594   {
7595     GNUNET_SERVER_notification_context_destroy (nc);
7596     nc = NULL;
7597   }
7598   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
7599   {
7600     GNUNET_SCHEDULER_cancel (announce_id_task);
7601     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
7602   }
7603   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
7604 }
7605
7606 /**
7607  * Process mesh requests.
7608  *
7609  * @param cls closure
7610  * @param server the initialized server
7611  * @param c configuration to use
7612  */
7613 static void
7614 run (void *cls, struct GNUNET_SERVER_Handle *server,
7615      const struct GNUNET_CONFIGURATION_Handle *c)
7616 {
7617   struct MeshPeerInfo *peer;
7618   struct MeshPeerPath *p;
7619   char *keyfile;
7620
7621   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
7622   server_handle = server;
7623   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
7624                                      NULL,      /* Closure passed to MESH functions */
7625                                      &core_init,        /* Call core_init once connected */
7626                                      &core_connect,     /* Handle connects */
7627                                      &core_disconnect,  /* remove peers on disconnects */
7628                                      NULL,      /* Don't notify about all incoming messages */
7629                                      GNUNET_NO, /* For header only in notification */
7630                                      NULL,      /* Don't notify about all outbound messages */
7631                                      GNUNET_NO, /* For header-only out notification */
7632                                      core_handlers);    /* Register these handlers */
7633
7634   if (core_handle == NULL)
7635   {
7636     GNUNET_break (0);
7637     GNUNET_SCHEDULER_shutdown ();
7638     return;
7639   }
7640
7641   if (GNUNET_OK !=
7642       GNUNET_CONFIGURATION_get_value_filename (c, "GNUNETD", "HOSTKEY",
7643                                                &keyfile))
7644   {
7645     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7646                 _
7647                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7648                 "hostkey");
7649     GNUNET_SCHEDULER_shutdown ();
7650     return;
7651   }
7652
7653   if (GNUNET_OK !=
7654       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_PATH_TIME",
7655                                            &refresh_path_time))
7656   {
7657     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7658                 _
7659                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7660                 "refresh path time");
7661     GNUNET_SCHEDULER_shutdown ();
7662     return;
7663   }
7664
7665   if (GNUNET_OK !=
7666       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "APP_ANNOUNCE_TIME",
7667                                            &app_announce_time))
7668   {
7669     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7670                 _
7671                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7672                 "app announce time");
7673     GNUNET_SCHEDULER_shutdown ();
7674     return;
7675   }
7676
7677   if (GNUNET_OK !=
7678       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "ID_ANNOUNCE_TIME",
7679                                            &id_announce_time))
7680   {
7681     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7682                 _
7683                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7684                 "id announce time");
7685     GNUNET_SCHEDULER_shutdown ();
7686     return;
7687   }
7688
7689   if (GNUNET_OK !=
7690       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "UNACKNOWLEDGED_WAIT",
7691                                            &unacknowledged_wait_time))
7692   {
7693     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7694                 _
7695                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7696                 "unacknowledged wait time");
7697     GNUNET_SCHEDULER_shutdown ();
7698     return;
7699   }
7700
7701   if (GNUNET_OK !=
7702       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "CONNECT_TIMEOUT",
7703                                            &connect_timeout))
7704   {
7705     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7706                 _
7707                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7708                 "connect timeout");
7709     GNUNET_SCHEDULER_shutdown ();
7710     return;
7711   }
7712
7713   if (GNUNET_OK !=
7714       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
7715                                              &max_msgs_queue))
7716   {
7717     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7718                 _
7719                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7720                 "max msgs queue");
7721     GNUNET_SCHEDULER_shutdown ();
7722     return;
7723   }
7724
7725   if (GNUNET_OK !=
7726       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_TUNNELS",
7727                                              &max_tunnels))
7728   {
7729     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7730                 _
7731                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7732                 "max tunnels");
7733     GNUNET_SCHEDULER_shutdown ();
7734     return;
7735   }
7736
7737   if (GNUNET_OK !=
7738       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
7739                                              &default_ttl))
7740   {
7741     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7742                 _
7743                 ("Mesh service is lacking key configuration settings (%s). Using default (%u).\n"),
7744                 "default ttl", 64);
7745     default_ttl = 64;
7746   }
7747
7748   if (GNUNET_OK !=
7749       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DHT_REPLICATION_LEVEL",
7750                                              &dht_replication_level))
7751   {
7752     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7753                 _
7754                 ("Mesh service is lacking key configuration settings (%s). Using default (%u).\n"),
7755                 "dht replication level", 10);
7756     dht_replication_level = 10;
7757   }
7758
7759   
7760   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
7761   GNUNET_free (keyfile);
7762   if (my_private_key == NULL)
7763   {
7764     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7765                 _("Mesh service could not access hostkey.  Exiting.\n"));
7766     GNUNET_SCHEDULER_shutdown ();
7767     return;
7768   }
7769   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
7770   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
7771                       &my_full_id.hashPubKey);
7772   myid = GNUNET_PEER_intern (&my_full_id);
7773   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
7774               "Mesh for peer [%s] starting\n",
7775               GNUNET_i2s(&my_full_id));
7776
7777 //   transport_handle = GNUNET_TRANSPORT_connect(c,
7778 //                                               &my_full_id,
7779 //                                               NULL,
7780 //                                               NULL,
7781 //                                               NULL,
7782 //                                               NULL);
7783
7784   dht_handle = GNUNET_DHT_connect (c, 64);
7785   if (dht_handle == NULL)
7786   {
7787     GNUNET_break (0);
7788   }
7789
7790   stats = GNUNET_STATISTICS_create ("mesh", c);
7791
7792
7793   next_tid = 0;
7794   next_local_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
7795
7796   tunnels = GNUNET_CONTAINER_multihashmap_create (32);
7797   incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
7798   peers = GNUNET_CONTAINER_multihashmap_create (32);
7799   applications = GNUNET_CONTAINER_multihashmap_create (32);
7800   types = GNUNET_CONTAINER_multihashmap_create (32);
7801
7802   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
7803   nc = GNUNET_SERVER_notification_context_create (server_handle, 1);
7804   GNUNET_SERVER_disconnect_notify (server_handle,
7805                                    &handle_local_client_disconnect, NULL);
7806
7807
7808   clients = NULL;
7809   clients_tail = NULL;
7810   next_client_id = 0;
7811
7812   announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
7813   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
7814
7815   /* Create a peer_info for the local peer */
7816   peer = peer_info_get (&my_full_id);
7817   p = path_new (1);
7818   p->peers[0] = myid;
7819   GNUNET_PEER_change_rc (myid, 1);
7820   peer_info_add_path (peer, p, GNUNET_YES);
7821
7822   /* Scheduled the task to clean up when shutdown is called */
7823   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
7824                                 NULL);
7825
7826   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "end of run()\n");
7827 }
7828
7829 /**
7830  * The main function for the mesh service.
7831  *
7832  * @param argc number of arguments from the command line
7833  * @param argv command line arguments
7834  * @return 0 ok, 1 on error
7835  */
7836 int
7837 main (int argc, char *const *argv)
7838 {
7839   int ret;
7840
7841   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
7842   ret =
7843       (GNUNET_OK ==
7844        GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
7845                            NULL)) ? 0 : 1;
7846   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");
7847
7848   INTERVAL_SHOW;
7849
7850   return ret;
7851 }