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