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