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