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