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