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