- use message ID for end-to-end ACKs
[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   ack = t->prev_fc.last_pid_recv + delta;
2159   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " FWD ACK %u\n", ack);
2160   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2161               " last %u, qmax %u, q %u\n",
2162               t->prev_fc.last_pid_recv, t->queue_max, t->next_fc.queue_n);
2163   if (ack == t->prev_fc.last_ack_sent && GNUNET_NO == t->force_ack)
2164   {
2165     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending FWD ACK, not needed\n");
2166     return;
2167   }
2168
2169   t->prev_fc.last_ack_sent = ack;
2170   if (NULL != t->owner)
2171     send_local_ack (t, t->owner, GNUNET_YES);
2172   else if (0 != t->prev_hop)
2173     send_ack (t, t->prev_hop, ack);
2174   else
2175     GNUNET_break (0);
2176   debug_fwd_ack++;
2177   t->force_ack = GNUNET_NO;
2178 }
2179
2180
2181 /**
2182  * Send an ACK informing the children node/client about the available
2183  * buffer space.
2184  * If buffering is off, send only on behalf of root (can be self).
2185  * If buffering is on, send when sent to predecessor and buffer space is free.
2186  * Note that although the name is bck_ack, the BCK mean backwards *traffic*,
2187  * the ACK itself goes "forward" (towards children/clients).
2188  * 
2189  * @param t Tunnel on which to send the ACK.
2190  * @param type Type of message that triggered the ACK transmission.
2191  */
2192 static void
2193 tunnel_send_bck_ack (struct MeshTunnel *t, uint16_t type)
2194 {
2195   uint32_t ack;
2196   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2197               "Sending BCK ACK on tunnel %u [%u] due to %s\n",
2198               t->id.oid, t->id.tid, GNUNET_MESH_DEBUG_M2S(type));
2199   /* Is it after data to_origin retransmission? */
2200   switch (type)
2201   {
2202     case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
2203       if (GNUNET_YES == t->nobuffer)
2204       {
2205         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2206                     "    Not sending ACK, nobuffer + traffic\n");
2207         return;
2208       }
2209       if (GNUNET_YES == t->reliable && NULL != t->owner)
2210         tunnel_send_bck_data_ack (t);
2211       break;
2212     case GNUNET_MESSAGE_TYPE_MESH_ACK:
2213     case GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK:
2214       break;
2215     case GNUNET_MESSAGE_TYPE_MESH_PATH_ACK:
2216     case GNUNET_MESSAGE_TYPE_MESH_POLL:
2217       t->force_ack = GNUNET_YES;
2218       break;
2219     default:
2220       GNUNET_break (0);
2221   }
2222
2223   /* TODO: Check if we need to transmit the ACK (as in fwd) */
2224
2225   ack = t->next_fc.last_pid_recv + t->queue_max - t->prev_fc.queue_n;
2226
2227   if (t->next_fc.last_ack_sent == ack && GNUNET_NO == t->force_ack)
2228   {
2229     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2230                 "    Not sending ACK, not needed, last ack sent was %u\n",
2231                 t->next_fc.last_ack_sent);
2232     return;
2233   }
2234   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2235               "    Sending BCK ACK %u (last sent: %u)\n",
2236               ack, t->next_fc.last_ack_sent);
2237   t->next_fc.last_ack_sent = ack;
2238
2239   if (NULL != t->client)
2240     send_local_ack (t, t->client, GNUNET_NO);
2241   else if (0 != t->next_hop)
2242     send_ack (t, t->next_hop, ack);
2243   else
2244     GNUNET_break (0);
2245   t->force_ack = GNUNET_NO;
2246 }
2247
2248
2249 /**
2250  * Modify the mesh message TID from global to local and send to client.
2251  * 
2252  * @param t Tunnel on which to send the message.
2253  * @param msg Message to modify and send.
2254  * @param c Client to send to.
2255  * @param tid Tunnel ID to use (c can be both owner and client).
2256  */
2257 static void
2258 tunnel_send_client_data (struct MeshTunnel *t,
2259                          const struct GNUNET_MESH_Data *msg,
2260                          struct MeshClient *c, MESH_TunnelNumber tid)
2261 {
2262   struct GNUNET_MESH_LocalData *copy;
2263   uint16_t size = ntohs (msg->header.size) - sizeof (struct GNUNET_MESH_Data);
2264   char cbuf[size + sizeof (struct GNUNET_MESH_LocalData)];
2265
2266   if (size < sizeof (struct GNUNET_MessageHeader))
2267   {
2268     GNUNET_break_op (0);
2269     return;
2270   }
2271   if (NULL == c)
2272   {
2273     GNUNET_break (0);
2274     return;
2275   }
2276   copy = (struct GNUNET_MESH_LocalData *) cbuf;
2277   memcpy (&copy[1], &msg[1], size);
2278   copy->header.size = htons (sizeof (struct GNUNET_MESH_LocalData) + size);
2279   copy->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_DATA);
2280   copy->tid = htonl (tid);
2281   GNUNET_SERVER_notification_context_unicast (nc, c->handle,
2282                                               &copy->header, GNUNET_NO);
2283 }
2284
2285 /**
2286  * Modify the unicast message TID from global to local and send to client.
2287  * 
2288  * @param t Tunnel on which to send the message.
2289  * @param msg Message to modify and send.
2290  */
2291 static void
2292 tunnel_send_client_ucast (struct MeshTunnel *t,
2293                           const struct GNUNET_MESH_Data *msg)
2294 {
2295   tunnel_send_client_data (t, msg, t->client, t->local_tid_dest);
2296 }
2297
2298
2299 /**
2300  * Modify the to_origin  message TID from global to local and send to client.
2301  * 
2302  * @param t Tunnel on which to send the message.
2303  * @param msg Message to modify and send.
2304  */
2305 static void
2306 tunnel_send_client_to_orig (struct MeshTunnel *t,
2307                             const struct GNUNET_MESH_Data *msg)
2308 {
2309   tunnel_send_client_data (t, msg, t->owner, t->local_tid);
2310 }
2311
2312
2313 /**
2314  * We haven't received an ACK after a certain time: restransmit the message.
2315  *
2316  * @param cls Closure (MeshReliableMessage with the message to restransmit)
2317  * @param tc TaskContext.
2318  */
2319 static void
2320 tunnel_retransmit_message (void *cls,
2321                            const struct GNUNET_SCHEDULER_TaskContext *tc)
2322 {
2323   struct MeshTunnelReliability *rel = cls;
2324   struct MeshReliableMessage *copy;
2325   struct MeshFlowControl *fc;
2326   struct MeshPeerQueue *q;
2327   struct MeshPeerInfo *pi;
2328   struct MeshTunnel *t;
2329   struct GNUNET_MESH_Data *payload;
2330   GNUNET_PEER_Id hop;
2331
2332   rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
2333   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2334     return;
2335
2336   t = rel->t;
2337   copy = rel->head_sent;
2338   if (NULL == copy)
2339   {
2340     GNUNET_break (0);
2341     return;
2342   }
2343
2344   /* Search the message to be retransmitted in the outgoing queue */
2345   payload = (struct GNUNET_MESH_Data *) &copy[1];
2346   hop = rel == t->fwd_rel ? t->next_hop : t->prev_hop;
2347   fc = rel == t->fwd_rel ? &t->next_fc : &t->prev_fc;
2348   pi = peer_get_short (hop);
2349   for (q = pi->queue_head; NULL != q; q = q->next)
2350   {
2351     if (ntohs (payload->header.type) == q->type)
2352     {
2353       struct GNUNET_MESH_Data *queued_data = q->cls;
2354
2355       if (queued_data->mid == payload->mid)
2356         break;
2357     }
2358   }
2359
2360   /* Message not found in the queue */
2361   if (NULL == q)
2362   {
2363     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! RETRANSMIT %llu\n", copy->mid);
2364     copy->timestamp = GNUNET_TIME_absolute_get ();
2365
2366     fc->last_ack_sent++;
2367     payload->pid = htonl (fc->last_pid_recv + 1);
2368     fc->last_pid_recv++;
2369     send_prebuilt_message (&payload->header, hop, t);
2370     GNUNET_STATISTICS_update (stats, "# data retransmitted", 1, GNUNET_NO);
2371   }
2372   else
2373   {
2374     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! STILL IN QUEUE %llu\n", copy->mid);
2375   }
2376
2377   rel->retry_timer = GNUNET_TIME_STD_BACKOFF (rel->retry_timer);
2378   rel->retry_task = GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
2379                                                   &tunnel_retransmit_message,
2380                                                   cls);
2381 }
2382
2383
2384 /**
2385  * @brief Re-initiate traffic to this peer if necessary.
2386  *
2387  * Check if there is traffic queued towards this peer
2388  * and the core transmit handle is NULL (traffic was stalled).
2389  * If so, call core tmt rdy.
2390  *
2391  * @param peer_id Short ID of peer to which initiate traffic.
2392  */
2393 static void
2394 peer_unlock_queue(GNUNET_PEER_Id peer_id)
2395 {
2396   struct MeshPeerInfo *peer;
2397   struct GNUNET_PeerIdentity id;
2398   struct MeshPeerQueue *q;
2399   size_t size;
2400
2401   peer = peer_get_short (peer_id);
2402   if (NULL != peer->core_transmit)
2403     return;
2404
2405   q = queue_get_next (peer);
2406   if (NULL == q)
2407   {
2408     /* Might br multicast traffic already sent to this particular peer but
2409      * not to other children in this tunnel.
2410      * This way t->queue_n would be > 0 but the queue of this particular peer
2411      * would be empty.
2412      */
2413     return;
2414   }
2415   size = q->size;
2416   GNUNET_PEER_resolve (peer->id, &id);
2417   peer->core_transmit =
2418         GNUNET_CORE_notify_transmit_ready(core_handle,
2419                                           0,
2420                                           0,
2421                                           GNUNET_TIME_UNIT_FOREVER_REL,
2422                                           &id,
2423                                           size,
2424                                           &queue_send,
2425                                           peer);
2426         return;
2427 }
2428
2429
2430 /**
2431  * Send a message to all peers and clients in this tunnel that the tunnel
2432  * is no longer valid. If some peer or client should not receive the message,
2433  * should be zero'ed out before calling this function.
2434  *
2435  * @param t The tunnel whose peers and clients to notify.
2436  */
2437 static void
2438 tunnel_send_destroy (struct MeshTunnel *t)
2439 {
2440   struct GNUNET_MESH_TunnelDestroy msg;
2441   struct GNUNET_PeerIdentity id;
2442
2443   msg.header.size = htons (sizeof (msg));
2444   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY);
2445   GNUNET_PEER_resolve (t->id.oid, &msg.oid);
2446   msg.tid = htonl (t->id.tid);
2447   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2448               "  sending tunnel destroy for tunnel: %s [%X]\n",
2449               GNUNET_i2s (&msg.oid), t->id.tid);
2450
2451   if (NULL == t->client && 0 != t->next_hop)
2452   {
2453     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  child: %u\n", t->next_hop);
2454     GNUNET_PEER_resolve (t->next_hop, &id);
2455     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2456                 "  sending forward to %s\n",
2457                 GNUNET_i2s (&id));
2458     send_prebuilt_message (&msg.header, t->next_hop, t);
2459   }
2460   if (NULL == t->owner && 0 != t->prev_hop)
2461   {
2462     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  parent: %u\n", t->prev_hop);
2463     GNUNET_PEER_resolve (t->prev_hop, &id);
2464     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2465                 "  sending back to %s\n",
2466                 GNUNET_i2s (&id));
2467     send_prebuilt_message (&msg.header, t->prev_hop, t);
2468   }
2469   if (NULL != t->owner)
2470   {
2471     send_client_tunnel_destroy (t->owner, t);
2472   }
2473   if (NULL != t->client)
2474   {
2475     send_client_tunnel_destroy (t->client, t);
2476   }
2477 }
2478
2479
2480 /**
2481  * Cancel all transmissions towards a neighbor that belongs to a certain tunnel.
2482  *
2483  * @param t Tunnel which to cancel.
2484  * @param neighbor Short ID of the neighbor to whom cancel the transmissions.
2485  */
2486 static void
2487 peer_cancel_queues (GNUNET_PEER_Id neighbor, struct MeshTunnel *t)
2488 {
2489   struct MeshPeerInfo *peer_info;
2490   struct MeshPeerQueue *pq;
2491   struct MeshPeerQueue *next;
2492
2493   if (0 == neighbor)
2494     return; /* Was local peer, 0'ed in tunnel_destroy_iterator */
2495   peer_info = peer_get_short (neighbor);
2496   for (pq = peer_info->queue_head; NULL != pq; pq = next)
2497   {
2498     next = pq->next;
2499     if (pq->tunnel == t)
2500     {
2501       if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == pq->type ||
2502           GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == pq->type)
2503       {
2504         /* Should have been removed on destroy children */
2505         GNUNET_break (0);
2506       }
2507       queue_destroy (pq, GNUNET_YES);
2508     }
2509   }
2510   if (NULL == peer_info->queue_head && NULL != peer_info->core_transmit)
2511   {
2512     GNUNET_CORE_notify_transmit_ready_cancel(peer_info->core_transmit);
2513     peer_info->core_transmit = NULL;
2514   }
2515 }
2516
2517
2518 /**
2519  * Destroy the tunnel.
2520  * 
2521  * This function does not generate any warning traffic to clients or peers.
2522  * 
2523  * Tasks:
2524  * Remove the tunnel from peer_info's and clients' hashmaps.
2525  * Cancel messages belonging to this tunnel queued to neighbors.
2526  * Free any allocated resources linked to the tunnel.
2527  *
2528  * @param t the tunnel to destroy
2529  *
2530  * @return GNUNET_OK on success
2531  */
2532 static int
2533 tunnel_destroy (struct MeshTunnel *t)
2534 {
2535   struct MeshClient *c;
2536   struct GNUNET_HashCode hash;
2537   int r;
2538
2539   if (NULL == t)
2540     return GNUNET_OK;
2541
2542   r = GNUNET_OK;
2543   c = t->owner;
2544 #if MESH_DEBUG
2545   {
2546     struct GNUNET_PeerIdentity id;
2547
2548     GNUNET_PEER_resolve (t->id.oid, &id);
2549     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s [%x]\n",
2550                 GNUNET_i2s (&id), t->id.tid);
2551     if (NULL != c)
2552       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
2553   }
2554 #endif
2555
2556   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
2557   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &hash, t))
2558   {
2559     GNUNET_break (0);
2560     r = GNUNET_SYSERR;
2561   }
2562
2563   if (NULL != c)
2564   {
2565     if (GNUNET_YES !=
2566       GNUNET_CONTAINER_multihashmap32_remove (c->own_tunnels, t->local_tid, t))
2567     {
2568       GNUNET_break (0);
2569       r = GNUNET_SYSERR;
2570     }
2571   }
2572
2573   if (NULL != t->client)
2574   {
2575     c = t->client;
2576     if (GNUNET_YES !=
2577         GNUNET_CONTAINER_multihashmap32_remove (c->incoming_tunnels,
2578                                                 t->local_tid_dest, t))
2579     {
2580       GNUNET_break (0);
2581       r = GNUNET_SYSERR;
2582     }
2583     if (GNUNET_YES != 
2584         GNUNET_CONTAINER_multihashmap32_remove (incoming_tunnels,
2585                                                 t->local_tid_dest, t))
2586     {
2587       GNUNET_break (0);
2588       r = GNUNET_SYSERR;
2589     }
2590   }
2591
2592   if (0 != t->prev_hop)
2593   {
2594     peer_cancel_queues (t->prev_hop, t);
2595     GNUNET_PEER_change_rc (t->prev_hop, -1);
2596   }
2597   if (0 != t->next_hop)
2598   {
2599     peer_cancel_queues (t->next_hop, t);
2600     GNUNET_PEER_change_rc (t->next_hop, -1);
2601   }
2602   if (0 != t->dest) {
2603       peer_info_remove_tunnel (peer_get_short (t->dest), t);
2604   }
2605
2606   if (GNUNET_SCHEDULER_NO_TASK != t->maintenance_task)
2607     GNUNET_SCHEDULER_cancel (t->maintenance_task);
2608
2609   n_tunnels--;
2610   GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
2611   path_destroy (t->path);
2612   GNUNET_free (t);
2613   return r;
2614 }
2615
2616 /**
2617  * Tunnel is empty: destroy it.
2618  * 
2619  * Notifies all participants (peers, cleints) about the destruction.
2620  * 
2621  * @param t Tunnel to destroy. 
2622  */
2623 static void
2624 tunnel_destroy_empty (struct MeshTunnel *t)
2625 {
2626   #if MESH_DEBUG
2627   {
2628     struct GNUNET_PeerIdentity id;
2629
2630     GNUNET_PEER_resolve (t->id.oid, &id);
2631     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2632                 "executing destruction of empty tunnel %s [%X]\n",
2633                 GNUNET_i2s (&id), t->id.tid);
2634   }
2635   #endif
2636
2637   if (GNUNET_NO == t->destroy)
2638     tunnel_send_destroy (t);
2639   if (0 == t->pending_messages)
2640     tunnel_destroy (t);
2641   else
2642     t->destroy = GNUNET_YES;
2643 }
2644
2645 /**
2646  * Initialize a Flow Control structure to the initial state.
2647  * 
2648  * @param fc Flow Control structure to initialize.
2649  */
2650 static void
2651 fc_init (struct MeshFlowControl *fc)
2652 {
2653   fc->last_pid_sent = (uint32_t) -1; /* Next (expected) = 0 */
2654   fc->last_pid_recv = (uint32_t) -1;
2655   fc->last_ack_sent = (uint32_t) -1; /* No traffic allowed yet */
2656   fc->last_ack_recv = (uint32_t) -1;
2657   fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
2658   fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
2659   fc->queue_n = 0;
2660 }
2661
2662 /**
2663  * Create a new tunnel
2664  * 
2665  * @param owner Who is the owner of the tunnel (short ID).
2666  * @param tid Tunnel Number of the tunnel.
2667  * @param client Clients that owns the tunnel, NULL for foreign tunnels.
2668  * @param local Tunnel Number for the tunnel, for the client point of view.
2669  * 
2670  * @return A new initialized tunnel. NULL on error.
2671  */
2672 static struct MeshTunnel *
2673 tunnel_new (GNUNET_PEER_Id owner,
2674             MESH_TunnelNumber tid,
2675             struct MeshClient *client,
2676             MESH_TunnelNumber local)
2677 {
2678   struct MeshTunnel *t;
2679   struct GNUNET_HashCode hash;
2680
2681   if (n_tunnels >= max_tunnels && NULL == client)
2682     return NULL;
2683
2684   t = GNUNET_malloc (sizeof (struct MeshTunnel));
2685   t->id.oid = owner;
2686   t->id.tid = tid;
2687   t->queue_max = (max_msgs_queue / max_tunnels) + 1;
2688   t->owner = client;
2689   fc_init (&t->next_fc);
2690   fc_init (&t->prev_fc);
2691   t->local_tid = local;
2692   n_tunnels++;
2693   GNUNET_STATISTICS_update (stats, "# tunnels", 1, GNUNET_NO);
2694
2695   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
2696   if (GNUNET_OK !=
2697       GNUNET_CONTAINER_multihashmap_put (tunnels, &hash, t,
2698                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2699   {
2700     GNUNET_break (0);
2701     tunnel_destroy (t);
2702     if (NULL != client)
2703     {
2704       GNUNET_break (0);
2705       GNUNET_SERVER_receive_done (client->handle, GNUNET_SYSERR);
2706     }
2707     return NULL;
2708   }
2709
2710   if (NULL != client)
2711   {
2712     if (GNUNET_OK !=
2713         GNUNET_CONTAINER_multihashmap32_put (client->own_tunnels,
2714                                              t->local_tid, t,
2715                                              GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2716     {
2717       tunnel_destroy (t);
2718       GNUNET_break (0);
2719       GNUNET_SERVER_receive_done (client->handle, GNUNET_SYSERR);
2720       return NULL;
2721     }
2722   }
2723
2724   return t;
2725 }
2726
2727
2728 /**
2729  * Set options in a tunnel, extracted from a bit flag field
2730  * 
2731  * @param t Tunnel to set options to.
2732  * @param options Bit array in host byte order.
2733  */
2734 static void
2735 tunnel_set_options (struct MeshTunnel *t, uint32_t options)
2736 {
2737   t->nobuffer = (options & GNUNET_MESH_OPTION_NOBUFFER) != 0 ?
2738                  GNUNET_YES : GNUNET_NO;
2739   t->reliable = (options & GNUNET_MESH_OPTION_RELIABLE) != 0 ?
2740                  GNUNET_YES : GNUNET_NO;
2741 }
2742
2743
2744 /**
2745  * Iterator for deleting each tunnel whose client endpoint disconnected.
2746  *
2747  * @param cls Closure (client that has disconnected).
2748  * @param key The local tunnel id (used to access the hashmap).
2749  * @param value The value stored at the key (tunnel to destroy).
2750  *
2751  * @return GNUNET_OK, keep iterating.
2752  */
2753 static int
2754 tunnel_destroy_iterator (void *cls,
2755                          uint32_t key,
2756                          void *value)
2757 {
2758   struct MeshTunnel *t = value;
2759   struct MeshClient *c = cls;
2760
2761   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2762               " Tunnel %X / %X destroy, due to client %u shutdown.\n",
2763               t->local_tid, t->local_tid_dest, c->id);
2764   client_delete_tunnel (c, t);
2765   if (c == t->client)
2766   {
2767     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Client %u is destination.\n", c->id);
2768     t->client = NULL;
2769     if (0 != t->next_hop) { /* destroy could come before a path is used */
2770         GNUNET_PEER_change_rc (t->next_hop, -1);
2771         t->next_hop = 0;
2772     }
2773   }
2774   if (c == t->owner)
2775   {
2776     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Client %u is owner.\n", c->id);
2777     t->owner = NULL;
2778     if (0 != t->prev_hop) { /* destroy could come before a path is used */
2779         GNUNET_PEER_change_rc (t->prev_hop, -1);
2780         t->prev_hop = 0;
2781     }
2782   }
2783
2784   tunnel_destroy_empty (t);
2785
2786   return GNUNET_OK;
2787 }
2788
2789
2790 /**
2791  * Timeout function, destroys tunnel if called
2792  *
2793  * @param cls Closure (tunnel to destroy).
2794  * @param tc TaskContext
2795  */
2796 static void
2797 tunnel_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2798 {
2799   struct MeshTunnel *t = cls;
2800   struct GNUNET_PeerIdentity id;
2801
2802   t->maintenance_task = GNUNET_SCHEDULER_NO_TASK;
2803   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2804     return;
2805   GNUNET_PEER_resolve(t->id.oid, &id);
2806   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2807               "Tunnel %s [%X] timed out. Destroying.\n",
2808               GNUNET_i2s(&id), t->id.tid);
2809   if (NULL != t->client)
2810     send_client_tunnel_destroy (t->client, t);
2811   tunnel_destroy (t); /* Do not notify other */
2812 }
2813
2814
2815 /**
2816  * Resets the tunnel timeout. Starts it if no timeout was running.
2817  *
2818  * @param t Tunnel whose timeout to reset.
2819  *
2820  * TODO use heap to improve efficiency of scheduler.
2821  */
2822 static void
2823 tunnel_reset_timeout (struct MeshTunnel *t)
2824 {
2825   if (NULL != t->owner || 0 != t->local_tid || 0 == t->prev_hop)
2826     return;
2827   if (GNUNET_SCHEDULER_NO_TASK != t->maintenance_task)
2828     GNUNET_SCHEDULER_cancel (t->maintenance_task);
2829   t->maintenance_task =
2830       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
2831                                     (refresh_path_time, 4), &tunnel_timeout, t);
2832 }
2833
2834
2835 /******************************************************************************/
2836 /****************      MESH NETWORK HANDLER HELPERS     ***********************/
2837 /******************************************************************************/
2838
2839 /**
2840  * Function to send a create path packet to a peer.
2841  *
2842  * @param cls closure
2843  * @param size number of bytes available in buf
2844  * @param buf where the callee should write the message
2845  * @return number of bytes written to buf
2846  */
2847 static size_t
2848 send_core_path_create (void *cls, size_t size, void *buf)
2849 {
2850   struct MeshTunnel *t = cls;
2851   struct GNUNET_MESH_CreateTunnel *msg;
2852   struct GNUNET_PeerIdentity *peer_ptr;
2853   struct MeshPeerPath *p = t->path;
2854   size_t size_needed;
2855   uint32_t opt;
2856   int i;
2857
2858   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATE PATH sending...\n");
2859   size_needed =
2860       sizeof (struct GNUNET_MESH_CreateTunnel) +
2861       p->length * sizeof (struct GNUNET_PeerIdentity);
2862
2863   if (size < size_needed || NULL == buf)
2864   {
2865     GNUNET_break (0);
2866     return 0;
2867   }
2868   msg = (struct GNUNET_MESH_CreateTunnel *) buf;
2869   msg->header.size = htons (size_needed);
2870   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE);
2871   msg->tid = ntohl (t->id.tid);
2872
2873   opt = 0;
2874   if (GNUNET_YES == t->nobuffer)
2875     opt |= GNUNET_MESH_OPTION_NOBUFFER;
2876   if (GNUNET_YES == t->reliable)
2877     opt |= GNUNET_MESH_OPTION_RELIABLE;
2878   msg->opt = htonl (opt);
2879   msg->port = htonl (t->port);
2880
2881   peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
2882   for (i = 0; i < p->length; i++)
2883   {
2884     GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
2885   }
2886
2887   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2888               "CREATE PATH (%u bytes long) sent!\n", size_needed);
2889   return size_needed;
2890 }
2891
2892
2893 /**
2894  * Creates a path ack message in buf and frees all unused resources.
2895  *
2896  * @param cls closure (MeshTransmissionDescriptor)
2897  * @param size number of bytes available in buf
2898  * @param buf where the callee should write the message
2899  * @return number of bytes written to buf
2900  */
2901 static size_t
2902 send_core_path_ack (void *cls, size_t size, void *buf)
2903 {
2904   struct MeshTunnel *t = cls;
2905   struct GNUNET_MESH_PathACK *msg = buf;
2906
2907   GNUNET_assert (NULL != t);
2908   if (sizeof (struct GNUNET_MESH_PathACK) > size)
2909   {
2910     GNUNET_break (0);
2911     return 0;
2912   }
2913   t->prev_fc.last_ack_sent = t->nobuffer ? 0 : t->queue_max - 1;
2914   msg->header.size = htons (sizeof (struct GNUNET_MESH_PathACK));
2915   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_ACK);
2916   GNUNET_PEER_resolve (t->id.oid, &msg->oid);
2917   msg->tid = htonl (t->id.tid);
2918   msg->peer_id = my_full_id;
2919   msg->ack = htonl (t->prev_fc.last_ack_sent);
2920
2921   /* TODO add signature */
2922
2923   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "PATH ACK sent!\n");
2924   return sizeof (struct GNUNET_MESH_PathACK);
2925 }
2926
2927
2928 /**
2929  * Free a transmission that was already queued with all resources
2930  * associated to the request.
2931  *
2932  * @param queue Queue handler to cancel.
2933  * @param clear_cls Is it necessary to free associated cls?
2934  */
2935 static void
2936 queue_destroy (struct MeshPeerQueue *queue, int clear_cls)
2937 {
2938   struct MeshFlowControl *fc;
2939
2940   if (GNUNET_YES == clear_cls)
2941   {
2942     switch (queue->type)
2943     {
2944       case GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY:
2945         GNUNET_log (GNUNET_ERROR_TYPE_INFO, "   cancelling TUNNEL_DESTROY\n");
2946         GNUNET_break (GNUNET_YES == queue->tunnel->destroy);
2947         /* fall through */
2948       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
2949       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
2950       case GNUNET_MESSAGE_TYPE_MESH_ACK:
2951       case GNUNET_MESSAGE_TYPE_MESH_POLL:
2952       case GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE:
2953         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2954                     "   prebuilt message\n");
2955         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2956                     "   type %s\n",
2957                     GNUNET_MESH_DEBUG_M2S (queue->type));
2958         break;
2959       case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
2960         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   type create path\n");
2961         break;
2962       default:
2963         GNUNET_break (0);
2964         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2965                     "   type %s unknown!\n",
2966                     GNUNET_MESH_DEBUG_M2S (queue->type));
2967     }
2968     GNUNET_free_non_null (queue->cls);
2969   }
2970   GNUNET_CONTAINER_DLL_remove (queue->peer->queue_head,
2971                                queue->peer->queue_tail,
2972                                queue);
2973
2974   /* Delete from appropriate fc in the tunnel */
2975   if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == queue->type ||
2976       GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == queue->type )
2977   {
2978     if (queue->peer->id == queue->tunnel->prev_hop)
2979       fc = &queue->tunnel->prev_fc;
2980     else if (queue->peer->id == queue->tunnel->next_hop)
2981       fc = &queue->tunnel->next_fc;
2982     else
2983     {
2984       GNUNET_break (0);
2985       GNUNET_free (queue);
2986       return;
2987     }
2988     fc->queue_n--;
2989   }
2990   GNUNET_free (queue);
2991 }
2992
2993
2994 /**
2995  * @brief Get the next transmittable message from the queue.
2996  *
2997  * This will be the head, except in the case of being a data packet
2998  * not allowed by the destination peer.
2999  *
3000  * @param peer Destination peer.
3001  *
3002  * @return The next viable MeshPeerQueue element to send to that peer.
3003  *         NULL when there are no transmittable messages.
3004  */
3005 struct MeshPeerQueue *
3006 queue_get_next (const struct MeshPeerInfo *peer)
3007 {
3008   struct MeshPeerQueue *q;
3009
3010   struct GNUNET_MESH_Data *dmsg;
3011   struct MeshTunnel* t;
3012   uint32_t pid;
3013   uint32_t ack;
3014
3015   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   selecting message\n");
3016   for (q = peer->queue_head; NULL != q; q = q->next)
3017   {
3018     t = q->tunnel;
3019     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3020                 "*     %s\n",
3021                 GNUNET_MESH_DEBUG_M2S (q->type));
3022     dmsg = (struct GNUNET_MESH_Data *) q->cls;
3023     pid = ntohl (dmsg->pid);
3024     switch (q->type)
3025     {
3026       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
3027         ack = t->next_fc.last_ack_recv;
3028         break;
3029       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
3030         ack = t->prev_fc.last_ack_recv;
3031         break;
3032       default:
3033         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3034                     "*   OK!\n");
3035         return q;
3036     }
3037     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3038                 "*     ACK: %u, PID: %u\n",
3039                 ack, pid);
3040     if (GNUNET_NO == GMC_is_pid_bigger (pid, ack))
3041     {
3042       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3043                   "*   OK!\n");
3044       return q;
3045     }
3046     else
3047     {
3048       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3049                   "*     NEXT!\n");
3050     }
3051   }
3052   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3053                 "*   nothing found\n");
3054   return NULL;
3055 }
3056
3057
3058 static size_t
3059 queue_send (void *cls, size_t size, void *buf)
3060 {
3061   struct MeshPeerInfo *peer = cls;
3062   struct GNUNET_MessageHeader *msg;
3063   struct MeshPeerQueue *queue;
3064   struct MeshTunnel *t;
3065   struct GNUNET_PeerIdentity dst_id;
3066   struct MeshFlowControl *fc;
3067   size_t data_size;
3068   uint32_t pid;
3069   uint16_t type;
3070
3071   peer->core_transmit = NULL;
3072
3073   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* Queue send\n");
3074   queue = queue_get_next (peer);
3075
3076   /* Queue has no internal mesh traffic nor sendable payload */
3077   if (NULL == queue)
3078   {
3079     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   not ready, return\n");
3080     if (NULL == peer->queue_head)
3081       GNUNET_break (0); /* Core tmt_rdy should've been canceled */
3082     return 0;
3083   }
3084   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   not empty\n");
3085
3086   GNUNET_PEER_resolve (peer->id, &dst_id);
3087   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3088               "*   towards %s\n",
3089               GNUNET_i2s (&dst_id));
3090   /* Check if buffer size is enough for the message */
3091   if (queue->size > size)
3092   {
3093       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3094                   "*   not enough room, reissue\n");
3095       peer->core_transmit =
3096           GNUNET_CORE_notify_transmit_ready (core_handle,
3097                                              GNUNET_NO,
3098                                              0,
3099                                              GNUNET_TIME_UNIT_FOREVER_REL,
3100                                              &dst_id,
3101                                              queue->size,
3102                                              &queue_send,
3103                                              peer);
3104       return 0;
3105   }
3106   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   size ok\n");
3107
3108   t = queue->tunnel;
3109   GNUNET_assert (0 < t->pending_messages);
3110   t->pending_messages--;
3111   type = 0;
3112
3113   /* Fill buf */
3114   switch (queue->type)
3115   {
3116     case 0:
3117     case GNUNET_MESSAGE_TYPE_MESH_ACK:
3118     case GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK:
3119     case GNUNET_MESSAGE_TYPE_MESH_TO_ORIG_ACK:
3120     case GNUNET_MESSAGE_TYPE_MESH_POLL:
3121     case GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN:
3122     case GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY:
3123     case GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY:
3124     case GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE:
3125       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3126                   "*   raw: %s\n",
3127                   GNUNET_MESH_DEBUG_M2S (queue->type));
3128       /* Fall through */
3129     case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
3130     case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
3131       data_size = send_core_data_raw (queue->cls, size, buf);
3132       msg = (struct GNUNET_MessageHeader *) buf;
3133       type = ntohs (msg->type);
3134       break;
3135     case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
3136       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   path create\n");
3137       data_size = send_core_path_create (queue->cls, size, buf);
3138       break;
3139     case GNUNET_MESSAGE_TYPE_MESH_PATH_ACK:
3140       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   path ack\n");
3141       data_size = send_core_path_ack (queue->cls, size, buf);
3142       break;
3143     default:
3144       GNUNET_break (0);
3145       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3146                   "*   type unknown: %u\n",
3147                   queue->type);
3148       data_size = 0;
3149   }
3150
3151   if (0 < drop_percent &&
3152       GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 101) < drop_percent)
3153   {
3154     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3155                 "Dropping message of type %s\n",
3156                 GNUNET_MESH_DEBUG_M2S(queue->type));
3157     data_size = 0;
3158   }
3159   /* Free queue, but cls was freed by send_core_* */
3160   queue_destroy (queue, GNUNET_NO);
3161
3162   /* Send ACK if needed, after accounting for sent ID in fc->queue_n */
3163   pid = ((struct GNUNET_MESH_Data *) buf)->pid;
3164   pid = ntohl (pid);
3165   switch (type)
3166   {
3167     case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
3168       t->next_fc.last_pid_sent = pid;
3169       tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_UNICAST);
3170       break;
3171     case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
3172       t->prev_fc.last_pid_sent = pid;
3173       tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
3174       break;
3175     default:
3176       break;
3177   }
3178
3179   if (GNUNET_YES == t->destroy && 0 == t->pending_messages)
3180   {
3181     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*  destroying tunnel!\n");
3182     tunnel_destroy (t);
3183   }
3184
3185   /* If more data in queue, send next */
3186   queue = queue_get_next (peer);
3187   if (NULL != queue)
3188   {
3189       struct GNUNET_PeerIdentity id;
3190
3191       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   more data!\n");
3192       GNUNET_PEER_resolve (peer->id, &id);
3193       peer->core_transmit =
3194           GNUNET_CORE_notify_transmit_ready(core_handle,
3195                                             0,
3196                                             0,
3197                                             GNUNET_TIME_UNIT_FOREVER_REL,
3198                                             &id,
3199                                             queue->size,
3200                                             &queue_send,
3201                                             peer);
3202   }
3203   else if (NULL != peer->queue_head)
3204   {
3205     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3206                 "*   %s stalled\n",
3207                 GNUNET_i2s (&my_full_id));
3208     if (peer->id == t->next_hop)
3209       fc = &t->next_fc;
3210     else if (peer->id == t->prev_hop)
3211       fc = &t->prev_fc;
3212     else
3213     {
3214       GNUNET_break (0);
3215       return data_size;
3216     }
3217     if (NULL != fc && GNUNET_SCHEDULER_NO_TASK == fc->poll_task)
3218     {
3219       fc->t = t;
3220       fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
3221                                                     &tunnel_poll, fc);
3222     }
3223   }
3224   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*  Return %d\n", data_size);
3225   return data_size;
3226 }
3227
3228
3229 /**
3230  * @brief Queue and pass message to core when possible.
3231  * 
3232  * If type is payload (UNICAST, TO_ORIGIN) checks for queue status and
3233  * accounts for it. In case the queue is full, the message is dropped and
3234  * a break issued.
3235  * 
3236  * Otherwise, message is treated as internal and allowed to go regardless of 
3237  * queue status.
3238  *
3239  * @param cls Closure (@c type dependant). It will be used by queue_send to
3240  *            build the message to be sent if not already prebuilt.
3241  * @param type Type of the message, 0 for a raw message.
3242  * @param size Size of the message.
3243  * @param dst Neighbor to send message to.
3244  * @param t Tunnel this message belongs to.
3245  */
3246 static void
3247 queue_add (void *cls, uint16_t type, size_t size,
3248            struct MeshPeerInfo *dst, struct MeshTunnel *t)
3249 {
3250   struct MeshPeerQueue *queue;
3251   struct GNUNET_PeerIdentity id;
3252   struct MeshFlowControl *fc;
3253   int priority;
3254
3255   fc = NULL;
3256   priority = GNUNET_NO;
3257   if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == type)
3258   {
3259     fc = &t->next_fc;
3260   }
3261   else if (GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == type)
3262   {
3263     fc = &t->prev_fc;
3264   }
3265   if (NULL != fc)
3266   {
3267     if (fc->queue_n >= t->queue_max)
3268     {
3269       GNUNET_break (0);
3270       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3271                   "queue full: %u/%u\n",
3272                   fc->queue_n, t->queue_max);
3273
3274       /* If this isn't a retransmission, drop the message */
3275       if (GNUNET_NO == t->reliable ||
3276           (NULL == t->owner && GNUNET_MESSAGE_TYPE_MESH_UNICAST == type) ||
3277           (NULL == t->client && GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == type))
3278       {
3279         GNUNET_STATISTICS_update (stats, "# messages dropped (buffer full)",
3280                                   1, GNUNET_NO);
3281         return; /* Drop this message */
3282       }
3283       priority = GNUNET_YES;
3284     }
3285     fc->queue_n++;
3286   }
3287   queue = GNUNET_malloc (sizeof (struct MeshPeerQueue));
3288   queue->cls = cls;
3289   queue->type = type;
3290   queue->size = size;
3291   queue->peer = dst;
3292   queue->tunnel = t;
3293   if (GNUNET_YES == priority)
3294     GNUNET_CONTAINER_DLL_insert (dst->queue_head, dst->queue_tail, queue);
3295   else
3296     GNUNET_CONTAINER_DLL_insert_tail (dst->queue_head, dst->queue_tail, queue);
3297   if (NULL == dst->core_transmit)
3298   {
3299     GNUNET_PEER_resolve (dst->id, &id);
3300     dst->core_transmit =
3301         GNUNET_CORE_notify_transmit_ready (core_handle,
3302                                            0,
3303                                            0,
3304                                            GNUNET_TIME_UNIT_FOREVER_REL,
3305                                            &id,
3306                                            size,
3307                                            &queue_send,
3308                                            dst);
3309   }
3310   t->pending_messages++;
3311 }
3312
3313
3314 /******************************************************************************/
3315 /********************      MESH NETWORK HANDLERS     **************************/
3316 /******************************************************************************/
3317
3318
3319 /**
3320  * Core handler for path creation
3321  *
3322  * @param cls closure
3323  * @param message message
3324  * @param peer peer identity this notification is about
3325  *
3326  * @return GNUNET_OK to keep the connection open,
3327  *         GNUNET_SYSERR to close it (signal serious error)
3328  */
3329 static int
3330 handle_mesh_path_create (void *cls, const struct GNUNET_PeerIdentity *peer,
3331                          const struct GNUNET_MessageHeader *message)
3332 {
3333   unsigned int own_pos;
3334   uint16_t size;
3335   uint16_t i;
3336   MESH_TunnelNumber tid;
3337   struct GNUNET_MESH_CreateTunnel *msg;
3338   struct GNUNET_PeerIdentity *pi;
3339   struct MeshPeerPath *path;
3340   struct MeshPeerInfo *dest_peer_info;
3341   struct MeshPeerInfo *orig_peer_info;
3342   struct MeshTunnel *t;
3343
3344   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3345               "Received a path create msg [%s]\n",
3346               GNUNET_i2s (&my_full_id));
3347   size = ntohs (message->size);
3348   if (size < sizeof (struct GNUNET_MESH_CreateTunnel))
3349   {
3350     GNUNET_break_op (0);
3351     return GNUNET_OK;
3352   }
3353
3354   size -= sizeof (struct GNUNET_MESH_CreateTunnel);
3355   if (size % sizeof (struct GNUNET_PeerIdentity))
3356   {
3357     GNUNET_break_op (0);
3358     return GNUNET_OK;
3359   }
3360   size /= sizeof (struct GNUNET_PeerIdentity);
3361   if (size < 1)
3362   {
3363     GNUNET_break_op (0);
3364     return GNUNET_OK;
3365   }
3366   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
3367   msg = (struct GNUNET_MESH_CreateTunnel *) message;
3368
3369   tid = ntohl (msg->tid);
3370   pi = (struct GNUNET_PeerIdentity *) &msg[1];
3371   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3372               "    path is for tunnel %s[%X].\n", GNUNET_i2s (pi), tid);
3373   t = tunnel_get (pi, tid);
3374   if (NULL == t) /* might be a local tunnel */
3375   {
3376     uint32_t opt;
3377
3378     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating tunnel\n");
3379     t = tunnel_new (GNUNET_PEER_intern (pi), tid, NULL, 0);
3380     if (NULL == t)
3381     {
3382       GNUNET_break (0);
3383       return GNUNET_OK;
3384     }
3385     t->port = ntohl (msg->port);
3386     opt = ntohl (msg->opt);
3387     if (0 != (opt & GNUNET_MESH_OPTION_NOBUFFER))
3388     {
3389       t->nobuffer = GNUNET_YES;
3390       t->queue_max = 1;
3391     }
3392     if (0 != (opt & GNUNET_MESH_OPTION_RELIABLE))
3393     {
3394       t->reliable = GNUNET_YES;
3395     }
3396     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  nobuffer:%d\n", t->nobuffer);
3397
3398     tunnel_reset_timeout (t);
3399   }
3400   t->state = MESH_TUNNEL_WAITING;
3401   dest_peer_info =
3402       GNUNET_CONTAINER_multihashmap_get (peers, &pi[size - 1].hashPubKey);
3403   if (NULL == dest_peer_info)
3404   {
3405     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3406                 "  Creating PeerInfo for destination.\n");
3407     dest_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
3408     dest_peer_info->id = GNUNET_PEER_intern (&pi[size - 1]);
3409     GNUNET_CONTAINER_multihashmap_put (peers, &pi[size - 1].hashPubKey,
3410                                        dest_peer_info,
3411                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3412   }
3413   orig_peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &pi->hashPubKey);
3414   if (NULL == orig_peer_info)
3415   {
3416     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3417                 "  Creating PeerInfo for origin.\n");
3418     orig_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
3419     orig_peer_info->id = GNUNET_PEER_intern (pi);
3420     GNUNET_CONTAINER_multihashmap_put (peers, &pi->hashPubKey, orig_peer_info,
3421                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3422   }
3423   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
3424   path = path_new (size);
3425   own_pos = 0;
3426   for (i = 0; i < size; i++)
3427   {
3428     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
3429                 GNUNET_i2s (&pi[i]));
3430     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
3431     if (path->peers[i] == myid)
3432       own_pos = i;
3433   }
3434   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
3435   if (own_pos == 0 && path->peers[own_pos] != myid)
3436   {
3437     /* create path: self not found in path through self */
3438     GNUNET_break_op (0);
3439     path_destroy (path);
3440     tunnel_destroy (t);
3441     return GNUNET_OK;
3442   }
3443   path_add_to_peers (path, GNUNET_NO);
3444   tunnel_use_path (t, path);
3445
3446   peer_info_add_tunnel (dest_peer_info, t);
3447
3448   if (own_pos == size - 1)
3449   {
3450     struct MeshClient *c;
3451
3452     /* Find target client */
3453     c = GNUNET_CONTAINER_multihashmap32_get (ports, t->port);
3454     if (NULL == c)
3455     {
3456       /* TODO send reject */
3457       return GNUNET_OK;
3458     }
3459
3460     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
3461     peer_info_add_path_to_origin (orig_peer_info, path, GNUNET_YES);
3462
3463     /* Assign local tid */
3464     while (NULL != tunnel_get_incoming (next_local_tid))
3465       next_local_tid = (next_local_tid + 1) | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
3466     t->local_tid_dest = next_local_tid++;
3467     next_local_tid = next_local_tid | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
3468
3469     if (GNUNET_YES == t->reliable)
3470     {
3471       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! Reliable\n");
3472       t->bck_rel = GNUNET_malloc (sizeof (struct MeshTunnelReliability));
3473       t->bck_rel->t = t;
3474       t->bck_rel->expected_delay = MESH_RETRANSMIT_TIME;
3475     }
3476
3477     tunnel_add_client (t, c);
3478     send_client_tunnel_create (t);
3479     send_path_ack (t);
3480   }
3481   else
3482   {
3483     struct MeshPeerPath *path2;
3484
3485     t->next_hop = path->peers[own_pos + 1];
3486     GNUNET_PEER_change_rc(t->next_hop, 1);
3487
3488     /* It's for somebody else! Retransmit. */
3489     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Retransmitting.\n");
3490     path2 = path_duplicate (path);
3491     peer_info_add_path (dest_peer_info, path2, GNUNET_NO);
3492     peer_info_add_path_to_origin (orig_peer_info, path, GNUNET_NO);
3493     send_create_path (t);
3494   }
3495   return GNUNET_OK;
3496 }
3497
3498
3499
3500 /**
3501  * Core handler for path ACKs
3502  *
3503  * @param cls closure
3504  * @param message message
3505  * @param peer peer identity this notification is about
3506  *
3507  * @return GNUNET_OK to keep the connection open,
3508  *         GNUNET_SYSERR to close it (signal serious error)
3509  */
3510 static int
3511 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
3512                       const struct GNUNET_MessageHeader *message)
3513 {
3514   struct GNUNET_MESH_PathACK *msg;
3515   struct MeshPeerInfo *peer_info;
3516   struct MeshPeerPath *p;
3517   struct MeshTunnel *t;
3518
3519   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a path ACK msg [%s]\n",
3520               GNUNET_i2s (&my_full_id));
3521   msg = (struct GNUNET_MESH_PathACK *) message;
3522   t = tunnel_get (&msg->oid, ntohl(msg->tid));
3523   if (NULL == t)
3524   {
3525     /* TODO notify that we don't know the tunnel */
3526     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel", 1, GNUNET_NO);
3527     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  don't know the tunnel %s [%X]!\n",
3528                 GNUNET_i2s (&msg->oid), ntohl(msg->tid));
3529     return GNUNET_OK;
3530   }
3531   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %s [%X]\n",
3532               GNUNET_i2s (&msg->oid), ntohl(msg->tid));
3533
3534   peer_info = peer_get (&msg->peer_id);
3535   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by peer %s\n",
3536               GNUNET_i2s (&msg->peer_id));
3537   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  via peer %s\n",
3538               GNUNET_i2s (peer));
3539
3540   /* Add path to peers? */
3541   p = t->path;
3542   if (NULL != p)
3543   {
3544     path_add_to_peers (p, GNUNET_YES);
3545   }
3546   else
3547   {
3548     GNUNET_break (0);
3549   }
3550   t->state = MESH_TUNNEL_READY;
3551   t->next_fc.last_ack_recv = (NULL == t->client) ? ntohl (msg->ack) : 0;
3552   t->prev_fc.last_ack_sent = ntohl (msg->ack);
3553
3554   /* Message for us? */
3555   if (0 == memcmp (&msg->oid, &my_full_id, sizeof (struct GNUNET_PeerIdentity)))
3556   {
3557     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
3558     if (NULL == t->owner)
3559     {
3560       GNUNET_break_op (0);
3561       return GNUNET_OK;
3562     }
3563     if (NULL != peer_info->dhtget)
3564     {
3565       GNUNET_DHT_get_stop (peer_info->dhtget);
3566       peer_info->dhtget = NULL;
3567     }
3568     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK);
3569     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK);
3570     return GNUNET_OK;
3571   }
3572
3573   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3574               "  not for us, retransmitting...\n");
3575   peer_info = peer_get (&msg->oid);
3576   send_prebuilt_message (message, t->prev_hop, t);
3577   return GNUNET_OK;
3578 }
3579
3580
3581 /**
3582  * Core handler for notifications of broken paths
3583  *
3584  * @param cls closure
3585  * @param message message
3586  * @param peer peer identity this notification is about
3587  *
3588  * @return GNUNET_OK to keep the connection open,
3589  *         GNUNET_SYSERR to close it (signal serious error)
3590  */
3591 static int
3592 handle_mesh_path_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
3593                          const struct GNUNET_MessageHeader *message)
3594 {
3595   struct GNUNET_MESH_PathBroken *msg;
3596   struct MeshTunnel *t;
3597
3598   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3599               "Received a PATH BROKEN msg from %s\n", GNUNET_i2s (peer));
3600   msg = (struct GNUNET_MESH_PathBroken *) message;
3601   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
3602               GNUNET_i2s (&msg->peer1));
3603   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
3604               GNUNET_i2s (&msg->peer2));
3605   t = tunnel_get (&msg->oid, ntohl (msg->tid));
3606   if (NULL == t)
3607   {
3608     GNUNET_break_op (0);
3609     return GNUNET_OK;
3610   }
3611   tunnel_notify_connection_broken (t, GNUNET_PEER_search (&msg->peer1),
3612                                    GNUNET_PEER_search (&msg->peer2));
3613   return GNUNET_OK;
3614
3615 }
3616
3617
3618 /**
3619  * Core handler for tunnel destruction
3620  *
3621  * @param cls closure
3622  * @param message message
3623  * @param peer peer identity this notification is about
3624  *
3625  * @return GNUNET_OK to keep the connection open,
3626  *         GNUNET_SYSERR to close it (signal serious error)
3627  */
3628 static int
3629 handle_mesh_tunnel_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
3630                             const struct GNUNET_MessageHeader *message)
3631 {
3632   struct GNUNET_MESH_TunnelDestroy *msg;
3633   struct MeshTunnel *t;
3634
3635   msg = (struct GNUNET_MESH_TunnelDestroy *) message;
3636   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3637               "Got a TUNNEL DESTROY packet from %s\n",
3638               GNUNET_i2s (peer));
3639   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3640               "  for tunnel %s [%u]\n",
3641               GNUNET_i2s (&msg->oid), ntohl (msg->tid));
3642   t = tunnel_get (&msg->oid, ntohl (msg->tid));
3643   if (NULL == t)
3644   {
3645     /* Probably already got the message from another path,
3646      * destroyed the tunnel and retransmitted to children.
3647      * Safe to ignore.
3648      */
3649     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel",
3650                               1, GNUNET_NO);
3651     return GNUNET_OK;
3652   }
3653   if (t->local_tid_dest >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
3654   {
3655     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "INCOMING TUNNEL %X %X\n",
3656                 t->local_tid, t->local_tid_dest);
3657   }
3658   if (GNUNET_PEER_search (peer) == t->prev_hop)
3659   {
3660     // TODO check owner's signature
3661     // TODO add owner's signatue to tunnel for retransmission
3662     peer_cancel_queues (t->prev_hop, t);
3663     GNUNET_PEER_change_rc (t->prev_hop, -1);
3664     t->prev_hop = 0;
3665   }
3666   else if (GNUNET_PEER_search (peer) == t->next_hop)
3667   {
3668     // TODO check dest's signature
3669     // TODO add dest's signatue to tunnel for retransmission
3670     peer_cancel_queues (t->next_hop, t);
3671     GNUNET_PEER_change_rc (t->next_hop, -1);
3672     t->next_hop = 0;
3673   }
3674   else
3675   {
3676     GNUNET_break_op (0);
3677     // TODO check both owner AND destination's signature to see which matches
3678     // TODO restransmit in appropriate direction
3679     return GNUNET_OK;
3680   }
3681   tunnel_destroy_empty (t);
3682
3683   // TODO: add timeout to destroy the tunnel anyway
3684   return GNUNET_OK;
3685 }
3686
3687
3688 /**
3689  * Core handler for mesh network traffic going from the origin to a peer
3690  *
3691  * @param cls closure
3692  * @param peer peer identity this notification is about
3693  * @param message message
3694  * @return GNUNET_OK to keep the connection open,
3695  *         GNUNET_SYSERR to close it (signal serious error)
3696  */
3697 static int
3698 handle_mesh_unicast (void *cls, const struct GNUNET_PeerIdentity *peer,
3699                           const struct GNUNET_MessageHeader *message)
3700 {
3701   struct GNUNET_MESH_Data *msg;
3702   struct MeshTunnel *t;
3703   uint32_t pid;
3704   uint32_t ttl;
3705   size_t size;
3706
3707   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a unicast packet from %s\n",
3708               GNUNET_i2s (peer));
3709   /* Check size */
3710   size = ntohs (message->size);
3711   if (size <
3712       sizeof (struct GNUNET_MESH_Data) +
3713       sizeof (struct GNUNET_MessageHeader))
3714   {
3715     GNUNET_break (0);
3716     return GNUNET_OK;
3717   }
3718   msg = (struct GNUNET_MESH_Data *) message;
3719   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %s\n",
3720               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
3721   /* Check tunnel */
3722   t = tunnel_get (&msg->oid, ntohl (msg->tid));
3723   if (NULL == t)
3724   {
3725     /* TODO notify back: we don't know this tunnel */
3726     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
3727     GNUNET_break_op (0);
3728     return GNUNET_OK;
3729   }
3730   pid = ntohl (msg->pid);
3731   if (GMC_is_pid_bigger (pid, t->prev_fc.last_ack_sent))
3732   {
3733     GNUNET_STATISTICS_update (stats, "# unsolicited unicast", 1, GNUNET_NO);
3734     GNUNET_break_op (0);
3735     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3736                 "Received PID %u, ACK %u\n",
3737                 pid, t->prev_fc.last_ack_sent);
3738     tunnel_send_fwd_ack(t, GNUNET_MESSAGE_TYPE_MESH_POLL);
3739     return GNUNET_OK;
3740   }
3741
3742   tunnel_reset_timeout (t);
3743   if (t->dest == myid)
3744   {
3745     /* TODO signature verification */
3746     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3747                 "  it's for us! sending to clients...\n");
3748     GNUNET_STATISTICS_update (stats, "# unicast received", 1, GNUNET_NO);
3749 //     if (GMC_is_pid_bigger(pid, t->prev_fc.last_pid_recv)) FIXME use
3750     if (GMC_is_pid_bigger (pid, t->prev_fc.last_pid_recv)
3751         &&
3752           (GNUNET_NO == t->reliable ||
3753            GNUNET_ntohll (msg->mid) == (t->bck_rel->mid_recv + 1)) )
3754     {
3755       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3756                   " pid %u not seen yet, forwarding\n", pid);
3757       t->prev_fc.last_pid_recv = pid;
3758       t->bck_rel->mid_recv++;
3759       tunnel_send_client_ucast (t, msg);
3760     }
3761     else
3762     {
3763 //       GNUNET_STATISTICS_update (stats, "# duplicate PID", 1, GNUNET_NO);
3764       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3765                   " Pid %u not expected (%u), sending FWD ACK!\n",
3766                   pid, t->prev_fc.last_pid_recv + 1);
3767     }
3768     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_UNICAST);
3769     return GNUNET_OK;
3770   }
3771   if (GMC_is_pid_bigger(pid, t->prev_fc.last_pid_recv))
3772     t->prev_fc.last_pid_recv = pid;
3773   if (0 == t->next_hop)
3774   {
3775     GNUNET_break (0);
3776     return GNUNET_OK;
3777   }
3778   ttl = ntohl (msg->ttl);
3779   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ttl);
3780   if (ttl == 0)
3781   {
3782     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
3783     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
3784     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
3785     return GNUNET_OK;
3786   }
3787   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3788               "  not for us, retransmitting...\n");
3789
3790   send_prebuilt_message (message, t->next_hop, t);
3791   GNUNET_STATISTICS_update (stats, "# unicast forwarded", 1, GNUNET_NO);
3792   return GNUNET_OK;
3793 }
3794
3795
3796 /**
3797  * Core handler for mesh network traffic toward the owner of a tunnel
3798  *
3799  * @param cls closure
3800  * @param message message
3801  * @param peer peer identity this notification is about
3802  *
3803  * @return GNUNET_OK to keep the connection open,
3804  *         GNUNET_SYSERR to close it (signal serious error)
3805  */
3806 static int
3807 handle_mesh_to_orig (void *cls, const struct GNUNET_PeerIdentity *peer,
3808                           const struct GNUNET_MessageHeader *message)
3809 {
3810   struct GNUNET_MESH_Data *msg;
3811   struct MeshTunnel *t;
3812   size_t size;
3813   uint32_t pid;
3814   uint32_t ttl;
3815
3816   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a ToOrigin packet from %s\n",
3817               GNUNET_i2s (peer));
3818   size = ntohs (message->size);
3819   if (size < sizeof (struct GNUNET_MESH_Data) +     /* Payload must be */
3820       sizeof (struct GNUNET_MessageHeader))     /* at least a header */
3821   {
3822     GNUNET_break_op (0);
3823     return GNUNET_OK;
3824   }
3825   msg = (struct GNUNET_MESH_Data *) message;
3826   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %s\n",
3827               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
3828   t = tunnel_get (&msg->oid, ntohl (msg->tid));
3829   pid = ntohl (msg->pid);
3830   if (NULL == t)
3831   {
3832     /* TODO notify that we dont know this tunnel (whom)? */
3833     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
3834     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3835                 "Received to_origin with PID %u on unknown tunnel %s [%u]\n",
3836                 pid, GNUNET_i2s (&msg->oid), ntohl (msg->tid));
3837     return GNUNET_OK;
3838   }
3839
3840   if (GMC_is_pid_bigger (pid, t->next_fc.last_ack_sent))
3841   {
3842     GNUNET_STATISTICS_update (stats, "# unsolicited to_orig", 1, GNUNET_NO);
3843     GNUNET_break_op (0);
3844     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3845                 "Received PID %u, ACK %u\n",
3846                 pid, t->next_fc.last_ack_sent);
3847     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_POLL);
3848     return GNUNET_OK;
3849   }
3850
3851   if (myid == t->id.oid)
3852   {
3853     /* TODO signature verification */
3854     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3855                 "  it's for us! sending to clients...\n");
3856     GNUNET_STATISTICS_update (stats, "# to origin received", 1, GNUNET_NO);
3857     if ( (GNUNET_NO == t->reliable &&
3858           GMC_is_pid_bigger(pid, t->next_fc.last_pid_recv))
3859         ||
3860           (GNUNET_YES == t->reliable &&
3861            pid == t->next_fc.last_pid_recv + 1) ) // FIXME use "futures" as accepting
3862     {
3863       t->next_fc.last_pid_recv = pid;
3864       tunnel_send_client_to_orig (t, msg);
3865     }
3866     else
3867     {
3868 //       GNUNET_STATISTICS_update (stats, "# duplicate PID drops BCK", 1, GNUNET_NO);
3869       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3870                   " Pid %u not expected, sending FWD ACK!\n", pid);
3871     }
3872     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
3873     return GNUNET_OK;
3874   }
3875   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3876               "  not for us, retransmitting...\n");
3877   if (GMC_is_pid_bigger (pid, t->next_fc.last_pid_recv))
3878     t->next_fc.last_pid_recv = pid;
3879   if (0 == t->prev_hop) /* No owner AND no prev hop */
3880   {
3881     if (GNUNET_YES == t->destroy)
3882     {
3883       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3884                   "to orig received on a dying tunnel %s [%X]\n",
3885                   GNUNET_i2s (&msg->oid), ntohl(msg->tid));
3886       return GNUNET_OK;
3887     }
3888     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
3889                 "unknown to origin at %s\n",
3890                 GNUNET_i2s (&my_full_id));
3891     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
3892                 "from peer %s\n",
3893                 GNUNET_i2s (peer));
3894     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
3895                 "on tunnel %s [%X]\n",
3896                 GNUNET_i2s (&msg->oid), ntohl(msg->tid));
3897     return GNUNET_OK;
3898   }
3899   ttl = ntohl (msg->ttl);
3900   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ttl);
3901   if (ttl == 0)
3902   {
3903     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
3904     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
3905     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
3906     return GNUNET_OK;
3907   }
3908   send_prebuilt_message (message, t->prev_hop, t);
3909   GNUNET_STATISTICS_update (stats, "# to origin forwarded", 1, GNUNET_NO);
3910
3911   return GNUNET_OK;
3912 }
3913
3914
3915 /**
3916  * Core handler for mesh network traffic end-to-end ACKs.
3917  *
3918  * @param cls Closure.
3919  * @param message Message.
3920  * @param peer Peer identity this notification is about.
3921  *
3922  * @return GNUNET_OK to keep the connection open,
3923  *         GNUNET_SYSERR to close it (signal serious error)
3924  */
3925 static int
3926 handle_mesh_data_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
3927                       const struct GNUNET_MessageHeader *message)
3928 {
3929   struct GNUNET_MESH_DataACK *msg;
3930   struct MeshTunnelReliability *rel;
3931   struct MeshReliableMessage *copy;
3932   struct MeshReliableMessage *next;
3933   struct MeshTunnel *t;
3934   GNUNET_PEER_Id id;
3935   uint64_t ack;
3936   uint16_t type;
3937   int work;
3938
3939   type = ntohs (message->type);
3940   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a %s message from %s!\n",
3941               GNUNET_MESH_DEBUG_M2S (type), GNUNET_i2s (peer));
3942   msg = (struct GNUNET_MESH_DataACK *) message;
3943
3944   t = tunnel_get (&msg->oid, ntohl (msg->tid));
3945   if (NULL == t)
3946   {
3947     /* TODO notify that we dont know this tunnel (whom)? */
3948     GNUNET_STATISTICS_update (stats, "# ack on unknown tunnel", 1, GNUNET_NO);
3949     return GNUNET_OK;
3950   }
3951   ack = GNUNET_ntohll (msg->mid);
3952   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ACK %llu\n", ack);
3953
3954   /* Is this a forward or backward ACK? */
3955   id = GNUNET_PEER_search (peer);
3956   if (t->next_hop == id && GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK == type)
3957   {
3958     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
3959     if (NULL == t->owner)
3960     {
3961       send_prebuilt_message (message, t->prev_hop, t);
3962       return GNUNET_OK;
3963     }
3964     rel = t->fwd_rel;
3965     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_UNICAST);
3966   }
3967   else if (t->prev_hop == id && GNUNET_MESSAGE_TYPE_MESH_TO_ORIG_ACK == type)
3968   {
3969     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
3970     if (NULL == t->client)
3971     {
3972       send_prebuilt_message (message, t->next_hop, t);
3973       return GNUNET_OK;
3974     }
3975     rel = t->bck_rel;
3976     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
3977   }
3978   else
3979   {
3980     GNUNET_break_op (0);
3981     return GNUNET_OK;
3982   }
3983
3984   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! ACK %llu\n", ack);
3985   for (work = GNUNET_NO, copy = rel->head_sent; copy != NULL; copy = next)
3986   {
3987     struct GNUNET_TIME_Relative time;
3988
3989     if (copy->mid > ack)
3990     {
3991       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!!  head %llu, out!\n", copy->mid);
3992       break;
3993     }
3994     work = GNUNET_YES;
3995     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!!  id %llu\n", copy->mid);
3996     next = copy->next;
3997     time = GNUNET_TIME_absolute_get_duration (copy->timestamp);
3998     rel->expected_delay.rel_value += time.rel_value;
3999     rel->expected_delay.rel_value /= 2;
4000     rel->n_sent--;
4001     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!!  new expected delay %s\n",
4002                 GNUNET_STRINGS_relative_time_to_string (rel->expected_delay,
4003                                                         GNUNET_NO));
4004     rel->retry_timer = rel->expected_delay;
4005     GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
4006     GNUNET_free (copy);
4007   }
4008
4009   if (GNUNET_YES == work)
4010   {
4011     if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
4012     {
4013       GNUNET_SCHEDULER_cancel (rel->retry_task);
4014       if (NULL == rel->head_sent)
4015       {
4016         rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
4017       }
4018       else
4019       {
4020         struct GNUNET_TIME_Absolute new_target;
4021         struct GNUNET_TIME_Relative delay;
4022
4023         new_target = GNUNET_TIME_absolute_add (rel->head_sent->timestamp,
4024                                                rel->retry_timer);
4025         delay = GNUNET_TIME_absolute_get_remaining (new_target);
4026         rel->retry_task =
4027             GNUNET_SCHEDULER_add_delayed (delay,
4028                                           &tunnel_retransmit_message,
4029                                           rel);
4030       }
4031     }
4032     else
4033       GNUNET_break (0);
4034   }
4035   return GNUNET_OK;
4036 }
4037
4038 /**
4039  * Core handler for mesh network traffic point-to-point acks.
4040  *
4041  * @param cls closure
4042  * @param message message
4043  * @param peer peer identity this notification is about
4044  *
4045  * @return GNUNET_OK to keep the connection open,
4046  *         GNUNET_SYSERR to close it (signal serious error)
4047  */
4048 static int
4049 handle_mesh_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
4050                  const struct GNUNET_MessageHeader *message)
4051 {
4052   struct GNUNET_MESH_ACK *msg;
4053   struct MeshTunnel *t;
4054   struct MeshFlowControl *fc;
4055   GNUNET_PEER_Id id;
4056   uint32_t ack;
4057
4058   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK packet from %s!\n",
4059               GNUNET_i2s (peer));
4060   msg = (struct GNUNET_MESH_ACK *) message;
4061
4062   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4063
4064   if (NULL == t)
4065   {
4066     /* TODO notify that we dont know this tunnel (whom)? */
4067     GNUNET_STATISTICS_update (stats, "# ack on unknown tunnel", 1, GNUNET_NO);
4068     return GNUNET_OK;
4069   }
4070   ack = ntohl (msg->pid);
4071   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ACK %u\n", ack);
4072
4073   /* Is this a forward or backward ACK? */
4074   id = GNUNET_PEER_search (peer);
4075   if (t->next_hop == id)
4076   {
4077     debug_fwd_ack++;
4078     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
4079     fc = &t->next_fc;
4080   }
4081   else if (t->prev_hop == id)
4082   {
4083     debug_bck_ack++;
4084     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
4085     fc = &t->prev_fc;
4086   }
4087   else
4088   {
4089     GNUNET_break_op (0);
4090     return GNUNET_OK;
4091   }
4092
4093   if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task &&
4094       GMC_is_pid_bigger (ack, fc->last_ack_recv))
4095   {
4096     GNUNET_SCHEDULER_cancel (fc->poll_task);
4097     fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
4098     fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
4099   }
4100   fc->last_ack_recv = ack;
4101   peer_unlock_queue (id);
4102
4103   if (t->next_hop == id)
4104     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
4105   else
4106     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
4107
4108   return GNUNET_OK;
4109 }
4110
4111
4112 /**
4113  * Core handler for mesh network traffic point-to-point ack polls.
4114  *
4115  * @param cls closure
4116  * @param message message
4117  * @param peer peer identity this notification is about
4118  *
4119  * @return GNUNET_OK to keep the connection open,
4120  *         GNUNET_SYSERR to close it (signal serious error)
4121  */
4122 static int
4123 handle_mesh_poll (void *cls, const struct GNUNET_PeerIdentity *peer,
4124                   const struct GNUNET_MessageHeader *message)
4125 {
4126   struct GNUNET_MESH_Poll *msg;
4127   struct MeshTunnel *t;
4128   struct MeshFlowControl *fc;
4129   GNUNET_PEER_Id id;
4130   uint32_t pid;
4131   uint32_t old;
4132
4133   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an POLL packet from %s!\n",
4134               GNUNET_i2s (peer));
4135
4136   msg = (struct GNUNET_MESH_Poll *) message;
4137
4138   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4139
4140   if (NULL == t)
4141   {
4142     /* TODO notify that we dont know this tunnel (whom)? */
4143     GNUNET_STATISTICS_update (stats, "# poll on unknown tunnel", 1, GNUNET_NO);
4144     GNUNET_break_op (0);
4145     return GNUNET_OK;
4146   }
4147
4148   /* Is this a forward or backward ACK? */
4149   id = GNUNET_PEER_search(peer);
4150   pid = ntohl (msg->pid);
4151   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  PID %u\n", pid);
4152   if (t->next_hop == id)
4153   {
4154     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  from FWD\n");
4155     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  was %u\n", t->next_fc.last_pid_recv);
4156     fc = &t->next_fc;
4157     old = fc->last_pid_recv;
4158     fc->last_pid_recv = pid;
4159     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_POLL);
4160   }
4161   else if (t->prev_hop == id)
4162   {
4163     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  from BCK\n");
4164     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  was %u\n", t->prev_fc.last_pid_recv);
4165     fc = &t->prev_fc;
4166     old = fc->last_pid_recv;
4167     fc->last_pid_recv = pid;
4168     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_POLL);
4169   }
4170   else
4171     GNUNET_break (0);
4172   
4173   if (GNUNET_YES == t->reliable)
4174     fc->last_pid_recv = old;
4175
4176   return GNUNET_OK;
4177 }
4178
4179
4180 /**
4181  * Core handler for mesh keepalives.
4182  *
4183  * @param cls closure
4184  * @param message message
4185  * @param peer peer identity this notification is about
4186  * @return GNUNET_OK to keep the connection open,
4187  *         GNUNET_SYSERR to close it (signal serious error)
4188  *
4189  * TODO: Check who we got this from, to validate route.
4190  */
4191 static int
4192 handle_mesh_keepalive (void *cls, const struct GNUNET_PeerIdentity *peer,
4193                        const struct GNUNET_MessageHeader *message)
4194 {
4195   struct GNUNET_MESH_TunnelKeepAlive *msg;
4196   struct MeshTunnel *t;
4197
4198   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a keepalive packet from %s\n",
4199               GNUNET_i2s (peer));
4200
4201   msg = (struct GNUNET_MESH_TunnelKeepAlive *) message;
4202   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4203
4204   if (NULL == t)
4205   {
4206     /* TODO notify that we dont know that tunnel */
4207     GNUNET_STATISTICS_update (stats, "# keepalive on unknown tunnel", 1,
4208                               GNUNET_NO);
4209     return GNUNET_OK;
4210   }
4211
4212   tunnel_reset_timeout (t);
4213   if (NULL != t->client || 0 == t->next_hop || myid == t->next_hop)
4214     return GNUNET_OK;
4215
4216   GNUNET_STATISTICS_update (stats, "# keepalives forwarded", 1, GNUNET_NO);
4217   send_prebuilt_message (message, t->next_hop, t);
4218   return GNUNET_OK;
4219   }
4220
4221
4222
4223 /**
4224  * Functions to handle messages from core
4225  */
4226 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
4227   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
4228   {&handle_mesh_path_broken, GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN,
4229    sizeof (struct GNUNET_MESH_PathBroken)},
4230   {&handle_mesh_tunnel_destroy, GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY,
4231    sizeof (struct GNUNET_MESH_TunnelDestroy)},
4232   {&handle_mesh_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
4233   {&handle_mesh_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
4234   {&handle_mesh_data_ack, GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK,
4235     sizeof (struct GNUNET_MESH_DataACK)},
4236   {&handle_mesh_data_ack, GNUNET_MESSAGE_TYPE_MESH_TO_ORIG_ACK,
4237     sizeof (struct GNUNET_MESH_DataACK)},
4238   {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE,
4239     sizeof (struct GNUNET_MESH_TunnelKeepAlive)},
4240   {&handle_mesh_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
4241     sizeof (struct GNUNET_MESH_ACK)},
4242   {&handle_mesh_poll, GNUNET_MESSAGE_TYPE_MESH_POLL,
4243     sizeof (struct GNUNET_MESH_Poll)},
4244   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
4245    sizeof (struct GNUNET_MESH_PathACK)},
4246   {NULL, 0, 0}
4247 };
4248
4249
4250
4251 /******************************************************************************/
4252 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
4253 /******************************************************************************/
4254
4255
4256 #if LATER
4257 /**
4258  * notify_client_connection_failure: notify a client that the connection to the
4259  * requested remote peer is not possible (for instance, no route found)
4260  * Function called when the socket is ready to queue more data. "buf" will be
4261  * NULL and "size" zero if the socket was closed for writing in the meantime.
4262  *
4263  * @param cls closure
4264  * @param size number of bytes available in buf
4265  * @param buf where the callee should write the message
4266  * @return number of bytes written to buf
4267  */
4268 static size_t
4269 notify_client_connection_failure (void *cls, size_t size, void *buf)
4270 {
4271   int size_needed;
4272   struct MeshPeerInfo *peer_info;
4273   struct GNUNET_MESH_PeerControl *msg;
4274   struct GNUNET_PeerIdentity id;
4275
4276   if (0 == size && NULL == buf)
4277   {
4278     // TODO retry? cancel?
4279     return 0;
4280   }
4281
4282   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
4283   peer_info = (struct MeshPeerInfo *) cls;
4284   msg = (struct GNUNET_MESH_PeerControl *) buf;
4285   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
4286   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
4287 //     msg->tunnel_id = htonl(peer_info->t->tid);
4288   GNUNET_PEER_resolve (peer_info->id, &id);
4289   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
4290
4291   return size_needed;
4292 }
4293 #endif
4294
4295
4296 /**
4297  * Send keepalive packets for a tunnel.
4298  *
4299  * @param cls Closure (tunnel for which to send the keepalive).
4300  * @param tc Notification context.
4301  * 
4302  * FIXME: add a refresh reset in case of normal unicast traffic is doing the job
4303  */
4304 static void
4305 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4306 {
4307   struct MeshTunnel *t = cls;
4308   struct GNUNET_MESH_TunnelKeepAlive *msg;
4309   size_t size = sizeof (struct GNUNET_MESH_TunnelKeepAlive);
4310   char cbuf[size];
4311
4312   t->maintenance_task = GNUNET_SCHEDULER_NO_TASK;
4313   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) ||
4314       NULL == t->owner || 0 == t->local_tid)
4315   {
4316     return;
4317   }
4318
4319   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4320               "sending keepalive for tunnel %d\n", t->id.tid);
4321
4322   msg = (struct GNUNET_MESH_TunnelKeepAlive *) cbuf;
4323   msg->header.size = htons (size);
4324   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE);
4325   msg->oid = my_full_id;
4326   msg->tid = htonl (t->id.tid);
4327   send_prebuilt_message (&msg->header, t->next_hop, t);
4328
4329   t->maintenance_task =
4330       GNUNET_SCHEDULER_add_delayed (refresh_path_time, &path_refresh, t);
4331 }
4332
4333
4334 /**
4335  * Function to process paths received for a new peer addition. The recorded
4336  * paths form the initial tunnel, which can be optimized later.
4337  * Called on each result obtained for the DHT search.
4338  *
4339  * @param cls closure
4340  * @param exp when will this value expire
4341  * @param key key of the result
4342  * @param get_path path of the get request
4343  * @param get_path_length lenght of get_path
4344  * @param put_path path of the put request
4345  * @param put_path_length length of the put_path
4346  * @param type type of the result
4347  * @param size number of bytes in data
4348  * @param data pointer to the result data
4349  */
4350 static void
4351 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
4352                     const struct GNUNET_HashCode * key,
4353                     const struct GNUNET_PeerIdentity *get_path,
4354                     unsigned int get_path_length,
4355                     const struct GNUNET_PeerIdentity *put_path,
4356                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
4357                     size_t size, const void *data)
4358 {
4359   struct MeshPeerInfo *peer = cls;
4360   struct MeshPeerPath *p;
4361   struct GNUNET_PeerIdentity pi;
4362   int i;
4363
4364   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
4365   GNUNET_PEER_resolve (peer->id, &pi);
4366   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", GNUNET_i2s (&pi));
4367
4368   p = path_build_from_dht (get_path, get_path_length,
4369                            put_path, put_path_length);
4370   path_add_to_peers (p, GNUNET_NO);
4371   path_destroy (p);
4372   for (i = 0; i < peer->ntunnels; i++)
4373   {
4374     struct GNUNET_PeerIdentity id;
4375
4376     GNUNET_PEER_resolve (peer->tunnels[i]->id.oid, &id);
4377     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ... tunnel %s:%X (%X / %X)\n",
4378                 GNUNET_i2s (&id), peer->tunnels[i]->id.tid,
4379                 peer->tunnels[i]->local_tid, 
4380                 peer->tunnels[i]->local_tid_dest);
4381     if (peer->tunnels[i]->state == MESH_TUNNEL_SEARCHING)
4382     {
4383       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ... connect!\n");
4384       peer_connect (peer, peer->tunnels[i]);
4385     }
4386   }
4387
4388   return;
4389 }
4390
4391
4392 /******************************************************************************/
4393 /*********************       MESH LOCAL HANDLES      **************************/
4394 /******************************************************************************/
4395
4396
4397 /**
4398  * Handler for client disconnection
4399  *
4400  * @param cls closure
4401  * @param client identification of the client; NULL
4402  *        for the last call when the server is destroyed
4403  */
4404 static void
4405 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
4406 {
4407   struct MeshClient *c;
4408   struct MeshClient *next;
4409
4410   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected: %p\n", client);
4411   if (client == NULL)
4412   {
4413     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (SERVER DOWN)\n");
4414     return;
4415   }
4416
4417   c = client_get (client);
4418   if (NULL != c)
4419   {
4420     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u)\n",
4421                 c->id);
4422     GNUNET_SERVER_client_drop (c->handle);
4423     c->shutting_down = GNUNET_YES;
4424     GNUNET_CONTAINER_multihashmap32_iterate (c->own_tunnels,
4425                                              &tunnel_destroy_iterator, c);
4426     GNUNET_CONTAINER_multihashmap32_iterate (c->incoming_tunnels,
4427                                              &tunnel_destroy_iterator, c);
4428     GNUNET_CONTAINER_multihashmap32_destroy (c->own_tunnels);
4429     GNUNET_CONTAINER_multihashmap32_destroy (c->incoming_tunnels);
4430
4431     if (NULL != c->ports)
4432       GNUNET_CONTAINER_multihashmap32_destroy (c->ports);
4433     next = c->next;
4434     GNUNET_CONTAINER_DLL_remove (clients_head, clients_tail, c);
4435     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT FREE at %p\n", c);
4436     GNUNET_free (c);
4437     GNUNET_STATISTICS_update (stats, "# clients", -1, GNUNET_NO);
4438     c = next;
4439   }
4440   else
4441   {
4442     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " context NULL!\n");
4443   }
4444   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "done!\n");
4445   return;
4446 }
4447
4448
4449 /**
4450  * Handler for new clients
4451  *
4452  * @param cls closure
4453  * @param client identification of the client
4454  * @param message the actual message, which includes messages the client wants
4455  */
4456 static void
4457 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
4458                          const struct GNUNET_MessageHeader *message)
4459 {
4460   struct GNUNET_MESH_ClientConnect *cc_msg;
4461   struct MeshClient *c;
4462   unsigned int size;
4463   uint32_t *p;
4464   unsigned int i;
4465
4466   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected %p\n", client);
4467
4468   /* Check data sanity */
4469   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
4470   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
4471   if (0 != (size % sizeof (uint32_t)))
4472   {
4473     GNUNET_break (0);
4474     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4475     return;
4476   }
4477   size /= sizeof (uint32_t);
4478
4479   /* Create new client structure */
4480   c = GNUNET_malloc (sizeof (struct MeshClient));
4481   c->id = next_client_id++; /* overflow not important: just for debug */
4482   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  client id %u\n", c->id);
4483   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  client has %u ports\n", size);
4484   c->handle = client;
4485   GNUNET_SERVER_client_keep (client);
4486   GNUNET_SERVER_client_set_user_context (client, c);
4487   if (size > 0)
4488   {
4489     uint32_t u32;
4490
4491     p = (uint32_t *) &cc_msg[1];
4492     c->ports = GNUNET_CONTAINER_multihashmap32_create (size);
4493     for (i = 0; i < size; i++)
4494     {
4495       u32 = ntohl (p[i]);
4496       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    port: %u\n", u32);
4497
4498       /* store in client's hashmap */
4499       GNUNET_CONTAINER_multihashmap32_put (c->ports, u32, c,
4500                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
4501       /* store in global hashmap */
4502       /* FIXME only allow one client to have the port open,
4503        *       have a backup hashmap with waiting clients */
4504       GNUNET_CONTAINER_multihashmap32_put (ports, u32, c,
4505                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
4506     }
4507   }
4508
4509   GNUNET_CONTAINER_DLL_insert (clients_head, clients_tail, c);
4510   c->own_tunnels = GNUNET_CONTAINER_multihashmap32_create (32);
4511   c->incoming_tunnels = GNUNET_CONTAINER_multihashmap32_create (32);
4512   GNUNET_SERVER_notification_context_add (nc, client);
4513   GNUNET_STATISTICS_update (stats, "# clients", 1, GNUNET_NO);
4514
4515   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4516   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
4517 }
4518
4519
4520 /**
4521  * Handler for requests of new tunnels
4522  *
4523  * @param cls Closure.
4524  * @param client Identification of the client.
4525  * @param message The actual message.
4526  */
4527 static void
4528 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
4529                             const struct GNUNET_MessageHeader *message)
4530 {
4531   struct GNUNET_MESH_TunnelMessage *t_msg;
4532   struct MeshPeerInfo *peer_info;
4533   struct MeshTunnel *t;
4534   struct MeshClient *c;
4535   MESH_TunnelNumber tid;
4536
4537   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel requested\n");
4538
4539   /* Sanity check for client registration */
4540   if (NULL == (c = client_get (client)))
4541   {
4542     GNUNET_break (0);
4543     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4544     return;
4545   }
4546   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
4547
4548   /* Message size sanity check */
4549   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
4550   {
4551     GNUNET_break (0);
4552     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4553     return;
4554   }
4555
4556   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
4557   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  towards %s\n",
4558               GNUNET_i2s (&t_msg->peer));
4559   /* Sanity check for tunnel numbering */
4560   tid = ntohl (t_msg->tunnel_id);
4561   if (0 == (tid & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
4562   {
4563     GNUNET_break (0);
4564     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4565     return;
4566   }
4567   /* Sanity check for duplicate tunnel IDs */
4568   if (NULL != tunnel_get_by_local_id (c, tid))
4569   {
4570     GNUNET_break (0);
4571     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4572     return;
4573   }
4574
4575   /* Create tunnel */
4576   while (NULL != tunnel_get_by_pi (myid, next_tid))
4577     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
4578   t = tunnel_new (myid, next_tid, c, tid);
4579   next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
4580   if (NULL == t)
4581   {
4582     GNUNET_break (0);
4583     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4584     return;
4585   }
4586   t->port = ntohl (t_msg->port);
4587   tunnel_set_options (t, ntohl (t_msg->options));
4588   if (GNUNET_YES == t->reliable)
4589   {
4590     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! Reliable\n");
4591     t->fwd_rel = GNUNET_malloc (sizeof (struct MeshTunnelReliability));
4592     t->fwd_rel->t = t;
4593     t->fwd_rel->expected_delay = MESH_RETRANSMIT_TIME;
4594   }
4595
4596   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED TUNNEL %s[%x]:%u (%x)\n",
4597               GNUNET_i2s (&my_full_id), t->id.tid, t->port, t->local_tid);
4598
4599   peer_info = peer_get (&t_msg->peer);
4600   peer_info_add_tunnel (peer_info, t);
4601   peer_connect (peer_info, t);
4602   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4603   return;
4604 }
4605
4606
4607 /**
4608  * Handler for requests of deleting tunnels
4609  *
4610  * @param cls closure
4611  * @param client identification of the client
4612  * @param message the actual message
4613  */
4614 static void
4615 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
4616                              const struct GNUNET_MessageHeader *message)
4617 {
4618   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
4619   struct MeshClient *c;
4620   struct MeshTunnel *t;
4621   MESH_TunnelNumber tid;
4622
4623   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4624               "Got a DESTROY TUNNEL from client!\n");
4625
4626   /* Sanity check for client registration */
4627   if (NULL == (c = client_get (client)))
4628   {
4629     GNUNET_break (0);
4630     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4631     return;
4632   }
4633   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
4634
4635   /* Message sanity check */
4636   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
4637   {
4638     GNUNET_break (0);
4639     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4640     return;
4641   }
4642
4643   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
4644
4645   /* Retrieve tunnel */
4646   tid = ntohl (tunnel_msg->tunnel_id);
4647   t = tunnel_get_by_local_id(c, tid);
4648   if (NULL == t)
4649   {
4650     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
4651     GNUNET_break (0);
4652     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4653     return;
4654   }
4655
4656   /* Cleanup after the tunnel */
4657   client_delete_tunnel (c, t);
4658   if (c == t->client)
4659   {
4660     t->client = NULL;
4661   }
4662   if (c == t->owner)
4663   {
4664     peer_info_remove_tunnel (peer_get_short (t->dest), t);
4665     t->owner = NULL;
4666   }
4667
4668   /* The tunnel will be destroyed when the last message is transmitted. */
4669   tunnel_destroy_empty (t);
4670
4671   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4672   return;
4673 }
4674
4675
4676 /**
4677  * Handler for client traffic
4678  *
4679  * @param cls closure
4680  * @param client identification of the client
4681  * @param message the actual message
4682  */
4683 static void
4684 handle_local_data (void *cls, struct GNUNET_SERVER_Client *client,
4685                    const struct GNUNET_MessageHeader *message)
4686 {
4687   struct GNUNET_MESH_LocalData *data_msg;
4688   struct MeshClient *c;
4689   struct MeshTunnel *t;
4690   struct MeshFlowControl *fc;
4691   MESH_TunnelNumber tid;
4692   size_t size;
4693
4694   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4695               "Got data from a client!\n");
4696
4697   /* Sanity check for client registration */
4698   if (NULL == (c = client_get (client)))
4699   {
4700     GNUNET_break (0);
4701     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4702     return;
4703   }
4704   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
4705
4706   data_msg = (struct GNUNET_MESH_LocalData *) message;
4707
4708   /* Sanity check for message size */
4709   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_LocalData);
4710   if (size < sizeof (struct GNUNET_MessageHeader))
4711   {
4712     GNUNET_break (0);
4713     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4714     return;
4715   }
4716
4717   /* Tunnel exists? */
4718   tid = ntohl (data_msg->tid);
4719   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_CLI)
4720   {
4721     GNUNET_break (0);
4722     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4723     return;
4724   }
4725   t = tunnel_get_by_local_id (c, tid);
4726   if (NULL == t)
4727   {
4728     GNUNET_break (0);
4729     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4730     return;
4731   }
4732
4733   /* Is the client in the tunnel? */
4734   if ( !( (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV &&
4735            t->owner &&
4736            t->owner->handle == client)
4737          ||
4738           (tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV &&
4739            t->client && 
4740            t->client->handle == client) ) )
4741   {
4742     GNUNET_break (0);
4743     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4744     return;
4745   }
4746
4747   /* Ok, everything is correct, send the message
4748    * (pretend we got it from a mesh peer)
4749    */
4750   {
4751     struct GNUNET_MESH_Data *payload;
4752     char cbuf[sizeof(struct GNUNET_MESH_Data) + size];
4753
4754     fc = tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV ? &t->prev_fc : &t->next_fc;
4755     if (GNUNET_YES == t->reliable)
4756     {
4757       struct MeshTunnelReliability *rel;
4758       struct MeshReliableMessage *copy;
4759
4760       rel = (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV) ? t->fwd_rel : t->bck_rel;
4761       copy = GNUNET_malloc (sizeof (struct MeshReliableMessage)
4762                             + sizeof(struct GNUNET_MESH_Data)
4763                             + size);
4764       copy->mid = rel->mid_sent++;
4765       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! DATA %llu\n", copy->mid);
4766       copy->timestamp = GNUNET_TIME_absolute_get ();
4767       copy->rel = rel;
4768       rel->n_sent++;
4769       GNUNET_CONTAINER_DLL_insert_tail (rel->head_sent, rel->tail_sent, copy);
4770       if (GNUNET_SCHEDULER_NO_TASK == rel->retry_task)
4771       {
4772         rel->retry_timer =
4773             GNUNET_TIME_relative_multiply (rel->expected_delay,
4774                                            MESH_RETRANSMIT_MARGIN);
4775         rel->retry_task =
4776             GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
4777                                           &tunnel_retransmit_message,
4778                                           rel);
4779       }
4780       payload = (struct GNUNET_MESH_Data *) &copy[1];
4781       payload->mid = GNUNET_htonll (copy->mid);
4782     }
4783     else
4784     {
4785       payload = (struct GNUNET_MESH_Data *) cbuf;
4786       payload->mid = 0;
4787       // FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME 
4788       // use different struct for unreliable traffic, save 8 bytes
4789     }
4790     memcpy (&payload[1], &data_msg[1], size);
4791     payload->header.size = htons (sizeof (struct GNUNET_MESH_Data) + size);
4792     payload->header.type = htons (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV ?
4793                                   GNUNET_MESSAGE_TYPE_MESH_UNICAST :
4794                                   GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
4795     GNUNET_PEER_resolve(t->id.oid, &payload->oid);;
4796     payload->tid = htonl (t->id.tid);
4797     payload->ttl = htonl (default_ttl);
4798     payload->pid = htonl (fc->last_pid_recv + 1);
4799     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4800                 "  calling generic handler...\n");
4801     if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
4802       handle_mesh_unicast (NULL, &my_full_id, &payload->header);
4803     else
4804       handle_mesh_to_orig (NULL, &my_full_id, &payload->header);
4805   }
4806   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "receive done OK\n");
4807   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4808
4809   return;
4810 }
4811
4812
4813 /**
4814  * Handler for client's ACKs for payload traffic.
4815  *
4816  * @param cls Closure (unused).
4817  * @param client Identification of the client.
4818  * @param message The actual message.
4819  */
4820 static void
4821 handle_local_ack (void *cls, struct GNUNET_SERVER_Client *client,
4822                   const struct GNUNET_MessageHeader *message)
4823 {
4824   struct GNUNET_MESH_LocalAck *msg;
4825   struct MeshTunnel *t;
4826   struct MeshClient *c;
4827   MESH_TunnelNumber tid;
4828
4829   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a local ACK\n");
4830   /* Sanity check for client registration */
4831   if (NULL == (c = client_get (client)))
4832   {
4833     GNUNET_break (0);
4834     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4835     return;
4836   }
4837   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
4838
4839   msg = (struct GNUNET_MESH_LocalAck *) message;
4840
4841   /* Tunnel exists? */
4842   tid = ntohl (msg->tunnel_id);
4843   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
4844   t = tunnel_get_by_local_id (c, tid);
4845   if (NULL == t)
4846   {
4847     GNUNET_break (0);
4848     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
4849     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
4850     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4851     return;
4852   }
4853
4854   /* Does client own tunnel? I.E: Is this an ACK for BCK traffic? */
4855   if (t->owner == c)
4856   {
4857     /* The client owns the tunnel, ACK is for data to_origin, send BCK ACK. */
4858     t->prev_fc.last_ack_recv++;
4859     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
4860   }
4861   else
4862   {
4863     /* The client doesn't own the tunnel, this ACK is for FWD traffic. */
4864     t->next_fc.last_ack_recv++;
4865     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
4866   }
4867
4868   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4869
4870   return;
4871 }
4872
4873
4874
4875 /**
4876  * Iterator over all tunnels to send a monitoring client info about each tunnel.
4877  *
4878  * @param cls Closure (client handle).
4879  * @param key Key (hashed tunnel ID, unused).
4880  * @param value Tunnel info.
4881  *
4882  * @return GNUNET_YES, to keep iterating.
4883  */
4884 static int
4885 monitor_all_tunnels_iterator (void *cls,
4886                               const struct GNUNET_HashCode * key,
4887                               void *value)
4888 {
4889   struct GNUNET_SERVER_Client *client = cls;
4890   struct MeshTunnel *t = value;
4891   struct GNUNET_MESH_LocalMonitor *msg;
4892
4893   msg = GNUNET_malloc (sizeof(struct GNUNET_MESH_LocalMonitor));
4894   GNUNET_PEER_resolve(t->id.oid, &msg->owner);
4895   msg->tunnel_id = htonl (t->id.tid);
4896   msg->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
4897   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS);
4898   GNUNET_PEER_resolve (t->dest, &msg->destination);
4899
4900   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4901               "*  sending info about tunnel %s [%u]\n",
4902               GNUNET_i2s (&msg->owner), t->id.tid);
4903
4904   GNUNET_SERVER_notification_context_unicast (nc, client,
4905                                               &msg->header, GNUNET_NO);
4906   return GNUNET_YES;
4907 }
4908
4909
4910 /**
4911  * Handler for client's MONITOR request.
4912  *
4913  * @param cls Closure (unused).
4914  * @param client Identification of the client.
4915  * @param message The actual message.
4916  */
4917 static void
4918 handle_local_get_tunnels (void *cls, struct GNUNET_SERVER_Client *client,
4919                           const struct GNUNET_MessageHeader *message)
4920 {
4921   struct MeshClient *c;
4922
4923   /* Sanity check for client registration */
4924   if (NULL == (c = client_get (client)))
4925   {
4926     GNUNET_break (0);
4927     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4928     return;
4929   }
4930
4931   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4932               "Received get tunnels request from client %u\n",
4933               c->id);
4934   GNUNET_CONTAINER_multihashmap_iterate (tunnels,
4935                                          monitor_all_tunnels_iterator,
4936                                          client);
4937   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4938               "Get tunnels request from client %u completed\n",
4939               c->id);
4940   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4941 }
4942
4943
4944 /**
4945  * Handler for client's MONITOR_TUNNEL request.
4946  *
4947  * @param cls Closure (unused).
4948  * @param client Identification of the client.
4949  * @param message The actual message.
4950  */
4951 static void
4952 handle_local_show_tunnel (void *cls, struct GNUNET_SERVER_Client *client,
4953                           const struct GNUNET_MessageHeader *message)
4954 {
4955   const struct GNUNET_MESH_LocalMonitor *msg;
4956   struct GNUNET_MESH_LocalMonitor *resp;
4957   struct MeshClient *c;
4958   struct MeshTunnel *t;
4959
4960   /* Sanity check for client registration */
4961   if (NULL == (c = client_get (client)))
4962   {
4963     GNUNET_break (0);
4964     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4965     return;
4966   }
4967
4968   msg = (struct GNUNET_MESH_LocalMonitor *) message;
4969   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4970               "Received tunnel info request from client %u for tunnel %s[%X]\n",
4971               c->id,
4972               &msg->owner,
4973               ntohl (msg->tunnel_id));
4974   t = tunnel_get (&msg->owner, ntohl (msg->tunnel_id));
4975   if (NULL == t)
4976   {
4977     /* We don't know the tunnel FIXME */
4978     struct GNUNET_MESH_LocalMonitor warn;
4979
4980     warn = *msg;
4981     GNUNET_SERVER_notification_context_unicast (nc, client,
4982                                                 &warn.header,
4983                                                 GNUNET_NO);
4984     GNUNET_SERVER_receive_done (client, GNUNET_OK);
4985     return;
4986   }
4987
4988   /* Initialize context */
4989   resp = GNUNET_malloc (sizeof (struct GNUNET_MESH_LocalMonitor));
4990   *resp = *msg;
4991   GNUNET_PEER_resolve (t->dest, &resp->destination);
4992   resp->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
4993   GNUNET_SERVER_notification_context_unicast (nc, c->handle,
4994                                               &resp->header, GNUNET_NO);
4995   GNUNET_free (resp);
4996
4997   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4998               "Monitor tunnel request from client %u completed\n",
4999               c->id);
5000   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5001 }
5002
5003
5004 /**
5005  * Functions to handle messages from clients
5006  */
5007 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
5008   {&handle_local_new_client, NULL,
5009    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
5010   {&handle_local_tunnel_create, NULL,
5011    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
5012    sizeof (struct GNUNET_MESH_TunnelMessage)},
5013   {&handle_local_tunnel_destroy, NULL,
5014    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
5015    sizeof (struct GNUNET_MESH_TunnelMessage)},
5016   {&handle_local_data, NULL,
5017    GNUNET_MESSAGE_TYPE_MESH_LOCAL_DATA, 0},
5018   {&handle_local_ack, NULL,
5019    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK,
5020    sizeof (struct GNUNET_MESH_LocalAck)},
5021   {&handle_local_get_tunnels, NULL,
5022    GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS,
5023    sizeof (struct GNUNET_MessageHeader)},
5024   {&handle_local_show_tunnel, NULL,
5025    GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNEL,
5026      sizeof (struct GNUNET_MESH_LocalMonitor)},
5027   {NULL, NULL, 0, 0}
5028 };
5029
5030
5031 /**
5032  * Method called whenever a given peer connects.
5033  *
5034  * @param cls closure
5035  * @param peer peer identity this notification is about
5036  */
5037 static void
5038 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer)
5039 {
5040   struct MeshPeerInfo *peer_info;
5041   struct MeshPeerPath *path;
5042
5043   DEBUG_CONN ("Peer connected\n");
5044   DEBUG_CONN ("     %s\n", GNUNET_i2s (&my_full_id));
5045   peer_info = peer_get (peer);
5046   if (myid == peer_info->id)
5047   {
5048     DEBUG_CONN ("     (self)\n");
5049     path = path_new (1);
5050   }
5051   else
5052   {
5053     DEBUG_CONN ("     %s\n", GNUNET_i2s (peer));
5054     path = path_new (2);
5055     path->peers[1] = peer_info->id;
5056     GNUNET_PEER_change_rc (peer_info->id, 1);
5057     GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
5058   }
5059   path->peers[0] = myid;
5060   GNUNET_PEER_change_rc (myid, 1);
5061   peer_info_add_path (peer_info, path, GNUNET_YES);
5062   return;
5063 }
5064
5065
5066 /**
5067  * Method called whenever a peer disconnects.
5068  *
5069  * @param cls closure
5070  * @param peer peer identity this notification is about
5071  */
5072 static void
5073 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
5074 {
5075   struct MeshPeerInfo *pi;
5076   struct MeshPeerQueue *q;
5077   struct MeshPeerQueue *n;
5078
5079   DEBUG_CONN ("Peer disconnected\n");
5080   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
5081   if (NULL == pi)
5082   {
5083     GNUNET_break (0);
5084     return;
5085   }
5086   q = pi->queue_head;
5087   while (NULL != q)
5088   {
5089       n = q->next;
5090       /* TODO try to reroute this traffic instead */
5091       queue_destroy(q, GNUNET_YES);
5092       q = n;
5093   }
5094   if (NULL != pi->core_transmit)
5095   {
5096     GNUNET_CORE_notify_transmit_ready_cancel(pi->core_transmit);
5097     pi->core_transmit = NULL;
5098   }
5099     peer_remove_path (pi, pi->id, myid);
5100   if (myid == pi->id)
5101   {
5102     DEBUG_CONN ("     (self)\n");
5103   }
5104   GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
5105   return;
5106 }
5107
5108
5109 /**
5110  * Install server (service) handlers and start listening to clients.
5111  */
5112 static void
5113 server_init (void)
5114 {
5115   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
5116   GNUNET_SERVER_disconnect_notify (server_handle,
5117                                    &handle_local_client_disconnect, NULL);
5118   nc = GNUNET_SERVER_notification_context_create (server_handle, 1);
5119
5120   clients_head = NULL;
5121   clients_tail = NULL;
5122   next_client_id = 0;
5123   GNUNET_SERVER_resume (server_handle);
5124 }
5125
5126
5127 /**
5128  * To be called on core init/fail.
5129  *
5130  * @param cls Closure (config)
5131  * @param server handle to the server for this service
5132  * @param identity the public identity of this peer
5133  */
5134 static void
5135 core_init (void *cls, struct GNUNET_CORE_Handle *server,
5136            const struct GNUNET_PeerIdentity *identity)
5137 {
5138   const struct GNUNET_CONFIGURATION_Handle *c = cls;
5139   static int i = 0;
5140
5141   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
5142   GNUNET_break (core_handle == server);
5143   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)) ||
5144     NULL == server)
5145   {
5146     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
5147     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5148                 " core id %s\n",
5149                 GNUNET_i2s (identity));
5150     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5151                 " my id %s\n",
5152                 GNUNET_i2s (&my_full_id));
5153     GNUNET_CORE_disconnect (core_handle);
5154     core_handle = GNUNET_CORE_connect (c, /* Main configuration */
5155                                        NULL,      /* Closure passed to MESH functions */
5156                                        &core_init,        /* Call core_init once connected */
5157                                        &core_connect,     /* Handle connects */
5158                                        &core_disconnect,  /* remove peers on disconnects */
5159                                        NULL,      /* Don't notify about all incoming messages */
5160                                        GNUNET_NO, /* For header only in notification */
5161                                        NULL,      /* Don't notify about all outbound messages */
5162                                        GNUNET_NO, /* For header-only out notification */
5163                                        core_handlers);    /* Register these handlers */
5164     if (10 < i++)
5165       GNUNET_abort();
5166   }
5167   server_init ();
5168   return;
5169 }
5170
5171
5172 /******************************************************************************/
5173 /************************      MAIN FUNCTIONS      ****************************/
5174 /******************************************************************************/
5175
5176 /**
5177  * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
5178  *
5179  * @param cls closure
5180  * @param key current key code
5181  * @param value value in the hash map
5182  * @return GNUNET_YES if we should continue to iterate,
5183  *         GNUNET_NO if not.
5184  */
5185 static int
5186 shutdown_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
5187 {
5188   struct MeshTunnel *t = value;
5189
5190   tunnel_destroy (t);
5191   return GNUNET_YES;
5192 }
5193
5194 /**
5195  * Iterator over peer hash map entries to destroy the tunnel during shutdown.
5196  *
5197  * @param cls closure
5198  * @param key current key code
5199  * @param value value in the hash map
5200  * @return GNUNET_YES if we should continue to iterate,
5201  *         GNUNET_NO if not.
5202  */
5203 static int
5204 shutdown_peer (void *cls, const struct GNUNET_HashCode * key, void *value)
5205 {
5206   struct MeshPeerInfo *p = value;
5207   struct MeshPeerQueue *q;
5208   struct MeshPeerQueue *n;
5209
5210   q = p->queue_head;
5211   while (NULL != q)
5212   {
5213       n = q->next;
5214       if (q->peer == p)
5215       {
5216         queue_destroy(q, GNUNET_YES);
5217       }
5218       q = n;
5219   }
5220   peer_info_destroy (p);
5221   return GNUNET_YES;
5222 }
5223
5224
5225 /**
5226  * Task run during shutdown.
5227  *
5228  * @param cls unused
5229  * @param tc unused
5230  */
5231 static void
5232 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
5233 {
5234   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
5235
5236   if (core_handle != NULL)
5237   {
5238     GNUNET_CORE_disconnect (core_handle);
5239     core_handle = NULL;
5240   }
5241   GNUNET_CONTAINER_multihashmap_iterate (tunnels, &shutdown_tunnel, NULL);
5242   GNUNET_CONTAINER_multihashmap_iterate (peers, &shutdown_peer, NULL);
5243   if (dht_handle != NULL)
5244   {
5245     GNUNET_DHT_disconnect (dht_handle);
5246     dht_handle = NULL;
5247   }
5248   if (nc != NULL)
5249   {
5250     GNUNET_SERVER_notification_context_destroy (nc);
5251     nc = NULL;
5252   }
5253   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
5254   {
5255     GNUNET_SCHEDULER_cancel (announce_id_task);
5256     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
5257   }
5258   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
5259 }
5260
5261
5262 /**
5263  * Process mesh requests.
5264  *
5265  * @param cls closure
5266  * @param server the initialized server
5267  * @param c configuration to use
5268  */
5269 static void
5270 run (void *cls, struct GNUNET_SERVER_Handle *server,
5271      const struct GNUNET_CONFIGURATION_Handle *c)
5272 {
5273   char *keyfile;
5274   struct GNUNET_CRYPTO_EccPrivateKey *pk;
5275
5276   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
5277   server_handle = server;
5278   GNUNET_SERVER_suspend (server_handle);
5279
5280   if (GNUNET_OK !=
5281       GNUNET_CONFIGURATION_get_value_filename (c, "PEER", "PRIVATE_KEY",
5282                                                &keyfile))
5283   {
5284     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5285                 _
5286                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5287                 "mesh", "peer/privatekey");
5288     GNUNET_SCHEDULER_shutdown ();
5289     return;
5290   }
5291
5292   if (GNUNET_OK !=
5293       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_PATH_TIME",
5294                                            &refresh_path_time))
5295   {
5296     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5297                 _
5298                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5299                 "mesh", "refresh path time");
5300     GNUNET_SCHEDULER_shutdown ();
5301     return;
5302   }
5303
5304   if (GNUNET_OK !=
5305       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "ID_ANNOUNCE_TIME",
5306                                            &id_announce_time))
5307   {
5308     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5309                 _
5310                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5311                 "mesh", "id announce time");
5312     GNUNET_SCHEDULER_shutdown ();
5313     return;
5314   }
5315
5316   if (GNUNET_OK !=
5317       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "CONNECT_TIMEOUT",
5318                                            &connect_timeout))
5319   {
5320     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5321                 _
5322                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5323                 "mesh", "connect timeout");
5324     GNUNET_SCHEDULER_shutdown ();
5325     return;
5326   }
5327
5328   if (GNUNET_OK !=
5329       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
5330                                              &max_msgs_queue))
5331   {
5332     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5333                 _
5334                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5335                 "mesh", "max msgs queue");
5336     GNUNET_SCHEDULER_shutdown ();
5337     return;
5338   }
5339
5340   if (GNUNET_OK !=
5341       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_TUNNELS",
5342                                              &max_tunnels))
5343   {
5344     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5345                 _
5346                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5347                 "mesh", "max tunnels");
5348     GNUNET_SCHEDULER_shutdown ();
5349     return;
5350   }
5351
5352   if (GNUNET_OK !=
5353       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
5354                                              &default_ttl))
5355   {
5356     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5357                 _
5358                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
5359                 "mesh", "default ttl", 64);
5360     default_ttl = 64;
5361   }
5362
5363   if (GNUNET_OK !=
5364       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_PEERS",
5365                                              &max_peers))
5366   {
5367     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5368                 _("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
5369                 "mesh", "max peers", 1000);
5370     max_peers = 1000;
5371   }
5372
5373   if (GNUNET_OK !=
5374       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DROP_PERCENT",
5375                                              &drop_percent))
5376   {
5377     drop_percent = 0;
5378   }
5379   else
5380   {
5381     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5382                 "Mesh is running with drop mode enabled. "
5383                 "This is NOT a good idea! "
5384                 "Remove the DROP_PERCENT option from your configuration.\n");
5385   }
5386
5387   if (GNUNET_OK !=
5388       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DHT_REPLICATION_LEVEL",
5389                                              &dht_replication_level))
5390   {
5391     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5392                 _
5393                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
5394                 "mesh", "dht replication level", 3);
5395     dht_replication_level = 3;
5396   }
5397
5398   tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
5399   incoming_tunnels = GNUNET_CONTAINER_multihashmap32_create (32);
5400   peers = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
5401   ports = GNUNET_CONTAINER_multihashmap32_create (32);
5402
5403   dht_handle = GNUNET_DHT_connect (c, 64);
5404   if (NULL == dht_handle)
5405   {
5406     GNUNET_break (0);
5407   }
5408   stats = GNUNET_STATISTICS_create ("mesh", c);
5409
5410   /* Scheduled the task to clean up when shutdown is called */
5411   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
5412                                 NULL);
5413   pk = GNUNET_CRYPTO_ecc_key_create_from_file (keyfile);
5414   GNUNET_free (keyfile);
5415   GNUNET_assert (NULL != pk);
5416   my_private_key = pk;
5417   GNUNET_CRYPTO_ecc_key_get_public (my_private_key, &my_public_key);
5418   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
5419                       &my_full_id.hashPubKey);
5420   myid = GNUNET_PEER_intern (&my_full_id);
5421   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5422               "Mesh for peer [%s] starting\n",
5423               GNUNET_i2s(&my_full_id));
5424
5425   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
5426                                      NULL,      /* Closure passed to MESH functions */
5427                                      &core_init,        /* Call core_init once connected */
5428                                      &core_connect,     /* Handle connects */
5429                                      &core_disconnect,  /* remove peers on disconnects */
5430                                      NULL,      /* Don't notify about all incoming messages */
5431                                      GNUNET_NO, /* For header only in notification */
5432                                      NULL,      /* Don't notify about all outbound messages */
5433                                      GNUNET_NO, /* For header-only out notification */
5434                                      core_handlers);    /* Register these handlers */
5435   if (NULL == core_handle)
5436   {
5437     GNUNET_break (0);
5438     GNUNET_SCHEDULER_shutdown ();
5439     return;
5440   }
5441   next_tid = 0;
5442   next_local_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
5443   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
5444   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Mesh service running\n");
5445 }
5446
5447
5448 /**
5449  * The main function for the mesh service.
5450  *
5451  * @param argc number of arguments from the command line
5452  * @param argv command line arguments
5453  * @return 0 ok, 1 on error
5454  */
5455 int
5456 main (int argc, char *const *argv)
5457 {
5458   int ret;
5459   int r;
5460
5461   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
5462   r = GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
5463                           NULL);
5464   ret = (GNUNET_OK == r) ? 0 : 1;
5465   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");
5466
5467   INTERVAL_SHOW;
5468
5469   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5470               "Mesh for peer [%s] FWD ACKs %u, BCK ACKs %u\n",
5471               GNUNET_i2s(&my_full_id), debug_fwd_ack, debug_bck_ack);
5472
5473   return ret;
5474 }