- remove trees from tunnels
[oweals/gnunet.git] / src / mesh / gnunet-service-mesh-new.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 "mesh2.h"
50 #include "mesh2_protocol.h"
51 #include "mesh_tunnel_tree.h"
52 #include "block_mesh.h"
53 #include "gnunet_dht_service.h"
54 #include "gnunet_statistics_service.h"
55
56 #define MESH_BLOOM_SIZE         128
57
58 #define MESH_DEBUG_DHT          GNUNET_NO
59 #define MESH_DEBUG_CONNECTION   GNUNET_NO
60 #define MESH_DEBUG_TIMING       __LINUX__ && GNUNET_NO
61
62 #define MESH_MAX_POLL_TIME      GNUNET_TIME_relative_multiply (\
63                                   GNUNET_TIME_UNIT_MINUTES,\
64                                   10)
65
66 #if MESH_DEBUG_CONNECTION
67 #define DEBUG_CONN(...) GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
68 #else
69 #define DEBUG_CONN(...)
70 #endif
71
72 #if MESH_DEBUG_DHT
73 #define DEBUG_DHT(...) GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
74 #else
75 #define DEBUG_DHT(...)
76 #endif
77
78 #if MESH_DEBUG_TIMING
79 #include <time.h>
80 double __sum;
81 uint64_t __count;
82 struct timespec __mesh_start;
83 struct timespec __mesh_end;
84 #define INTERVAL_START clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &(__mesh_start))
85 #define INTERVAL_END \
86 do {\
87   clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &(__mesh_end));\
88   double __diff = __mesh_end.tv_nsec - __mesh_start.tv_nsec;\
89   if (__diff < 0) __diff += 1000000000;\
90   __sum += __diff;\
91   __count++;\
92 } while (0)
93 #define INTERVAL_SHOW \
94 if (0 < __count)\
95   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "AVG process time: %f ns\n", __sum/__count)
96 #else
97 #define INTERVAL_START
98 #define INTERVAL_END
99 #define INTERVAL_SHOW
100 #endif
101
102 /******************************************************************************/
103 /************************      DATA STRUCTURES     ****************************/
104 /******************************************************************************/
105
106 /** FWD declaration */
107 struct MeshPeerInfo;
108 struct MeshClient;
109
110
111 /**
112  * Struct representing a piece of data being sent to other peers
113  */
114 struct MeshData
115 {
116   /** Tunnel it belongs to. */
117   struct MeshTunnel *t;
118
119   /** How many remaining neighbors still hav't got it. */
120   unsigned int reference_counter;
121
122   /** How many remaining neighbors we need to send this to. */
123   unsigned int total_out;
124
125   /** Size of the data. */
126   size_t data_len;
127
128   /** Data itself */
129   void *data;
130 };
131
132
133 /**
134  * Struct containing info about a queued transmission to this peer
135  */
136 struct MeshPeerQueue
137 {
138     /**
139       * DLL next
140       */
141   struct MeshPeerQueue *next;
142
143     /**
144       * DLL previous
145       */
146   struct MeshPeerQueue *prev;
147
148     /**
149      * Peer this transmission is directed to.
150      */
151   struct MeshPeerInfo *peer;
152
153     /**
154      * Tunnel this message belongs to.
155      */
156   struct MeshTunnel *tunnel;
157
158     /**
159      * Pointer to info stucture used as cls.
160      */
161   void *cls;
162
163     /**
164      * Type of message
165      */
166   uint16_t type;
167
168     /**
169      * Size of the message
170      */
171   size_t size;
172 };
173
174
175 /**
176  * Struct containing all info possibly needed to build a package when called
177  * back by core.
178  */
179 struct MeshTransmissionDescriptor
180 {
181     /** ID of the tunnel this packet travels in */
182   struct MESH_TunnelID *origin;
183
184     /** Who was this message being sent to */
185   struct MeshPeerInfo *peer;
186
187     /** Ultimate destination of the packet */
188   GNUNET_PEER_Id destination;
189
190     /** Data descriptor */
191   struct MeshData* mesh_data;
192 };
193
194
195 /**
196  * Struct containing all information regarding a given peer
197  */
198 struct MeshPeerInfo
199 {
200     /**
201      * ID of the peer
202      */
203   GNUNET_PEER_Id id;
204
205     /**
206      * Last time we heard from this peer
207      */
208   struct GNUNET_TIME_Absolute last_contact;
209
210     /**
211      * Task handler for delayed connect task;
212      */
213   GNUNET_SCHEDULER_TaskIdentifier connect_task;
214
215     /**
216      * Number of attempts to reconnect so far
217      */
218   int n_reconnect_attempts;
219
220     /**
221      * Paths to reach the peer, ordered by ascending hop count
222      */
223   struct MeshPeerPath *path_head;
224
225     /**
226      * Paths to reach the peer, ordered by ascending hop count
227      */
228   struct MeshPeerPath *path_tail;
229
230     /**
231      * Handle to stop the DHT search for a path to this peer
232      */
233   struct GNUNET_DHT_GetHandle *dhtget;
234
235     /**
236      * Closure given to the DHT GET
237      */
238   struct MeshPathInfo *dhtgetcls;
239
240     /**
241      * Array of tunnels this peer participates in
242      * (most probably a small amount, therefore not a hashmap)
243      * When the path to the peer changes, notify these tunnels to let them
244      * re-adjust their path trees.
245      */
246   struct MeshTunnel **tunnels;
247
248     /**
249      * Number of tunnels this peers participates in
250      */
251   unsigned int ntunnels;
252
253    /**
254     * Transmission queue to core DLL head
255     */
256   struct MeshPeerQueue *queue_head;
257
258    /**
259     * Transmission queue to core DLL tail
260     */
261    struct MeshPeerQueue *queue_tail;
262
263    /**
264     * How many messages are in the queue to this peer.
265     */
266    unsigned int queue_n;
267
268    /**
269     * Handle to for queued transmissions
270     */
271   struct GNUNET_CORE_TransmitHandle *core_transmit;
272 };
273
274
275 /**
276  * Globally unique tunnel identification (owner + number)
277  * DO NOT USE OVER THE NETWORK
278  */
279 struct MESH_TunnelID
280 {
281     /**
282      * Node that owns the tunnel
283      */
284   GNUNET_PEER_Id oid;
285
286     /**
287      * Tunnel number to differentiate all the tunnels owned by the node oid
288      * ( tid < GNUNET_MESH_LOCAL_TUNNEL_ID_CLI )
289      */
290   MESH_TunnelNumber tid;
291 };
292
293
294 /**
295  * Struct containing all information regarding a tunnel
296  * For an intermediate node the improtant info used will be:
297  * - id        Tunnel unique identification
298  * - paths[0]  To know where to send it next
299  * - metainfo: ready, speeds, accounting
300  */
301 struct MeshTunnel
302 {
303     /**
304      * Tunnel ID
305      */
306   struct MESH_TunnelID id;
307
308     /**
309      * Local tunnel number ( >= GNUNET_MESH_LOCAL_TUNNEL_ID_CLI or 0 )
310      */
311   MESH_TunnelNumber local_tid;
312
313     /**
314      * Local tunnel number for local destination clients (incoming number)
315      * ( >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV or 0). All clients share the same
316      * number.
317      */
318   MESH_TunnelNumber local_tid_dest;
319
320     /**
321      * Is the tunnel bufferless (minimum latency)?
322      */
323   int nobuffer;
324
325     /**
326      * Packet ID of the last fwd packet seen (sent/retransmitted/received).
327      */
328   uint32_t fwd_pid;
329
330     /**
331      * Packet ID of the last bck packet sent (unique counter per hop).
332      */
333   uint32_t bck_pid;
334
335     /**
336      * Force sending ACK? Flag to allow duplicate ACK on POLL.
337      */
338   int force_ack;
339
340     /**
341      * Last ACK sent towards the origin (for traffic towards leaf node).
342      */
343   uint32_t last_fwd_ack;
344
345     /**
346      * BCK ACK value received from the hop towards the owner of the tunnel,
347      * (previous node / owner): up to what message PID can we sent back to him.
348      */
349   uint32_t bck_ack;
350
351     /**
352      * How many messages are in the forward queue (towards leaves).
353      */
354   unsigned int fwd_queue_n;
355
356     /**
357      * How many messages do we accept in the forward queue.
358      */
359   unsigned int fwd_queue_max;
360
361     /**
362      * How many messages are in the backward queue (towards origin).
363      */
364   unsigned int bck_queue_n;
365
366     /**
367      * How many messages do we accept in the backward queue.
368     */
369    unsigned int bck_queue_max;
370
371     /**
372      * Task to poll peer in case of a stall.
373      */
374    GNUNET_SCHEDULER_TaskIdentifier fc_poll_bck;
375
376     /**
377      * Last time the tunnel was used
378      */
379   struct GNUNET_TIME_Absolute timestamp;
380
381     /**
382      * Peer of the tunnel.
383      */
384   GNUNET_PEER_Id peer;
385
386   /**
387    * Next hop in the tunnel.
388    */
389   GNUNET_PEER_Id next_hop;
390
391   /**
392    * Previous hop in the tunnel.
393    */
394   GNUNET_PEER_Id prev_hop;
395
396     /**
397      * Client owner of the tunnel, if any
398      */
399   struct MeshClient *owner;
400
401     /**
402      * Clients that have been informed about and want to stay in the tunnel.
403      */
404   struct MeshClient **clients;
405
406     /**
407      * Flow control info for each client.
408      */
409   struct MeshTunnelClientInfo *clients_fc;
410
411   /**
412      * Number of elements in clients/clients_fc
413      */
414   unsigned int nclients;
415
416     /**
417      * Clients that have been informed but requested to leave the tunnel.
418      */
419   struct MeshClient **ignore;
420
421     /**
422      * Number of elements in clients
423      */
424   unsigned int nignore;
425
426   /**
427    * Path being used for the tunnel.
428    */
429   struct MeshPeerPath *path;
430
431     /**
432      * Task to keep the used paths alive
433      */
434   GNUNET_SCHEDULER_TaskIdentifier path_refresh_task;
435
436     /**
437      * Task to destroy the tunnel after timeout
438      *
439      * FIXME: merge the two? a tunnel will have either
440      * a path refresh OR a timeout, never both!
441      */
442   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
443
444     /**
445      * Flag to signal the destruction of the tunnel.
446      * If this is set GNUNET_YES the tunnel will be destroyed
447      * when the queue is empty.
448      */
449   int destroy;
450
451     /**
452      * Total messages pending for this tunnels, payload or not.
453      */
454   unsigned int pending_messages;
455
456   /**
457    * If the tunnel is empty, destoy it.
458    */
459   GNUNET_SCHEDULER_TaskIdentifier delayed_destroy;
460 };
461
462
463 /**
464  * Info about a leaf client of a tunnel, needed to perform flow control.
465  */
466 struct MeshTunnelClientInfo
467 {
468   /**
469    * PID of the last packet sent to the client (FWD).
470    */
471   uint32_t fwd_pid;
472
473   /**
474    * PID of the last packet received from the client (BCK).
475    */
476   uint32_t bck_pid;
477
478   /**
479    * Maximum PID allowed (FWD ACK received).
480    */
481   uint32_t fwd_ack;
482   
483   /**
484    * Last ACK sent to that child (BCK ACK).
485    */
486   uint32_t bck_ack;
487 };
488
489
490 /**
491  * Info needed to work with tunnel paths and peers
492  */
493 struct MeshPathInfo
494 {
495   /**
496    * Tunnel
497    */
498   struct MeshTunnel *t;
499
500   /**
501    * Neighbouring peer to whom we send the packet to
502    */
503   struct MeshPeerInfo *peer;
504
505   /**
506    * Path itself
507    */
508   struct MeshPeerPath *path;
509 };
510
511
512 /**
513  * Struct containing information about a client of the service
514  */
515 struct MeshClient
516 {
517     /**
518      * Linked list next
519      */
520   struct MeshClient *next;
521
522     /**
523      * Linked list prev
524      */
525   struct MeshClient *prev;
526
527     /**
528      * Tunnels that belong to this client, indexed by local id
529      */
530   struct GNUNET_CONTAINER_MultiHashMap *own_tunnels;
531
532    /**
533      * Tunnels this client has accepted, indexed by incoming local id
534      */
535   struct GNUNET_CONTAINER_MultiHashMap *incoming_tunnels;
536
537    /**
538      * Tunnels this client has rejected, indexed by incoming local id
539      */
540   struct GNUNET_CONTAINER_MultiHashMap *ignore_tunnels;
541     /**
542      * Handle to communicate with the client
543      */
544   struct GNUNET_SERVER_Client *handle;
545
546     /**
547      * Messages that this client has declared interest in
548      */
549   struct GNUNET_CONTAINER_MultiHashMap *types;
550
551     /**
552      * Whether the client is active or shutting down (don't send confirmations
553      * to a client that is shutting down.
554      */
555   int shutting_down;
556
557     /**
558      * ID of the client, mainly for debug messages
559      */
560   unsigned int id;
561
562 };
563
564
565 /******************************************************************************/
566 /************************      DEBUG FUNCTIONS     ****************************/
567 /******************************************************************************/
568
569 #if MESH_DEBUG
570 /**
571  * GNUNET_SCHEDULER_Task for printing a message after some operation is done
572  * @param cls string to print
573  * @param success  GNUNET_OK if the PUT was transmitted,
574  *                GNUNET_NO on timeout,
575  *                GNUNET_SYSERR on disconnect from service
576  *                after the PUT message was transmitted
577  *                (so we don't know if it was received or not)
578  */
579
580 #if 0
581 static void
582 mesh_debug (void *cls, int success)
583 {
584   char *s = cls;
585
586   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s (%d)\n", s, success);
587 }
588 #endif
589
590 unsigned int debug_fwd_ack;
591 unsigned int debug_bck_ack;
592
593 #endif
594
595 /******************************************************************************/
596 /***********************      GLOBAL VARIABLES     ****************************/
597 /******************************************************************************/
598
599 /************************** Configuration parameters **************************/
600
601 /**
602  * How often to send tunnel keepalives. Tunnels timeout after 4 missed.
603  */
604 static struct GNUNET_TIME_Relative refresh_path_time;
605
606 /**
607  * How often to PUT own ID in the DHT.
608  */
609 static struct GNUNET_TIME_Relative id_announce_time;
610
611 /**
612  * Maximum time allowed to connect to a peer found by string.
613  */
614 static struct GNUNET_TIME_Relative connect_timeout;
615
616 /**
617  * Default TTL for payload packets.
618  */
619 static unsigned long long default_ttl;
620
621 /**
622  * DHT replication level, see DHT API: GNUNET_DHT_get_start, GNUNET_DHT_put.
623  */
624 static unsigned long long dht_replication_level;
625
626 /**
627  * How many tunnels are we willing to maintain.
628  * Local tunnels are always allowed, even if there are more tunnels than max.
629  */
630 static unsigned long long max_tunnels;
631
632 /**
633  * How many messages *in total* are we willing to queue, divided by number of 
634  * tunnels to get tunnel queue size.
635  */
636 static unsigned long long max_msgs_queue;
637
638 /**
639  * How many peers do we want to remember?
640  */
641 static unsigned long long max_peers;
642
643
644 /*************************** Static global variables **************************/
645
646 /**
647  * Hostkey generation context
648  */
649 static struct GNUNET_CRYPTO_EccKeyGenerationContext *keygen;
650
651 /**
652  * DLL with all the clients, head.
653  */
654 static struct MeshClient *clients_head;
655
656 /**
657  * DLL with all the clients, tail.
658  */
659 static struct MeshClient *clients_tail;
660
661 /**
662  * Tunnels known, indexed by MESH_TunnelID (MeshTunnel).
663  */
664 static struct GNUNET_CONTAINER_MultiHashMap *tunnels;
665
666 /**
667  * Number of tunnels known.
668  */
669 static unsigned long long n_tunnels;
670
671 /**
672  * Tunnels incoming, indexed by MESH_TunnelNumber
673  * (which is greater than GNUNET_MESH_LOCAL_TUNNEL_ID_SERV).
674  */
675 static struct GNUNET_CONTAINER_MultiHashMap *incoming_tunnels;
676
677 /**
678  * Peers known, indexed by PeerIdentity (MeshPeerInfo).
679  */
680 static struct GNUNET_CONTAINER_MultiHashMap *peers;
681
682 /*
683  * Handle to communicate with transport
684  */
685 // static struct GNUNET_TRANSPORT_Handle *transport_handle;
686
687 /**
688  * Handle to communicate with core.
689  */
690 static struct GNUNET_CORE_Handle *core_handle;
691
692 /**
693  * Handle to use DHT.
694  */
695 static struct GNUNET_DHT_Handle *dht_handle;
696
697 /**
698  * Handle to server.
699  */
700 static struct GNUNET_SERVER_Handle *server_handle;
701
702 /**
703  * Handle to the statistics service.
704  */
705 static struct GNUNET_STATISTICS_Handle *stats;
706
707 /**
708  * Notification context, to send messages to local clients.
709  */
710 static struct GNUNET_SERVER_NotificationContext *nc;
711
712 /**
713  * Local peer own ID (memory efficient handle).
714  */
715 static GNUNET_PEER_Id myid;
716
717 /**
718  * Local peer own ID (full value).
719  */
720 static struct GNUNET_PeerIdentity my_full_id;
721
722 /**
723  * Own private key.
724  */
725 static struct GNUNET_CRYPTO_EccPrivateKey *my_private_key;
726
727 /**
728  * Own public key.
729  */
730 static struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded my_public_key;
731
732 /**
733  * Tunnel ID for the next created tunnel (global tunnel number).
734  */
735 static MESH_TunnelNumber next_tid;
736
737 /**
738  * Tunnel ID for the next incoming tunnel (local tunnel number).
739  */
740 static MESH_TunnelNumber next_local_tid;
741
742 /**
743  * All message types clients of this peer are interested in.
744  */
745 static struct GNUNET_CONTAINER_MultiHashMap *types;
746
747 /**
748  * Task to periodically announce itself in the network.
749  */
750 GNUNET_SCHEDULER_TaskIdentifier announce_id_task;
751
752 /**
753  * Next ID to assign to a client.
754  */
755 unsigned int next_client_id;
756
757
758 /******************************************************************************/
759 /***********************         DECLARATIONS        **************************/
760 /******************************************************************************/
761
762 /**
763  * Function to process paths received for a new peer addition. The recorded
764  * paths form the initial tunnel, which can be optimized later.
765  * Called on each result obtained for the DHT search.
766  *
767  * @param cls closure
768  * @param exp when will this value expire
769  * @param key key of the result
770  * @param type type of the result
771  * @param size number of bytes in data
772  * @param data pointer to the result data
773  */
774 static void
775 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
776                     const struct GNUNET_HashCode * key,
777                     const struct GNUNET_PeerIdentity *get_path,
778                     unsigned int get_path_length,
779                     const struct GNUNET_PeerIdentity *put_path,
780                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
781                     size_t size, const void *data);
782
783
784 /**
785  * Retrieve the MeshPeerInfo stucture associated with the peer, create one
786  * and insert it in the appropiate structures if the peer is not known yet.
787  *
788  * @param peer Full identity of the peer.
789  *
790  * @return Existing or newly created peer info.
791  */
792 static struct MeshPeerInfo *
793 peer_get (const struct GNUNET_PeerIdentity *peer);
794
795
796 /**
797  * Retrieve the MeshPeerInfo stucture associated with the peer, create one
798  * and insert it in the appropiate structures if the peer is not known yet.
799  *
800  * @param peer Short identity of the peer.
801  *
802  * @return Existing or newly created peer info.
803  */
804 static struct MeshPeerInfo *
805 peer_get_short (const GNUNET_PEER_Id peer);
806
807
808 /**
809  * Build a PeerPath from the paths returned from the DHT, reversing the paths
810  * to obtain a local peer -> destination path and interning the peer ids.
811  *
812  * @return Newly allocated and created path
813  */
814 static struct MeshPeerPath *
815 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
816                      unsigned int get_path_length,
817                      const struct GNUNET_PeerIdentity *put_path,
818                      unsigned int put_path_length);
819
820
821 /**
822  * Adds a path to the peer_infos of all the peers in the path
823  *
824  * @param p Path to process.
825  * @param confirmed Whether we know if the path works or not.
826  */
827 static void
828 path_add_to_peers (struct MeshPeerPath *p, int confirmed);
829
830
831
832 /**
833  * Search for a tunnel by global ID using full PeerIdentities.
834  *
835  * @param oid owner of the tunnel.
836  * @param tid global tunnel number.
837  *
838  * @return tunnel handler, NULL if doesn't exist.
839  */
840 static struct MeshTunnel *
841 tunnel_get (const struct GNUNET_PeerIdentity *oid, MESH_TunnelNumber tid);
842
843
844 /**
845  * Delete an active client from the tunnel.
846  *
847  * @param t Tunnel.
848  * @param c Client.
849  */
850 static void
851 tunnel_delete_active_client (struct MeshTunnel *t, const struct MeshClient *c);
852
853 /**
854  * Notify a tunnel that a connection has broken that affects at least
855  * some of its peers.
856  *
857  * @param t Tunnel affected.
858  * @param p1 Peer that got disconnected from p2.
859  * @param p2 Peer that got disconnected from p1.
860  *
861  * @return Short ID of the peer disconnected (either p1 or p2).
862  *         0 if the tunnel remained unaffected.
863  */
864 static GNUNET_PEER_Id
865 tunnel_notify_connection_broken (struct MeshTunnel *t, GNUNET_PEER_Id p1,
866                                  GNUNET_PEER_Id p2);
867
868
869 /**
870  * Get the current ack value for a tunnel, for data going from root to leaves,
871  * taking in account the tunnel mode and the status of all children and clients.
872  *
873  * @param t Tunnel.
874  *
875  * @return Maximum PID allowed.
876  */
877 static uint32_t
878 tunnel_get_fwd_ack (struct MeshTunnel *t);
879
880
881 /**
882  * Add a client to a tunnel, initializing all needed data structures.
883  * 
884  * @param t Tunnel to which add the client.
885  * @param c Client which to add to the tunnel.
886  */
887 static void
888 tunnel_add_client (struct MeshTunnel *t, struct MeshClient *c);
889
890
891 /**
892  * .Use the given path for the tunnel.
893  * 
894  * @param t Tunnel to update.
895  * @param p Path to use.
896  */
897 static void
898 tunnel_use_path (struct MeshTunnel *t, struct MeshPeerPath *p);
899
900 /**
901  * @brief Queue and pass message to core when possible.
902  * 
903  * If type is payload (UNICAST, TO_ORIGIN, MULTICAST) checks for queue status
904  * and accounts for it. In case the queue is full, the message is dropped and
905  * a break issued.
906  * 
907  * Otherwise, message is treated as internal and allowed to go regardless of 
908  * queue status.
909  *
910  * @param cls Closure (@c type dependant). It will be used by queue_send to
911  *            build the message to be sent if not already prebuilt.
912  * @param type Type of the message, 0 for a raw message.
913  * @param size Size of the message.
914  * @param dst Neighbor to send message to.
915  * @param t Tunnel this message belongs to.
916  */
917 static void
918 queue_add (void *cls, uint16_t type, size_t size,
919            struct MeshPeerInfo *dst, struct MeshTunnel *t);
920
921
922 /**
923  * Free a transmission that was already queued with all resources
924  * associated to the request.
925  *
926  * @param queue Queue handler to cancel.
927  * @param clear_cls Is it necessary to free associated cls?
928  */
929 static void
930 queue_destroy (struct MeshPeerQueue *queue, int clear_cls);
931
932
933 /**
934  * @brief Get the next transmittable message from the queue.
935  *
936  * This will be the head, except in the case of being a data packet
937  * not allowed by the destination peer.
938  *
939  * @param peer Destination peer.
940  *
941  * @return The next viable MeshPeerQueue element to send to that peer.
942  *         NULL when there are no transmittable messages.
943  */
944 struct MeshPeerQueue *
945 queue_get_next (const struct MeshPeerInfo *peer);
946
947
948 /**
949  * Core callback to write a queued packet to core buffer
950  *
951  * @param cls Closure (peer info).
952  * @param size Number of bytes available in buf.
953  * @param buf Where the to write the message.
954  *
955  * @return number of bytes written to buf
956  */
957 static size_t
958 queue_send (void *cls, size_t size, void *buf);
959
960
961 /******************************************************************************/
962 /************************    PERIODIC FUNCTIONS    ****************************/
963 /******************************************************************************/
964
965 /**
966  * Periodically announce self id in the DHT
967  *
968  * @param cls closure
969  * @param tc task context
970  */
971 static void
972 announce_id (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
973 {
974   struct PBlock block;
975
976   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
977   {
978     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
979     return;
980   }
981   /* TODO
982    * - Set data expiration in function of X
983    * - Adapt X to churn
984    */
985   DEBUG_DHT ("DHT_put for ID %s started.\n", GNUNET_i2s (&my_full_id));
986
987   block.id = my_full_id;
988   block.type = htonl (0);
989   GNUNET_DHT_put (dht_handle,   /* DHT handle */
990                   &my_full_id.hashPubKey,       /* Key to use */
991                   dht_replication_level,     /* Replication level */
992                   GNUNET_DHT_RO_RECORD_ROUTE | GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,    /* DHT options */
993                   GNUNET_BLOCK_TYPE_MESH_PEER,       /* Block type */
994                   sizeof (block),  /* Size of the data */
995                   (const char *) &block, /* Data itself */
996                   GNUNET_TIME_UNIT_FOREVER_ABS,  /* Data expiration */
997                   GNUNET_TIME_UNIT_FOREVER_REL, /* Retry time */
998                   NULL,         /* Continuation */
999                   NULL);        /* Continuation closure */
1000   announce_id_task =
1001       GNUNET_SCHEDULER_add_delayed (id_announce_time, &announce_id, cls);
1002 }
1003
1004
1005 /******************************************************************************/
1006 /******************      GENERAL HELPER FUNCTIONS      ************************/
1007 /******************************************************************************/
1008
1009 /**
1010  * Decrements the reference counter and frees all resources if needed
1011  *
1012  * @param mesh_data Data Descriptor used in a multicast message.
1013  *                  Freed no longer needed (last message).
1014  */
1015 static void
1016 data_descriptor_decrement_rc (struct MeshData *mesh_data)
1017 {
1018   if (0 == --(mesh_data->reference_counter))
1019   {
1020     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Last copy!\n");
1021     GNUNET_free (mesh_data->data);
1022     GNUNET_free (mesh_data);
1023   }
1024 }
1025
1026
1027 /**
1028  * Check if client has registered with the service and has not disconnected
1029  *
1030  * @param client the client to check
1031  *
1032  * @return non-NULL if client exists in the global DLL
1033  */
1034 static struct MeshClient *
1035 client_get (struct GNUNET_SERVER_Client *client)
1036 {
1037   struct MeshClient *c;
1038
1039   c = clients_head;
1040   while (NULL != c)
1041   {
1042     if (c->handle == client)
1043       return c;
1044     c = c->next;
1045   }
1046   return NULL;
1047 }
1048
1049
1050 /**
1051  * Checks if a given client has subscribed to certain message type
1052  *
1053  * @param message_type Type of message to check
1054  * @param c Client to check
1055  *
1056  * @return GNUNET_YES or GNUNET_NO, depending on subscription status
1057  * 
1058  * FIXME: use of crypto_hash slows it down
1059  *  The hash function alone takes 8-10us out of the ~55us for the whole
1060  * process of retransmitting the message from one local client to another.
1061  * Find faster implementation!
1062  */
1063 static int
1064 client_is_subscribed (uint16_t message_type, struct MeshClient *c)
1065 {
1066   struct GNUNET_HashCode hc;
1067
1068   if (NULL == c->types)
1069     return GNUNET_NO;
1070
1071   GNUNET_CRYPTO_hash (&message_type, sizeof (uint16_t), &hc);
1072   return GNUNET_CONTAINER_multihashmap_contains (c->types, &hc);
1073 }
1074
1075
1076 /**
1077  * Check whether client wants traffic from a tunnel.
1078  *
1079  * @param c Client to check.
1080  * @param t Tunnel to be found.
1081  *
1082  * @return GNUNET_YES if client knows tunnel.
1083  * 
1084  * TODO look in client hashmap
1085  */
1086 static int
1087 client_wants_tunnel (struct MeshClient *c, struct MeshTunnel *t)
1088 {
1089   unsigned int i;
1090
1091   for (i = 0; i < t->nclients; i++)
1092     if (t->clients[i] == c)
1093       return GNUNET_YES;
1094   return GNUNET_NO;
1095 }
1096
1097
1098 /**
1099  * Check whether client has been informed about a tunnel.
1100  *
1101  * @param c Client to check.
1102  * @param t Tunnel to be found.
1103  *
1104  * @return GNUNET_YES if client knows tunnel.
1105  * 
1106  * TODO look in client hashmap
1107  */
1108 static int
1109 client_knows_tunnel (struct MeshClient *c, struct MeshTunnel *t)
1110 {
1111   unsigned int i;
1112
1113   for (i = 0; i < t->nignore; i++)
1114     if (t->ignore[i] == c)
1115       return GNUNET_YES;
1116   return client_wants_tunnel(c, t);
1117 }
1118
1119
1120 /**
1121  * Marks a client as uninterested in traffic from the tunnel, updating both
1122  * client and tunnel to reflect this.
1123  *
1124  * @param c Client that doesn't want traffic anymore.
1125  * @param t Tunnel which should be ignored.
1126  *
1127  * FIXME when to delete an incoming tunnel?
1128  */
1129 static void
1130 client_ignore_tunnel (struct MeshClient *c, struct MeshTunnel *t)
1131 {
1132   struct GNUNET_HashCode hash;
1133
1134   GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
1135   GNUNET_break (GNUNET_YES ==
1136                 GNUNET_CONTAINER_multihashmap_remove (c->incoming_tunnels,
1137                                                       &hash, t));
1138   GNUNET_break (GNUNET_YES ==
1139                 GNUNET_CONTAINER_multihashmap_put (c->ignore_tunnels, &hash, t,
1140                                                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
1141   tunnel_delete_active_client (t, c);
1142   GNUNET_array_append (t->ignore, t->nignore, c);
1143 }
1144
1145
1146 /**
1147  * Deletes a tunnel from a client (either owner or destination). To be used on
1148  * tunnel destroy, otherwise, use client_ignore_tunnel.
1149  *
1150  * @param c Client whose tunnel to delete.
1151  * @param t Tunnel which should be deleted.
1152  */
1153 static void
1154 client_delete_tunnel (struct MeshClient *c, struct MeshTunnel *t)
1155 {
1156   struct GNUNET_HashCode hash;
1157
1158   if (c == t->owner)
1159   {
1160     GNUNET_CRYPTO_hash(&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
1161     GNUNET_assert (GNUNET_YES ==
1162                    GNUNET_CONTAINER_multihashmap_remove (c->own_tunnels,
1163                                                          &hash,
1164                                                          t));
1165   }
1166   else
1167   {
1168     GNUNET_CRYPTO_hash(&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
1169     // FIXME XOR?
1170     GNUNET_assert (GNUNET_YES ==
1171                    GNUNET_CONTAINER_multihashmap_remove (c->incoming_tunnels,
1172                                                          &hash,
1173                                                          t) ||
1174                    GNUNET_YES ==
1175                    GNUNET_CONTAINER_multihashmap_remove (c->ignore_tunnels,
1176                                                          &hash,
1177                                                          t));
1178   }
1179 }
1180
1181
1182 /**
1183  * Send the message to all clients that have subscribed to its type
1184  *
1185  * @param msg Pointer to the message itself
1186  * @param payload Pointer to the payload of the message.
1187  * @param t The tunnel to whose clients this message goes.
1188  * 
1189  * @return number of clients this message was sent to
1190  */
1191 static unsigned int
1192 send_subscribed_clients (const struct GNUNET_MessageHeader *msg,
1193                          const struct GNUNET_MessageHeader *payload,
1194                          struct MeshTunnel *t)
1195 {
1196   struct MeshClient *c;
1197   MESH_TunnelNumber *tid;
1198   unsigned int count;
1199   uint16_t type;
1200   char cbuf[htons (msg->size)];
1201
1202   type = ntohs (payload->type);
1203   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending to clients...\n");
1204   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "message of type %s\n",
1205               GNUNET_MESH_DEBUG_M2S (type));
1206
1207   memcpy (cbuf, msg, sizeof (cbuf));
1208   switch (htons (msg->type))
1209   {
1210     struct GNUNET_MESH_Unicast *uc;
1211     struct GNUNET_MESH_ToOrigin *to;
1212
1213     case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
1214       uc = (struct GNUNET_MESH_Unicast *) cbuf;
1215       tid = &uc->tid;
1216       break;
1217     case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
1218       to = (struct GNUNET_MESH_ToOrigin *) cbuf;
1219       tid = &to->tid;
1220       break;
1221     default:
1222       GNUNET_break (0);
1223       return 0;
1224   }
1225
1226   for (count = 0, c = clients_head; c != NULL; c = c->next)
1227   {
1228     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   client %u\n", c->id);
1229     if (client_is_subscribed (type, c))
1230     {
1231       if (htons (msg->type) == GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN)
1232       {
1233         if (c != t->owner)
1234           continue;
1235         *tid = htonl (t->local_tid);
1236       }
1237       else
1238       {
1239         if (GNUNET_NO == client_knows_tunnel (c, t))
1240         {
1241           /* This client doesn't know the tunnel */
1242           struct GNUNET_MESH_TunnelNotification tmsg;
1243           struct GNUNET_HashCode hash;
1244
1245           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "     sending tunnel create\n");
1246           tmsg.header.size = htons (sizeof (tmsg));
1247           tmsg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
1248           GNUNET_PEER_resolve (t->id.oid, &tmsg.peer);
1249           tmsg.tunnel_id = htonl (t->local_tid_dest);
1250           tmsg.opt = 0;
1251           if (GNUNET_YES == t->nobuffer)
1252             tmsg.opt |= MESH_TUNNEL_OPT_NOBUFFER;
1253           GNUNET_SERVER_notification_context_unicast (nc, c->handle,
1254                                                       &tmsg.header, GNUNET_NO);
1255           tunnel_add_client (t, c);
1256           GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber),
1257                               &hash);
1258           GNUNET_break (GNUNET_OK == GNUNET_CONTAINER_multihashmap_put (
1259                                        c->incoming_tunnels, &hash, t,
1260                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
1261         }
1262         *tid = htonl (t->local_tid_dest);
1263       }
1264
1265       /* Check if the client wants to get traffic from the tunnel */
1266       if (GNUNET_NO == client_wants_tunnel(c, t))
1267         continue;
1268       count++;
1269       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "     sending\n");
1270       GNUNET_SERVER_notification_context_unicast (nc, c->handle,
1271                                                   (struct GNUNET_MessageHeader
1272                                                    *) cbuf, GNUNET_NO);
1273     }
1274   }
1275
1276   return count;
1277 }
1278
1279
1280 /**
1281  * Notify all clients (not depending on registration status) that the incoming
1282  * tunnel is no longer valid.
1283  *
1284  * @param t Tunnel that was destroyed.
1285  */
1286 static void
1287 send_clients_tunnel_destroy (struct MeshTunnel *t)
1288 {
1289   struct GNUNET_MESH_TunnelMessage msg;
1290
1291   msg.header.size = htons (sizeof (msg));
1292   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
1293   msg.tunnel_id = htonl (t->local_tid_dest);
1294   GNUNET_SERVER_notification_context_broadcast (nc, &msg.header, GNUNET_NO);
1295 }
1296
1297
1298 /**
1299  * Notify clients of tunnel disconnections, if needed.
1300  * In case the origin disconnects, the destination clients get a tunnel destroy
1301  * notification. If the last destination disconnects (only one remaining client
1302  * in tunnel), the origin gets a (local ID) peer disconnected.
1303  * Note that the function must be called BEFORE removing the client from
1304  * the tunnel.
1305  *
1306  * @param t Tunnel that was destroyed.
1307  * @param c Client that disconnected.
1308  */
1309 static void
1310 send_client_tunnel_disconnect (struct MeshTunnel *t, struct MeshClient *c)
1311 {
1312   unsigned int i;
1313
1314   if (c == t->owner)
1315   {
1316     struct GNUNET_MESH_TunnelMessage msg;
1317
1318     msg.header.size = htons (sizeof (msg));
1319     msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
1320     msg.tunnel_id = htonl (t->local_tid_dest);
1321     for (i = 0; i < t->nclients; i++)
1322       GNUNET_SERVER_notification_context_unicast (nc, t->clients[i]->handle,
1323                                                   &msg.header, GNUNET_NO);
1324   }
1325   // FIXME when to disconnect an incoming tunnel?
1326 }
1327
1328
1329 /**
1330  * Iterator over all the peers to remove the oldest not-used entry.
1331  *
1332  * @param cls Closure (unsued).
1333  * @param key ID of the peer.
1334  * @param value Peer_Info of the peer.
1335  *
1336  * FIXME implement
1337  */
1338 static int
1339 peer_info_timeout (void *cls,
1340                    const struct GNUNET_HashCode *key,
1341                    void *value)
1342 {
1343   return GNUNET_YES;
1344 }
1345
1346 /**
1347  * Retrieve the MeshPeerInfo stucture associated with the peer, create one
1348  * and insert it in the appropiate structures if the peer is not known yet.
1349  *
1350  * @param peer Full identity of the peer.
1351  *
1352  * @return Existing or newly created peer info.
1353  */
1354 static struct MeshPeerInfo *
1355 peer_get (const struct GNUNET_PeerIdentity *peer)
1356 {
1357   struct MeshPeerInfo *peer_info;
1358
1359   peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
1360   if (NULL == peer_info)
1361   {
1362     peer_info =
1363         (struct MeshPeerInfo *) GNUNET_malloc (sizeof (struct MeshPeerInfo));
1364     if (GNUNET_CONTAINER_multihashmap_size (peers) > max_peers)
1365     {
1366       GNUNET_CONTAINER_multihashmap_iterate (peers,
1367                                              &peer_info_timeout,
1368                                              NULL);
1369     }
1370     GNUNET_CONTAINER_multihashmap_put (peers, &peer->hashPubKey, peer_info,
1371                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1372     peer_info->id = GNUNET_PEER_intern (peer);
1373   }
1374   peer_info->last_contact = GNUNET_TIME_absolute_get();
1375
1376   return peer_info;
1377 }
1378
1379
1380 /**
1381  * Retrieve the MeshPeerInfo stucture associated with the peer, create one
1382  * and insert it in the appropiate structures if the peer is not known yet.
1383  *
1384  * @param peer Short identity of the peer.
1385  *
1386  * @return Existing or newly created peer info.
1387  */
1388 static struct MeshPeerInfo *
1389 peer_get_short (const GNUNET_PEER_Id peer)
1390 {
1391   struct GNUNET_PeerIdentity id;
1392
1393   GNUNET_PEER_resolve (peer, &id);
1394   return peer_get (&id);
1395 }
1396
1397
1398 /**
1399  * Choose the best path towards a peer considering the tunnel properties.
1400  * 
1401  * @param peer The destination peer.
1402  * @param t The tunnel the path is for.
1403  *
1404  * @return Best current known path towards the peer, if any.
1405  */
1406 static struct MeshPeerPath *
1407 peer_get_best_path (const struct MeshPeerInfo *peer, const struct MeshTunnel *t)
1408 {
1409   struct MeshPeerPath *best_p;
1410   struct MeshPeerPath *p;
1411   unsigned int best_cost;
1412   unsigned int cost;
1413
1414   best_p = p = peer->path_head;
1415   best_cost = cost = p->length;
1416   while (NULL != p)
1417   {
1418     if ((cost = p->length) < best_cost)
1419     {
1420       best_cost = cost;
1421       best_p = p;
1422     }
1423         p = p->next;
1424   }
1425   return best_p;
1426 }
1427
1428
1429 /**
1430  * Iterator to remove the tunnel from the list of tunnels a peer participates
1431  * in.
1432  *
1433  * @param cls Closure (tunnel info)
1434  * @param key GNUNET_PeerIdentity of the peer (unused)
1435  * @param value PeerInfo of the peer
1436  *
1437  * @return always GNUNET_YES, to keep iterating
1438  */
1439 static int
1440 peer_info_delete_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
1441 {
1442   struct MeshTunnel *t = cls;
1443   struct MeshPeerInfo *peer = value;
1444   unsigned int i;
1445
1446   for (i = 0; i < peer->ntunnels; i++)
1447   {
1448     if (0 ==
1449         memcmp (&peer->tunnels[i]->id, &t->id, sizeof (struct MESH_TunnelID)))
1450     {
1451       peer->ntunnels--;
1452       peer->tunnels[i] = peer->tunnels[peer->ntunnels];
1453       peer->tunnels = 
1454         GNUNET_realloc (peer->tunnels, 
1455                         peer->ntunnels * sizeof(struct MeshTunnel *));
1456       return GNUNET_YES;
1457     }
1458   }
1459   return GNUNET_YES;
1460 }
1461
1462
1463 /**
1464   * Core callback to write a pre-constructed data packet to core buffer
1465   *
1466   * @param cls Closure (MeshTransmissionDescriptor with data in "data" member).
1467   * @param size Number of bytes available in buf.
1468   * @param buf Where the to write the message.
1469   *
1470   * @return number of bytes written to buf
1471   */
1472 static size_t
1473 send_core_data_raw (void *cls, size_t size, void *buf)
1474 {
1475   struct MeshTransmissionDescriptor *info = cls;
1476   struct GNUNET_MessageHeader *msg;
1477   size_t total_size;
1478
1479   GNUNET_assert (NULL != info);
1480   GNUNET_assert (NULL != info->mesh_data);
1481   msg = (struct GNUNET_MessageHeader *) info->mesh_data->data;
1482   total_size = ntohs (msg->size);
1483
1484   if (total_size > size)
1485   {
1486     GNUNET_break (0);
1487     return 0;
1488   }
1489   memcpy (buf, msg, total_size);
1490   data_descriptor_decrement_rc (info->mesh_data);
1491   GNUNET_free (info);
1492   return total_size;
1493 }
1494
1495
1496 /**
1497  * Sends an already built non-multicast message to a peer,
1498  * properly registrating all used resources.
1499  *
1500  * @param message Message to send. Function makes a copy of it.
1501  * @param peer Short ID of the neighbor whom to send the message.
1502  * @param t Tunnel on which this message is transmitted.
1503  */
1504 static void
1505 send_prebuilt_message (const struct GNUNET_MessageHeader *message,
1506                        const struct GNUNET_PeerIdentity *peer,
1507                        struct MeshTunnel *t)
1508 {
1509   struct MeshTransmissionDescriptor *info;
1510   struct MeshPeerInfo *neighbor;
1511   struct MeshPeerPath *p;
1512   size_t size;
1513   uint16_t type;
1514
1515 //   GNUNET_TRANSPORT_try_connect(); FIXME use?
1516
1517   size = ntohs (message->size);
1518   info = GNUNET_malloc (sizeof (struct MeshTransmissionDescriptor));
1519   info->mesh_data = GNUNET_malloc (sizeof (struct MeshData));
1520   info->mesh_data->data = GNUNET_malloc (size);
1521   memcpy (info->mesh_data->data, message, size);
1522   type = ntohs(message->type);
1523   switch (type)
1524   {
1525     struct GNUNET_MESH_Unicast *m;
1526     struct GNUNET_MESH_ToOrigin *to;
1527
1528     case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
1529       m = (struct GNUNET_MESH_Unicast *) info->mesh_data->data;
1530       m->ttl = htonl (ntohl (m->ttl) - 1);
1531       break;
1532     case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
1533       to = (struct GNUNET_MESH_ToOrigin *) info->mesh_data->data;
1534       t->bck_pid++;
1535       to->pid = htonl(t->bck_pid);
1536   }
1537   info->mesh_data->data_len = size;
1538   info->mesh_data->reference_counter = 1;
1539   info->mesh_data->total_out = 1;
1540   neighbor = peer_get (peer);
1541   for (p = neighbor->path_head; NULL != p; p = p->next)
1542   {
1543     if (2 >= p->length)
1544     {
1545       break;
1546     }
1547   }
1548   if (NULL == p)
1549   {
1550 #if MESH_DEBUG
1551     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1552                 "  %s IS NOT DIRECTLY CONNECTED\n",
1553                 GNUNET_i2s(peer));
1554     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1555                 "  PATHS TO %s:\n",
1556                 GNUNET_i2s(peer));
1557     for (p = neighbor->path_head; NULL != p; p = p->next)
1558     {
1559       struct GNUNET_PeerIdentity debug_id;
1560       unsigned int i;
1561
1562       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1563                   "    path with %u hops through:\n",
1564                   p->length);
1565       for (i = 0; i < p->length; i++)
1566       {
1567         GNUNET_PEER_resolve(p->peers[i], &debug_id);
1568         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1569                     "      hop %u: %s\n",
1570                     i, GNUNET_i2s(&debug_id));
1571       }
1572     }
1573 #endif
1574     GNUNET_break (0); // FIXME sometimes fails (testing disconnect?)
1575     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1576                     " no direct connection to %s\n",
1577                     GNUNET_i2s (peer));
1578     GNUNET_free (info->mesh_data->data);
1579     GNUNET_free (info->mesh_data);
1580     GNUNET_free (info);
1581     return;
1582   }
1583   info->peer = neighbor;
1584   if (GNUNET_MESSAGE_TYPE_MESH_PATH_ACK == type)
1585     type = 0;
1586   queue_add (info,
1587              type,
1588              size,
1589              neighbor,
1590              t);
1591 }
1592
1593
1594 /**
1595  * Sends a CREATE PATH message for a path to a peer, properly registrating
1596  * all used resources.
1597  *
1598  * @param peer PeerInfo of the final peer for whom this path is being created.
1599  * @param p Path itself.
1600  * @param t Tunnel for which the path is created.
1601  */
1602 static void
1603 send_create_path (struct MeshPeerInfo *peer, struct MeshPeerPath *p,
1604                   struct MeshTunnel *t)
1605 {
1606   struct MeshPathInfo *path_info;
1607   struct MeshPeerInfo *neighbor;
1608
1609   if (NULL == p)
1610   {
1611     GNUNET_break (0);
1612     return;
1613   }
1614
1615   path_info = GNUNET_malloc (sizeof (struct MeshPathInfo));
1616   path_info->path = p;
1617   path_info->t = t;
1618   neighbor = peer_get_short (t->next_hop);
1619   path_info->peer = neighbor;
1620   queue_add (path_info,
1621              GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE,
1622              sizeof (struct GNUNET_MESH_ManipulatePath) +
1623                 (p->length * sizeof (struct GNUNET_PeerIdentity)),
1624              neighbor,
1625              t);
1626 }
1627
1628
1629 /**
1630  * Sends a DESTROY PATH message to free resources for a path in a tunnel.
1631  * Does not free the path itself.
1632  *
1633  * @param t Tunnel whose path to destroy.
1634  * @param destination Short ID of the peer to whom the path to destroy.
1635  */
1636 static void
1637 send_destroy_path (struct MeshTunnel *t)
1638 {
1639   struct MeshPeerPath *p;
1640   size_t size;
1641
1642   p = t->path;
1643   if (NULL == p)
1644   {
1645     GNUNET_break (0);
1646     return;
1647   }
1648   size = sizeof (struct GNUNET_MESH_ManipulatePath);
1649   size += p->length * sizeof (struct GNUNET_PeerIdentity);
1650   {
1651     struct GNUNET_MESH_ManipulatePath *msg;
1652     struct GNUNET_PeerIdentity *pi;
1653     struct GNUNET_PeerIdentity id;
1654     char cbuf[size];
1655     unsigned int i;
1656
1657     msg = (struct GNUNET_MESH_ManipulatePath *) cbuf;
1658     msg->header.size = htons (size);
1659     msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY);
1660     msg->tid = htonl (t->id.tid);
1661     pi = (struct GNUNET_PeerIdentity *) &msg[1];
1662     for (i = 0; i < p->length; i++)
1663     {
1664       GNUNET_PEER_resolve (p->peers[i], &pi[i]);
1665     }
1666     GNUNET_PEER_resolve (t->next_hop, &id);
1667     send_prebuilt_message (&msg->header, &id, t);
1668   }
1669 }
1670
1671
1672 /**
1673  * Sends a PATH ACK message in reponse to a received PATH_CREATE directed to us.
1674  *
1675  * @param t Tunnel which to confirm.
1676  */
1677 static void
1678 send_path_ack (struct MeshTunnel *t) 
1679 {
1680   struct MeshTransmissionDescriptor *info;
1681   struct GNUNET_PeerIdentity id;
1682
1683   GNUNET_PEER_resolve (t->prev_hop, &id);
1684   info = GNUNET_malloc (sizeof (struct MeshTransmissionDescriptor));
1685   info->origin = &t->id;
1686   info->peer = GNUNET_CONTAINER_multihashmap_get (peers, &id.hashPubKey);
1687   GNUNET_assert (NULL != info->peer);
1688
1689   queue_add (info,
1690              GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
1691              sizeof (struct GNUNET_MESH_PathACK),
1692              info->peer,
1693              t);
1694 }
1695
1696
1697 /**
1698  * Try to establish a new connection to this peer in the fiven tunnel.
1699  * If the peer doesn't have any path to it yet, try to get one.
1700  * If the peer already has some path, send a CREATE PATH towards it.
1701  *
1702  * @param peer PeerInfo of the peer.
1703  * @param t Tunnel for which to create the path, if possible.
1704  */
1705 static void
1706 peer_connect (struct MeshPeerInfo *peer, struct MeshTunnel *t)
1707 {
1708   struct MeshPathInfo *path_info;
1709   struct MeshPeerPath *p;
1710
1711   if (NULL != peer->path_head)
1712   {
1713     p = peer_get_best_path (peer, t);
1714     tunnel_use_path (t, p);
1715     send_create_path (peer, p, t);
1716   }
1717   else if (NULL == peer->dhtget)
1718   {
1719     struct GNUNET_PeerIdentity id;
1720
1721     GNUNET_PEER_resolve (peer->id, &id);
1722     path_info = GNUNET_malloc (sizeof (struct MeshPathInfo));
1723     path_info->peer = peer;
1724     path_info->t = t;
1725     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1726                 "  Starting DHT GET for peer %s\n", GNUNET_i2s (&id));
1727     peer->dhtgetcls = path_info;
1728     peer->dhtget = GNUNET_DHT_get_start (dht_handle,    /* handle */
1729                                          GNUNET_BLOCK_TYPE_MESH_PEER, /* type */
1730                                          &id.hashPubKey,     /* key to search */
1731                                          dht_replication_level, /* replication level */
1732                                          GNUNET_DHT_RO_RECORD_ROUTE |
1733                                          GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
1734                                          NULL,       /* xquery */ // FIXME BLOOMFILTER
1735                                          0,     /* xquery bits */ // FIXME BLOOMFILTER SIZE
1736                                          &dht_get_id_handler, path_info);
1737   }
1738   /* Otherwise, there is no path but the DHT get is already started. */
1739 }
1740
1741
1742 /**
1743  * Task to delay the connection of a peer
1744  *
1745  * @param cls Closure (path info with tunnel and peer to connect).
1746  *            Will be free'd on exection.
1747  * @param tc TaskContext
1748  */
1749 static void
1750 peer_info_connect_task (void *cls,
1751                         const struct GNUNET_SCHEDULER_TaskContext *tc)
1752 {
1753   struct MeshPathInfo *path_info = cls;
1754
1755   path_info->peer->connect_task = GNUNET_SCHEDULER_NO_TASK;
1756
1757   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1758   {
1759     GNUNET_free (cls);
1760     return;
1761   }
1762     peer_connect (path_info->peer, path_info->t);
1763   GNUNET_free (cls);
1764 }
1765
1766
1767 /**
1768  * Destroy the peer_info and free any allocated resources linked to it
1769  *
1770  * @param pi The peer_info to destroy.
1771  *
1772  * @return GNUNET_OK on success
1773  */
1774 static int
1775 peer_info_destroy (struct MeshPeerInfo *pi)
1776 {
1777   struct GNUNET_PeerIdentity id;
1778   struct MeshPeerPath *p;
1779   struct MeshPeerPath *nextp;
1780
1781   GNUNET_PEER_resolve (pi->id, &id);
1782   GNUNET_PEER_change_rc (pi->id, -1);
1783
1784   if (GNUNET_YES !=
1785       GNUNET_CONTAINER_multihashmap_remove (peers, &id.hashPubKey, pi))
1786   {
1787     GNUNET_break (0);
1788     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1789                 "removing peer %s, not in hashmap\n", GNUNET_i2s (&id));
1790   }
1791   if (NULL != pi->dhtget)
1792   {
1793     GNUNET_DHT_get_stop (pi->dhtget);
1794     GNUNET_free (pi->dhtgetcls);
1795   }
1796   p = pi->path_head;
1797   while (NULL != p)
1798   {
1799     nextp = p->next;
1800     GNUNET_CONTAINER_DLL_remove (pi->path_head, pi->path_tail, p);
1801     path_destroy (p);
1802     p = nextp;
1803   }
1804   if (GNUNET_SCHEDULER_NO_TASK != pi->connect_task)
1805   {
1806     GNUNET_free (GNUNET_SCHEDULER_cancel (pi->connect_task));
1807   }
1808   GNUNET_free (pi);
1809   return GNUNET_OK;
1810 }
1811
1812
1813 /**
1814  * Remove all paths that rely on a direct connection between p1 and p2
1815  * from the peer itself and notify all tunnels about it.
1816  *
1817  * @param peer PeerInfo of affected peer.
1818  * @param p1 GNUNET_PEER_Id of one peer.
1819  * @param p2 GNUNET_PEER_Id of another peer that was connected to the first and
1820  *           no longer is.
1821  *
1822  * TODO: optimize (see below)
1823  */
1824 static void
1825 peer_info_remove_path (struct MeshPeerInfo *peer, GNUNET_PEER_Id p1,
1826                        GNUNET_PEER_Id p2)
1827 {
1828   struct MeshPeerPath *p;
1829   struct MeshPeerPath *next;
1830   struct MeshPeerInfo *peer_d;
1831   GNUNET_PEER_Id d;
1832   unsigned int destroyed;
1833   unsigned int i;
1834
1835   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "peer_info_remove_path\n");
1836   destroyed = 0;
1837   for (p = peer->path_head; NULL != p; p = next)
1838   {
1839     next = p->next;
1840     for (i = 0; i < (p->length - 1); i++)
1841     {
1842       if ((p->peers[i] == p1 && p->peers[i + 1] == p2) ||
1843           (p->peers[i] == p2 && p->peers[i + 1] == p1))
1844       {
1845         GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, p);
1846         path_destroy (p);
1847         destroyed++;
1848         break;
1849       }
1850     }
1851   }
1852   if (0 == destroyed)
1853     return;
1854
1855   for (i = 0; i < peer->ntunnels; i++)
1856   {
1857     d = tunnel_notify_connection_broken (peer->tunnels[i], p1, p2);
1858     if (0 == d)
1859       continue;
1860
1861     peer_d = peer_get_short (d);
1862     next = peer_get_best_path (peer_d, peer->tunnels[i]);
1863     tunnel_use_path (peer->tunnels[i], next);
1864     peer_connect (peer_d, peer->tunnels[i]);
1865   }
1866   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "peer_info_remove_path END\n");
1867 }
1868
1869
1870 /**
1871  * Add the path to the peer and update the path used to reach it in case this
1872  * is the shortest.
1873  *
1874  * @param peer_info Destination peer to add the path to.
1875  * @param path New path to add. Last peer must be the peer in arg 1.
1876  *             Path will be either used of freed if already known.
1877  * @param trusted Do we trust that this path is real?
1878  */
1879 void
1880 peer_info_add_path (struct MeshPeerInfo *peer_info, struct MeshPeerPath *path,
1881                     int trusted)
1882 {
1883   struct MeshPeerPath *aux;
1884   unsigned int l;
1885   unsigned int l2;
1886
1887   if ((NULL == peer_info) || (NULL == path))
1888   {
1889     GNUNET_break (0);
1890     path_destroy (path);
1891     return;
1892   }
1893   if (path->peers[path->length - 1] != peer_info->id)
1894   {
1895     GNUNET_break (0);
1896     path_destroy (path);
1897     return;
1898   }
1899   if (path->length <= 2 && GNUNET_NO == trusted)
1900   {
1901     /* Only allow CORE to tell us about direct paths */
1902     path_destroy (path);
1903     return;
1904   }
1905   GNUNET_assert (peer_info->id == path->peers[path->length - 1]);
1906   for (l = 1; l < path->length; l++)
1907   {
1908     if (path->peers[l] == myid)
1909     {
1910       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shortening path by %u\n", l);
1911       for (l2 = 0; l2 < path->length - l; l2++)
1912       {
1913         path->peers[l2] = path->peers[l + l2];
1914       }
1915       path->length -= l;
1916       l = 1;
1917       path->peers =
1918           GNUNET_realloc (path->peers, path->length * sizeof (GNUNET_PEER_Id));
1919     }
1920   }
1921 #if MESH_DEBUG
1922   {
1923     struct GNUNET_PeerIdentity id;
1924
1925     GNUNET_PEER_resolve (peer_info->id, &id);
1926     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "adding path [%u] to peer %s\n",
1927                 path->length, GNUNET_i2s (&id));
1928   }
1929 #endif
1930   l = path_get_length (path);
1931   if (0 == l)
1932   {
1933     GNUNET_free (path);
1934     return;
1935   }
1936
1937   GNUNET_assert (peer_info->id == path->peers[path->length - 1]);
1938   for (aux = peer_info->path_head; aux != NULL; aux = aux->next)
1939   {
1940     l2 = path_get_length (aux);
1941     if (l2 > l)
1942     {
1943       GNUNET_CONTAINER_DLL_insert_before (peer_info->path_head,
1944                                           peer_info->path_tail, aux, path);
1945       return;
1946     }
1947     else
1948     {
1949       if (l2 == l && memcmp (path->peers, aux->peers, l) == 0)
1950       {
1951         path_destroy (path);
1952         return;
1953       }
1954     }
1955   }
1956   GNUNET_CONTAINER_DLL_insert_tail (peer_info->path_head, peer_info->path_tail,
1957                                     path);
1958   return;
1959 }
1960
1961
1962 /**
1963  * Add the path to the origin peer and update the path used to reach it in case
1964  * this is the shortest.
1965  * The path is given in peer_info -> destination, therefore we turn the path
1966  * upside down first.
1967  *
1968  * @param peer_info Peer to add the path to, being the origin of the path.
1969  * @param path New path to add after being inversed.
1970  * @param trusted Do we trust that this path is real?
1971  */
1972 static void
1973 peer_info_add_path_to_origin (struct MeshPeerInfo *peer_info,
1974                               struct MeshPeerPath *path, int trusted)
1975 {
1976   path_invert (path);
1977   peer_info_add_path (peer_info, path, trusted);
1978 }
1979
1980
1981 /** FIXME
1982  * Function called if the connection to the peer has been stalled for a while,
1983  * possibly due to a missed ACK. Poll the peer about its ACK status.
1984  *
1985  * @param cls Closure (cinfo).
1986  * @param tc TaskContext.
1987  */
1988 static void
1989 tunnel_poll (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1990 {
1991 //   struct GNUNET_MESH_Poll msg;
1992 //   struct GNUNET_PeerIdentity id;
1993 //   struct MeshTunnel *t;
1994
1995 //   cinfo->fc_poll = GNUNET_SCHEDULER_NO_TASK;
1996   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1997   {
1998     return;
1999   }
2000
2001 //   t = cinfo->t;
2002 //   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_POLL);
2003 //   msg.header.size = htons (sizeof (msg));
2004 //   msg.tid = htonl (t->id.tid);
2005 //   GNUNET_PEER_resolve (t->id.oid, &msg.oid);
2006 //   msg.last_ack = htonl (cinfo->fwd_ack);
2007 // 
2008 //   GNUNET_PEER_resolve (cinfo->id, &id);
2009 //   send_prebuilt_message (&msg.header, &id, cinfo->t);
2010 //   cinfo->fc_poll_time = GNUNET_TIME_relative_min (
2011 //     MESH_MAX_POLL_TIME,
2012 //     GNUNET_TIME_relative_multiply (cinfo->fc_poll_time, 2));
2013 //   cinfo->fc_poll = GNUNET_SCHEDULER_add_delayed (cinfo->fc_poll_time,
2014 //                                                  &tunnel_poll, cinfo);
2015 }
2016
2017
2018 /**
2019  * Build a PeerPath from the paths returned from the DHT, reversing the paths
2020  * to obtain a local peer -> destination path and interning the peer ids.
2021  *
2022  * @return Newly allocated and created path
2023  */
2024 static struct MeshPeerPath *
2025 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
2026                      unsigned int get_path_length,
2027                      const struct GNUNET_PeerIdentity *put_path,
2028                      unsigned int put_path_length)
2029 {
2030   struct MeshPeerPath *p;
2031   GNUNET_PEER_Id id;
2032   int i;
2033
2034   p = path_new (1);
2035   p->peers[0] = myid;
2036   GNUNET_PEER_change_rc (myid, 1);
2037   i = get_path_length;
2038   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   GET has %d hops.\n", i);
2039   for (i--; i >= 0; i--)
2040   {
2041     id = GNUNET_PEER_intern (&get_path[i]);
2042     if (p->length > 0 && id == p->peers[p->length - 1])
2043     {
2044       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Optimizing 1 hop out.\n");
2045       GNUNET_PEER_change_rc (id, -1);
2046     }
2047     else
2048     {
2049       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Adding from GET: %s.\n",
2050                   GNUNET_i2s (&get_path[i]));
2051       p->length++;
2052       p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
2053       p->peers[p->length - 1] = id;
2054     }
2055   }
2056   i = put_path_length;
2057   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   PUT has %d hops.\n", i);
2058   for (i--; i >= 0; i--)
2059   {
2060     id = GNUNET_PEER_intern (&put_path[i]);
2061     if (id == myid)
2062     {
2063       /* PUT path went through us, so discard the path up until now and start
2064        * from here to get a much shorter (and loop-free) path.
2065        */
2066       path_destroy (p);
2067       p = path_new (0);
2068     }
2069     if (p->length > 0 && id == p->peers[p->length - 1])
2070     {
2071       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Optimizing 1 hop out.\n");
2072       GNUNET_PEER_change_rc (id, -1);
2073     }
2074     else
2075     {
2076       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Adding from PUT: %s.\n",
2077                   GNUNET_i2s (&put_path[i]));
2078       p->length++;
2079       p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
2080       p->peers[p->length - 1] = id;
2081     }
2082   }
2083 #if MESH_DEBUG
2084   if (get_path_length > 0)
2085     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (first of GET: %s)\n",
2086                 GNUNET_i2s (&get_path[0]));
2087   if (put_path_length > 0)
2088     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (first of PUT: %s)\n",
2089                 GNUNET_i2s (&put_path[0]));
2090   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   In total: %d hops\n",
2091               p->length);
2092   for (i = 0; i < p->length; i++)
2093   {
2094     struct GNUNET_PeerIdentity peer_id;
2095
2096     GNUNET_PEER_resolve (p->peers[i], &peer_id);
2097     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "       %u: %s\n", p->peers[i],
2098                 GNUNET_i2s (&peer_id));
2099   }
2100 #endif
2101   return p;
2102 }
2103
2104
2105 /**
2106  * Adds a path to the peer_infos of all the peers in the path
2107  *
2108  * @param p Path to process.
2109  * @param confirmed Whether we know if the path works or not.
2110  */
2111 static void
2112 path_add_to_peers (struct MeshPeerPath *p, int confirmed)
2113 {
2114   unsigned int i;
2115
2116   /* TODO: invert and add */
2117   for (i = 0; i < p->length && p->peers[i] != myid; i++) /* skip'em */ ;
2118   for (i++; i < p->length; i++)
2119   {
2120     struct MeshPeerInfo *aux;
2121     struct MeshPeerPath *copy;
2122
2123     aux = peer_get_short (p->peers[i]);
2124     copy = path_duplicate (p);
2125     copy->length = i + 1;
2126     peer_info_add_path (aux, copy, GNUNET_NO);
2127   }
2128 }
2129
2130
2131 /**
2132  * Send keepalive packets for a peer
2133  *
2134  * @param cls Closure (tunnel for which to send the keepalive).
2135  * @param tc Notification context.
2136  *
2137  * TODO: implement explicit multicast keepalive?
2138  */
2139 static void
2140 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
2141
2142
2143 /**
2144  * Search for a tunnel among the incoming tunnels
2145  *
2146  * @param tid the local id of the tunnel
2147  *
2148  * @return tunnel handler, NULL if doesn't exist
2149  */
2150 static struct MeshTunnel *
2151 tunnel_get_incoming (MESH_TunnelNumber tid)
2152 {
2153   struct GNUNET_HashCode hash;
2154
2155   GNUNET_assert (tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV);
2156   GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
2157   return GNUNET_CONTAINER_multihashmap_get (incoming_tunnels, &hash);
2158 }
2159
2160
2161 /**
2162  * Search for a tunnel among the tunnels for a client
2163  *
2164  * @param c the client whose tunnels to search in
2165  * @param tid the local id of the tunnel
2166  *
2167  * @return tunnel handler, NULL if doesn't exist
2168  */
2169 static struct MeshTunnel *
2170 tunnel_get_by_local_id (struct MeshClient *c, MESH_TunnelNumber tid)
2171 {
2172   if (tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
2173   {
2174     return tunnel_get_incoming (tid);
2175   }
2176   else
2177   {
2178     struct GNUNET_HashCode hash;
2179
2180     GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
2181     return GNUNET_CONTAINER_multihashmap_get (c->own_tunnels, &hash);
2182   }
2183 }
2184
2185
2186 /**
2187  * Search for a tunnel by global ID using PEER_ID
2188  *
2189  * @param pi owner of the tunnel
2190  * @param tid global tunnel number
2191  *
2192  * @return tunnel handler, NULL if doesn't exist
2193  */
2194 static struct MeshTunnel *
2195 tunnel_get_by_pi (GNUNET_PEER_Id pi, MESH_TunnelNumber tid)
2196 {
2197   struct MESH_TunnelID id;
2198   struct GNUNET_HashCode hash;
2199
2200   id.oid = pi;
2201   id.tid = tid;
2202
2203   GNUNET_CRYPTO_hash (&id, sizeof (struct MESH_TunnelID), &hash);
2204   return GNUNET_CONTAINER_multihashmap_get (tunnels, &hash);
2205 }
2206
2207
2208 /**
2209  * Search for a tunnel by global ID using full PeerIdentities
2210  *
2211  * @param oid owner of the tunnel
2212  * @param tid global tunnel number
2213  *
2214  * @return tunnel handler, NULL if doesn't exist
2215  */
2216 static struct MeshTunnel *
2217 tunnel_get (const struct GNUNET_PeerIdentity *oid, MESH_TunnelNumber tid)
2218 {
2219   return tunnel_get_by_pi (GNUNET_PEER_search (oid), tid);
2220 }
2221
2222
2223 /**
2224  * Delete an active client from the tunnel.
2225  * 
2226  * @param t Tunnel.
2227  * @param c Client.
2228  */
2229 static void
2230 tunnel_delete_active_client (struct MeshTunnel *t, const struct MeshClient *c)
2231 {
2232   unsigned int i;
2233
2234   for (i = 0; i < t->nclients; i++)
2235   {
2236     if (t->clients[i] == c)
2237     {
2238       t->clients[i] = t->clients[t->nclients - 1];
2239       t->clients_fc[i] = t->clients_fc[t->nclients - 1];
2240       GNUNET_array_grow (t->clients, t->nclients, t->nclients - 1);
2241       t->nclients++;
2242       GNUNET_array_grow (t->clients_fc, t->nclients, t->nclients - 1);
2243       break;
2244     }
2245   }
2246 }
2247
2248
2249 /**
2250  * Delete an ignored client from the tunnel.
2251  * 
2252  * @param t Tunnel.
2253  * @param c Client.
2254  */
2255 static void
2256 tunnel_delete_ignored_client (struct MeshTunnel *t, const struct MeshClient *c)
2257 {
2258   unsigned int i;
2259
2260   for (i = 0; i < t->nignore; i++)
2261   {
2262     if (t->ignore[i] == c)
2263     {
2264       t->ignore[i] = t->ignore[t->nignore - 1];
2265       GNUNET_array_grow (t->ignore, t->nignore, t->nignore - 1);
2266       break;
2267     }
2268   }
2269 }
2270
2271
2272 /**
2273  * Delete a client from the tunnel. It should be only done on
2274  * client disconnection, otherwise use client_ignore_tunnel.
2275  * 
2276  * @param t Tunnel.
2277  * @param c Client.
2278  */
2279 static void
2280 tunnel_delete_client (struct MeshTunnel *t, const struct MeshClient *c)
2281 {
2282   tunnel_delete_ignored_client (t, c);
2283   tunnel_delete_active_client (t, c);
2284 }
2285
2286
2287 static void
2288 tunnel_add_client (struct MeshTunnel *t, struct MeshClient *c)
2289 {
2290   struct MeshTunnelClientInfo clinfo;
2291
2292   GNUNET_array_append (t->clients, t->nclients, c);
2293   clinfo.fwd_ack = t->fwd_pid + 1;
2294   clinfo.bck_ack = t->nobuffer ? 1 : INITIAL_WINDOW_SIZE - 1;
2295   clinfo.fwd_pid = t->fwd_pid;
2296   clinfo.bck_pid = (uint32_t) -1; // Expected next: 0
2297   t->nclients--;
2298   GNUNET_array_append (t->clients_fc, t->nclients, clinfo);
2299 }
2300
2301
2302 static void
2303 tunnel_use_path (struct MeshTunnel *t, struct MeshPeerPath *p)
2304 {
2305   unsigned int i;
2306
2307   for (i = 0; i < p->length; i++)
2308   {
2309     if (p->peers[i] == myid)
2310       break;
2311   }
2312   if (i > p->length - 1)
2313   {
2314     GNUNET_break (0);
2315     return;
2316   }
2317   if (i < p->length - 1)
2318     t->next_hop = p->peers[i + 1];
2319   else
2320     t->next_hop = 0;
2321   if (0 < i)
2322     t->prev_hop = p->peers[i - 1];
2323   else
2324     t->prev_hop = 0;
2325   if (NULL != t->path)
2326     path_destroy (t->path);
2327   t->path = path_duplicate (p);
2328 }
2329
2330
2331 /**
2332  * Notifies a tunnel that a connection has broken that affects at least
2333  * some of its peers. Sends a notification towards the root of the tree.
2334  * In case the peer is the owner of the tree, notifies the client that owns
2335  * the tunnel and tries to reconnect.
2336  *
2337  * @param t Tunnel affected.
2338  * @param p1 Peer that got disconnected from p2.
2339  * @param p2 Peer that got disconnected from p1.
2340  *
2341  * @return Short ID of the peer disconnected (either p1 or p2).
2342  *         0 if the tunnel remained unaffected.
2343  */
2344 static GNUNET_PEER_Id
2345 tunnel_notify_connection_broken (struct MeshTunnel *t, GNUNET_PEER_Id p1,
2346                                  GNUNET_PEER_Id p2)
2347 {
2348 //   if (myid != p1 && myid != p2) FIXME
2349 //   {
2350 //     return;
2351 //   }
2352 // 
2353 //   if (tree_get_predecessor (t->tree) != 0)
2354 //   {
2355 //     /* We are the peer still connected, notify owner of the disconnection. */
2356 //     struct GNUNET_MESH_PathBroken msg;
2357 //     struct GNUNET_PeerIdentity neighbor;
2358 // 
2359 //     msg.header.size = htons (sizeof (msg));
2360 //     msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN);
2361 //     GNUNET_PEER_resolve (t->id.oid, &msg.oid);
2362 //     msg.tid = htonl (t->id.tid);
2363 //     msg.peer1 = my_full_id;
2364 //     GNUNET_PEER_resolve (pid, &msg.peer2);
2365 //     GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &neighbor);
2366 //     send_prebuilt_message (&msg.header, &neighbor, t);
2367 //   }
2368   return 0;
2369 }
2370
2371
2372 /**
2373  * Get the Flow Control info of a client.
2374  * 
2375  * @param t Tunnel on which to look.
2376  * @param c Client whose ACK to get.
2377  * 
2378  * @return ACK value.
2379  */
2380 static struct MeshTunnelClientInfo *
2381 tunnel_get_client_fc (struct MeshTunnel *t,
2382                       struct MeshClient *c)
2383 {
2384   unsigned int i;
2385
2386   for (i = 0; i < t->nclients; i++)
2387   {
2388     if (t->clients[i] != c)
2389       continue;
2390     return &t->clients_fc[i];
2391   }
2392   GNUNET_assert (0);
2393   return NULL; // avoid compiler / coverity complaints
2394 }
2395
2396
2397 /**
2398  * Set the FWD ACK value of a client in a particular tunnel.
2399  * 
2400  * @param t Tunnel affected.
2401  * @param c Client whose ACK to set.
2402  * @param ack ACK value.
2403  */
2404 static void
2405 tunnel_set_client_fwd_ack (struct MeshTunnel *t,
2406                            struct MeshClient *c, 
2407                            uint32_t ack)
2408 {
2409   unsigned int i;
2410
2411   for (i = 0; i < t->nclients; i++)
2412   {
2413     if (t->clients[i] != c)
2414       continue;
2415     t->clients_fc[i].fwd_ack = ack;
2416     return;
2417   }
2418   GNUNET_break (0);
2419 }
2420
2421
2422 /**
2423  * Get the highest ACK value of all clients in a particular tunnel,
2424  * according to the buffering/speed settings.
2425  * 
2426  * @param t Tunnel on which to look.
2427  * 
2428  * @return Corresponding ACK value (max uint32_t).
2429  *         If no clients are suscribed, -1LL.
2430  */
2431 static int64_t
2432 tunnel_get_clients_fwd_ack (struct MeshTunnel *t)
2433 {
2434   unsigned int i;
2435   int64_t ack;
2436
2437   if (0 == t->nclients)
2438   {
2439     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2440                 "  tunnel has no clients, no FWD ACK\n");
2441     return -1LL;
2442   }
2443
2444   for (ack = -1LL, i = 0; i < t->nclients; i++)
2445   {
2446     if (-1LL == ack ||
2447         GNUNET_YES == GMC_is_pid_bigger (ack, t->clients_fc[i].fwd_ack))
2448     {
2449       ack = t->clients_fc[i].fwd_ack;
2450     }
2451   }
2452
2453   if (GNUNET_YES == t->nobuffer && GMC_is_pid_bigger(ack, t->fwd_pid))
2454     ack = (uint32_t) t->fwd_pid + 1; // Might overflow, it's ok.
2455
2456   return (uint32_t) ack;
2457 }
2458
2459
2460 /** FIXME
2461  * Get the current fwd ack value for a tunnel, taking in account the tunnel
2462  * mode and the status of all children nodes.
2463  *
2464  * @param t Tunnel.
2465  *
2466  * @return Maximum PID allowed.
2467  */
2468 static uint32_t
2469 tunnel_get_fwd_ack (struct MeshTunnel *t)
2470 {
2471   uint32_t ack;
2472   uint32_t count;
2473   uint32_t buffer_free;
2474   int64_t client_ack;
2475
2476   count = t->fwd_pid;
2477   buffer_free = t->fwd_queue_max - t->fwd_queue_n;
2478   client_ack = tunnel_get_clients_fwd_ack (t);
2479   if (GNUNET_YES == t->nobuffer)
2480   {
2481     ack = count;
2482   }
2483   else
2484   {
2485     ack = count + buffer_free; // Overflow? OK!
2486   }
2487   if (-1LL == client_ack)
2488   {
2489     client_ack = ack;
2490   }
2491   /* FIXME check */
2492   ack = GMC_max_pid ((uint32_t) client_ack, ack);
2493
2494   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2495               "c %u, bf %u, cl %lld, ACK: %u\n",
2496               count, buffer_free, client_ack, ack);
2497   return ack;
2498 }
2499
2500
2501 /**
2502  * Build a local ACK message and send it to a local client.
2503  * 
2504  * @param t Tunnel on which to send the ACK.
2505  * @param c Client to whom send the ACK.
2506  * @param ack Value of the ACK.
2507  */
2508 static void
2509 send_local_ack (struct MeshTunnel *t, struct MeshClient *c, uint32_t ack)
2510 {
2511   struct GNUNET_MESH_LocalAck msg;
2512
2513   msg.header.size = htons (sizeof (msg));
2514   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
2515   msg.tunnel_id = htonl (t->owner == c ? t->local_tid : t->local_tid_dest);
2516   msg.max_pid = htonl (ack); 
2517   GNUNET_SERVER_notification_context_unicast(nc,
2518                                               c->handle,
2519                                               &msg.header,
2520                                               GNUNET_NO);
2521 }
2522
2523 /**
2524  * Build an ACK message and queue it to send to the given peer.
2525  * 
2526  * @param t Tunnel on which to send the ACK.
2527  * @param peer Peer to whom send the ACK.
2528  * @param ack Value of the ACK.
2529  */
2530 static void
2531 send_ack (struct MeshTunnel *t, struct GNUNET_PeerIdentity *peer,  uint32_t ack)
2532 {
2533   struct GNUNET_MESH_ACK msg;
2534
2535   GNUNET_PEER_resolve (t->id.oid, &msg.oid);
2536   msg.header.size = htons (sizeof (msg));
2537   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_ACK);
2538   msg.pid = htonl (ack);
2539   msg.tid = htonl (t->id.tid);
2540
2541   send_prebuilt_message (&msg.header, peer, t);
2542 }
2543
2544
2545 /**
2546  * Notify a the owner of a tunnel about how many more
2547  * payload packages will we accept on a given tunnel.
2548  *
2549  * @param t Tunnel on which to send the ACK.
2550  */
2551 static void
2552 tunnel_send_client_fwd_ack (struct MeshTunnel *t)
2553 {
2554   uint32_t ack;
2555
2556   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2557               "Sending client FWD ACK on tunnel %X\n",
2558               t->local_tid);
2559
2560   ack = tunnel_get_fwd_ack (t);
2561
2562   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ack %u\n", ack);
2563   if (t->last_fwd_ack == ack)
2564   {
2565     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " same as last, not sending!\n");
2566     return;
2567   }
2568
2569   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " sending!\n");
2570   t->last_fwd_ack = ack;
2571   send_local_ack (t, t->owner, ack);
2572 }
2573
2574
2575 /**
2576  * Send an ACK informing the predecessor about the available buffer space.
2577  * In case there is no predecessor, inform the owning client.
2578  * If buffering is off, send only on behalf of children or self if endpoint.
2579  * If buffering is on, send when sent to children and buffer space is free.
2580  * Note that although the name is fwd_ack, the FWD mean forward *traffic*,
2581  * the ACK itself goes "back" (towards root).
2582  * 
2583  * @param t Tunnel on which to send the ACK.
2584  * @param type Type of message that triggered the ACK transmission.
2585  */
2586 static void
2587 tunnel_send_fwd_ack (struct MeshTunnel *t, uint16_t type)
2588 {
2589   struct GNUNET_PeerIdentity id;
2590   uint32_t ack;
2591
2592   if (NULL != t->owner)
2593   {
2594     tunnel_send_client_fwd_ack (t);
2595     return;
2596   }
2597   /* Is it after unicast / multicast retransmission? */
2598   switch (type)
2599   {
2600     case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
2601       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2602                   "ACK due to FWD DATA retransmission\n");
2603       if (GNUNET_YES == t->nobuffer)
2604       {
2605         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, nobuffer\n");
2606         return;
2607       }
2608       break;
2609     case GNUNET_MESSAGE_TYPE_MESH_ACK:
2610     case GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK:
2611       break;
2612     case GNUNET_MESSAGE_TYPE_MESH_POLL:
2613       t->force_ack = GNUNET_YES;
2614       break;
2615     default:
2616       GNUNET_break (0);
2617   }
2618
2619   /* Check if we need to transmit the ACK */
2620   if (t->fwd_queue_max > t->fwd_queue_n * 4 &&
2621       GMC_is_pid_bigger(t->last_fwd_ack, t->fwd_pid) &&
2622       GNUNET_NO == t->force_ack)
2623   {
2624     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, buffer free\n");
2625     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2626                 "  t->qmax: %u, t->qn: %u\n",
2627                 t->fwd_queue_max, t->fwd_queue_n);
2628     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2629                 "  t->pid: %u, t->ack: %u\n",
2630                 t->fwd_pid, t->last_fwd_ack);
2631     return;
2632   }
2633
2634   /* Ok, ACK might be necessary, what PID to ACK? */
2635   ack = tunnel_get_fwd_ack (t);
2636
2637   /* If speed_min and not all children have ack'd, dont send yet */
2638   if (ack == t->last_fwd_ack && GNUNET_NO == t->force_ack)
2639   {
2640     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending FWD ACK, not ready\n");
2641     return;
2642   }
2643
2644   t->last_fwd_ack = ack;
2645   GNUNET_PEER_resolve (t->prev_hop, &id);
2646   send_ack (t, &id, ack);
2647   debug_fwd_ack++;
2648   t->force_ack = GNUNET_NO;
2649 }
2650
2651
2652 /**
2653  * Send a child node a BCK ACK to allow him to send more to_origin data.
2654  *
2655  * @param t Tunnel.
2656  * @param id Id of the child node.
2657  */
2658 static void
2659 tunnel_send_child_bck_ack (struct MeshTunnel *t,
2660                            GNUNET_PEER_Id id)
2661 {
2662   struct GNUNET_PeerIdentity peer;
2663   uint32_t ack = 0; // FIXME
2664
2665   GNUNET_PEER_resolve (id, &peer);
2666 //   ack = cinfo->bck_pid + t->bck_queue_max - t->bck_queue_n;
2667 // 
2668 //   if (cinfo->bck_ack == ack && GNUNET_NO == t->force_ack)
2669 //   {
2670 //     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2671 //                 "    Not sending ACK, not needed\n");
2672 //     return;
2673 //   }
2674 //   cinfo->bck_ack = ack;
2675 // 
2676 //   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2677 //               "    Sending BCK ACK %u (last sent: %u)\n",
2678 //               ack, cinfo->bck_ack);
2679   send_ack (t, &peer, ack);
2680 }
2681
2682
2683 /**
2684  * @brief Send BCK ACKs to clients to allow them more to_origin traffic
2685  * 
2686  * Iterates over all clients and sends BCK ACKs to the ones that need it.
2687  *
2688  * FIXME fc: what happens if we have 2 clients but q_size is 1?
2689  *           - implement a size 1 buffer in each client_fc AND children_fc
2690  *           to hold at least 1 message per "child".
2691  *             problem: violates no buffer policy
2692  *           - ack 0 and make "children" poll for transmission slots
2693  *             problem: big overhead, extra latency even in low traffic
2694  *                      settings
2695  * 
2696  * @param t Tunnel on which to send the BCK ACKs.
2697  */
2698 static void
2699 tunnel_send_clients_bck_ack (struct MeshTunnel *t)
2700 {
2701   unsigned int i;
2702   unsigned int tunnel_delta;
2703
2704   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Sending BCK ACK to clients\n");
2705
2706   tunnel_delta = t->bck_queue_max - t->bck_queue_n;
2707   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   tunnel delta: %u\n", tunnel_delta);
2708
2709   /* Find client whom to allow to send to origin (with lowest buffer space) */
2710   for (i = 0; i < t->nclients; i++)
2711   {
2712     struct MeshTunnelClientInfo *clinfo;
2713     unsigned int delta;
2714
2715     clinfo = &t->clients_fc[i];
2716     delta = clinfo->bck_ack - clinfo->bck_pid;
2717     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    client %u delta: %u\n",
2718          t->clients[i]->id, delta);
2719
2720     if ((GNUNET_NO == t->nobuffer && tunnel_delta > delta) ||
2721         (GNUNET_YES == t->nobuffer && 0 == delta))
2722     {
2723       uint32_t ack;
2724
2725       ack = clinfo->bck_pid;
2726       ack += t->nobuffer ? 1 : tunnel_delta;
2727       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2728                   "    sending ack to client %u: %u\n",
2729                   t->clients[i]->id, ack);
2730       send_local_ack (t, t->clients[i], ack);
2731       clinfo->bck_ack = ack;
2732     }
2733     else
2734     {
2735       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2736                   "    not sending ack to client %u (td %u, d %u)\n",
2737                   t->clients[i]->id, tunnel_delta, delta);
2738     }
2739   }
2740 }
2741
2742
2743 /**
2744  * Send an ACK informing the children nodes and destination clients about
2745  * the available buffer space.
2746  * If buffering is off, send only on behalf of root (can be self).
2747  * If buffering is on, send when sent to predecessor and buffer space is free.
2748  * Note that although the name is bck_ack, the BCK mean backwards *traffic*,
2749  * the ACK itself goes "forward" (towards children/clients).
2750  * 
2751  * @param t Tunnel on which to send the ACK.
2752  * @param type Type of message that triggered the ACK transmission.
2753  */
2754 static void
2755 tunnel_send_bck_ack (struct MeshTunnel *t, uint16_t type)
2756 {
2757   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2758               "Sending BCK ACK on tunnel %u [%u] due to %s\n",
2759               t->id.oid, t->id.tid, GNUNET_MESH_DEBUG_M2S(type));
2760   /* Is it after data to_origin retransmission? */
2761   switch (type)
2762   {
2763     case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
2764       if (GNUNET_YES == t->nobuffer)
2765       {
2766         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2767                     "    Not sending ACK, nobuffer\n");
2768         return;
2769       }
2770       break;
2771     case GNUNET_MESSAGE_TYPE_MESH_ACK:
2772     case GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK:
2773       break;
2774     case GNUNET_MESSAGE_TYPE_MESH_POLL:
2775       t->force_ack = GNUNET_YES;
2776       break;
2777     default:
2778       GNUNET_break (0);
2779   }
2780
2781   tunnel_send_clients_bck_ack (t);
2782   tunnel_send_child_bck_ack (t, t->next_hop);
2783   t->force_ack = GNUNET_NO;
2784 }
2785
2786
2787 /**
2788  * @brief Re-initiate traffic to this peer if necessary.
2789  *
2790  * Check if there is traffic queued towards this peer
2791  * and the core transmit handle is NULL (traffic was stalled).
2792  * If so, call core tmt rdy.
2793  *
2794  * @param peer_id Short ID of peer to which initiate traffic.
2795  */
2796 static void
2797 peer_unlock_queue(GNUNET_PEER_Id peer_id)
2798 {
2799   struct MeshPeerInfo *peer;
2800   struct GNUNET_PeerIdentity id;
2801   struct MeshPeerQueue *q;
2802   size_t size;
2803
2804   peer = peer_get_short (peer_id);
2805   if (NULL != peer->core_transmit)
2806     return;
2807
2808   q = queue_get_next(peer);
2809   if (NULL == q)
2810   {
2811     /* Might br multicast traffic already sent to this particular peer but
2812      * not to other children in this tunnel.
2813      * This way t->queue_n would be > 0 but the queue of this particular peer
2814      * would be empty.
2815      */
2816     return;
2817   }
2818   size = q->size;
2819   GNUNET_PEER_resolve (peer->id, &id);
2820   peer->core_transmit =
2821         GNUNET_CORE_notify_transmit_ready(core_handle,
2822                                           0,
2823                                           0,
2824                                           GNUNET_TIME_UNIT_FOREVER_REL,
2825                                           &id,
2826                                           size,
2827                                           &queue_send,
2828                                           peer);
2829         return;
2830 }
2831
2832
2833 /**
2834  * Send a message to all peers in this tunnel that the tunnel is no longer
2835  * valid.
2836  *
2837  * @param t The tunnel whose peers to notify.
2838  */
2839 static void
2840 tunnel_send_destroy (struct MeshTunnel *t)
2841 {
2842   struct GNUNET_MESH_TunnelDestroy msg;
2843   struct GNUNET_PeerIdentity id;
2844
2845   msg.header.size = htons (sizeof (msg));
2846   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY);
2847   GNUNET_PEER_resolve (t->id.oid, &msg.oid);
2848   msg.tid = htonl (t->id.tid);
2849   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2850               "  sending tunnel destroy for tunnel: %s [%X]\n",
2851               GNUNET_i2s (&msg.oid), t->id.tid);
2852
2853   if (0 != t->next_hop)
2854   {
2855     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  child: %u\n", t->next_hop);
2856     GNUNET_PEER_resolve (t->next_hop, &id);
2857     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2858                 "  sending back to %s\n",
2859                 GNUNET_i2s (&id));
2860     send_prebuilt_message (&msg.header, &id, t);
2861   }
2862   if (0 != t->prev_hop)
2863   {
2864     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  parent: %u\n", t->prev_hop);
2865     GNUNET_PEER_resolve (t->prev_hop, &id);
2866     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2867                 "  sending back to %s\n",
2868                 GNUNET_i2s (&id));
2869     send_prebuilt_message (&msg.header, &id, t);
2870   }
2871 }
2872
2873
2874 /**
2875  * Cancel all transmissions towards a neighbor that belongs to a certain tunnel.
2876  *
2877  * @param t Tunnel which to cancel.
2878  * @param neighbor Short ID of the neighbor to whom cancel the transmissions.
2879  */
2880 static void
2881 peer_cancel_queues (GNUNET_PEER_Id neighbor, struct MeshTunnel *t)
2882 {
2883   struct MeshPeerInfo *peer_info;
2884   struct MeshPeerQueue *pq;
2885   struct MeshPeerQueue *next;
2886
2887   peer_info = peer_get_short (neighbor);
2888   for (pq = peer_info->queue_head; NULL != pq; pq = next)
2889   {
2890     next = pq->next;
2891     if (pq->tunnel == t)
2892     {
2893       if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == pq->type ||
2894           GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == pq->type)
2895       {
2896         // Should have been removed on destroy children
2897         GNUNET_break (0);
2898       }
2899       queue_destroy (pq, GNUNET_YES);
2900     }
2901   }
2902   if (NULL == peer_info->queue_head && NULL != peer_info->core_transmit)
2903   {
2904     GNUNET_CORE_notify_transmit_ready_cancel(peer_info->core_transmit);
2905     peer_info->core_transmit = NULL;
2906   }
2907 }
2908
2909
2910 /**
2911  * Destroy the tunnel and free any allocated resources linked to it.
2912  *
2913  * @param t the tunnel to destroy
2914  *
2915  * @return GNUNET_OK on success
2916  */
2917 static int
2918 tunnel_destroy (struct MeshTunnel *t)
2919 {
2920   struct MeshClient *c;
2921   struct GNUNET_HashCode hash;
2922   unsigned int i;
2923   int r;
2924
2925   if (NULL == t)
2926     return GNUNET_OK;
2927
2928   r = GNUNET_OK;
2929   c = t->owner;
2930 #if MESH_DEBUG
2931   {
2932     struct GNUNET_PeerIdentity id;
2933
2934     GNUNET_PEER_resolve (t->id.oid, &id);
2935     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s [%x]\n",
2936                 GNUNET_i2s (&id), t->id.tid);
2937     if (NULL != c)
2938       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
2939   }
2940 #endif
2941
2942   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
2943   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &hash, t))
2944   {
2945     GNUNET_break (0);
2946     r = GNUNET_SYSERR;
2947   }
2948
2949   if (NULL != c)
2950   {
2951     GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
2952     if (GNUNET_YES !=
2953         GNUNET_CONTAINER_multihashmap_remove (c->own_tunnels, &hash, t))
2954     {
2955       GNUNET_break (0);
2956       r = GNUNET_SYSERR;
2957     }
2958   }
2959
2960   GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
2961   for (i = 0; i < t->nclients; i++)
2962   {
2963     c = t->clients[i];
2964     if (GNUNET_YES !=
2965           GNUNET_CONTAINER_multihashmap_remove (c->incoming_tunnels, &hash, t))
2966     {
2967       GNUNET_break (0);
2968       r = GNUNET_SYSERR;
2969     }
2970   }
2971   for (i = 0; i < t->nignore; i++)
2972   {
2973     c = t->ignore[i];
2974     if (GNUNET_YES !=
2975           GNUNET_CONTAINER_multihashmap_remove (c->ignore_tunnels, &hash, t))
2976     {
2977       GNUNET_break (0);
2978       r = GNUNET_SYSERR;
2979     }
2980   }
2981
2982   (void) GNUNET_CONTAINER_multihashmap_remove (incoming_tunnels, &hash, t);
2983   GNUNET_free_non_null (t->clients);
2984   GNUNET_free_non_null (t->ignore);
2985   GNUNET_free_non_null (t->clients_fc);
2986
2987   peer_cancel_queues (t->next_hop, t);
2988   peer_cancel_queues (t->prev_hop, t);
2989
2990   if (GNUNET_SCHEDULER_NO_TASK != t->timeout_task)
2991     GNUNET_SCHEDULER_cancel (t->timeout_task);
2992   if (GNUNET_SCHEDULER_NO_TASK != t->path_refresh_task)
2993     GNUNET_SCHEDULER_cancel (t->path_refresh_task);
2994
2995   n_tunnels--;
2996   GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
2997   GNUNET_free (t);
2998   return r;
2999 }
3000
3001 #define TUNNEL_DESTROY_EMPTY_TIME GNUNET_TIME_UNIT_MILLISECONDS
3002
3003 /**
3004  * Tunnel is empty: destroy it.
3005  * 
3006  * @param cls Closure (Tunnel).
3007  * @param tc TaskContext. 
3008  */
3009 static void
3010 tunnel_destroy_empty_delayed (void *cls,
3011                               const struct GNUNET_SCHEDULER_TaskContext *tc)
3012 {
3013   struct MeshTunnel *t = cls;
3014
3015   t->delayed_destroy = GNUNET_SCHEDULER_NO_TASK;
3016   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3017     return;
3018
3019   if (0 != t->nclients)
3020     return;
3021
3022   #if MESH_DEBUG
3023   {
3024     struct GNUNET_PeerIdentity id;
3025
3026     GNUNET_PEER_resolve (t->id.oid, &id);
3027     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3028                 "executing destruction of empty tunnel %s [%X]\n",
3029                 GNUNET_i2s (&id), t->id.tid);
3030   }
3031   #endif
3032
3033   tunnel_send_destroy (t);
3034   if (0 == t->pending_messages)
3035     tunnel_destroy (t);
3036   else
3037     t->destroy = GNUNET_YES;
3038 }
3039
3040
3041 /**
3042  * Schedule tunnel destruction if is empty and no new traffic comes in a time.
3043  * 
3044  * @param t Tunnel to destroy if empty.
3045  */
3046 static void
3047 tunnel_destroy_empty (struct MeshTunnel *t)
3048 {
3049   if (GNUNET_SCHEDULER_NO_TASK != t->delayed_destroy || 
3050       0 != t->nclients)
3051   {
3052     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%u %u\n",
3053                 t->delayed_destroy, t->nclients);
3054     return;
3055   }
3056
3057   #if MESH_DEBUG
3058   {
3059     struct GNUNET_PeerIdentity id;
3060
3061     GNUNET_PEER_resolve (t->id.oid, &id);
3062     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3063                 "scheduling destruction of empty tunnel %s [%X]\n",
3064                 GNUNET_i2s (&id), t->id.tid);
3065   }
3066   #endif
3067
3068   t->delayed_destroy =
3069       GNUNET_SCHEDULER_add_delayed (TUNNEL_DESTROY_EMPTY_TIME,
3070                                     &tunnel_destroy_empty_delayed,
3071                                     t);
3072 }
3073
3074
3075 /**
3076  * Create a new tunnel
3077  * 
3078  * @param owner Who is the owner of the tunnel (short ID).
3079  * @param tid Tunnel Number of the tunnel.
3080  * @param client Clients that owns the tunnel, NULL for foreign tunnels.
3081  * @param local Tunnel Number for the tunnel, for the client point of view.
3082  * 
3083  * @return A new initialized tunnel. NULL on error.
3084  */
3085 static struct MeshTunnel *
3086 tunnel_new (GNUNET_PEER_Id owner,
3087             MESH_TunnelNumber tid,
3088             struct MeshClient *client,
3089             MESH_TunnelNumber local)
3090 {
3091   struct MeshTunnel *t;
3092   struct GNUNET_HashCode hash;
3093
3094   if (n_tunnels >= max_tunnels && NULL == client)
3095     return NULL;
3096
3097   t = GNUNET_malloc (sizeof (struct MeshTunnel));
3098   t->id.oid = owner;
3099   t->id.tid = tid;
3100   t->fwd_queue_max = (max_msgs_queue / max_tunnels) + 1;
3101   t->bck_queue_max = t->fwd_queue_max;
3102   t->owner = client;
3103   t->fwd_pid = (uint32_t) -1; // Next (expected) = 0
3104   t->bck_pid = (uint32_t) -1; // Next (expected) = 0
3105   t->bck_ack = INITIAL_WINDOW_SIZE - 1;
3106   t->last_fwd_ack = INITIAL_WINDOW_SIZE - 1;
3107   t->local_tid = local;
3108   n_tunnels++;
3109   GNUNET_STATISTICS_update (stats, "# tunnels", 1, GNUNET_NO);
3110
3111   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
3112   if (GNUNET_OK !=
3113       GNUNET_CONTAINER_multihashmap_put (tunnels, &hash, t,
3114                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
3115   {
3116     GNUNET_break (0);
3117     tunnel_destroy (t);
3118     if (NULL != client)
3119     {
3120       GNUNET_break (0);
3121       GNUNET_SERVER_receive_done (client->handle, GNUNET_SYSERR);
3122     }
3123     return NULL;
3124   }
3125
3126   if (NULL != client)
3127   {
3128     GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
3129     if (GNUNET_OK !=
3130         GNUNET_CONTAINER_multihashmap_put (client->own_tunnels, &hash, t,
3131                                           GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
3132     {
3133       tunnel_destroy (t);
3134       GNUNET_break (0);
3135       GNUNET_SERVER_receive_done (client->handle, GNUNET_SYSERR);
3136       return NULL;
3137     }
3138   }
3139
3140   return t;
3141 }
3142
3143
3144
3145 /**
3146  * tunnel_destroy_iterator: iterator for deleting each tunnel that belongs to a
3147  * client when the client disconnects. If the client is not the owner, the
3148  * owner will get notified if no more clients are in the tunnel and the client
3149  * get removed from the tunnel's list.
3150  *
3151  * @param cls closure (client that is disconnecting)
3152  * @param key the hash of the local tunnel id (used to access the hashmap)
3153  * @param value the value stored at the key (tunnel to destroy)
3154  *
3155  * @return GNUNET_OK, keep iterating.
3156  */
3157 static int
3158 tunnel_destroy_iterator (void *cls,
3159                          const struct GNUNET_HashCode * key,
3160                          void *value)
3161 {
3162   struct MeshTunnel *t = value;
3163   struct MeshClient *c = cls;
3164
3165   send_client_tunnel_disconnect (t, c);
3166   if (c != t->owner)
3167   {
3168     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Client %u is destination.\n", c->id);
3169     tunnel_delete_client (t, c);
3170     client_delete_tunnel (c, t);
3171     tunnel_destroy_empty (t);
3172     return GNUNET_OK;
3173   }
3174   tunnel_send_destroy (t);
3175   t->owner = NULL;
3176   t->destroy = GNUNET_YES;
3177
3178   return GNUNET_OK;
3179 }
3180
3181
3182 /**
3183  * Timeout function, destroys tunnel if called
3184  *
3185  * @param cls Closure (tunnel to destroy).
3186  * @param tc TaskContext
3187  */
3188 static void
3189 tunnel_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3190 {
3191   struct MeshTunnel *t = cls;
3192   struct GNUNET_PeerIdentity id;
3193
3194   t->timeout_task = GNUNET_SCHEDULER_NO_TASK;
3195   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3196     return;
3197   GNUNET_PEER_resolve(t->id.oid, &id);
3198   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3199               "Tunnel %s [%X] timed out. Destroying.\n",
3200               GNUNET_i2s(&id), t->id.tid);
3201   send_clients_tunnel_destroy (t);
3202   tunnel_destroy (t);
3203 }
3204
3205 /**
3206  * Resets the tunnel timeout. Starts it if no timeout was running.
3207  *
3208  * @param t Tunnel whose timeout to reset.
3209  *
3210  * TODO use heap to improve efficiency of scheduler.
3211  */
3212 static void
3213 tunnel_reset_timeout (struct MeshTunnel *t)
3214 {
3215   if (GNUNET_SCHEDULER_NO_TASK != t->timeout_task)
3216     GNUNET_SCHEDULER_cancel (t->timeout_task);
3217   t->timeout_task =
3218       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
3219                                     (refresh_path_time, 4), &tunnel_timeout, t);
3220 }
3221
3222
3223 /******************************************************************************/
3224 /****************      MESH NETWORK HANDLER HELPERS     ***********************/
3225 /******************************************************************************/
3226
3227 /**
3228  * Function to send a create path packet to a peer.
3229  *
3230  * @param cls closure
3231  * @param size number of bytes available in buf
3232  * @param buf where the callee should write the message
3233  * @return number of bytes written to buf
3234  */
3235 static size_t
3236 send_core_path_create (void *cls, size_t size, void *buf)
3237 {
3238   struct MeshPathInfo *info = cls;
3239   struct GNUNET_MESH_ManipulatePath *msg;
3240   struct GNUNET_PeerIdentity *peer_ptr;
3241   struct MeshTunnel *t = info->t;
3242   struct MeshPeerPath *p = info->path;
3243   size_t size_needed;
3244   uint32_t opt;
3245   int i;
3246
3247   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATE PATH sending...\n");
3248   size_needed =
3249       sizeof (struct GNUNET_MESH_ManipulatePath) +
3250       p->length * sizeof (struct GNUNET_PeerIdentity);
3251
3252   if (size < size_needed || NULL == buf)
3253   {
3254     GNUNET_break (0);
3255     return 0;
3256   }
3257   msg = (struct GNUNET_MESH_ManipulatePath *) buf;
3258   msg->header.size = htons (size_needed);
3259   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE);
3260   msg->tid = ntohl (t->id.tid);
3261
3262   opt = 0;
3263   if (GNUNET_YES == t->nobuffer)
3264     opt |= MESH_TUNNEL_OPT_NOBUFFER;
3265   msg->opt = htonl(opt);
3266   msg->reserved = 0;
3267
3268   peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
3269   for (i = 0; i < p->length; i++)
3270   {
3271     GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
3272   }
3273
3274   path_destroy (p);
3275   GNUNET_free (info);
3276
3277   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3278               "CREATE PATH (%u bytes long) sent!\n", size_needed);
3279   return size_needed;
3280 }
3281
3282
3283 /**
3284  * Fill the core buffer 
3285  *
3286  * @param cls closure (data itself)
3287  * @param size number of bytes available in buf
3288  * @param buf where the callee should write the message
3289  *
3290  * @return number of bytes written to buf
3291  */
3292 static size_t
3293 send_core_data_multicast (void *cls, size_t size, void *buf)
3294 {
3295   struct MeshTransmissionDescriptor *info = cls;
3296   size_t total_size;
3297
3298   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Multicast callback.\n");
3299   GNUNET_assert (NULL != info);
3300   GNUNET_assert (NULL != info->peer);
3301   total_size = info->mesh_data->data_len;
3302   GNUNET_assert (total_size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
3303
3304   if (total_size > size)
3305   {
3306     GNUNET_break (0);
3307     return 0;
3308   }
3309   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " copying data...\n");
3310   memcpy (buf, info->mesh_data->data, total_size);
3311 #if MESH_DEBUG
3312   {
3313     struct GNUNET_MessageHeader *mh;
3314
3315     mh = buf;
3316     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " type %s\n",
3317                 GNUNET_MESH_DEBUG_M2S (ntohs (mh->type)));
3318   }
3319 #endif
3320   data_descriptor_decrement_rc (info->mesh_data);
3321   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "freeing info...\n");
3322   GNUNET_free (info);
3323   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "return %u\n", total_size);
3324   return total_size;
3325 }
3326
3327
3328 /**
3329  * Creates a path ack message in buf and frees all unused resources.
3330  *
3331  * @param cls closure (MeshTransmissionDescriptor)
3332  * @param size number of bytes available in buf
3333  * @param buf where the callee should write the message
3334  * @return number of bytes written to buf
3335  */
3336 static size_t
3337 send_core_path_ack (void *cls, size_t size, void *buf)
3338 {
3339   struct MeshTransmissionDescriptor *info = cls;
3340   struct GNUNET_MESH_PathACK *msg = buf;
3341
3342   GNUNET_assert (NULL != info);
3343   if (sizeof (struct GNUNET_MESH_PathACK) > size)
3344   {
3345     GNUNET_break (0);
3346     return 0;
3347   }
3348   msg->header.size = htons (sizeof (struct GNUNET_MESH_PathACK));
3349   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_ACK);
3350   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
3351   msg->tid = htonl (info->origin->tid);
3352   msg->peer_id = my_full_id;
3353
3354   GNUNET_free (info);
3355   /* TODO add signature */
3356
3357   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "PATH ACK sent!\n");
3358   return sizeof (struct GNUNET_MESH_PathACK);
3359 }
3360
3361
3362 /**
3363  * Free a transmission that was already queued with all resources
3364  * associated to the request.
3365  *
3366  * @param queue Queue handler to cancel.
3367  * @param clear_cls Is it necessary to free associated cls?
3368  */
3369 static void
3370 queue_destroy (struct MeshPeerQueue *queue, int clear_cls)
3371 {
3372   struct MeshTransmissionDescriptor *dd;
3373   struct MeshPathInfo *path_info;
3374 //   unsigned int max;
3375
3376   if (GNUNET_YES == clear_cls)
3377   {
3378     switch (queue->type)
3379     {
3380       case GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY:
3381         GNUNET_log (GNUNET_ERROR_TYPE_INFO, "   cancelling TUNNEL_DESTROY\n");
3382         GNUNET_break (GNUNET_YES == queue->tunnel->destroy);
3383         /* fall through */
3384       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
3385       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
3386       case GNUNET_MESSAGE_TYPE_MESH_ACK:
3387       case GNUNET_MESSAGE_TYPE_MESH_POLL:
3388       case GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE:
3389         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3390                     "   prebuilt message\n");
3391         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3392                     "   type %s\n",
3393                     GNUNET_MESH_DEBUG_M2S(queue->type));
3394         dd = queue->cls;
3395         data_descriptor_decrement_rc (dd->mesh_data);
3396         break;
3397       case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
3398         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   type create path\n");
3399         path_info = queue->cls;
3400         path_destroy (path_info->path);
3401         break;
3402       default:
3403         GNUNET_break (0);
3404         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3405                     "   type %s unknown!\n",
3406                     GNUNET_MESH_DEBUG_M2S(queue->type));
3407     }
3408     GNUNET_free_non_null (queue->cls);
3409   }
3410   GNUNET_CONTAINER_DLL_remove (queue->peer->queue_head,
3411                                queue->peer->queue_tail,
3412                                queue);
3413
3414   /* Delete from child_fc in the appropiate tunnel */
3415 //   max = queue->tunnel->fwd_queue_max;
3416 //   GNUNET_PEER_resolve (queue->peer->id, &id);
3417 //   if (NULL != cinfo)
3418 //   { FIXME
3419 //     for (i = 0; i < cinfo->send_buffer_n; i++)
3420 //     {
3421 //       i2 = (cinfo->send_buffer_start + i) % max;
3422 //       if (cinfo->send_buffer[i2] == queue)
3423 //       {
3424 //         /* Found corresponding entry in the send_buffer. Move all others back. */
3425 //         unsigned int j;
3426 // 
3427 // 
3428 //         for (j = i, j2 = 0, j3 = 0; j < cinfo->send_buffer_n - 1; j++)
3429 //         {
3430 //           j2 = (cinfo->send_buffer_start + j) % max;
3431 //           j3 = (cinfo->send_buffer_start + j + 1) % max;
3432 //           cinfo->send_buffer[j2] = cinfo->send_buffer[j3];
3433 //         }
3434 // 
3435 //         cinfo->send_buffer[j3] = NULL;
3436 //         cinfo->send_buffer_n--;
3437 //       }
3438 //     }
3439 //   }
3440
3441   GNUNET_free (queue);
3442 }
3443
3444
3445 /**
3446  * @brief Get the next transmittable message from the queue.
3447  *
3448  * This will be the head, except in the case of being a data packet
3449  * not allowed by the destination peer.
3450  *
3451  * @param peer Destination peer.
3452  *
3453  * @return The next viable MeshPeerQueue element to send to that peer.
3454  *         NULL when there are no transmittable messages.
3455  */
3456 struct MeshPeerQueue *
3457 queue_get_next (const struct MeshPeerInfo *peer)
3458 {
3459   struct MeshPeerQueue *q;
3460  
3461   struct MeshTransmissionDescriptor *info;
3462 //   struct GNUNET_MESH_Unicast *ucast;
3463 //   struct GNUNET_MESH_ToOrigin *to_orig;
3464   struct GNUNET_PeerIdentity id;
3465 //   uint32_t pid;
3466 //   uint32_t ack; FIXME
3467
3468   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   selecting message\n");
3469   for (q = peer->queue_head; NULL != q; q = q->next)
3470   {
3471 //     t = q->tunnel;
3472     info = q->cls;
3473     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3474                 "*********     %s\n",
3475                 GNUNET_MESH_DEBUG_M2S(q->type));
3476     switch (q->type)
3477     {
3478       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
3479 //         ucast = (struct GNUNET_MESH_Unicast *) info->mesh_data->data;
3480 //         pid = ntohl (ucast->pid);
3481         GNUNET_PEER_resolve (info->peer->id, &id);
3482 //         ack = cinfo->fwd_ack;
3483         break;
3484       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
3485 //         to_orig = (struct GNUNET_MESH_ToOrigin *) info->mesh_data->data;
3486 //         pid = ntohl (to_orig->pid);
3487 //         ack = t->bck_ack;
3488         break;
3489       default:
3490         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3491                     "*********   OK!\n");
3492         return q;
3493     }
3494 //     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3495 //                 "*********     ACK: %u, PID: %u\n",
3496 //                 ack, pid);
3497 //     if (GNUNET_NO == GMC_is_pid_bigger(pid, ack))
3498 //     {
3499 //       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3500 //                   "*********   OK!\n");
3501 //       return q;
3502 //     }
3503 //     else
3504 //     {
3505 //       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3506 //                   "*********     NEXT!\n");
3507 //     }
3508   }
3509   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3510                 "*********   nothing found\n");
3511   return NULL;
3512 }
3513
3514
3515 static size_t
3516 queue_send (void *cls, size_t size, void *buf)
3517 {
3518     struct MeshPeerInfo *peer = cls;
3519     struct GNUNET_MessageHeader *msg;
3520     struct MeshPeerQueue *queue;
3521     struct MeshTunnel *t;
3522     struct GNUNET_PeerIdentity dst_id;
3523     size_t data_size;
3524
3525     peer->core_transmit = NULL;
3526
3527     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "********* Queue send\n");
3528     queue = queue_get_next (peer);
3529
3530     /* Queue has no internal mesh traffic nor sendable payload */
3531     if (NULL == queue)
3532     {
3533       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   not ready, return\n");
3534       if (NULL == peer->queue_head)
3535         GNUNET_break (0); // Should've been canceled
3536       return 0;
3537     }
3538     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   not empty\n");
3539
3540     GNUNET_PEER_resolve (peer->id, &dst_id);
3541     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3542                 "*********   towards %s\n",
3543                 GNUNET_i2s(&dst_id));
3544     /* Check if buffer size is enough for the message */
3545     if (queue->size > size)
3546     {
3547         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3548                     "*********   not enough room, reissue\n");
3549         peer->core_transmit =
3550             GNUNET_CORE_notify_transmit_ready (core_handle,
3551                                                0,
3552                                                0,
3553                                                GNUNET_TIME_UNIT_FOREVER_REL,
3554                                                &dst_id,
3555                                                queue->size,
3556                                                &queue_send,
3557                                                peer);
3558         return 0;
3559     }
3560     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   size ok\n");
3561
3562     t = queue->tunnel;
3563     GNUNET_assert (0 < t->pending_messages);
3564     t->pending_messages--;
3565     if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == queue->type)
3566     {
3567       t->fwd_queue_n--;
3568       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3569                   "*********   unicast: t->q (%u/%u)\n",
3570                   t->fwd_queue_n, t->fwd_queue_max);
3571     }
3572     else if (GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == queue->type)
3573     {
3574       t->bck_queue_n--;
3575       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   to origin\n");
3576     }
3577
3578     /* Fill buf */
3579     switch (queue->type)
3580     {
3581       case 0:
3582       case GNUNET_MESSAGE_TYPE_MESH_ACK:
3583       case GNUNET_MESSAGE_TYPE_MESH_POLL:
3584       case GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN:
3585       case GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY:
3586       case GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY:
3587         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3588                     "*********   raw: %s\n",
3589                     GNUNET_MESH_DEBUG_M2S (queue->type));
3590         /* Fall through */
3591       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
3592       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
3593         data_size = send_core_data_raw (queue->cls, size, buf);
3594         msg = (struct GNUNET_MessageHeader *) buf;
3595         switch (ntohs (msg->type)) // Type of preconstructed message
3596         {
3597           case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
3598             tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_UNICAST);
3599             break;
3600           case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
3601             tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
3602             break;
3603           default:
3604               break;
3605         }
3606         break;
3607       case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
3608         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path create\n");
3609         data_size = send_core_path_create (queue->cls, size, buf);
3610         break;
3611       case GNUNET_MESSAGE_TYPE_MESH_PATH_ACK:
3612         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path ack\n");
3613         data_size = send_core_path_ack (queue->cls, size, buf);
3614         break;
3615       case GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE:
3616         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path keepalive\n");
3617         data_size = send_core_data_multicast (queue->cls, size, buf);
3618         break;
3619       default:
3620         GNUNET_break (0);
3621         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3622                     "*********   type unknown: %u\n",
3623                     queue->type);
3624         data_size = 0;
3625     }
3626     switch (queue->type)
3627     {
3628       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
3629       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
3630 //         if (cinfo->send_buffer[cinfo->send_buffer_start] != queue)
3631 //         { FIXME
3632 //           GNUNET_break (0);
3633 //           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3634 //                       "at pos %u (%p) != %p\n",
3635 //                       cinfo->send_buffer_start,
3636 //                       cinfo->send_buffer[cinfo->send_buffer_start],
3637 //                       queue);
3638 //         }
3639 //         if (cinfo->send_buffer_n > 0)
3640 //         {
3641 //           cinfo->send_buffer[cinfo->send_buffer_start] = NULL;
3642 //           cinfo->send_buffer_n--;
3643 //           cinfo->send_buffer_start++;
3644 //           cinfo->send_buffer_start %= t->fwd_queue_max;
3645 //         }
3646 //         else
3647 //         {
3648 //           GNUNET_break (0);
3649 //         }
3650         break;
3651       default:
3652         break;
3653     }
3654
3655     /* Free queue, but cls was freed by send_core_* */
3656     queue_destroy (queue, GNUNET_NO);
3657
3658     if (GNUNET_YES == t->destroy && 0 == t->pending_messages)
3659     {
3660       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********  destroying tunnel!\n");
3661       tunnel_destroy (t);
3662     }
3663
3664     /* If more data in queue, send next */
3665     queue = queue_get_next(peer);
3666     if (NULL != queue)
3667     {
3668         struct GNUNET_PeerIdentity id;
3669
3670         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   more data!\n");
3671         GNUNET_PEER_resolve (peer->id, &id);
3672         peer->core_transmit =
3673             GNUNET_CORE_notify_transmit_ready(core_handle,
3674                                               0,
3675                                               0,
3676                                               GNUNET_TIME_UNIT_FOREVER_REL,
3677                                               &id,
3678                                               queue->size,
3679                                               &queue_send,
3680                                               peer);
3681     }
3682     else
3683     {
3684       if (NULL != peer->queue_head)
3685       {
3686         GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3687                     "*********   %s stalled\n",
3688                     GNUNET_i2s(&my_full_id));
3689 //         if (NULL == cinfo) FIXME
3690 //           cinfo = tunnel_get_neighbor_fc (t, &dst_id);
3691 //         // FIXME unify bck/fwd structures, bck does not have cinfo right now
3692 //         if (NULL != cinfo && GNUNET_SCHEDULER_NO_TASK == cinfo->fc_poll)
3693 //         {
3694 //           cinfo->fc_poll = GNUNET_SCHEDULER_add_delayed (cinfo->fc_poll_time,
3695 //                                                          &tunnel_poll, cinfo);
3696 //         }
3697       }
3698     }
3699     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   return %d\n", data_size);
3700     return data_size;
3701 }
3702
3703
3704 /**
3705  * @brief Queue and pass message to core when possible.
3706  * 
3707  * If type is payload (UNICAST, TO_ORIGIN) checks for queue status and
3708  * accounts for it. In case the queue is full, the message is dropped and
3709  * a break issued.
3710  * 
3711  * Otherwise, message is treated as internal and allowed to go regardless of 
3712  * queue status.
3713  *
3714  * @param cls Closure (@c type dependant). It will be used by queue_send to
3715  *            build the message to be sent if not already prebuilt.
3716  * @param type Type of the message, 0 for a raw message.
3717  * @param size Size of the message.
3718  * @param dst Neighbor to send message to.
3719  * @param t Tunnel this message belongs to.
3720  */
3721 static void
3722 queue_add (void *cls, uint16_t type, size_t size,
3723            struct MeshPeerInfo *dst, struct MeshTunnel *t)
3724 {
3725   struct MeshPeerQueue *queue;
3726   struct GNUNET_PeerIdentity id;
3727   unsigned int *max;
3728   unsigned int *n;
3729
3730   n = NULL;
3731   if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == type)
3732   {
3733     n = &t->fwd_queue_n;
3734     max = &t->fwd_queue_max;
3735   }
3736   else if (GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == type)
3737   {
3738     n = &t->bck_queue_n;
3739     max = &t->bck_queue_max;
3740   }
3741   if (NULL != n)
3742   {
3743     if (*n >= *max)
3744     {
3745       GNUNET_break(0);
3746       GNUNET_STATISTICS_update(stats,
3747                                "# messages dropped (buffer full)",
3748                                1, GNUNET_NO);
3749       return; // Drop message
3750     }
3751     (*n)++;
3752   }
3753   queue = GNUNET_malloc (sizeof (struct MeshPeerQueue));
3754   queue->cls = cls;
3755   queue->type = type;
3756   queue->size = size;
3757   queue->peer = dst;
3758   queue->tunnel = t;
3759   GNUNET_CONTAINER_DLL_insert_tail (dst->queue_head, dst->queue_tail, queue);
3760   if (NULL == dst->core_transmit)
3761   {
3762     GNUNET_PEER_resolve (dst->id, &id);
3763     dst->core_transmit =
3764         GNUNET_CORE_notify_transmit_ready (core_handle,
3765                                            0,
3766                                            0,
3767                                            GNUNET_TIME_UNIT_FOREVER_REL,
3768                                            &id,
3769                                            size,
3770                                            &queue_send,
3771                                            dst);
3772   }
3773   t->pending_messages++;
3774 }
3775
3776
3777 /******************************************************************************/
3778 /********************      MESH NETWORK HANDLERS     **************************/
3779 /******************************************************************************/
3780
3781
3782 /**
3783  * Core handler for path creation
3784  *
3785  * @param cls closure
3786  * @param message message
3787  * @param peer peer identity this notification is about
3788  *
3789  * @return GNUNET_OK to keep the connection open,
3790  *         GNUNET_SYSERR to close it (signal serious error)
3791  */
3792 static int
3793 handle_mesh_path_create (void *cls, const struct GNUNET_PeerIdentity *peer,
3794                          const struct GNUNET_MessageHeader *message)
3795 {
3796   unsigned int own_pos;
3797   uint16_t size;
3798   uint16_t i;
3799   MESH_TunnelNumber tid;
3800   struct GNUNET_MESH_ManipulatePath *msg;
3801   struct GNUNET_PeerIdentity *pi;
3802   struct GNUNET_HashCode hash;
3803   struct MeshPeerPath *path;
3804   struct MeshPeerInfo *dest_peer_info;
3805   struct MeshPeerInfo *orig_peer_info;
3806   struct MeshTunnel *t;
3807
3808   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3809               "Received a path create msg [%s]\n",
3810               GNUNET_i2s (&my_full_id));
3811   size = ntohs (message->size);
3812   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
3813   {
3814     GNUNET_break_op (0);
3815     return GNUNET_OK;
3816   }
3817
3818   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
3819   if (size % sizeof (struct GNUNET_PeerIdentity))
3820   {
3821     GNUNET_break_op (0);
3822     return GNUNET_OK;
3823   }
3824   size /= sizeof (struct GNUNET_PeerIdentity);
3825   if (size < 2)
3826   {
3827     GNUNET_break_op (0);
3828     return GNUNET_OK;
3829   }
3830   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
3831   msg = (struct GNUNET_MESH_ManipulatePath *) message;
3832
3833   tid = ntohl (msg->tid);
3834   pi = (struct GNUNET_PeerIdentity *) &msg[1];
3835   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3836               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi), tid);
3837   t = tunnel_get (pi, tid);
3838   if (NULL == t) // FIXME only for INCOMING tunnels?
3839   {
3840     uint32_t opt;
3841
3842     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating tunnel\n");
3843     t = tunnel_new (GNUNET_PEER_intern (pi), tid, NULL, 0);
3844     if (NULL == t)
3845     {
3846       // FIXME notify failure
3847       return GNUNET_OK;
3848     }
3849     opt = ntohl (msg->opt);
3850     if (0 != (opt & MESH_TUNNEL_OPT_NOBUFFER))
3851     {
3852       t->nobuffer = GNUNET_YES;
3853       t->last_fwd_ack = t->fwd_pid + 1;
3854     }
3855     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  nobuffer:%d\n", t->nobuffer);
3856
3857     if (GNUNET_YES == t->nobuffer)
3858     {
3859       t->bck_queue_max = 1;
3860       t->fwd_queue_max = 1;
3861     }
3862
3863     // FIXME only assign a local tid if a local client is interested (on demand)
3864     while (NULL != tunnel_get_incoming (next_local_tid))
3865       next_local_tid = (next_local_tid + 1) | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
3866     t->local_tid_dest = next_local_tid++;
3867     next_local_tid = next_local_tid | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
3868     // FIXME end
3869
3870     tunnel_reset_timeout (t);
3871     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
3872     if (GNUNET_OK !=
3873         GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
3874                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
3875     {
3876       tunnel_destroy (t);
3877       GNUNET_break (0);
3878       return GNUNET_OK;
3879     }
3880   }
3881   dest_peer_info =
3882       GNUNET_CONTAINER_multihashmap_get (peers, &pi[size - 1].hashPubKey);
3883   if (NULL == dest_peer_info)
3884   {
3885     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3886                 "  Creating PeerInfo for destination.\n");
3887     dest_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
3888     dest_peer_info->id = GNUNET_PEER_intern (&pi[size - 1]);
3889     GNUNET_CONTAINER_multihashmap_put (peers, &pi[size - 1].hashPubKey,
3890                                        dest_peer_info,
3891                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3892   }
3893   orig_peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &pi->hashPubKey);
3894   if (NULL == orig_peer_info)
3895   {
3896     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3897                 "  Creating PeerInfo for origin.\n");
3898     orig_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
3899     orig_peer_info->id = GNUNET_PEER_intern (pi);
3900     GNUNET_CONTAINER_multihashmap_put (peers, &pi->hashPubKey, orig_peer_info,
3901                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3902   }
3903   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
3904   path = path_new (size);
3905   own_pos = 0;
3906   for (i = 0; i < size; i++)
3907   {
3908     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
3909                 GNUNET_i2s (&pi[i]));
3910     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
3911     if (path->peers[i] == myid)
3912       own_pos = i;
3913   }
3914   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
3915   if (own_pos == 0)
3916   {
3917     /* cannot be self, must be 'not found' */
3918     /* create path: self not found in path through self */
3919     GNUNET_break_op (0);
3920     path_destroy (path);
3921     tunnel_destroy (t);
3922     return GNUNET_OK;
3923   }
3924   path_add_to_peers (path, GNUNET_NO);
3925   t->prev_hop = path->peers[own_pos - 1];
3926   GNUNET_PEER_change_rc (t->prev_hop, 1);
3927   if (own_pos == size - 1)
3928   {
3929     /* It is for us! Send ack. */
3930     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
3931     peer_info_add_path_to_origin (orig_peer_info, path, GNUNET_NO);
3932     t->peer = path->peers[0];
3933     send_path_ack (t);
3934   }
3935   else
3936   {
3937     struct MeshPeerPath *path2;
3938
3939     t->next_hop = path->peers[own_pos + 1];
3940     GNUNET_PEER_change_rc(t->next_hop, 1);
3941
3942     /* It's for somebody else! Retransmit. */
3943     path2 = path_duplicate (path);
3944     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Retransmitting.\n");
3945     peer_info_add_path (dest_peer_info, path2, GNUNET_NO);
3946     path2 = path_duplicate (path);
3947     peer_info_add_path_to_origin (orig_peer_info, path2, GNUNET_NO);
3948     send_create_path (dest_peer_info, path, t);
3949   }
3950   return GNUNET_OK;
3951 }
3952
3953
3954 /**
3955  * Core handler for path destruction
3956  *
3957  * @param cls closure
3958  * @param message message
3959  * @param peer peer identity this notification is about
3960  *
3961  * @return GNUNET_OK to keep the connection open,
3962  *         GNUNET_SYSERR to close it (signal serious error)
3963  */
3964 static int
3965 handle_mesh_path_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
3966                           const struct GNUNET_MessageHeader *message)
3967 {
3968   struct GNUNET_MESH_ManipulatePath *msg;
3969   struct GNUNET_PeerIdentity *pi;
3970   struct MeshPeerPath *path;
3971   struct MeshTunnel *t;
3972   unsigned int own_pos;
3973   unsigned int i;
3974   size_t size;
3975
3976   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3977               "Received a PATH DESTROY msg from %s\n", GNUNET_i2s (peer));
3978   size = ntohs (message->size);
3979   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
3980   {
3981     GNUNET_break_op (0);
3982     return GNUNET_OK;
3983   }
3984
3985   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
3986   if (size % sizeof (struct GNUNET_PeerIdentity))
3987   {
3988     GNUNET_break_op (0);
3989     return GNUNET_OK;
3990   }
3991   size /= sizeof (struct GNUNET_PeerIdentity);
3992   if (size < 2)
3993   {
3994     GNUNET_break_op (0);
3995     return GNUNET_OK;
3996   }
3997   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
3998
3999   msg = (struct GNUNET_MESH_ManipulatePath *) message;
4000   pi = (struct GNUNET_PeerIdentity *) &msg[1];
4001   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4002               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi),
4003               msg->tid);
4004   t = tunnel_get (pi, ntohl (msg->tid));
4005   if (NULL == t)
4006   {
4007     /* TODO notify back: we don't know this tunnel */
4008     GNUNET_break_op (0);
4009     return GNUNET_OK;
4010   }
4011   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
4012   path = path_new (size);
4013   own_pos = 0;
4014   for (i = 0; i < size; i++)
4015   {
4016     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
4017                 GNUNET_i2s (&pi[i]));
4018     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
4019     if (path->peers[i] == myid)
4020       own_pos = i;
4021   }
4022   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
4023   if (own_pos < path->length - 1)
4024     send_prebuilt_message (message, &pi[own_pos + 1], t);
4025   else
4026     send_client_tunnel_disconnect(t, NULL);
4027
4028 //   tunnel_delete_peer (t, path->peers[path->length - 1]); FIXME
4029   path_destroy (path);
4030   return GNUNET_OK;
4031 }
4032
4033
4034 /**
4035  * Core handler for notifications of broken paths
4036  *
4037  * @param cls closure
4038  * @param message message
4039  * @param peer peer identity this notification is about
4040  *
4041  * @return GNUNET_OK to keep the connection open,
4042  *         GNUNET_SYSERR to close it (signal serious error)
4043  */
4044 static int
4045 handle_mesh_path_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
4046                          const struct GNUNET_MessageHeader *message)
4047 {
4048   struct GNUNET_MESH_PathBroken *msg;
4049   struct MeshTunnel *t;
4050
4051   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4052               "Received a PATH BROKEN msg from %s\n", GNUNET_i2s (peer));
4053   msg = (struct GNUNET_MESH_PathBroken *) message;
4054   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
4055               GNUNET_i2s (&msg->peer1));
4056   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
4057               GNUNET_i2s (&msg->peer2));
4058   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4059   if (NULL == t)
4060   {
4061     GNUNET_break_op (0);
4062     return GNUNET_OK;
4063   }
4064   tunnel_notify_connection_broken (t, GNUNET_PEER_search (&msg->peer1),
4065                                    GNUNET_PEER_search (&msg->peer2));
4066   return GNUNET_OK;
4067
4068 }
4069
4070
4071 /**
4072  * Core handler for tunnel destruction
4073  *
4074  * @param cls closure
4075  * @param message message
4076  * @param peer peer identity this notification is about
4077  *
4078  * @return GNUNET_OK to keep the connection open,
4079  *         GNUNET_SYSERR to close it (signal serious error)
4080  */
4081 static int
4082 handle_mesh_tunnel_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
4083                             const struct GNUNET_MessageHeader *message)
4084 {
4085   struct GNUNET_MESH_TunnelDestroy *msg;
4086   struct MeshTunnel *t;
4087   GNUNET_PEER_Id pid;
4088
4089   msg = (struct GNUNET_MESH_TunnelDestroy *) message;
4090   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4091               "Got a TUNNEL DESTROY packet from %s\n",
4092               GNUNET_i2s (peer));
4093   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4094               "  for tunnel %s [%u]\n",
4095               GNUNET_i2s (&msg->oid), ntohl (msg->tid));
4096   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4097   /* Check signature */
4098   if (NULL == t)
4099   {
4100     /* Probably already got the message from another path,
4101      * destroyed the tunnel and retransmitted to children.
4102      * Safe to ignore.
4103      */
4104     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel",
4105                               1, GNUNET_NO);
4106     return GNUNET_OK;
4107   }
4108   pid = GNUNET_PEER_search (peer);
4109   if (pid != t->prev_hop && 0 < t->nclients)
4110   {
4111     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4112                 "still in use by %u clients\n",
4113                 t->nclients);
4114     return GNUNET_OK;
4115   }
4116   if (t->local_tid_dest >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
4117   {
4118     /* Tunnel was incoming, notify clients */
4119     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "INCOMING TUNNEL %X %X\n",
4120                 t->local_tid, t->local_tid_dest);
4121     send_clients_tunnel_destroy (t);
4122   }
4123   tunnel_send_destroy (t);
4124   t->destroy = GNUNET_YES;
4125   // TODO: add timeout to destroy the tunnel anyway
4126   return GNUNET_OK;
4127 }
4128
4129
4130 /**
4131  * Core handler for mesh network traffic going from the origin to a peer
4132  *
4133  * @param cls closure
4134  * @param peer peer identity this notification is about
4135  * @param message message
4136  * @return GNUNET_OK to keep the connection open,
4137  *         GNUNET_SYSERR to close it (signal serious error)
4138  */
4139 static int
4140 handle_mesh_data_unicast (void *cls, const struct GNUNET_PeerIdentity *peer,
4141                           const struct GNUNET_MessageHeader *message)
4142 {
4143   struct GNUNET_MESH_Unicast *msg;
4144   struct GNUNET_PeerIdentity neighbor;
4145   struct MeshTunnel *t;
4146   GNUNET_PEER_Id dest_id;
4147   uint32_t pid;
4148   uint32_t ttl;
4149   size_t size;
4150
4151   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a unicast packet from %s\n",
4152               GNUNET_i2s (peer));
4153   /* Check size */
4154   size = ntohs (message->size);
4155   if (size <
4156       sizeof (struct GNUNET_MESH_Unicast) +
4157       sizeof (struct GNUNET_MessageHeader))
4158   {
4159     GNUNET_break (0);
4160     return GNUNET_OK;
4161   }
4162   msg = (struct GNUNET_MESH_Unicast *) message;
4163   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %s\n",
4164               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
4165   /* Check tunnel */
4166   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4167   if (NULL == t)
4168   {
4169     /* TODO notify back: we don't know this tunnel */
4170     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
4171     GNUNET_break_op (0);
4172     return GNUNET_OK;
4173   }
4174   pid = ntohl (msg->pid);
4175   if (t->fwd_pid == pid)
4176   {
4177     GNUNET_STATISTICS_update (stats, "# duplicate PID drops", 1, GNUNET_NO);
4178     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4179                 " Already seen pid %u, DROPPING!\n", pid);
4180     return GNUNET_OK;
4181   }
4182   else
4183   {
4184     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4185                 " pid %u not seen yet, forwarding\n", pid);
4186   }
4187
4188   t->fwd_pid = pid;
4189
4190   if (GMC_is_pid_bigger (pid, t->last_fwd_ack))
4191   {
4192     GNUNET_STATISTICS_update (stats, "# unsolicited unicast", 1, GNUNET_NO);
4193     GNUNET_break_op (0);
4194     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4195                 "Received PID %u, ACK %u\n",
4196                 pid, t->last_fwd_ack);
4197     return GNUNET_OK;
4198   }
4199
4200   tunnel_reset_timeout (t);
4201   dest_id = t->peer;
4202   if (dest_id == myid)
4203   {
4204     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4205                 "  it's for us! sending to clients...\n");
4206     GNUNET_STATISTICS_update (stats, "# unicast received", 1, GNUNET_NO);
4207     send_subscribed_clients (message, &msg[1].header, t);
4208     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_UNICAST);
4209     return GNUNET_OK;
4210   }
4211   ttl = ntohl (msg->ttl);
4212   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ttl);
4213   if (ttl == 0)
4214   {
4215     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
4216     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
4217     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
4218     return GNUNET_OK;
4219   }
4220   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4221               "  not for us, retransmitting...\n");
4222
4223   GNUNET_PEER_resolve (t->next_hop, &neighbor);
4224
4225 /*   cinfo->fwd_pid = pid; FIXME
4226
4227   if (GNUNET_YES == t->nobuffer &&
4228       GNUNET_YES == GMC_is_pid_bigger (pid, cinfo->fwd_ack))
4229   {
4230     GNUNET_STATISTICS_update (stats, "# unsolicited unicast", 1, GNUNET_NO);
4231     GNUNET_log (GNUNET_ERROR_TYPE_INFO, "  %u > %u\n", pid, cinfo->fwd_ack);
4232     GNUNET_break_op (0);
4233     return GNUNET_OK;
4234   }*/
4235   send_prebuilt_message (message, &neighbor, t);
4236   GNUNET_STATISTICS_update (stats, "# unicast forwarded", 1, GNUNET_NO);
4237   return GNUNET_OK;
4238 }
4239
4240
4241 /**
4242  * Core handler for mesh network traffic toward the owner of a tunnel
4243  *
4244  * @param cls closure
4245  * @param message message
4246  * @param peer peer identity this notification is about
4247  *
4248  * @return GNUNET_OK to keep the connection open,
4249  *         GNUNET_SYSERR to close it (signal serious error)
4250  */
4251 static int
4252 handle_mesh_data_to_orig (void *cls, const struct GNUNET_PeerIdentity *peer,
4253                           const struct GNUNET_MessageHeader *message)
4254 {
4255   struct GNUNET_MESH_ToOrigin *msg;
4256   struct GNUNET_PeerIdentity id;
4257   struct MeshPeerInfo *peer_info;
4258   struct MeshTunnel *t;
4259   size_t size;
4260   uint32_t pid;
4261
4262   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a ToOrigin packet from %s\n",
4263               GNUNET_i2s (peer));
4264   size = ntohs (message->size);
4265   if (size < sizeof (struct GNUNET_MESH_ToOrigin) +     /* Payload must be */
4266       sizeof (struct GNUNET_MessageHeader))     /* at least a header */
4267   {
4268     GNUNET_break_op (0);
4269     return GNUNET_OK;
4270   }
4271   msg = (struct GNUNET_MESH_ToOrigin *) message;
4272   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %s\n",
4273               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
4274   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4275   pid = ntohl (msg->pid);
4276
4277   if (NULL == t)
4278   {
4279     /* TODO notify that we dont know this tunnel (whom)? */
4280     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
4281     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4282                 "Received to_origin with PID %u on unknown tunnel %s [%u]\n",
4283                 pid, GNUNET_i2s (&msg->oid), ntohl (msg->tid));
4284     return GNUNET_OK;
4285   }
4286
4287
4288 //   if (cinfo->bck_pid == pid) FIXME
4289 //   {
4290 //     /* already seen this packet, drop */
4291 //     GNUNET_STATISTICS_update (stats, "# duplicate PID drops BCK", 1, GNUNET_NO);
4292 //     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4293 //                 " Already seen pid %u, DROPPING!\n", pid);
4294 //     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
4295 //     return GNUNET_OK;
4296 //   }
4297
4298   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4299               " pid %u not seen yet, forwarding\n", pid);
4300 //   cinfo->bck_pid = pid; FIXME
4301
4302   if (NULL != t->owner)
4303   {
4304     char cbuf[size];
4305     struct GNUNET_MESH_ToOrigin *copy;
4306
4307     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4308                 "  it's for us! sending to clients...\n");
4309     /* TODO signature verification */
4310     memcpy (cbuf, message, size);
4311     copy = (struct GNUNET_MESH_ToOrigin *) cbuf;
4312     copy->tid = htonl (t->local_tid);
4313     t->bck_pid++;
4314     copy->pid = htonl (t->bck_pid);
4315     GNUNET_STATISTICS_update (stats, "# to origin received", 1, GNUNET_NO);
4316     GNUNET_SERVER_notification_context_unicast (nc, t->owner->handle,
4317                                                 &copy->header, GNUNET_NO);
4318     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
4319     return GNUNET_OK;
4320   }
4321   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4322               "  not for us, retransmitting...\n");
4323
4324   peer_info = peer_get (&msg->oid);
4325   if (NULL == peer_info)
4326   {
4327     /* unknown origin of tunnel */
4328     GNUNET_break (0);
4329     return GNUNET_OK;
4330   }
4331   if (0 == t->prev_hop)
4332   {
4333     if (GNUNET_YES == t->destroy)
4334     {
4335       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4336                   "to orig received on a dying tunnel %s [%X]\n",
4337                   GNUNET_i2s (&msg->oid), ntohl(msg->tid));
4338       return GNUNET_OK;
4339     }
4340     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
4341                 "unknown to origin at %s\n",
4342                 GNUNET_i2s (&my_full_id));
4343     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
4344                 "from peer %s\n",
4345                 GNUNET_i2s (peer));
4346     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
4347                 "for tunnel %s [%X]\n",
4348                 GNUNET_i2s (&msg->oid), ntohl(msg->tid));
4349     return GNUNET_OK;
4350   }
4351   GNUNET_PEER_resolve (t->prev_hop, &id);
4352   send_prebuilt_message (message, &id, t);
4353   GNUNET_STATISTICS_update (stats, "# to origin forwarded", 1, GNUNET_NO);
4354
4355   return GNUNET_OK;
4356 }
4357
4358
4359 /**
4360  * Core handler for mesh network traffic point-to-point acks.
4361  *
4362  * @param cls closure
4363  * @param message message
4364  * @param peer peer identity this notification is about
4365  *
4366  * @return GNUNET_OK to keep the connection open,
4367  *         GNUNET_SYSERR to close it (signal serious error)
4368  */
4369 static int
4370 handle_mesh_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
4371                  const struct GNUNET_MessageHeader *message)
4372 {
4373   struct GNUNET_MESH_ACK *msg;
4374   struct MeshTunnel *t;
4375   uint32_t ack;
4376
4377   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK packet from %s!\n",
4378               GNUNET_i2s (peer));
4379   msg = (struct GNUNET_MESH_ACK *) message;
4380
4381   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4382
4383   if (NULL == t)
4384   {
4385     /* TODO notify that we dont know this tunnel (whom)? */
4386     GNUNET_STATISTICS_update (stats, "# ack on unknown tunnel", 1, GNUNET_NO);
4387     return GNUNET_OK;
4388   }
4389   ack = ntohl (msg->pid);
4390   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ACK %u\n", ack);
4391
4392   /* Is this a forward or backward ACK? */
4393   if (t->prev_hop != GNUNET_PEER_search(peer))
4394   {
4395
4396     debug_bck_ack++;
4397     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
4398 //     cinfo->fwd_ack = ack; FIXME
4399     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
4400     peer_unlock_queue (t->next_hop);
4401 //     if (GNUNET_SCHEDULER_NO_TASK != cinfo->fc_poll) FIXME
4402 //     {
4403 //       GNUNET_SCHEDULER_cancel (cinfo->fc_poll);
4404 //       cinfo->fc_poll = GNUNET_SCHEDULER_NO_TASK;
4405 //       cinfo->fc_poll_time = GNUNET_TIME_UNIT_SECONDS;
4406 //     }
4407   }
4408   else
4409   {
4410     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
4411     t->bck_ack = ack;
4412     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
4413     peer_unlock_queue (t->prev_hop);
4414   }
4415   return GNUNET_OK;
4416 }
4417
4418
4419 /**
4420  * Core handler for mesh network traffic point-to-point ack polls.
4421  *
4422  * @param cls closure
4423  * @param message message
4424  * @param peer peer identity this notification is about
4425  *
4426  * @return GNUNET_OK to keep the connection open,
4427  *         GNUNET_SYSERR to close it (signal serious error)
4428  */
4429 static int
4430 handle_mesh_poll (void *cls, const struct GNUNET_PeerIdentity *peer,
4431                   const struct GNUNET_MessageHeader *message)
4432 {
4433   struct GNUNET_MESH_Poll *msg;
4434   struct MeshTunnel *t;
4435
4436   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an POLL packet from %s!\n",
4437               GNUNET_i2s (peer));
4438
4439   msg = (struct GNUNET_MESH_Poll *) message;
4440
4441   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4442
4443   if (NULL == t)
4444   {
4445     /* TODO notify that we dont know this tunnel (whom)? */
4446     GNUNET_STATISTICS_update (stats, "# poll on unknown tunnel", 1, GNUNET_NO);
4447     GNUNET_break_op (0);
4448     return GNUNET_OK;
4449   }
4450
4451   /* Is this a forward or backward ACK? */
4452   if (t->prev_hop != GNUNET_PEER_search(peer))
4453   {
4454     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  from FWD\n");
4455     /* FIXME cinfo->bck_ack = cinfo->fwd_pid; // mark as ready to send */
4456     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_POLL);
4457   }
4458   else
4459   {
4460     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  from BCK\n");
4461     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_POLL);
4462   }
4463
4464   return GNUNET_OK;
4465 }
4466
4467 /**
4468  * Core handler for path ACKs
4469  *
4470  * @param cls closure
4471  * @param message message
4472  * @param peer peer identity this notification is about
4473  *
4474  * @return GNUNET_OK to keep the connection open,
4475  *         GNUNET_SYSERR to close it (signal serious error)
4476  */
4477 static int
4478 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
4479                       const struct GNUNET_MessageHeader *message)
4480 {
4481   struct GNUNET_MESH_PathACK *msg;
4482   struct GNUNET_PeerIdentity id;
4483   struct MeshPeerInfo *peer_info;
4484   struct MeshPeerPath *p;
4485   struct MeshTunnel *t;
4486
4487   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a path ACK msg [%s]\n",
4488               GNUNET_i2s (&my_full_id));
4489   msg = (struct GNUNET_MESH_PathACK *) message;
4490   t = tunnel_get (&msg->oid, ntohl(msg->tid));
4491   if (NULL == t)
4492   {
4493     /* TODO notify that we don't know the tunnel */
4494     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel", 1, GNUNET_NO);
4495     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  don't know the tunnel %s [%X]!\n",
4496                 GNUNET_i2s (&msg->oid), ntohl(msg->tid));
4497     return GNUNET_OK;
4498   }
4499   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %s [%X]\n",
4500               GNUNET_i2s (&msg->oid), ntohl(msg->tid));
4501
4502   peer_info = peer_get (&msg->peer_id);
4503   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by peer %s\n",
4504               GNUNET_i2s (&msg->peer_id));
4505   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  via peer %s\n",
4506               GNUNET_i2s (peer));
4507
4508   /* Add path to peers? */
4509   p = t->path;
4510   if (NULL != p)
4511   {
4512     path_add_to_peers (p, GNUNET_YES);
4513   }
4514   else
4515   {
4516     GNUNET_break (0);
4517   }
4518
4519   /* Message for us? */
4520   if (0 == memcmp (&msg->oid, &my_full_id, sizeof (struct GNUNET_PeerIdentity)))
4521   {
4522     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
4523     if (NULL == t->owner)
4524     {
4525       GNUNET_break_op (0);
4526       return GNUNET_OK;
4527     }
4528     if (NULL != peer_info->dhtget)
4529     {
4530       GNUNET_DHT_get_stop (peer_info->dhtget);
4531       peer_info->dhtget = NULL;
4532     }
4533     return GNUNET_OK;
4534   }
4535
4536   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4537               "  not for us, retransmitting...\n");
4538   GNUNET_PEER_resolve (t->prev_hop, &id);
4539   peer_info = peer_get (&msg->oid);
4540   send_prebuilt_message (message, &id, t);
4541   return GNUNET_OK;
4542 }
4543
4544
4545 /**
4546  * Core handler for mesh keepalives.
4547  *
4548  * @param cls closure
4549  * @param message message
4550  * @param peer peer identity this notification is about
4551  * @return GNUNET_OK to keep the connection open,
4552  *         GNUNET_SYSERR to close it (signal serious error)
4553  *
4554  * TODO: Check who we got this from, to validate route.
4555  */
4556 static int
4557 handle_mesh_keepalive (void *cls, const struct GNUNET_PeerIdentity *peer,
4558                        const struct GNUNET_MessageHeader *message)
4559 {
4560   struct GNUNET_MESH_TunnelKeepAlive *msg;
4561   struct MeshTunnel *t;
4562
4563   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a keepalive packet from %s\n",
4564               GNUNET_i2s (peer));
4565
4566   msg = (struct GNUNET_MESH_TunnelKeepAlive *) message;
4567   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4568
4569   if (NULL == t)
4570   {
4571     /* TODO notify that we dont know that tunnel */
4572     GNUNET_STATISTICS_update (stats, "# keepalive on unknown tunnel", 1,
4573                               GNUNET_NO);
4574     return GNUNET_OK;
4575   }
4576
4577   tunnel_reset_timeout (t);
4578
4579   GNUNET_STATISTICS_update (stats, "# keepalives forwarded", 1, GNUNET_NO);
4580   /* FIXME tunnel_send_multicast (t, message); */
4581   return GNUNET_OK;
4582   }
4583
4584
4585
4586 /**
4587  * Functions to handle messages from core
4588  */
4589 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
4590   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
4591   {&handle_mesh_path_destroy, GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY, 0},
4592   {&handle_mesh_path_broken, GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN,
4593    sizeof (struct GNUNET_MESH_PathBroken)},
4594   {&handle_mesh_tunnel_destroy, GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY,
4595    sizeof (struct GNUNET_MESH_TunnelDestroy)},
4596   {&handle_mesh_data_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
4597   {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE,
4598     sizeof (struct GNUNET_MESH_TunnelKeepAlive)},
4599   {&handle_mesh_data_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
4600   {&handle_mesh_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
4601     sizeof (struct GNUNET_MESH_ACK)},
4602   {&handle_mesh_poll, GNUNET_MESSAGE_TYPE_MESH_POLL,
4603     sizeof (struct GNUNET_MESH_Poll)},
4604   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
4605    sizeof (struct GNUNET_MESH_PathACK)},
4606   {NULL, 0, 0}
4607 };
4608
4609
4610
4611 /******************************************************************************/
4612 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
4613 /******************************************************************************/
4614
4615
4616 #if LATER
4617 /**
4618  * notify_client_connection_failure: notify a client that the connection to the
4619  * requested remote peer is not possible (for instance, no route found)
4620  * Function called when the socket is ready to queue more data. "buf" will be
4621  * NULL and "size" zero if the socket was closed for writing in the meantime.
4622  *
4623  * @param cls closure
4624  * @param size number of bytes available in buf
4625  * @param buf where the callee should write the message
4626  * @return number of bytes written to buf
4627  */
4628 static size_t
4629 notify_client_connection_failure (void *cls, size_t size, void *buf)
4630 {
4631   int size_needed;
4632   struct MeshPeerInfo *peer_info;
4633   struct GNUNET_MESH_PeerControl *msg;
4634   struct GNUNET_PeerIdentity id;
4635
4636   if (0 == size && NULL == buf)
4637   {
4638     // TODO retry? cancel?
4639     return 0;
4640   }
4641
4642   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
4643   peer_info = (struct MeshPeerInfo *) cls;
4644   msg = (struct GNUNET_MESH_PeerControl *) buf;
4645   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
4646   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
4647 //     msg->tunnel_id = htonl(peer_info->t->tid);
4648   GNUNET_PEER_resolve (peer_info->id, &id);
4649   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
4650
4651   return size_needed;
4652 }
4653 #endif
4654
4655
4656 /**
4657  * Send keepalive packets for a tunnel.
4658  *
4659  * @param cls Closure (tunnel for which to send the keepalive).
4660  * @param tc Notification context.
4661  */
4662 static void
4663 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4664 {
4665   struct MeshTunnel *t = cls;
4666   struct GNUNET_MESH_TunnelKeepAlive *msg;
4667   size_t size = sizeof (struct GNUNET_MESH_TunnelKeepAlive);
4668   char cbuf[size];
4669
4670   t->path_refresh_task = GNUNET_SCHEDULER_NO_TASK;
4671   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4672   {
4673     return;
4674   }
4675
4676   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4677               "sending keepalive for tunnel %d\n", t->id.tid);
4678
4679   msg = (struct GNUNET_MESH_TunnelKeepAlive *) cbuf;
4680   msg->header.size = htons (size);
4681   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE);
4682   msg->oid = my_full_id;
4683   msg->tid = htonl (t->id.tid);
4684   /* FIXME tunnel_send_multicast (t, &msg->header); */
4685
4686   t->path_refresh_task =
4687       GNUNET_SCHEDULER_add_delayed (refresh_path_time, &path_refresh, t);
4688   tunnel_reset_timeout(t);
4689 }
4690
4691
4692 /**
4693  * Function to process paths received for a new peer addition. The recorded
4694  * paths form the initial tunnel, which can be optimized later.
4695  * Called on each result obtained for the DHT search.
4696  *
4697  * @param cls closure
4698  * @param exp when will this value expire
4699  * @param key key of the result
4700  * @param get_path path of the get request
4701  * @param get_path_length lenght of get_path
4702  * @param put_path path of the put request
4703  * @param put_path_length length of the put_path
4704  * @param type type of the result
4705  * @param size number of bytes in data
4706  * @param data pointer to the result data
4707  *
4708  * TODO: re-issue the request after certain time? cancel after X results?
4709  */
4710 static void
4711 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
4712                     const struct GNUNET_HashCode * key,
4713                     const struct GNUNET_PeerIdentity *get_path,
4714                     unsigned int get_path_length,
4715                     const struct GNUNET_PeerIdentity *put_path,
4716                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
4717                     size_t size, const void *data)
4718 {
4719   struct MeshPathInfo *path_info = cls;
4720   struct MeshPeerPath *p;
4721   struct GNUNET_PeerIdentity pi;
4722   int i;
4723
4724   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
4725   GNUNET_PEER_resolve (path_info->peer->id, &pi);
4726   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", GNUNET_i2s (&pi));
4727
4728   p = path_build_from_dht (get_path, get_path_length,
4729                            put_path, put_path_length);
4730   path_add_to_peers (p, GNUNET_NO);
4731   path_destroy (p);
4732   for (i = 0; i < path_info->peer->ntunnels; i++)
4733   {
4734         peer_connect (path_info->peer, path_info->t);
4735   }
4736
4737   return;
4738 }
4739
4740
4741 /******************************************************************************/
4742 /*********************       MESH LOCAL HANDLES      **************************/
4743 /******************************************************************************/
4744
4745
4746 /**
4747  * Handler for client disconnection
4748  *
4749  * @param cls closure
4750  * @param client identification of the client; NULL
4751  *        for the last call when the server is destroyed
4752  */
4753 static void
4754 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
4755 {
4756   struct MeshClient *c;
4757   struct MeshClient *next;
4758
4759   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected\n");
4760   if (client == NULL)
4761   {
4762     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (SERVER DOWN)\n");
4763     return;
4764   }
4765
4766   c = clients_head;
4767   while (NULL != c)
4768   {
4769     if (c->handle != client)
4770     {
4771       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ... searching\n");
4772       c = c->next;
4773       continue;
4774     }
4775     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u)\n",
4776                 c->id);
4777     GNUNET_SERVER_client_drop (c->handle);
4778     c->shutting_down = GNUNET_YES;
4779     GNUNET_CONTAINER_multihashmap_iterate (c->own_tunnels,
4780                                            &tunnel_destroy_iterator, c);
4781     GNUNET_CONTAINER_multihashmap_iterate (c->incoming_tunnels,
4782                                            &tunnel_destroy_iterator, c);
4783     GNUNET_CONTAINER_multihashmap_iterate (c->ignore_tunnels,
4784                                            &tunnel_destroy_iterator, c);
4785     GNUNET_CONTAINER_multihashmap_destroy (c->own_tunnels);
4786     GNUNET_CONTAINER_multihashmap_destroy (c->incoming_tunnels);
4787     GNUNET_CONTAINER_multihashmap_destroy (c->ignore_tunnels);
4788
4789     if (NULL != c->types)
4790       GNUNET_CONTAINER_multihashmap_destroy (c->types);
4791     next = c->next;
4792     GNUNET_CONTAINER_DLL_remove (clients_head, clients_tail, c);
4793     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT FREE at %p\n", c);
4794     GNUNET_free (c);
4795     GNUNET_STATISTICS_update (stats, "# clients", -1, GNUNET_NO);
4796     c = next;
4797   }
4798   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "done!\n");
4799   return;
4800 }
4801
4802
4803 /**
4804  * Handler for new clients
4805  *
4806  * @param cls closure
4807  * @param client identification of the client
4808  * @param message the actual message, which includes messages the client wants
4809  */
4810 static void
4811 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
4812                          const struct GNUNET_MessageHeader *message)
4813 {
4814   struct GNUNET_MESH_ClientConnect *cc_msg;
4815   struct MeshClient *c;
4816   unsigned int size;
4817   uint16_t ntypes;
4818   uint16_t *t;
4819   uint16_t i;
4820
4821   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected\n");
4822
4823   /* Check data sanity */
4824   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
4825   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
4826   ntypes = ntohs (cc_msg->types);
4827   if (size != ntypes * sizeof (uint16_t))
4828   {
4829     GNUNET_break (0);
4830     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4831     return;
4832   }
4833
4834   /* Create new client structure */
4835   c = GNUNET_malloc (sizeof (struct MeshClient));
4836   c->id = next_client_id++; // overflow not important: just for debug
4837   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT NEW %u\n", c->id);
4838   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  client has %u types\n", ntypes);
4839   c->handle = client;
4840   GNUNET_SERVER_client_keep (client);
4841   if (ntypes > 0)
4842   {
4843     uint16_t u16;
4844     struct GNUNET_HashCode hc;
4845
4846     t = (uint16_t *) &cc_msg[1];
4847     c->types = GNUNET_CONTAINER_multihashmap_create (ntypes, GNUNET_NO);
4848     for (i = 0; i < ntypes; i++)
4849     {
4850       u16 = ntohs (t[i]);
4851       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    msg type: %u\n", u16);
4852       GNUNET_CRYPTO_hash (&u16, sizeof (u16), &hc); // FIXME pseudo hash
4853
4854       /* store in clients hashmap */
4855       GNUNET_CONTAINER_multihashmap_put (c->types, &hc, c,
4856                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
4857       /* store in global hashmap */
4858       GNUNET_CONTAINER_multihashmap_put (types, &hc, c,
4859                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
4860     }
4861   }
4862
4863   GNUNET_CONTAINER_DLL_insert (clients_head, clients_tail, c);
4864   c->own_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
4865   c->incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
4866   c->ignore_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
4867   GNUNET_SERVER_notification_context_add (nc, client);
4868   GNUNET_STATISTICS_update (stats, "# clients", 1, GNUNET_NO);
4869
4870   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4871   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
4872 }
4873
4874
4875 /**
4876  * Handler for requests of new tunnels
4877  *
4878  * @param cls Closure.
4879  * @param client Identification of the client.
4880  * @param message The actual message.
4881  */
4882 static void
4883 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
4884                             const struct GNUNET_MessageHeader *message)
4885 {
4886   struct GNUNET_MESH_TunnelMessage *t_msg;
4887   struct MeshPeerInfo *peer_info;
4888   struct MeshTunnel *t;
4889   struct MeshClient *c;
4890   MESH_TunnelNumber tid;
4891
4892   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel requested\n");
4893
4894   /* Sanity check for client registration */
4895   if (NULL == (c = client_get (client)))
4896   {
4897     GNUNET_break (0);
4898     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4899     return;
4900   }
4901   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
4902
4903   /* Message sanity check */
4904   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
4905   {
4906     GNUNET_break (0);
4907     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4908     return;
4909   }
4910
4911   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
4912   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  towards %s\n",
4913               GNUNET_i2s (&t_msg->peer));
4914   /* Sanity check for tunnel numbering */
4915   tid = ntohl (t_msg->tunnel_id);
4916   if (0 == (tid & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
4917   {
4918     GNUNET_break (0);
4919     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4920     return;
4921   }
4922   /* Sanity check for duplicate tunnel IDs */
4923   if (NULL != tunnel_get_by_local_id (c, tid))
4924   {
4925     GNUNET_break (0);
4926     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4927     return;
4928   }
4929
4930   while (NULL != tunnel_get_by_pi (myid, next_tid))
4931     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
4932   t = tunnel_new (myid, next_tid, c, tid);
4933   next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
4934   if (NULL == t)
4935   {
4936     GNUNET_break (0);
4937     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4938     return;
4939   }
4940   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED TUNNEL %s [%x] (%x)\n",
4941               GNUNET_i2s (&my_full_id), t->id.tid, t->local_tid);
4942
4943   peer_info = peer_get (&t_msg->peer);
4944   GNUNET_array_append (peer_info->tunnels, peer_info->ntunnels, t);
4945   peer_connect (peer_info, t);
4946   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4947   return;
4948 }
4949
4950
4951 /**
4952  * Handler for requests of deleting tunnels
4953  *
4954  * @param cls closure
4955  * @param client identification of the client
4956  * @param message the actual message
4957  */
4958 static void
4959 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
4960                              const struct GNUNET_MessageHeader *message)
4961 {
4962   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
4963   struct MeshClient *c;
4964   struct MeshTunnel *t;
4965   MESH_TunnelNumber tid;
4966
4967   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4968               "Got a DESTROY TUNNEL from client!\n");
4969
4970   /* Sanity check for client registration */
4971   if (NULL == (c = client_get (client)))
4972   {
4973     GNUNET_break (0);
4974     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4975     return;
4976   }
4977   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
4978
4979   /* Message sanity check */
4980   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
4981   {
4982     GNUNET_break (0);
4983     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4984     return;
4985   }
4986
4987   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
4988
4989   /* Retrieve tunnel */
4990   tid = ntohl (tunnel_msg->tunnel_id);
4991   t = tunnel_get_by_local_id(c, tid);
4992   if (NULL == t)
4993   {
4994     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
4995     GNUNET_break (0);
4996     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4997     return;
4998   }
4999   if (c != t->owner || tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
5000   {
5001     client_ignore_tunnel (c, t);
5002     tunnel_destroy_empty (t);
5003     GNUNET_SERVER_receive_done (client, GNUNET_OK);
5004     return;
5005   }
5006   send_client_tunnel_disconnect (t, c);
5007   client_delete_tunnel (c, t);
5008
5009   /* Don't try to ACK the client about the tunnel_destroy multicast packet */
5010   t->owner = NULL;
5011   tunnel_send_destroy (t);
5012   t->destroy = GNUNET_YES;
5013   /* The tunnel will be destroyed when the last message is transmitted. */
5014   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5015   return;
5016 }
5017
5018
5019 /**
5020  * Handler for requests of seeting tunnel's buffering policy.
5021  *
5022  * @param cls Closure (unused).
5023  * @param client Identification of the client.
5024  * @param message The actual message.
5025  */
5026 static void
5027 handle_local_tunnel_buffer (void *cls, struct GNUNET_SERVER_Client *client,
5028                             const struct GNUNET_MessageHeader *message)
5029 {
5030   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
5031   struct MeshClient *c;
5032   struct MeshTunnel *t;
5033   MESH_TunnelNumber tid;
5034
5035   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5036               "Got a BUFFER request from client!\n");
5037
5038   /* Sanity check for client registration */
5039   if (NULL == (c = client_get (client)))
5040   {
5041     GNUNET_break (0);
5042     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5043     return;
5044   }
5045   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
5046
5047   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
5048
5049   /* Retrieve tunnel */
5050   tid = ntohl (tunnel_msg->tunnel_id);
5051   t = tunnel_get_by_local_id(c, tid);
5052   if (NULL == t)
5053   {
5054     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
5055     GNUNET_break (0);
5056     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5057     return;
5058   }
5059
5060   switch (ntohs(message->type))
5061   {
5062       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER:
5063           t->nobuffer = GNUNET_NO;
5064           break;
5065       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER:
5066           t->nobuffer = GNUNET_YES;
5067           break;
5068       default:
5069           GNUNET_break (0);
5070   }
5071
5072   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5073 }
5074
5075
5076 /**
5077  * Handler for client traffic directed to one peer
5078  *
5079  * @param cls closure
5080  * @param client identification of the client
5081  * @param message the actual message
5082  */
5083 static void
5084 handle_local_unicast (void *cls, struct GNUNET_SERVER_Client *client,
5085                       const struct GNUNET_MessageHeader *message)
5086 {
5087   struct MeshClient *c;
5088   struct MeshTunnel *t;
5089   struct GNUNET_MESH_Unicast *data_msg;
5090   MESH_TunnelNumber tid;
5091   size_t size;
5092
5093   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5094               "Got a unicast request from a client!\n");
5095
5096   /* Sanity check for client registration */
5097   if (NULL == (c = client_get (client)))
5098   {
5099     GNUNET_break (0);
5100     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5101     return;
5102   }
5103   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
5104
5105   data_msg = (struct GNUNET_MESH_Unicast *) message;
5106
5107   /* Sanity check for message size */
5108   size = ntohs (message->size);
5109   if (sizeof (struct GNUNET_MESH_Unicast) +
5110       sizeof (struct GNUNET_MessageHeader) > size)
5111   {
5112     GNUNET_break (0);
5113     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5114     return;
5115   }
5116
5117   /* Tunnel exists? */
5118   tid = ntohl (data_msg->tid);
5119   t = tunnel_get_by_local_id (c, tid);
5120   if (NULL == t)
5121   {
5122     GNUNET_break (0);
5123     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5124     return;
5125   }
5126
5127   /*  Is it a local tunnel? Then, does client own the tunnel? */
5128   if (t->owner->handle != client)
5129   {
5130     GNUNET_break (0);
5131     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5132     return;
5133   }
5134
5135   /* PID should be as expected */
5136   if (ntohl (data_msg->pid) != t->fwd_pid + 1)
5137   {
5138     GNUNET_break (0);
5139     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5140               "Unicast PID, expected %u, got %u\n",
5141               t->fwd_pid + 1, ntohl (data_msg->pid));
5142     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5143     return;
5144   }
5145
5146   /* Ok, everything is correct, send the message
5147    * (pretend we got it from a mesh peer)
5148    */
5149   {
5150     /* Work around const limitation */
5151     char buf[ntohs (message->size)] GNUNET_ALIGN;
5152     struct GNUNET_MESH_Unicast *copy;
5153
5154     copy = (struct GNUNET_MESH_Unicast *) buf;
5155     memcpy (buf, data_msg, size);
5156     copy->oid = my_full_id;
5157     copy->tid = htonl (t->id.tid);
5158     copy->ttl = htonl (default_ttl);
5159     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5160                 "  calling generic handler...\n");
5161     handle_mesh_data_unicast (NULL, &my_full_id, &copy->header);
5162   }
5163   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "receive done OK\n");
5164   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5165
5166   return;
5167 }
5168
5169
5170 /**
5171  * Handler for client traffic directed to the origin
5172  *
5173  * @param cls closure
5174  * @param client identification of the client
5175  * @param message the actual message
5176  */
5177 static void
5178 handle_local_to_origin (void *cls, struct GNUNET_SERVER_Client *client,
5179                         const struct GNUNET_MessageHeader *message)
5180 {
5181   struct GNUNET_MESH_ToOrigin *data_msg;
5182   struct MeshTunnelClientInfo *clinfo;
5183   struct MeshClient *c;
5184   struct MeshTunnel *t;
5185   MESH_TunnelNumber tid;
5186   size_t size;
5187
5188   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5189               "Got a ToOrigin request from a client!\n");
5190   /* Sanity check for client registration */
5191   if (NULL == (c = client_get (client)))
5192   {
5193     GNUNET_break (0);
5194     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5195     return;
5196   }
5197   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
5198
5199   data_msg = (struct GNUNET_MESH_ToOrigin *) message;
5200
5201   /* Sanity check for message size */
5202   size = ntohs (message->size);
5203   if (sizeof (struct GNUNET_MESH_ToOrigin) +
5204       sizeof (struct GNUNET_MessageHeader) > size)
5205   {
5206     GNUNET_break (0);
5207     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5208     return;
5209   }
5210
5211   /* Tunnel exists? */
5212   tid = ntohl (data_msg->tid);
5213   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
5214   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
5215   {
5216     GNUNET_break (0);
5217     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5218     return;
5219   }
5220   t = tunnel_get_by_local_id (c, tid);
5221   if (NULL == t)
5222   {
5223     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
5224     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
5225     GNUNET_break (0);
5226     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5227     return;
5228   }
5229
5230   /*  It should be sent by someone who has this as incoming tunnel. */
5231   if (GNUNET_NO == client_knows_tunnel (c, t))
5232   {
5233     GNUNET_break (0);
5234     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5235     return;
5236   }
5237
5238   /* PID should be as expected */
5239   clinfo = tunnel_get_client_fc (t, c);
5240   if (ntohl (data_msg->pid) != clinfo->bck_pid + 1)
5241   {
5242     GNUNET_break (0);
5243     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5244                 "To Origin PID, expected %u, got %u\n",
5245                 clinfo->bck_pid + 1,
5246                 ntohl (data_msg->pid));
5247     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5248     return;
5249   }
5250   clinfo->bck_pid++;
5251
5252   /* Ok, everything is correct, send the message
5253    * (pretend we got it from a mesh peer)
5254    */
5255   {
5256     char buf[ntohs (message->size)] GNUNET_ALIGN;
5257     struct GNUNET_MESH_ToOrigin *copy;
5258
5259     /* Work around const limitation */
5260     copy = (struct GNUNET_MESH_ToOrigin *) buf;
5261     memcpy (buf, data_msg, size);
5262     GNUNET_PEER_resolve (t->id.oid, &copy->oid);
5263     copy->tid = htonl (t->id.tid);
5264     copy->ttl = htonl (default_ttl);
5265     copy->pid = htonl (t->bck_pid + 1);
5266
5267     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5268                 "  calling generic handler...\n");
5269     handle_mesh_data_to_orig (NULL, &my_full_id, &copy->header);
5270   }
5271   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5272
5273   return;
5274 }
5275
5276
5277 /**
5278  * Handler for client's ACKs for payload traffic.
5279  *
5280  * @param cls Closure (unused).
5281  * @param client Identification of the client.
5282  * @param message The actual message.
5283  */
5284 static void
5285 handle_local_ack (void *cls, struct GNUNET_SERVER_Client *client,
5286                   const struct GNUNET_MessageHeader *message)
5287 {
5288   struct GNUNET_MESH_LocalAck *msg;
5289   struct MeshTunnel *t;
5290   struct MeshClient *c;
5291   MESH_TunnelNumber tid;
5292   uint32_t ack;
5293
5294   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a local ACK\n");
5295   /* Sanity check for client registration */
5296   if (NULL == (c = client_get (client)))
5297   {
5298     GNUNET_break (0);
5299     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5300     return;
5301   }
5302   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
5303
5304   msg = (struct GNUNET_MESH_LocalAck *) message;
5305
5306   /* Tunnel exists? */
5307   tid = ntohl (msg->tunnel_id);
5308   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
5309   t = tunnel_get_by_local_id (c, tid);
5310   if (NULL == t)
5311   {
5312     GNUNET_break (0);
5313     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
5314     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
5315     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5316     return;
5317   }
5318
5319   ack = ntohl (msg->max_pid);
5320   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ack %u\n", ack);
5321
5322   /* Does client own tunnel? I.E: Is this an ACK for BCK traffic? */
5323   if (NULL != t->owner && t->owner->handle == client)
5324   {
5325     /* The client owns the tunnel, ACK is for data to_origin, send BCK ACK. */
5326     t->bck_ack = ack;
5327     tunnel_send_bck_ack(t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
5328   }
5329   else
5330   {
5331     /* The client doesn't own the tunnel, this ACK is for FWD traffic. */
5332     tunnel_set_client_fwd_ack (t, c, ack);
5333     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
5334   }
5335
5336   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5337
5338   return;
5339 }
5340
5341
5342
5343 /**
5344  * Iterator over all tunnels to send a monitoring client info about each tunnel.
5345  *
5346  * @param cls Closure (client handle).
5347  * @param key Key (hashed tunnel ID, unused).
5348  * @param value Tunnel info.
5349  *
5350  * @return GNUNET_YES, to keep iterating.
5351  */
5352 static int
5353 monitor_all_tunnels_iterator (void *cls,
5354                               const struct GNUNET_HashCode * key,
5355                               void *value)
5356 {
5357   struct GNUNET_SERVER_Client *client = cls;
5358   struct MeshTunnel *t = value;
5359   struct GNUNET_MESH_LocalMonitor *msg;
5360
5361   msg = GNUNET_malloc (sizeof(struct GNUNET_MESH_LocalMonitor));
5362   GNUNET_PEER_resolve(t->id.oid, &msg->owner);
5363   msg->tunnel_id = htonl (t->id.tid);
5364   msg->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
5365   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS);
5366   GNUNET_PEER_resolve (t->peer, &msg->destination);
5367
5368   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5369               "*  sending info about tunnel %s [%u]\n",
5370               GNUNET_i2s (&msg->owner), t->id.tid);
5371
5372   GNUNET_SERVER_notification_context_unicast (nc, client,
5373                                               &msg->header, GNUNET_NO);
5374   return GNUNET_YES;
5375 }
5376
5377
5378 /**
5379  * Handler for client's MONITOR request.
5380  *
5381  * @param cls Closure (unused).
5382  * @param client Identification of the client.
5383  * @param message The actual message.
5384  */
5385 static void
5386 handle_local_get_tunnels (void *cls, struct GNUNET_SERVER_Client *client,
5387                           const struct GNUNET_MessageHeader *message)
5388 {
5389   struct MeshClient *c;
5390
5391   /* Sanity check for client registration */
5392   if (NULL == (c = client_get (client)))
5393   {
5394     GNUNET_break (0);
5395     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5396     return;
5397   }
5398
5399   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5400               "Received get tunnels request from client %u\n",
5401               c->id);
5402   GNUNET_CONTAINER_multihashmap_iterate (tunnels,
5403                                          monitor_all_tunnels_iterator,
5404                                          client);
5405   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5406               "Get tunnels request from client %u completed\n",
5407               c->id);
5408   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5409 }
5410
5411
5412 /**
5413  * Handler for client's MONITOR_TUNNEL request.
5414  *
5415  * @param cls Closure (unused).
5416  * @param client Identification of the client.
5417  * @param message The actual message.
5418  */
5419 static void
5420 handle_local_show_tunnel (void *cls, struct GNUNET_SERVER_Client *client,
5421                           const struct GNUNET_MessageHeader *message)
5422 {
5423   const struct GNUNET_MESH_LocalMonitor *msg;
5424   struct GNUNET_MESH_LocalMonitor *resp;
5425   struct MeshClient *c;
5426   struct MeshTunnel *t;
5427
5428   /* Sanity check for client registration */
5429   if (NULL == (c = client_get (client)))
5430   {
5431     GNUNET_break (0);
5432     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5433     return;
5434   }
5435
5436   msg = (struct GNUNET_MESH_LocalMonitor *) message;
5437   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5438               "Received tunnel info request from client %u for tunnel %s[%X]\n",
5439               c->id,
5440               &msg->owner,
5441               ntohl (msg->tunnel_id));
5442   t = tunnel_get (&msg->owner, ntohl (msg->tunnel_id));
5443   if (NULL == t)
5444   {
5445     /* We don't know the tunnel FIXME */
5446     struct GNUNET_MESH_LocalMonitor warn;
5447
5448     warn = *msg;
5449     GNUNET_SERVER_notification_context_unicast (nc, client,
5450                                                 &warn.header,
5451                                                 GNUNET_NO);
5452     GNUNET_SERVER_receive_done (client, GNUNET_OK);
5453     return;
5454   }
5455
5456   /* Initialize context */
5457   resp = GNUNET_malloc (sizeof (struct GNUNET_MESH_LocalMonitor));
5458   *resp = *msg;
5459   GNUNET_PEER_resolve (t->peer, &resp->destination);
5460   resp->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
5461   GNUNET_SERVER_notification_context_unicast (nc, c->handle,
5462                                               &resp->header, GNUNET_NO);
5463   GNUNET_free (resp);
5464
5465   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5466               "Monitor tunnel request from client %u completed\n",
5467               c->id);
5468   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5469 }
5470
5471
5472 /**
5473  * Functions to handle messages from clients
5474  */
5475 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
5476   {&handle_local_new_client, NULL,
5477    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
5478   {&handle_local_tunnel_create, NULL,
5479    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
5480    sizeof (struct GNUNET_MESH_TunnelMessage)},
5481   {&handle_local_tunnel_destroy, NULL,
5482    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
5483    sizeof (struct GNUNET_MESH_TunnelMessage)},
5484   {&handle_local_tunnel_buffer, NULL,
5485    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER,
5486    sizeof (struct GNUNET_MESH_TunnelMessage)},
5487   {&handle_local_tunnel_buffer, NULL,
5488    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER,
5489    sizeof (struct GNUNET_MESH_TunnelMessage)},
5490   {&handle_local_unicast, NULL,
5491    GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
5492   {&handle_local_to_origin, NULL,
5493    GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
5494   {&handle_local_ack, NULL,
5495    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK,
5496    sizeof (struct GNUNET_MESH_LocalAck)},
5497   {&handle_local_get_tunnels, NULL,
5498    GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS,
5499    sizeof (struct GNUNET_MessageHeader)},
5500   {&handle_local_show_tunnel, NULL,
5501    GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNEL,
5502      sizeof (struct GNUNET_MESH_LocalMonitor)},
5503   {NULL, NULL, 0, 0}
5504 };
5505
5506
5507 /**
5508  * To be called on core init/fail.
5509  *
5510  * @param cls service closure
5511  * @param server handle to the server for this service
5512  * @param identity the public identity of this peer
5513  */
5514 static void
5515 core_init (void *cls, struct GNUNET_CORE_Handle *server,
5516            const struct GNUNET_PeerIdentity *identity)
5517 {
5518   static int i = 0;
5519   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
5520   core_handle = server;
5521   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)) ||
5522       NULL == server)
5523   {
5524     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
5525     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5526                 " core id %s\n",
5527                 GNUNET_i2s (identity));
5528     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5529                 " my id %s\n",
5530                 GNUNET_i2s (&my_full_id));
5531     GNUNET_SCHEDULER_shutdown (); // Try gracefully
5532     if (10 < i++)
5533       GNUNET_abort(); // Try harder
5534   }
5535   return;
5536 }
5537
5538
5539 /**
5540  * Method called whenever a given peer connects.
5541  *
5542  * @param cls closure
5543  * @param peer peer identity this notification is about
5544  */
5545 static void
5546 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer)
5547 {
5548   struct MeshPeerInfo *peer_info;
5549   struct MeshPeerPath *path;
5550
5551   DEBUG_CONN ("Peer connected\n");
5552   DEBUG_CONN ("     %s\n", GNUNET_i2s (&my_full_id));
5553   peer_info = peer_get (peer);
5554   if (myid == peer_info->id)
5555   {
5556     DEBUG_CONN ("     (self)\n");
5557     return;
5558   }
5559   else
5560   {
5561     DEBUG_CONN ("     %s\n", GNUNET_i2s (peer));
5562   }
5563   path = path_new (2);
5564   path->peers[0] = myid;
5565   path->peers[1] = peer_info->id;
5566   GNUNET_PEER_change_rc (myid, 1);
5567   GNUNET_PEER_change_rc (peer_info->id, 1);
5568   peer_info_add_path (peer_info, path, GNUNET_YES);
5569   GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
5570   return;
5571 }
5572
5573
5574 /**
5575  * Method called whenever a peer disconnects.
5576  *
5577  * @param cls closure
5578  * @param peer peer identity this notification is about
5579  */
5580 static void
5581 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
5582 {
5583   struct MeshPeerInfo *pi;
5584   struct MeshPeerQueue *q;
5585   struct MeshPeerQueue *n;
5586
5587   DEBUG_CONN ("Peer disconnected\n");
5588   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
5589   if (NULL == pi)
5590   {
5591     GNUNET_break (0);
5592     return;
5593   }
5594   q = pi->queue_head;
5595   while (NULL != q)
5596   {
5597       n = q->next;
5598       /* TODO try to reroute this traffic instead */
5599       queue_destroy(q, GNUNET_YES);
5600       q = n;
5601   }
5602   if (NULL != pi->core_transmit)
5603   {
5604     GNUNET_CORE_notify_transmit_ready_cancel(pi->core_transmit);
5605     pi->core_transmit = NULL;
5606   }
5607   peer_info_remove_path (pi, pi->id, myid);
5608   if (myid == pi->id)
5609   {
5610     DEBUG_CONN ("     (self)\n");
5611   }
5612   GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
5613   return;
5614 }
5615
5616
5617 /******************************************************************************/
5618 /************************      MAIN FUNCTIONS      ****************************/
5619 /******************************************************************************/
5620
5621 /**
5622  * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
5623  *
5624  * @param cls closure
5625  * @param key current key code
5626  * @param value value in the hash map
5627  * @return GNUNET_YES if we should continue to iterate,
5628  *         GNUNET_NO if not.
5629  */
5630 static int
5631 shutdown_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
5632 {
5633   struct MeshTunnel *t = value;
5634
5635   tunnel_destroy (t);
5636   return GNUNET_YES;
5637 }
5638
5639 /**
5640  * Iterator over peer hash map entries to destroy the tunnel during shutdown.
5641  *
5642  * @param cls closure
5643  * @param key current key code
5644  * @param value value in the hash map
5645  * @return GNUNET_YES if we should continue to iterate,
5646  *         GNUNET_NO if not.
5647  */
5648 static int
5649 shutdown_peer (void *cls, const struct GNUNET_HashCode * key, void *value)
5650 {
5651   struct MeshPeerInfo *p = value;
5652   struct MeshPeerQueue *q;
5653   struct MeshPeerQueue *n;
5654
5655   q = p->queue_head;
5656   while (NULL != q)
5657   {
5658       n = q->next;
5659       if (q->peer == p)
5660       {
5661         queue_destroy(q, GNUNET_YES);
5662       }
5663       q = n;
5664   }
5665   peer_info_destroy (p);
5666   return GNUNET_YES;
5667 }
5668
5669
5670 /**
5671  * Task run during shutdown.
5672  *
5673  * @param cls unused
5674  * @param tc unused
5675  */
5676 static void
5677 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
5678 {
5679   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
5680
5681   if (core_handle != NULL)
5682   {
5683     GNUNET_CORE_disconnect (core_handle);
5684     core_handle = NULL;
5685   }
5686   if (NULL != keygen)
5687   {
5688     GNUNET_CRYPTO_ecc_key_create_stop (keygen);
5689     keygen = NULL;
5690   }
5691   GNUNET_CONTAINER_multihashmap_iterate (tunnels, &shutdown_tunnel, NULL);
5692   GNUNET_CONTAINER_multihashmap_iterate (peers, &shutdown_peer, NULL);
5693   if (dht_handle != NULL)
5694   {
5695     GNUNET_DHT_disconnect (dht_handle);
5696     dht_handle = NULL;
5697   }
5698   if (nc != NULL)
5699   {
5700     GNUNET_SERVER_notification_context_destroy (nc);
5701     nc = NULL;
5702   }
5703   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
5704   {
5705     GNUNET_SCHEDULER_cancel (announce_id_task);
5706     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
5707   }
5708   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
5709 }
5710
5711
5712 /**
5713  * Callback for hostkey read/generation.
5714  *
5715  * @param cls Closure (Configuration handle).
5716  * @param pk The ECC private key.
5717  * @param emsg Error message, if any.
5718  */
5719 static void
5720 key_generation_cb (void *cls,
5721                    struct GNUNET_CRYPTO_EccPrivateKey *pk,
5722                    const char *emsg)
5723 {
5724   const struct GNUNET_CONFIGURATION_Handle *c = cls;
5725   struct MeshPeerInfo *peer;
5726   struct MeshPeerPath *p;
5727
5728   keygen = NULL;  
5729   if (NULL == pk)
5730   {
5731     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5732                 _("Mesh service could not access hostkey: %s. Exiting.\n"),
5733                 emsg);
5734     GNUNET_SCHEDULER_shutdown ();
5735     return;
5736   }
5737   my_private_key = pk;
5738   GNUNET_CRYPTO_ecc_key_get_public (my_private_key, &my_public_key);
5739   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
5740                       &my_full_id.hashPubKey);
5741   myid = GNUNET_PEER_intern (&my_full_id);
5742   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5743               "Mesh for peer [%s] starting\n",
5744               GNUNET_i2s(&my_full_id));
5745
5746   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
5747                                      NULL,      /* Closure passed to MESH functions */
5748                                      &core_init,        /* Call core_init once connected */
5749                                      &core_connect,     /* Handle connects */
5750                                      &core_disconnect,  /* remove peers on disconnects */
5751                                      NULL,      /* Don't notify about all incoming messages */
5752                                      GNUNET_NO, /* For header only in notification */
5753                                      NULL,      /* Don't notify about all outbound messages */
5754                                      GNUNET_NO, /* For header-only out notification */
5755                                      core_handlers);    /* Register these handlers */
5756   
5757   if (core_handle == NULL)
5758   {
5759     GNUNET_break (0);
5760     GNUNET_SCHEDULER_shutdown ();
5761     return;
5762   }
5763
5764   next_tid = 0;
5765   next_local_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
5766
5767
5768   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
5769   nc = GNUNET_SERVER_notification_context_create (server_handle, 1);
5770   GNUNET_SERVER_disconnect_notify (server_handle,
5771                                    &handle_local_client_disconnect, NULL);
5772
5773
5774   clients_head = NULL;
5775   clients_tail = NULL;
5776   next_client_id = 0;
5777
5778   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
5779
5780   /* Create a peer_info for the local peer */
5781   peer = peer_get (&my_full_id);
5782   p = path_new (1);
5783   p->peers[0] = myid;
5784   GNUNET_PEER_change_rc (myid, 1);
5785   peer_info_add_path (peer, p, GNUNET_YES);
5786   GNUNET_SERVER_resume (server_handle);
5787   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Mesh service running\n");
5788 }
5789
5790
5791 /**
5792  * Process mesh requests.
5793  *
5794  * @param cls closure
5795  * @param server the initialized server
5796  * @param c configuration to use
5797  */
5798 static void
5799 run (void *cls, struct GNUNET_SERVER_Handle *server,
5800      const struct GNUNET_CONFIGURATION_Handle *c)
5801 {
5802   char *keyfile;
5803
5804   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
5805   server_handle = server;
5806
5807   if (GNUNET_OK !=
5808       GNUNET_CONFIGURATION_get_value_filename (c, "PEER", "PRIVATE_KEY",
5809                                                &keyfile))
5810   {
5811     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5812                 _
5813                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5814                 "mesh", "peer/privatekey");
5815     GNUNET_SCHEDULER_shutdown ();
5816     return;
5817   }
5818
5819   if (GNUNET_OK !=
5820       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_PATH_TIME",
5821                                            &refresh_path_time))
5822   {
5823     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5824                 _
5825                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5826                 "mesh", "refresh path time");
5827     GNUNET_SCHEDULER_shutdown ();
5828     return;
5829   }
5830
5831   if (GNUNET_OK !=
5832       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "ID_ANNOUNCE_TIME",
5833                                            &id_announce_time))
5834   {
5835     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5836                 _
5837                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5838                 "mesh", "id announce time");
5839     GNUNET_SCHEDULER_shutdown ();
5840     return;
5841   }
5842
5843   if (GNUNET_OK !=
5844       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "CONNECT_TIMEOUT",
5845                                            &connect_timeout))
5846   {
5847     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5848                 _
5849                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5850                 "mesh", "connect timeout");
5851     GNUNET_SCHEDULER_shutdown ();
5852     return;
5853   }
5854
5855   if (GNUNET_OK !=
5856       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
5857                                              &max_msgs_queue))
5858   {
5859     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5860                 _
5861                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5862                 "mesh", "max msgs queue");
5863     GNUNET_SCHEDULER_shutdown ();
5864     return;
5865   }
5866
5867   if (GNUNET_OK !=
5868       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_TUNNELS",
5869                                              &max_tunnels))
5870   {
5871     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5872                 _
5873                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5874                 "mesh", "max tunnels");
5875     GNUNET_SCHEDULER_shutdown ();
5876     return;
5877   }
5878
5879   if (GNUNET_OK !=
5880       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
5881                                              &default_ttl))
5882   {
5883     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5884                 _
5885                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
5886                 "mesh", "default ttl", 64);
5887     default_ttl = 64;
5888   }
5889
5890   if (GNUNET_OK !=
5891       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_PEERS",
5892                                              &max_peers))
5893   {
5894     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5895                 _("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
5896                 "mesh", "max peers", 1000);
5897     max_peers = 1000;
5898   }
5899
5900   if (GNUNET_OK !=
5901       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DHT_REPLICATION_LEVEL",
5902                                              &dht_replication_level))
5903   {
5904     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5905                 _
5906                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
5907                 "mesh", "dht replication level", 3);
5908     dht_replication_level = 3;
5909   }
5910
5911   tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
5912   incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
5913   peers = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
5914   types = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
5915
5916   dht_handle = GNUNET_DHT_connect (c, 64);
5917   if (NULL == dht_handle)
5918   {
5919     GNUNET_break (0);
5920   }
5921   stats = GNUNET_STATISTICS_create ("mesh", c);
5922
5923   GNUNET_SERVER_suspend (server_handle);
5924   /* Scheduled the task to clean up when shutdown is called */
5925   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
5926                                 NULL);
5927   keygen = GNUNET_CRYPTO_ecc_key_create_start (keyfile,
5928                                                &key_generation_cb,
5929                                                (void *) c);
5930   GNUNET_free (keyfile);
5931 }
5932
5933
5934 /**
5935  * The main function for the mesh service.
5936  *
5937  * @param argc number of arguments from the command line
5938  * @param argv command line arguments
5939  * @return 0 ok, 1 on error
5940  */
5941 int
5942 main (int argc, char *const *argv)
5943 {
5944   int ret;
5945   int r;
5946
5947   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
5948   r = GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
5949                           NULL);
5950   ret = (GNUNET_OK == r) ? 0 : 1;
5951   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");
5952
5953   INTERVAL_SHOW;
5954
5955   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5956               "Mesh for peer [%s] FWD ACKs %u, BCK ACKs %u\n",
5957               GNUNET_i2s(&my_full_id), debug_fwd_ack, debug_bck_ack);
5958
5959   return ret;
5960 }