a03308fb823b61236dc1203bda76f122e821655f
[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 (GNUNET_YES == t->destroy);
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 (GNUNET_SCHEDULER_NO_TASK != t->next_fc.poll_task)
2796   {
2797     GNUNET_SCHEDULER_cancel (t->next_fc.poll_task);
2798     t->next_fc.poll_task = GNUNET_SCHEDULER_NO_TASK;
2799   }
2800   if (GNUNET_SCHEDULER_NO_TASK != t->prev_fc.poll_task)
2801   {
2802     GNUNET_SCHEDULER_cancel (t->prev_fc.poll_task);
2803     t->prev_fc.poll_task = GNUNET_SCHEDULER_NO_TASK;
2804   }
2805   if (0 != t->dest) {
2806       peer_info_remove_tunnel (peer_get_short (t->dest), t);
2807   }
2808
2809   if (GNUNET_SCHEDULER_NO_TASK != t->maintenance_task)
2810     GNUNET_SCHEDULER_cancel (t->maintenance_task);
2811
2812   n_tunnels--;
2813   GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
2814   path_destroy (t->path);
2815   GNUNET_free (t);
2816   return r;
2817 }
2818
2819 /**
2820  * Tunnel is empty: destroy it.
2821  * 
2822  * Notifies all participants (peers, cleints) about the destruction.
2823  * 
2824  * @param t Tunnel to destroy. 
2825  */
2826 static void
2827 tunnel_destroy_empty (struct MeshTunnel *t)
2828 {
2829   #if MESH_DEBUG
2830   {
2831     struct GNUNET_PeerIdentity id;
2832
2833     GNUNET_PEER_resolve (t->id.oid, &id);
2834     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2835                 "executing destruction of empty tunnel %s [%X]\n",
2836                 GNUNET_i2s (&id), t->id.tid);
2837   }
2838   #endif
2839
2840   if (GNUNET_NO == t->destroy)
2841     tunnel_send_destroy (t);
2842   if (0 == t->pending_messages)
2843     tunnel_destroy (t);
2844   else
2845     t->destroy = GNUNET_YES;
2846 }
2847
2848 /**
2849  * Initialize a Flow Control structure to the initial state.
2850  * 
2851  * @param fc Flow Control structure to initialize.
2852  */
2853 static void
2854 fc_init (struct MeshFlowControl *fc)
2855 {
2856   fc->last_pid_sent = (uint32_t) -1; /* Next (expected) = 0 */
2857   fc->last_pid_recv = (uint32_t) -1;
2858   fc->last_ack_sent = (uint32_t) -1; /* No traffic allowed yet */
2859   fc->last_ack_recv = (uint32_t) -1;
2860   fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
2861   fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
2862   fc->queue_n = 0;
2863 }
2864
2865 /**
2866  * Create a new tunnel
2867  * 
2868  * @param owner Who is the owner of the tunnel (short ID).
2869  * @param tid Tunnel Number of the tunnel.
2870  * @param client Clients that owns the tunnel, NULL for foreign tunnels.
2871  * @param local Tunnel Number for the tunnel, for the client point of view.
2872  * 
2873  * @return A new initialized tunnel. NULL on error.
2874  */
2875 static struct MeshTunnel *
2876 tunnel_new (GNUNET_PEER_Id owner,
2877             MESH_TunnelNumber tid,
2878             struct MeshClient *client,
2879             MESH_TunnelNumber local)
2880 {
2881   struct MeshTunnel *t;
2882   struct GNUNET_HashCode hash;
2883
2884   if (n_tunnels >= max_tunnels && NULL == client)
2885     return NULL;
2886
2887   t = GNUNET_malloc (sizeof (struct MeshTunnel));
2888   t->id.oid = owner;
2889   t->id.tid = tid;
2890   t->queue_max = (max_msgs_queue / max_tunnels) + 1;
2891   t->owner = client;
2892   fc_init (&t->next_fc);
2893   fc_init (&t->prev_fc);
2894   t->local_tid = local;
2895   n_tunnels++;
2896   GNUNET_STATISTICS_update (stats, "# tunnels", 1, GNUNET_NO);
2897
2898   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
2899   if (GNUNET_OK !=
2900       GNUNET_CONTAINER_multihashmap_put (tunnels, &hash, t,
2901                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2902   {
2903     GNUNET_break (0);
2904     tunnel_destroy (t);
2905     if (NULL != client)
2906     {
2907       GNUNET_break (0);
2908       GNUNET_SERVER_receive_done (client->handle, GNUNET_SYSERR);
2909     }
2910     return NULL;
2911   }
2912
2913   if (NULL != client)
2914   {
2915     if (GNUNET_OK !=
2916         GNUNET_CONTAINER_multihashmap32_put (client->own_tunnels,
2917                                              t->local_tid, t,
2918                                              GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2919     {
2920       tunnel_destroy (t);
2921       GNUNET_break (0);
2922       GNUNET_SERVER_receive_done (client->handle, GNUNET_SYSERR);
2923       return NULL;
2924     }
2925   }
2926
2927   return t;
2928 }
2929
2930
2931 /**
2932  * Set options in a tunnel, extracted from a bit flag field
2933  * 
2934  * @param t Tunnel to set options to.
2935  * @param options Bit array in host byte order.
2936  */
2937 static void
2938 tunnel_set_options (struct MeshTunnel *t, uint32_t options)
2939 {
2940   t->nobuffer = (options & GNUNET_MESH_OPTION_NOBUFFER) != 0 ?
2941                  GNUNET_YES : GNUNET_NO;
2942   t->reliable = (options & GNUNET_MESH_OPTION_RELIABLE) != 0 ?
2943                  GNUNET_YES : GNUNET_NO;
2944 }
2945
2946
2947 /**
2948  * Iterator for deleting each tunnel whose client endpoint disconnected.
2949  *
2950  * @param cls Closure (client that has disconnected).
2951  * @param key The local tunnel id (used to access the hashmap).
2952  * @param value The value stored at the key (tunnel to destroy).
2953  *
2954  * @return GNUNET_OK, keep iterating.
2955  */
2956 static int
2957 tunnel_destroy_iterator (void *cls,
2958                          uint32_t key,
2959                          void *value)
2960 {
2961   struct MeshTunnel *t = value;
2962   struct MeshClient *c = cls;
2963
2964   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2965               " Tunnel %X / %X destroy, due to client %u shutdown.\n",
2966               t->local_tid, t->local_tid_dest, c->id);
2967   client_delete_tunnel (c, t);
2968   if (c == t->client)
2969   {
2970     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Client %u is destination.\n", c->id);
2971     t->client = NULL;
2972     if (0 != t->next_hop) { /* destroy could come before a path is used */
2973         GNUNET_PEER_change_rc (t->next_hop, -1);
2974         t->next_hop = 0;
2975     }
2976   }
2977   if (c == t->owner)
2978   {
2979     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Client %u is owner.\n", c->id);
2980     t->owner = NULL;
2981     if (0 != t->prev_hop) { /* destroy could come before a path is used */
2982         GNUNET_PEER_change_rc (t->prev_hop, -1);
2983         t->prev_hop = 0;
2984     }
2985   }
2986
2987   tunnel_destroy_empty (t);
2988
2989   return GNUNET_OK;
2990 }
2991
2992
2993 /**
2994  * Timeout function, destroys tunnel if called
2995  *
2996  * @param cls Closure (tunnel to destroy).
2997  * @param tc TaskContext
2998  */
2999 static void
3000 tunnel_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3001 {
3002   struct MeshTunnel *t = cls;
3003   struct GNUNET_PeerIdentity id;
3004
3005   t->maintenance_task = GNUNET_SCHEDULER_NO_TASK;
3006   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3007     return;
3008   GNUNET_PEER_resolve(t->id.oid, &id);
3009   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3010               "Tunnel %s [%X] timed out. Destroying.\n",
3011               GNUNET_i2s(&id), t->id.tid);
3012   if (NULL != t->client)
3013     send_client_tunnel_destroy (t->client, t);
3014   tunnel_destroy (t); /* Do not notify other */
3015 }
3016
3017
3018 /**
3019  * Resets the tunnel timeout. Starts it if no timeout was running.
3020  *
3021  * @param t Tunnel whose timeout to reset.
3022  * @param fwd Is this forward?
3023  *
3024  * TODO use heap to improve efficiency of scheduler.
3025  * FIXME use fwd, keep 2 timers
3026  */
3027 static void
3028 tunnel_reset_timeout (struct MeshTunnel *t, int fwd)
3029 {
3030   if (NULL != t->owner || 0 != t->local_tid || 0 == t->prev_hop)
3031     return;
3032   if (GNUNET_SCHEDULER_NO_TASK != t->maintenance_task)
3033     GNUNET_SCHEDULER_cancel (t->maintenance_task);
3034   t->maintenance_task =
3035       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
3036                                     (refresh_path_time, 4), &tunnel_timeout, t);
3037 }
3038
3039
3040 /******************************************************************************/
3041 /****************      MESH NETWORK HANDLER HELPERS     ***********************/
3042 /******************************************************************************/
3043
3044 /**
3045  * Function to send a create path packet to a peer.
3046  *
3047  * @param cls closure
3048  * @param size number of bytes available in buf
3049  * @param buf where the callee should write the message
3050  * @return number of bytes written to buf
3051  */
3052 static size_t
3053 send_core_path_create (void *cls, size_t size, void *buf)
3054 {
3055   struct MeshTunnel *t = cls;
3056   struct GNUNET_MESH_CreateTunnel *msg;
3057   struct GNUNET_PeerIdentity *peer_ptr;
3058   struct MeshPeerPath *p = t->path;
3059   size_t size_needed;
3060   uint32_t opt;
3061   int i;
3062
3063   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATE PATH sending...\n");
3064   size_needed =
3065       sizeof (struct GNUNET_MESH_CreateTunnel) +
3066       p->length * sizeof (struct GNUNET_PeerIdentity);
3067
3068   if (size < size_needed || NULL == buf)
3069   {
3070     GNUNET_break (0);
3071     return 0;
3072   }
3073   msg = (struct GNUNET_MESH_CreateTunnel *) buf;
3074   msg->header.size = htons (size_needed);
3075   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE);
3076   msg->tid = ntohl (t->id.tid);
3077
3078   opt = 0;
3079   if (GNUNET_YES == t->nobuffer)
3080     opt |= GNUNET_MESH_OPTION_NOBUFFER;
3081   if (GNUNET_YES == t->reliable)
3082     opt |= GNUNET_MESH_OPTION_RELIABLE;
3083   msg->opt = htonl (opt);
3084   msg->port = htonl (t->port);
3085
3086   peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
3087   for (i = 0; i < p->length; i++)
3088   {
3089     GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
3090   }
3091
3092   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3093               "CREATE PATH (%u bytes long) sent!\n", size_needed);
3094   return size_needed;
3095 }
3096
3097
3098 /**
3099  * Creates a path ack message in buf and frees all unused resources.
3100  *
3101  * @param cls closure (MeshTransmissionDescriptor)
3102  * @param size number of bytes available in buf
3103  * @param buf where the callee should write the message
3104  * @return number of bytes written to buf
3105  */
3106 static size_t
3107 send_core_path_ack (void *cls, size_t size, void *buf)
3108 {
3109   struct MeshTunnel *t = cls;
3110   struct GNUNET_MESH_PathACK *msg = buf;
3111
3112   GNUNET_assert (NULL != t);
3113   if (sizeof (struct GNUNET_MESH_PathACK) > size)
3114   {
3115     GNUNET_break (0);
3116     return 0;
3117   }
3118   t->prev_fc.last_ack_sent = t->nobuffer ? 0 : t->queue_max - 1;
3119   msg->header.size = htons (sizeof (struct GNUNET_MESH_PathACK));
3120   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_ACK);
3121   GNUNET_PEER_resolve (t->id.oid, &msg->oid);
3122   msg->tid = htonl (t->id.tid);
3123   msg->peer_id = my_full_id;
3124   msg->ack = htonl (t->prev_fc.last_ack_sent);
3125
3126   /* TODO add signature */
3127
3128   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "PATH ACK sent!\n");
3129   return sizeof (struct GNUNET_MESH_PathACK);
3130 }
3131
3132
3133 /**
3134  * Free a transmission that was already queued with all resources
3135  * associated to the request.
3136  *
3137  * @param queue Queue handler to cancel.
3138  * @param clear_cls Is it necessary to free associated cls?
3139  */
3140 static void
3141 queue_destroy (struct MeshPeerQueue *queue, int clear_cls)
3142 {
3143   struct MeshFlowControl *fc;
3144
3145   if (GNUNET_YES == clear_cls)
3146   {
3147     switch (queue->type)
3148     {
3149       case GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY:
3150         GNUNET_log (GNUNET_ERROR_TYPE_INFO, "   cancelling TUNNEL_DESTROY\n");
3151         GNUNET_break (GNUNET_YES == queue->tunnel->destroy);
3152         /* fall through */
3153       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
3154       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
3155       case GNUNET_MESSAGE_TYPE_MESH_ACK:
3156       case GNUNET_MESSAGE_TYPE_MESH_POLL:
3157       case GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE:
3158         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3159                     "   prebuilt message\n");
3160         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3161                     "   type %s\n",
3162                     GNUNET_MESH_DEBUG_M2S (queue->type));
3163         break;
3164       case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
3165         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   type create path\n");
3166         break;
3167       default:
3168         GNUNET_break (0);
3169         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3170                     "   type %s unknown!\n",
3171                     GNUNET_MESH_DEBUG_M2S (queue->type));
3172     }
3173     GNUNET_free_non_null (queue->cls);
3174   }
3175   GNUNET_CONTAINER_DLL_remove (queue->peer->queue_head,
3176                                queue->peer->queue_tail,
3177                                queue);
3178
3179   /* Delete from appropriate fc in the tunnel */
3180   if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == queue->type ||
3181       GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == queue->type )
3182   {
3183     if (queue->peer->id == queue->tunnel->prev_hop)
3184       fc = &queue->tunnel->prev_fc;
3185     else if (queue->peer->id == queue->tunnel->next_hop)
3186       fc = &queue->tunnel->next_fc;
3187     else
3188     {
3189       GNUNET_break (0);
3190       GNUNET_free (queue);
3191       return;
3192     }
3193     fc->queue_n--;
3194   }
3195   GNUNET_free (queue);
3196 }
3197
3198
3199 /**
3200  * @brief Get the next transmittable message from the queue.
3201  *
3202  * This will be the head, except in the case of being a data packet
3203  * not allowed by the destination peer.
3204  *
3205  * @param peer Destination peer.
3206  *
3207  * @return The next viable MeshPeerQueue element to send to that peer.
3208  *         NULL when there are no transmittable messages.
3209  */
3210 struct MeshPeerQueue *
3211 queue_get_next (const struct MeshPeerInfo *peer)
3212 {
3213   struct MeshPeerQueue *q;
3214
3215   struct GNUNET_MESH_Data *dmsg;
3216   struct MeshTunnel* t;
3217   uint32_t pid;
3218   uint32_t ack;
3219
3220   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   selecting message\n");
3221   for (q = peer->queue_head; NULL != q; q = q->next)
3222   {
3223     t = q->tunnel;
3224     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3225                 "*     %s\n",
3226                 GNUNET_MESH_DEBUG_M2S (q->type));
3227     dmsg = (struct GNUNET_MESH_Data *) q->cls;
3228     pid = ntohl (dmsg->pid);
3229     switch (q->type)
3230     {
3231       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
3232         ack = t->next_fc.last_ack_recv;
3233         break;
3234       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
3235         ack = t->prev_fc.last_ack_recv;
3236         break;
3237       default:
3238         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3239                     "*   OK!\n");
3240         return q;
3241     }
3242     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3243                 "*     ACK: %u, PID: %u, MID: %u\n",
3244                 ack, pid, ntohl (dmsg->mid));
3245     if (GNUNET_NO == GMC_is_pid_bigger (pid, ack))
3246     {
3247       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3248                   "*   OK!\n");
3249       return q;
3250     }
3251     else
3252     {
3253       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3254                   "*     NEXT!\n");
3255     }
3256   }
3257   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3258                 "*   nothing found\n");
3259   return NULL;
3260 }
3261
3262
3263 static size_t
3264 queue_send (void *cls, size_t size, void *buf)
3265 {
3266   struct MeshPeerInfo *peer = cls;
3267   struct GNUNET_MessageHeader *msg;
3268   struct MeshPeerQueue *queue;
3269   struct MeshTunnel *t;
3270   struct GNUNET_PeerIdentity dst_id;
3271   struct MeshFlowControl *fc;
3272   size_t data_size;
3273   uint32_t pid;
3274   uint16_t type;
3275
3276   peer->core_transmit = NULL;
3277
3278   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* Queue send\n");
3279   queue = queue_get_next (peer);
3280
3281   /* Queue has no internal mesh traffic nor sendable payload */
3282   if (NULL == queue)
3283   {
3284     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   not ready, return\n");
3285     if (NULL == peer->queue_head)
3286       GNUNET_break (0); /* Core tmt_rdy should've been canceled */
3287     return 0;
3288   }
3289   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   not empty\n");
3290
3291   GNUNET_PEER_resolve (peer->id, &dst_id);
3292   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3293               "*   towards %s\n",
3294               GNUNET_i2s (&dst_id));
3295   /* Check if buffer size is enough for the message */
3296   if (queue->size > size)
3297   {
3298       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3299                   "*   not enough room, reissue\n");
3300       peer->core_transmit =
3301           GNUNET_CORE_notify_transmit_ready (core_handle,
3302                                              GNUNET_NO,
3303                                              0,
3304                                              GNUNET_TIME_UNIT_FOREVER_REL,
3305                                              &dst_id,
3306                                              queue->size,
3307                                              &queue_send,
3308                                              peer);
3309       return 0;
3310   }
3311   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   size ok\n");
3312
3313   t = queue->tunnel;
3314   GNUNET_assert (0 < t->pending_messages);
3315   t->pending_messages--;
3316   type = 0;
3317
3318   /* Fill buf */
3319   switch (queue->type)
3320   {
3321     case 0:
3322     case GNUNET_MESSAGE_TYPE_MESH_ACK:
3323     case GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK:
3324     case GNUNET_MESSAGE_TYPE_MESH_TO_ORIG_ACK:
3325     case GNUNET_MESSAGE_TYPE_MESH_POLL:
3326     case GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN:
3327     case GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY:
3328     case GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY:
3329     case GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE:
3330       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3331                   "*   raw: %s\n",
3332                   GNUNET_MESH_DEBUG_M2S (queue->type));
3333       /* Fall through */
3334     case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
3335     case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
3336       data_size = send_core_data_raw (queue->cls, size, buf);
3337       msg = (struct GNUNET_MessageHeader *) buf;
3338       type = ntohs (msg->type);
3339       break;
3340     case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
3341       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   path create\n");
3342       data_size = send_core_path_create (queue->cls, size, buf);
3343       break;
3344     case GNUNET_MESSAGE_TYPE_MESH_PATH_ACK:
3345       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   path ack\n");
3346       data_size = send_core_path_ack (queue->cls, size, buf);
3347       break;
3348     default:
3349       GNUNET_break (0);
3350       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3351                   "*   type unknown: %u\n",
3352                   queue->type);
3353       data_size = 0;
3354   }
3355
3356   if (0 < drop_percent &&
3357       GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 101) < drop_percent)
3358   {
3359     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3360                 "Dropping message of type %s\n",
3361                 GNUNET_MESH_DEBUG_M2S(queue->type));
3362     data_size = 0;
3363   }
3364   /* Free queue, but cls was freed by send_core_* */
3365   queue_destroy (queue, GNUNET_NO);
3366
3367   /* Send ACK if needed, after accounting for sent ID in fc->queue_n */
3368   pid = ((struct GNUNET_MESH_Data *) buf)->pid;
3369   pid = ntohl (pid);
3370   switch (type)
3371   {
3372     case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
3373       t->next_fc.last_pid_sent = pid;
3374       tunnel_send_ack (t, GNUNET_MESSAGE_TYPE_MESH_UNICAST, GNUNET_YES);
3375       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3376                   "!!! FWD  %u\n",
3377                   ntohl ( ((struct GNUNET_MESH_Data *) buf)->mid ) );
3378       break;
3379     case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
3380       t->prev_fc.last_pid_sent = pid;
3381       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3382                   "!!! BCK  %u\n",
3383                   ntohl ( ((struct GNUNET_MESH_Data *) buf)->mid ) );
3384       tunnel_send_ack (t, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, GNUNET_NO);
3385       break;
3386     default:
3387       break;
3388   }
3389
3390   /* If more data in queue, send next */
3391   queue = queue_get_next (peer);
3392   if (NULL != queue)
3393   {
3394       struct GNUNET_PeerIdentity id;
3395
3396       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   more data!\n");
3397       GNUNET_PEER_resolve (peer->id, &id);
3398       peer->core_transmit =
3399           GNUNET_CORE_notify_transmit_ready(core_handle,
3400                                             0,
3401                                             0,
3402                                             GNUNET_TIME_UNIT_FOREVER_REL,
3403                                             &id,
3404                                             queue->size,
3405                                             &queue_send,
3406                                             peer);
3407   }
3408   if (peer->id == t->next_hop)
3409     fc = &t->next_fc;
3410   else if (peer->id == t->prev_hop)
3411     fc = &t->prev_fc;
3412   else
3413   {
3414     GNUNET_break (0);
3415     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "id: %u, next: %u, prev: %u\n",
3416                 peer->id, t->next_hop, t->prev_hop);
3417     return data_size;
3418   }
3419   if (NULL != peer->queue_head)
3420   {
3421     if (GNUNET_SCHEDULER_NO_TASK == fc->poll_task && fc->queue_n > 0)
3422     {
3423       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3424                   "*   %s starting poll timeout\n",
3425                   GNUNET_i2s (&my_full_id));
3426       fc->t = t;
3427       fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
3428                                                     &tunnel_poll, fc);
3429     }
3430   }
3431   else
3432   {
3433     if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
3434     {
3435       GNUNET_SCHEDULER_cancel (fc->poll_task);
3436       fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
3437     }
3438   }
3439   if (GNUNET_YES == t->destroy && 0 == t->pending_messages)
3440   {
3441     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*  destroying tunnel!\n");
3442     tunnel_destroy (t);
3443   }
3444   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*  Return %d\n", data_size);
3445   return data_size;
3446 }
3447
3448
3449 /**
3450  * @brief Queue and pass message to core when possible.
3451  * 
3452  * If type is payload (UNICAST, TO_ORIGIN) checks for queue status and
3453  * accounts for it. In case the queue is full, the message is dropped and
3454  * a break issued.
3455  * 
3456  * Otherwise, message is treated as internal and allowed to go regardless of 
3457  * queue status.
3458  *
3459  * @param cls Closure (@c type dependant). It will be used by queue_send to
3460  *            build the message to be sent if not already prebuilt.
3461  * @param type Type of the message, 0 for a raw message.
3462  * @param size Size of the message.
3463  * @param dst Neighbor to send message to.
3464  * @param t Tunnel this message belongs to.
3465  */
3466 static void
3467 queue_add (void *cls, uint16_t type, size_t size,
3468            struct MeshPeerInfo *dst, struct MeshTunnel *t)
3469 {
3470   struct MeshPeerQueue *queue;
3471   struct GNUNET_PeerIdentity id;
3472   struct MeshFlowControl *fc;
3473   int priority;
3474
3475   fc = NULL;
3476   priority = GNUNET_NO;
3477   if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == type)
3478   {
3479     fc = &t->next_fc;
3480   }
3481   else if (GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == type)
3482   {
3483     fc = &t->prev_fc;
3484   }
3485   if (NULL != fc)
3486   {
3487     if (fc->queue_n >= t->queue_max)
3488     {
3489       /* If this isn't a retransmission, drop the message */
3490       if (GNUNET_NO == t->reliable ||
3491           (NULL == t->owner && GNUNET_MESSAGE_TYPE_MESH_UNICAST == type) ||
3492           (NULL == t->client && GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == type))
3493       {
3494         GNUNET_STATISTICS_update (stats, "# messages dropped (buffer full)",
3495                                   1, GNUNET_NO);
3496         GNUNET_break (0);
3497         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3498                     "queue full: %u/%u\n",
3499                     fc->queue_n, t->queue_max);
3500         return; /* Drop this message */
3501       }
3502       priority = GNUNET_YES;
3503     }
3504     fc->queue_n++;
3505   }
3506   queue = GNUNET_malloc (sizeof (struct MeshPeerQueue));
3507   queue->cls = cls;
3508   queue->type = type;
3509   queue->size = size;
3510   queue->peer = dst;
3511   queue->tunnel = t;
3512   if (GNUNET_YES == priority)
3513   {
3514     struct GNUNET_MESH_Data *d;
3515     uint32_t prev;
3516     uint32_t next;
3517
3518     GNUNET_CONTAINER_DLL_insert (dst->queue_head, dst->queue_tail, queue);
3519     d = (struct GNUNET_MESH_Data *) queue->cls;
3520     prev = d->pid;
3521     for (queue = dst->queue_tail; NULL != queue; queue = queue->prev)
3522     {
3523       if (queue->type != type)
3524         continue;
3525       d = (struct GNUNET_MESH_Data *) queue->cls;
3526       next = d->pid;
3527       d->pid = prev;
3528       prev = next;
3529     }
3530   }
3531   else
3532     GNUNET_CONTAINER_DLL_insert_tail (dst->queue_head, dst->queue_tail, queue);
3533   if (NULL == dst->core_transmit)
3534   {
3535     GNUNET_PEER_resolve (dst->id, &id);
3536     dst->core_transmit =
3537         GNUNET_CORE_notify_transmit_ready (core_handle,
3538                                            0,
3539                                            0,
3540                                            GNUNET_TIME_UNIT_FOREVER_REL,
3541                                            &id,
3542                                            size,
3543                                            &queue_send,
3544                                            dst);
3545   }
3546   t->pending_messages++;
3547 }
3548
3549
3550 /******************************************************************************/
3551 /********************      MESH NETWORK HANDLERS     **************************/
3552 /******************************************************************************/
3553
3554
3555 /**
3556  * Core handler for path creation
3557  *
3558  * @param cls closure
3559  * @param message message
3560  * @param peer peer identity this notification is about
3561  *
3562  * @return GNUNET_OK to keep the connection open,
3563  *         GNUNET_SYSERR to close it (signal serious error)
3564  */
3565 static int
3566 handle_mesh_path_create (void *cls, const struct GNUNET_PeerIdentity *peer,
3567                          const struct GNUNET_MessageHeader *message)
3568 {
3569   unsigned int own_pos;
3570   uint16_t size;
3571   uint16_t i;
3572   MESH_TunnelNumber tid;
3573   struct GNUNET_MESH_CreateTunnel *msg;
3574   struct GNUNET_PeerIdentity *pi;
3575   struct MeshPeerPath *path;
3576   struct MeshPeerInfo *dest_peer_info;
3577   struct MeshPeerInfo *orig_peer_info;
3578   struct MeshTunnel *t;
3579
3580   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3581               "Received a path create msg [%s]\n",
3582               GNUNET_i2s (&my_full_id));
3583   size = ntohs (message->size);
3584   if (size < sizeof (struct GNUNET_MESH_CreateTunnel))
3585   {
3586     GNUNET_break_op (0);
3587     return GNUNET_OK;
3588   }
3589
3590   size -= sizeof (struct GNUNET_MESH_CreateTunnel);
3591   if (size % sizeof (struct GNUNET_PeerIdentity))
3592   {
3593     GNUNET_break_op (0);
3594     return GNUNET_OK;
3595   }
3596   size /= sizeof (struct GNUNET_PeerIdentity);
3597   if (size < 1)
3598   {
3599     GNUNET_break_op (0);
3600     return GNUNET_OK;
3601   }
3602   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
3603   msg = (struct GNUNET_MESH_CreateTunnel *) message;
3604
3605   tid = ntohl (msg->tid);
3606   pi = (struct GNUNET_PeerIdentity *) &msg[1];
3607   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3608               "    path is for tunnel %s[%X].\n", GNUNET_i2s (pi), tid);
3609   t = tunnel_get (pi, tid);
3610   if (NULL == t) /* might be a local tunnel */
3611   {
3612     uint32_t opt;
3613
3614     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating tunnel\n");
3615     t = tunnel_new (GNUNET_PEER_intern (pi), tid, NULL, 0);
3616     if (NULL == t)
3617     {
3618       GNUNET_break (0);
3619       return GNUNET_OK;
3620     }
3621     t->port = ntohl (msg->port);
3622     opt = ntohl (msg->opt);
3623     if (0 != (opt & GNUNET_MESH_OPTION_NOBUFFER))
3624     {
3625       t->nobuffer = GNUNET_YES;
3626       t->queue_max = 1;
3627     }
3628     if (0 != (opt & GNUNET_MESH_OPTION_RELIABLE))
3629     {
3630       t->reliable = GNUNET_YES;
3631     }
3632     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  nobuffer:%d\n", t->nobuffer);
3633
3634     tunnel_reset_timeout (t, GNUNET_YES); // FIXME
3635   }
3636   t->state = MESH_TUNNEL_WAITING;
3637   dest_peer_info =
3638       GNUNET_CONTAINER_multihashmap_get (peers, &pi[size - 1].hashPubKey);
3639   if (NULL == dest_peer_info)
3640   {
3641     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3642                 "  Creating PeerInfo for destination.\n");
3643     dest_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
3644     dest_peer_info->id = GNUNET_PEER_intern (&pi[size - 1]);
3645     GNUNET_CONTAINER_multihashmap_put (peers, &pi[size - 1].hashPubKey,
3646                                        dest_peer_info,
3647                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3648   }
3649   orig_peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &pi->hashPubKey);
3650   if (NULL == orig_peer_info)
3651   {
3652     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3653                 "  Creating PeerInfo for origin.\n");
3654     orig_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
3655     orig_peer_info->id = GNUNET_PEER_intern (pi);
3656     GNUNET_CONTAINER_multihashmap_put (peers, &pi->hashPubKey, orig_peer_info,
3657                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3658   }
3659   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
3660   path = path_new (size);
3661   own_pos = 0;
3662   for (i = 0; i < size; i++)
3663   {
3664     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
3665                 GNUNET_i2s (&pi[i]));
3666     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
3667     if (path->peers[i] == myid)
3668       own_pos = i;
3669   }
3670   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
3671   if (own_pos == 0 && path->peers[own_pos] != myid)
3672   {
3673     /* create path: self not found in path through self */
3674     GNUNET_break_op (0);
3675     path_destroy (path);
3676     tunnel_destroy (t);
3677     return GNUNET_OK;
3678   }
3679   path_add_to_peers (path, GNUNET_NO);
3680   tunnel_use_path (t, path);
3681
3682   peer_info_add_tunnel (dest_peer_info, t);
3683
3684   if (own_pos == size - 1)
3685   {
3686     struct MeshClient *c;
3687
3688     /* Find target client */
3689     c = GNUNET_CONTAINER_multihashmap32_get (ports, t->port);
3690     if (NULL == c)
3691     {
3692       /* TODO send reject */
3693       return GNUNET_OK;
3694     }
3695
3696     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
3697     peer_info_add_path_to_origin (orig_peer_info, path, GNUNET_YES);
3698
3699     /* Assign local tid */
3700     while (NULL != tunnel_get_incoming (next_local_tid))
3701       next_local_tid = (next_local_tid + 1) | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
3702     t->local_tid_dest = next_local_tid++;
3703     next_local_tid = next_local_tid | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
3704
3705     if (GNUNET_YES == t->reliable)
3706     {
3707       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! Reliable\n");
3708       t->bck_rel = GNUNET_malloc (sizeof (struct MeshTunnelReliability));
3709       t->bck_rel->t = t;
3710       t->bck_rel->expected_delay = MESH_RETRANSMIT_TIME;
3711     }
3712
3713     tunnel_add_client (t, c);
3714     send_client_tunnel_create (t);
3715     send_path_ack (t);
3716   }
3717   else
3718   {
3719     struct MeshPeerPath *path2;
3720
3721     t->next_hop = path->peers[own_pos + 1];
3722     GNUNET_PEER_change_rc(t->next_hop, 1);
3723
3724     /* It's for somebody else! Retransmit. */
3725     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Retransmitting.\n");
3726     path2 = path_duplicate (path);
3727     peer_info_add_path (dest_peer_info, path2, GNUNET_NO);
3728     peer_info_add_path_to_origin (orig_peer_info, path, GNUNET_NO);
3729     send_create_path (t);
3730   }
3731   return GNUNET_OK;
3732 }
3733
3734
3735
3736 /**
3737  * Core handler for path ACKs
3738  *
3739  * @param cls closure
3740  * @param message message
3741  * @param peer peer identity this notification is about
3742  *
3743  * @return GNUNET_OK to keep the connection open,
3744  *         GNUNET_SYSERR to close it (signal serious error)
3745  */
3746 static int
3747 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
3748                       const struct GNUNET_MessageHeader *message)
3749 {
3750   struct GNUNET_MESH_PathACK *msg;
3751   struct MeshPeerInfo *peer_info;
3752   struct MeshPeerPath *p;
3753   struct MeshTunnel *t;
3754
3755   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a path ACK msg [%s]\n",
3756               GNUNET_i2s (&my_full_id));
3757   msg = (struct GNUNET_MESH_PathACK *) message;
3758   t = tunnel_get (&msg->oid, ntohl(msg->tid));
3759   if (NULL == t)
3760   {
3761     /* TODO notify that we don't know the tunnel */
3762     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel", 1, GNUNET_NO);
3763     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  don't know the tunnel %s [%X]!\n",
3764                 GNUNET_i2s (&msg->oid), ntohl(msg->tid));
3765     return GNUNET_OK;
3766   }
3767   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %s [%X]\n",
3768               GNUNET_i2s (&msg->oid), ntohl(msg->tid));
3769
3770   peer_info = peer_get (&msg->peer_id);
3771   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by peer %s\n",
3772               GNUNET_i2s (&msg->peer_id));
3773   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  via peer %s\n",
3774               GNUNET_i2s (peer));
3775
3776   /* Add path to peers? */
3777   p = t->path;
3778   if (NULL != p)
3779   {
3780     path_add_to_peers (p, GNUNET_YES);
3781   }
3782   else
3783   {
3784     GNUNET_break (0);
3785   }
3786   t->state = MESH_TUNNEL_READY;
3787   t->next_fc.last_ack_recv = (NULL == t->client) ? ntohl (msg->ack) : 0;
3788   t->prev_fc.last_ack_sent = ntohl (msg->ack);
3789
3790   /* Message for us? */
3791   if (0 == memcmp (&msg->oid, &my_full_id, sizeof (struct GNUNET_PeerIdentity)))
3792   {
3793     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
3794     if (NULL == t->owner)
3795     {
3796       GNUNET_break_op (0);
3797       return GNUNET_OK;
3798     }
3799     if (NULL != peer_info->dhtget)
3800     {
3801       GNUNET_DHT_get_stop (peer_info->dhtget);
3802       peer_info->dhtget = NULL;
3803     }
3804     tunnel_send_ack (t, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK, GNUNET_YES);
3805     tunnel_send_ack (t, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK, GNUNET_NO);
3806     return GNUNET_OK;
3807   }
3808
3809   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3810               "  not for us, retransmitting...\n");
3811   peer_info = peer_get (&msg->oid);
3812   send_prebuilt_message (message, t->prev_hop, t);
3813   return GNUNET_OK;
3814 }
3815
3816
3817 /**
3818  * Core handler for notifications of broken paths
3819  *
3820  * @param cls closure
3821  * @param message message
3822  * @param peer peer identity this notification is about
3823  *
3824  * @return GNUNET_OK to keep the connection open,
3825  *         GNUNET_SYSERR to close it (signal serious error)
3826  */
3827 static int
3828 handle_mesh_path_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
3829                          const struct GNUNET_MessageHeader *message)
3830 {
3831   struct GNUNET_MESH_PathBroken *msg;
3832   struct MeshTunnel *t;
3833
3834   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3835               "Received a PATH BROKEN msg from %s\n", GNUNET_i2s (peer));
3836   msg = (struct GNUNET_MESH_PathBroken *) message;
3837   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
3838               GNUNET_i2s (&msg->peer1));
3839   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
3840               GNUNET_i2s (&msg->peer2));
3841   t = tunnel_get (&msg->oid, ntohl (msg->tid));
3842   if (NULL == t)
3843   {
3844     GNUNET_break_op (0);
3845     return GNUNET_OK;
3846   }
3847   tunnel_notify_connection_broken (t, GNUNET_PEER_search (&msg->peer1),
3848                                    GNUNET_PEER_search (&msg->peer2));
3849   return GNUNET_OK;
3850
3851 }
3852
3853
3854 /**
3855  * Core handler for tunnel destruction
3856  *
3857  * @param cls closure
3858  * @param message message
3859  * @param peer peer identity this notification is about
3860  *
3861  * @return GNUNET_OK to keep the connection open,
3862  *         GNUNET_SYSERR to close it (signal serious error)
3863  */
3864 static int
3865 handle_mesh_tunnel_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
3866                             const struct GNUNET_MessageHeader *message)
3867 {
3868   struct GNUNET_MESH_TunnelDestroy *msg;
3869   struct MeshTunnel *t;
3870
3871   msg = (struct GNUNET_MESH_TunnelDestroy *) message;
3872   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3873               "Got a TUNNEL DESTROY packet from %s\n",
3874               GNUNET_i2s (peer));
3875   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3876               "  for tunnel %s [%u]\n",
3877               GNUNET_i2s (&msg->oid), ntohl (msg->tid));
3878   t = tunnel_get (&msg->oid, ntohl (msg->tid));
3879   if (NULL == t)
3880   {
3881     /* Probably already got the message from another path,
3882      * destroyed the tunnel and retransmitted to children.
3883      * Safe to ignore.
3884      */
3885     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel",
3886                               1, GNUNET_NO);
3887     return GNUNET_OK;
3888   }
3889   if (t->local_tid_dest >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
3890   {
3891     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "INCOMING TUNNEL %X %X\n",
3892                 t->local_tid, t->local_tid_dest);
3893   }
3894   if (GNUNET_PEER_search (peer) == t->prev_hop)
3895   {
3896     // TODO check owner's signature
3897     // TODO add owner's signatue to tunnel for retransmission
3898     peer_cancel_queues (t->prev_hop, t);
3899     GNUNET_PEER_change_rc (t->prev_hop, -1);
3900     t->prev_hop = 0;
3901   }
3902   else if (GNUNET_PEER_search (peer) == t->next_hop)
3903   {
3904     // TODO check dest's signature
3905     // TODO add dest's signatue to tunnel for retransmission
3906     peer_cancel_queues (t->next_hop, t);
3907     GNUNET_PEER_change_rc (t->next_hop, -1);
3908     t->next_hop = 0;
3909   }
3910   else
3911   {
3912     GNUNET_break_op (0);
3913     // TODO check both owner AND destination's signature to see which matches
3914     // TODO restransmit in appropriate direction
3915     return GNUNET_OK;
3916   }
3917   tunnel_destroy_empty (t);
3918
3919   // TODO: add timeout to destroy the tunnel anyway
3920   return GNUNET_OK;
3921 }
3922
3923
3924 /**
3925  * Generic handler for mesh network payload traffic.
3926  *
3927  * @param peer Peer identity this notification is about.
3928  * @param message Data message.
3929  * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
3930  *
3931  * @return GNUNET_OK to keep the connection open,
3932  *         GNUNET_SYSERR to close it (signal serious error)
3933  */
3934 static int
3935 handle_mesh_data (const struct GNUNET_PeerIdentity *peer,
3936                   const struct GNUNET_MessageHeader *message,
3937                   int fwd)
3938 {
3939   struct GNUNET_MESH_Data *msg;
3940   struct MeshFlowControl *fc;
3941   struct MeshTunnelReliability *rel;
3942   struct MeshTunnel *t;
3943   struct MeshClient *c;
3944   GNUNET_PEER_Id hop;
3945   uint32_t pid;
3946   uint32_t ttl;
3947   size_t size;
3948
3949   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a %s message from %s\n",
3950               GNUNET_MESH_DEBUG_M2S (ntohs (message->type)),
3951               GNUNET_i2s (peer));
3952   /* Check size */
3953   size = ntohs (message->size);
3954   if (size <
3955       sizeof (struct GNUNET_MESH_Data) +
3956       sizeof (struct GNUNET_MessageHeader))
3957   {
3958     GNUNET_break (0);
3959     return GNUNET_OK;
3960   }
3961   msg = (struct GNUNET_MESH_Data *) message;
3962   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
3963               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
3964   /* Check tunnel */
3965   t = tunnel_get (&msg->oid, ntohl (msg->tid));
3966   if (NULL == t)
3967   {
3968     /* TODO notify back: we don't know this tunnel */
3969     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
3970     GNUNET_break_op (0);
3971     return GNUNET_OK;
3972   }
3973
3974   /*  Initialize FWD/BCK data */
3975   pid = ntohl (msg->pid);
3976   fc =  fwd ? &t->prev_fc : &t->next_fc;
3977   c =   fwd ? t->client   : t->owner;
3978   rel = fwd ? t->bck_rel  : t->fwd_rel;
3979   hop = fwd ? t->next_hop : t->prev_hop;
3980   if (GMC_is_pid_bigger (pid, fc->last_ack_sent))
3981   {
3982     GNUNET_STATISTICS_update (stats, "# unsolicited data", 1, GNUNET_NO);
3983     GNUNET_break_op (0);
3984     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3985                 "Received PID %u, (prev %u), ACK %u\n",
3986                 pid, fc->last_pid_recv, fc->last_ack_sent);
3987     return GNUNET_OK;
3988   }
3989
3990   tunnel_reset_timeout (t, fwd);
3991   if (NULL != c)
3992   {
3993     /* TODO signature verification */
3994     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  it's for us! sending to client\n");
3995     GNUNET_STATISTICS_update (stats, "# data received", 1, GNUNET_NO);
3996     if (GMC_is_pid_bigger (pid, fc->last_pid_recv))
3997     {
3998       uint32_t mid;
3999
4000       mid = ntohl (msg->mid);
4001       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4002                   " pid %u (mid %u) not seen yet\n", pid, mid);
4003       fc->last_pid_recv = pid;
4004
4005       if (GNUNET_NO == t->reliable ||
4006           ( !GMC_is_pid_bigger (rel->mid_recv, mid) &&
4007             GMC_is_pid_bigger (rel->mid_recv + 64, mid) ) )
4008       {
4009         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4010                     "!!! RECV %u\n", ntohl (msg->mid));
4011         if (GNUNET_YES == t->reliable)
4012         {
4013           /* Is this the exact next expected messasge? */
4014           if (mid == rel->mid_recv)
4015           {
4016             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "as expected\n");
4017             rel->mid_recv++;
4018             tunnel_send_client_data (t, msg, fwd);
4019             tunnel_send_client_buffered_data (t, c, rel);
4020           }
4021           else
4022           {
4023             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "save for later\n");
4024             tunnel_add_buffered_data (t, msg, rel);
4025           }
4026         }
4027         else /* Tunnel unreliable, send to clients directly */
4028         {
4029           tunnel_send_client_data (t, msg, fwd);
4030         }
4031       }
4032       else
4033       {
4034         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4035                     " MID %u not expected (%u - %u), dropping!\n",
4036                     ntohl (msg->mid), rel->mid_recv, rel->mid_recv + 64);
4037       }
4038     }
4039     else
4040     {
4041 //       GNUNET_STATISTICS_update (stats, "# duplicate PID", 1, GNUNET_NO);
4042       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4043                   " Pid %u not expected (%u+), dropping!\n",
4044                   pid, fc->last_pid_recv + 1);
4045     }
4046     tunnel_send_ack (t, GNUNET_MESSAGE_TYPE_MESH_UNICAST, fwd);
4047     return GNUNET_OK;
4048   }
4049   fc->last_pid_recv = pid;
4050   if (0 == hop)
4051   {
4052     GNUNET_break (0);
4053     return GNUNET_OK;
4054   }
4055   ttl = ntohl (msg->ttl);
4056   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ttl);
4057   if (ttl == 0)
4058   {
4059     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
4060     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
4061     tunnel_send_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK, fwd);
4062     return GNUNET_OK;
4063   }
4064
4065   if (myid != hop)
4066   {
4067     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  not for us, retransmitting...\n");
4068     send_prebuilt_message (message, hop, t);
4069     GNUNET_STATISTICS_update (stats, "# unicast forwarded", 1, GNUNET_NO);
4070   }
4071   return GNUNET_OK;
4072 }
4073
4074
4075 /**
4076  * Core handler for mesh network traffic going from the origin to a peer
4077  *
4078  * @param cls Closure (unused).
4079  * @param message Message received.
4080  * @param peer Peer who sent the message.
4081  *
4082  * @return GNUNET_OK to keep the connection open,
4083  *         GNUNET_SYSERR to close it (signal serious error)
4084  */
4085 static int
4086 handle_mesh_unicast (void *cls, const struct GNUNET_PeerIdentity *peer,
4087                      const struct GNUNET_MessageHeader *message)
4088 {
4089   return handle_mesh_data (peer, message, GNUNET_YES);
4090 }
4091
4092 /**
4093  * Core handler for mesh network traffic towards the owner of a tunnel.
4094  *
4095  * @param cls Closure (unused).
4096  * @param message Message received.
4097  * @param peer Peer who sent the message.
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_to_orig (void *cls, const struct GNUNET_PeerIdentity *peer,
4104                      const struct GNUNET_MessageHeader *message)
4105 {
4106   return handle_mesh_data (peer, message, GNUNET_NO);
4107 }
4108
4109
4110 /**
4111  * Core handler for mesh network traffic end-to-end ACKs.
4112  *
4113  * @param cls Closure.
4114  * @param message Message.
4115  * @param peer Peer identity this notification is about.
4116  *
4117  * @return GNUNET_OK to keep the connection open,
4118  *         GNUNET_SYSERR to close it (signal serious error)
4119  */
4120 static int
4121 handle_mesh_data_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
4122                       const struct GNUNET_MessageHeader *message)
4123 {
4124   struct GNUNET_MESH_DataACK *msg;
4125   struct MeshTunnelReliability *rel;
4126   struct MeshReliableMessage *copy;
4127   struct MeshReliableMessage *next;
4128   struct MeshTunnel *t;
4129   GNUNET_PEER_Id id;
4130   uint32_t ack;
4131   uint16_t type;
4132   int work;
4133
4134   type = ntohs (message->type);
4135   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a %s message from %s!\n",
4136               GNUNET_MESH_DEBUG_M2S (type), GNUNET_i2s (peer));
4137   msg = (struct GNUNET_MESH_DataACK *) message;
4138
4139   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4140   if (NULL == t)
4141   {
4142     /* TODO notify that we dont know this tunnel (whom)? */
4143     GNUNET_STATISTICS_update (stats, "# ack on unknown tunnel", 1, GNUNET_NO);
4144     return GNUNET_OK;
4145   }
4146   ack = ntohl (msg->mid);
4147   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ACK %u\n", ack);
4148
4149   /* Is this a forward or backward ACK? */
4150   id = GNUNET_PEER_search (peer);
4151   if (t->next_hop == id && GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK == type)
4152   {
4153     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
4154     if (NULL == t->owner)
4155     {
4156       send_prebuilt_message (message, t->prev_hop, t);
4157       return GNUNET_OK;
4158     }
4159     rel = t->fwd_rel;
4160   }
4161   else if (t->prev_hop == id && GNUNET_MESSAGE_TYPE_MESH_TO_ORIG_ACK == type)
4162   {
4163     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
4164     if (NULL == t->client)
4165     {
4166       send_prebuilt_message (message, t->next_hop, t);
4167       return GNUNET_OK;
4168     }
4169     rel = t->bck_rel;
4170   }
4171   else
4172   {
4173     GNUNET_break_op (0);
4174     return GNUNET_OK;
4175   }
4176
4177   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! ACK %u\n", ack);
4178   for (work = GNUNET_NO, copy = rel->head_sent; copy != NULL; copy = next)
4179   {
4180    if (GMC_is_pid_bigger (copy->mid, ack))
4181     {
4182       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!!  head %u, out!\n", copy->mid);
4183       tunnel_free_sent_reliable (t, msg, rel);
4184       break;
4185     }
4186     work = GNUNET_YES;
4187     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!!  id %u\n", copy->mid);
4188     next = copy->next;
4189     tunnel_free_reliable_message (copy);
4190   }
4191   /* Once buffers have been free'd, send ACK */
4192   tunnel_send_ack (t, type, GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK == type);
4193
4194   /* If some message was free'd, update the retransmission delay*/
4195   if (GNUNET_YES == work)
4196   {
4197     if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
4198     {
4199       GNUNET_SCHEDULER_cancel (rel->retry_task);
4200       if (NULL == rel->head_sent)
4201       {
4202         rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
4203       }
4204       else
4205       {
4206         struct GNUNET_TIME_Absolute new_target;
4207         struct GNUNET_TIME_Relative delay;
4208
4209         delay = GNUNET_TIME_relative_multiply (rel->retry_timer,
4210                                                MESH_RETRANSMIT_MARGIN);
4211         new_target = GNUNET_TIME_absolute_add (rel->head_sent->timestamp,
4212                                                delay);
4213         delay = GNUNET_TIME_absolute_get_remaining (new_target);
4214         rel->retry_task =
4215             GNUNET_SCHEDULER_add_delayed (delay,
4216                                           &tunnel_retransmit_message,
4217                                           rel);
4218       }
4219     }
4220     else
4221       GNUNET_break (0);
4222   }
4223   return GNUNET_OK;
4224 }
4225
4226 /**
4227  * Core handler for mesh network traffic point-to-point acks.
4228  *
4229  * @param cls closure
4230  * @param message message
4231  * @param peer peer identity this notification is about
4232  *
4233  * @return GNUNET_OK to keep the connection open,
4234  *         GNUNET_SYSERR to close it (signal serious error)
4235  */
4236 static int
4237 handle_mesh_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
4238                  const struct GNUNET_MessageHeader *message)
4239 {
4240   struct GNUNET_MESH_ACK *msg;
4241   struct MeshTunnel *t;
4242   struct MeshFlowControl *fc;
4243   GNUNET_PEER_Id id;
4244   uint32_t ack;
4245
4246   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK packet from %s!\n",
4247               GNUNET_i2s (peer));
4248   msg = (struct GNUNET_MESH_ACK *) message;
4249
4250   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4251
4252   if (NULL == t)
4253   {
4254     /* TODO notify that we dont know this tunnel (whom)? */
4255     GNUNET_STATISTICS_update (stats, "# ack on unknown tunnel", 1, GNUNET_NO);
4256     return GNUNET_OK;
4257   }
4258   ack = ntohl (msg->pid);
4259   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ACK %u\n", ack);
4260
4261   /* Is this a forward or backward ACK? */
4262   id = GNUNET_PEER_search (peer);
4263   if (t->next_hop == id)
4264   {
4265     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
4266     fc = &t->next_fc;
4267   }
4268   else if (t->prev_hop == id)
4269   {
4270     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
4271     fc = &t->prev_fc;
4272   }
4273   else
4274   {
4275     GNUNET_break_op (0);
4276     return GNUNET_OK;
4277   }
4278
4279   if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task &&
4280       GMC_is_pid_bigger (ack, fc->last_ack_recv))
4281   {
4282     GNUNET_SCHEDULER_cancel (fc->poll_task);
4283     fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
4284     fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
4285   }
4286   fc->last_ack_recv = ack;
4287   peer_unlock_queue (id);
4288
4289   tunnel_send_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK, t->next_hop == id);
4290
4291   return GNUNET_OK;
4292 }
4293
4294
4295 /**
4296  * Core handler for mesh network traffic point-to-point ack polls.
4297  *
4298  * @param cls closure
4299  * @param message message
4300  * @param peer peer identity this notification is about
4301  *
4302  * @return GNUNET_OK to keep the connection open,
4303  *         GNUNET_SYSERR to close it (signal serious error)
4304  */
4305 static int
4306 handle_mesh_poll (void *cls, const struct GNUNET_PeerIdentity *peer,
4307                   const struct GNUNET_MessageHeader *message)
4308 {
4309   struct GNUNET_MESH_Poll *msg;
4310   struct MeshTunnel *t;
4311   struct MeshFlowControl *fc;
4312   GNUNET_PEER_Id id;
4313   uint32_t pid;
4314   uint32_t old;
4315
4316   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an POLL packet from %s!\n",
4317               GNUNET_i2s (peer));
4318
4319   msg = (struct GNUNET_MESH_Poll *) message;
4320
4321   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4322
4323   if (NULL == t)
4324   {
4325     /* TODO notify that we dont know this tunnel (whom)? */
4326     GNUNET_STATISTICS_update (stats, "# poll on unknown tunnel", 1, GNUNET_NO);
4327     GNUNET_break_op (0);
4328     return GNUNET_OK;
4329   }
4330
4331   /* Is this a forward or backward ACK? */
4332   id = GNUNET_PEER_search(peer);
4333   pid = ntohl (msg->pid);
4334   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  PID %u\n", pid);
4335   if (t->next_hop == id)
4336   {
4337     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  from FWD\n");
4338     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  was %u\n", t->next_fc.last_pid_recv);
4339     fc = &t->next_fc;
4340     old = fc->last_pid_recv;
4341     fc->last_pid_recv = pid;
4342     tunnel_send_ack (t, GNUNET_MESSAGE_TYPE_MESH_POLL, GNUNET_NO);
4343   }
4344   else if (t->prev_hop == id)
4345   {
4346     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  from BCK\n");
4347     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  was %u\n", t->prev_fc.last_pid_recv);
4348     fc = &t->prev_fc;
4349     old = fc->last_pid_recv;
4350     fc->last_pid_recv = pid;
4351     tunnel_send_ack (t, GNUNET_MESSAGE_TYPE_MESH_POLL, GNUNET_YES);
4352   }
4353   else
4354     GNUNET_break (0);
4355
4356   if (GNUNET_YES == t->reliable)
4357     fc->last_pid_recv = old;
4358
4359   return GNUNET_OK;
4360 }
4361
4362
4363 /**
4364  * Core handler for mesh keepalives.
4365  *
4366  * @param cls closure
4367  * @param message message
4368  * @param peer peer identity this notification is about
4369  * @return GNUNET_OK to keep the connection open,
4370  *         GNUNET_SYSERR to close it (signal serious error)
4371  *
4372  * TODO: Check who we got this from, to validate route.
4373  */
4374 static int
4375 handle_mesh_keepalive (void *cls, const struct GNUNET_PeerIdentity *peer,
4376                        const struct GNUNET_MessageHeader *message)
4377 {
4378   struct GNUNET_MESH_TunnelKeepAlive *msg;
4379   struct MeshTunnel *t;
4380
4381   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a keepalive packet from %s\n",
4382               GNUNET_i2s (peer));
4383
4384   msg = (struct GNUNET_MESH_TunnelKeepAlive *) message;
4385   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4386
4387   if (NULL == t)
4388   {
4389     /* TODO notify that we dont know that tunnel */
4390     GNUNET_STATISTICS_update (stats, "# keepalive on unknown tunnel", 1,
4391                               GNUNET_NO);
4392     return GNUNET_OK;
4393   }
4394
4395   tunnel_reset_timeout (t, GNUNET_YES); // FIXME
4396   if (NULL != t->client || 0 == t->next_hop || myid == t->next_hop)
4397     return GNUNET_OK;
4398
4399   GNUNET_STATISTICS_update (stats, "# keepalives forwarded", 1, GNUNET_NO);
4400   send_prebuilt_message (message, t->next_hop, t);
4401   return GNUNET_OK;
4402   }
4403
4404
4405
4406 /**
4407  * Functions to handle messages from core
4408  */
4409 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
4410   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
4411   {&handle_mesh_path_broken, GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN,
4412    sizeof (struct GNUNET_MESH_PathBroken)},
4413   {&handle_mesh_tunnel_destroy, GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY,
4414    sizeof (struct GNUNET_MESH_TunnelDestroy)},
4415   {&handle_mesh_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
4416   {&handle_mesh_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
4417   {&handle_mesh_data_ack, GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK,
4418     sizeof (struct GNUNET_MESH_DataACK)},
4419   {&handle_mesh_data_ack, GNUNET_MESSAGE_TYPE_MESH_TO_ORIG_ACK,
4420     sizeof (struct GNUNET_MESH_DataACK)},
4421   {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE,
4422     sizeof (struct GNUNET_MESH_TunnelKeepAlive)},
4423   {&handle_mesh_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
4424     sizeof (struct GNUNET_MESH_ACK)},
4425   {&handle_mesh_poll, GNUNET_MESSAGE_TYPE_MESH_POLL,
4426     sizeof (struct GNUNET_MESH_Poll)},
4427   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
4428    sizeof (struct GNUNET_MESH_PathACK)},
4429   {NULL, 0, 0}
4430 };
4431
4432
4433
4434 /******************************************************************************/
4435 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
4436 /******************************************************************************/
4437
4438
4439 #if LATER
4440 /**
4441  * notify_client_connection_failure: notify a client that the connection to the
4442  * requested remote peer is not possible (for instance, no route found)
4443  * Function called when the socket is ready to queue more data. "buf" will be
4444  * NULL and "size" zero if the socket was closed for writing in the meantime.
4445  *
4446  * @param cls closure
4447  * @param size number of bytes available in buf
4448  * @param buf where the callee should write the message
4449  * @return number of bytes written to buf
4450  */
4451 static size_t
4452 notify_client_connection_failure (void *cls, size_t size, void *buf)
4453 {
4454   int size_needed;
4455   struct MeshPeerInfo *peer_info;
4456   struct GNUNET_MESH_PeerControl *msg;
4457   struct GNUNET_PeerIdentity id;
4458
4459   if (0 == size && NULL == buf)
4460   {
4461     // TODO retry? cancel?
4462     return 0;
4463   }
4464
4465   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
4466   peer_info = (struct MeshPeerInfo *) cls;
4467   msg = (struct GNUNET_MESH_PeerControl *) buf;
4468   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
4469   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
4470 //     msg->tunnel_id = htonl(peer_info->t->tid);
4471   GNUNET_PEER_resolve (peer_info->id, &id);
4472   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
4473
4474   return size_needed;
4475 }
4476 #endif
4477
4478
4479 /**
4480  * Send keepalive packets for a tunnel.
4481  *
4482  * @param cls Closure (tunnel for which to send the keepalive).
4483  * @param tc Notification context.
4484  * 
4485  * FIXME: add a refresh reset in case of normal unicast traffic is doing the job
4486  */
4487 static void
4488 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4489 {
4490   struct MeshTunnel *t = cls;
4491   struct GNUNET_MESH_TunnelKeepAlive *msg;
4492   size_t size = sizeof (struct GNUNET_MESH_TunnelKeepAlive);
4493   char cbuf[size];
4494
4495   t->maintenance_task = GNUNET_SCHEDULER_NO_TASK;
4496   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) ||
4497       NULL == t->owner || 0 == t->local_tid)
4498   {
4499     return;
4500   }
4501
4502   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4503               "sending keepalive for tunnel %d\n", t->id.tid);
4504
4505   msg = (struct GNUNET_MESH_TunnelKeepAlive *) cbuf;
4506   msg->header.size = htons (size);
4507   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE);
4508   msg->oid = my_full_id;
4509   msg->tid = htonl (t->id.tid);
4510   send_prebuilt_message (&msg->header, t->next_hop, t);
4511
4512   t->maintenance_task =
4513       GNUNET_SCHEDULER_add_delayed (refresh_path_time, &path_refresh, t);
4514 }
4515
4516
4517 /**
4518  * Function to process paths received for a new peer addition. The recorded
4519  * paths form the initial tunnel, which can be optimized later.
4520  * Called on each result obtained for the DHT search.
4521  *
4522  * @param cls closure
4523  * @param exp when will this value expire
4524  * @param key key of the result
4525  * @param get_path path of the get request
4526  * @param get_path_length lenght of get_path
4527  * @param put_path path of the put request
4528  * @param put_path_length length of the put_path
4529  * @param type type of the result
4530  * @param size number of bytes in data
4531  * @param data pointer to the result data
4532  */
4533 static void
4534 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
4535                     const struct GNUNET_HashCode * key,
4536                     const struct GNUNET_PeerIdentity *get_path,
4537                     unsigned int get_path_length,
4538                     const struct GNUNET_PeerIdentity *put_path,
4539                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
4540                     size_t size, const void *data)
4541 {
4542   struct MeshPeerInfo *peer = cls;
4543   struct MeshPeerPath *p;
4544   struct GNUNET_PeerIdentity pi;
4545   int i;
4546
4547   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
4548   GNUNET_PEER_resolve (peer->id, &pi);
4549   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", GNUNET_i2s (&pi));
4550
4551   p = path_build_from_dht (get_path, get_path_length,
4552                            put_path, put_path_length);
4553   path_add_to_peers (p, GNUNET_NO);
4554   path_destroy (p);
4555   for (i = 0; i < peer->ntunnels; i++)
4556   {
4557     struct GNUNET_PeerIdentity id;
4558
4559     GNUNET_PEER_resolve (peer->tunnels[i]->id.oid, &id);
4560     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ... tunnel %s:%X (%X / %X)\n",
4561                 GNUNET_i2s (&id), peer->tunnels[i]->id.tid,
4562                 peer->tunnels[i]->local_tid, 
4563                 peer->tunnels[i]->local_tid_dest);
4564     if (peer->tunnels[i]->state == MESH_TUNNEL_SEARCHING)
4565     {
4566       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ... connect!\n");
4567       peer_connect (peer, peer->tunnels[i]);
4568     }
4569   }
4570
4571   return;
4572 }
4573
4574
4575 /******************************************************************************/
4576 /*********************       MESH LOCAL HANDLES      **************************/
4577 /******************************************************************************/
4578
4579
4580 /**
4581  * Handler for client connection.
4582  *
4583  * @param cls Closure (unused).
4584  * @param client Client handler.
4585  */
4586 static void
4587 handle_local_client_connect (void *cls, struct GNUNET_SERVER_Client *client)
4588 {
4589   struct MeshClient *c;
4590
4591   if (NULL == client)
4592     return;
4593   c = GNUNET_malloc (sizeof (struct MeshClient));
4594   c->handle = client;
4595   GNUNET_SERVER_client_keep (client);
4596   GNUNET_SERVER_client_set_user_context (client, c);
4597   GNUNET_CONTAINER_DLL_insert (clients_head, clients_tail, c);
4598 }
4599
4600
4601 /**
4602  * Handler for client disconnection
4603  *
4604  * @param cls closure
4605  * @param client identification of the client; NULL
4606  *        for the last call when the server is destroyed
4607  */
4608 static void
4609 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
4610 {
4611   struct MeshClient *c;
4612   struct MeshClient *next;
4613
4614   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected: %p\n", client);
4615   if (client == NULL)
4616   {
4617     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (SERVER DOWN)\n");
4618     return;
4619   }
4620
4621   c = client_get (client);
4622   if (NULL != c)
4623   {
4624     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u)\n",
4625                 c->id);
4626     GNUNET_SERVER_client_drop (c->handle);
4627     c->shutting_down = GNUNET_YES;
4628     if (NULL != c->own_tunnels)
4629     {
4630       GNUNET_CONTAINER_multihashmap32_iterate (c->own_tunnels,
4631                                                &tunnel_destroy_iterator, c);
4632       GNUNET_CONTAINER_multihashmap32_destroy (c->own_tunnels);
4633     }
4634
4635     if (NULL != c->incoming_tunnels)
4636     {
4637       GNUNET_CONTAINER_multihashmap32_iterate (c->incoming_tunnels,
4638                                              &tunnel_destroy_iterator, c);
4639       GNUNET_CONTAINER_multihashmap32_destroy (c->incoming_tunnels);
4640     }
4641
4642     if (NULL != c->ports)
4643       GNUNET_CONTAINER_multihashmap32_destroy (c->ports);
4644     next = c->next;
4645     GNUNET_CONTAINER_DLL_remove (clients_head, clients_tail, c);
4646     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT FREE at %p\n", c);
4647     GNUNET_free (c);
4648     GNUNET_STATISTICS_update (stats, "# clients", -1, GNUNET_NO);
4649     c = next;
4650   }
4651   else
4652   {
4653     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " context NULL!\n");
4654   }
4655   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "done!\n");
4656   return;
4657 }
4658
4659
4660 /**
4661  * Handler for new clients
4662  *
4663  * @param cls closure
4664  * @param client identification of the client
4665  * @param message the actual message, which includes messages the client wants
4666  */
4667 static void
4668 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
4669                          const struct GNUNET_MessageHeader *message)
4670 {
4671   struct GNUNET_MESH_ClientConnect *cc_msg;
4672   struct MeshClient *c;
4673   unsigned int size;
4674   uint32_t *p;
4675   unsigned int i;
4676
4677   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected %p\n", client);
4678
4679   /* Check data sanity */
4680   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
4681   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
4682   if (0 != (size % sizeof (uint32_t)))
4683   {
4684     GNUNET_break (0);
4685     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4686     return;
4687   }
4688   size /= sizeof (uint32_t);
4689
4690   /* Initialize new client structure */
4691   c = GNUNET_SERVER_client_get_user_context (client, struct MeshClient);
4692   c->id = next_client_id++; /* overflow not important: just for debug */
4693   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  client id %u\n", c->id);
4694   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  client has %u ports\n", size);
4695   if (size > 0)
4696   {
4697     uint32_t u32;
4698
4699     p = (uint32_t *) &cc_msg[1];
4700     c->ports = GNUNET_CONTAINER_multihashmap32_create (size);
4701     for (i = 0; i < size; i++)
4702     {
4703       u32 = ntohl (p[i]);
4704       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    port: %u\n", u32);
4705
4706       /* store in client's hashmap */
4707       GNUNET_CONTAINER_multihashmap32_put (c->ports, u32, c,
4708                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
4709       /* store in global hashmap */
4710       /* FIXME only allow one client to have the port open,
4711        *       have a backup hashmap with waiting clients */
4712       GNUNET_CONTAINER_multihashmap32_put (ports, u32, c,
4713                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
4714     }
4715   }
4716
4717   c->own_tunnels = GNUNET_CONTAINER_multihashmap32_create (32);
4718   c->incoming_tunnels = GNUNET_CONTAINER_multihashmap32_create (32);
4719   GNUNET_SERVER_notification_context_add (nc, client);
4720   GNUNET_STATISTICS_update (stats, "# clients", 1, GNUNET_NO);
4721
4722   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4723   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
4724 }
4725
4726
4727 /**
4728  * Handler for requests of new tunnels
4729  *
4730  * @param cls Closure.
4731  * @param client Identification of the client.
4732  * @param message The actual message.
4733  */
4734 static void
4735 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
4736                             const struct GNUNET_MessageHeader *message)
4737 {
4738   struct GNUNET_MESH_TunnelMessage *t_msg;
4739   struct MeshPeerInfo *peer_info;
4740   struct MeshTunnel *t;
4741   struct MeshClient *c;
4742   MESH_TunnelNumber tid;
4743
4744   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel requested\n");
4745
4746   /* Sanity check for client registration */
4747   if (NULL == (c = client_get (client)))
4748   {
4749     GNUNET_break (0);
4750     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4751     return;
4752   }
4753   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
4754
4755   /* Message size sanity check */
4756   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
4757   {
4758     GNUNET_break (0);
4759     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4760     return;
4761   }
4762
4763   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
4764   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  towards %s\n",
4765               GNUNET_i2s (&t_msg->peer));
4766   /* Sanity check for tunnel numbering */
4767   tid = ntohl (t_msg->tunnel_id);
4768   if (0 == (tid & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
4769   {
4770     GNUNET_break (0);
4771     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4772     return;
4773   }
4774   /* Sanity check for duplicate tunnel IDs */
4775   if (NULL != tunnel_get_by_local_id (c, tid))
4776   {
4777     GNUNET_break (0);
4778     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4779     return;
4780   }
4781
4782   /* Create tunnel */
4783   while (NULL != tunnel_get_by_pi (myid, next_tid))
4784     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
4785   t = tunnel_new (myid, next_tid, c, tid);
4786   next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
4787   if (NULL == t)
4788   {
4789     GNUNET_break (0);
4790     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4791     return;
4792   }
4793   t->port = ntohl (t_msg->port);
4794   tunnel_set_options (t, ntohl (t_msg->opt));
4795   if (GNUNET_YES == t->reliable)
4796   {
4797     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! Reliable\n");
4798     t->fwd_rel = GNUNET_malloc (sizeof (struct MeshTunnelReliability));
4799     t->fwd_rel->t = t;
4800     t->fwd_rel->expected_delay = MESH_RETRANSMIT_TIME;
4801   }
4802
4803   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED TUNNEL %s[%x]:%u (%x)\n",
4804               GNUNET_i2s (&my_full_id), t->id.tid, t->port, t->local_tid);
4805
4806   peer_info = peer_get (&t_msg->peer);
4807   peer_info_add_tunnel (peer_info, t);
4808   peer_connect (peer_info, t);
4809   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4810   return;
4811 }
4812
4813
4814 /**
4815  * Handler for requests of deleting tunnels
4816  *
4817  * @param cls closure
4818  * @param client identification of the client
4819  * @param message the actual message
4820  */
4821 static void
4822 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
4823                              const struct GNUNET_MessageHeader *message)
4824 {
4825   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
4826   struct MeshClient *c;
4827   struct MeshTunnel *t;
4828   MESH_TunnelNumber tid;
4829
4830   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4831               "Got a DESTROY TUNNEL from client!\n");
4832
4833   /* Sanity check for client registration */
4834   if (NULL == (c = client_get (client)))
4835   {
4836     GNUNET_break (0);
4837     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4838     return;
4839   }
4840   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
4841
4842   /* Message sanity check */
4843   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
4844   {
4845     GNUNET_break (0);
4846     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4847     return;
4848   }
4849
4850   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
4851
4852   /* Retrieve tunnel */
4853   tid = ntohl (tunnel_msg->tunnel_id);
4854   t = tunnel_get_by_local_id(c, tid);
4855   if (NULL == t)
4856   {
4857     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
4858     GNUNET_break (0);
4859     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4860     return;
4861   }
4862
4863   /* Cleanup after the tunnel */
4864   client_delete_tunnel (c, t);
4865   if (c == t->client)
4866   {
4867     t->client = NULL;
4868   }
4869   if (c == t->owner)
4870   {
4871     peer_info_remove_tunnel (peer_get_short (t->dest), t);
4872     t->owner = NULL;
4873   }
4874
4875   /* The tunnel will be destroyed when the last message is transmitted. */
4876   tunnel_destroy_empty (t);
4877
4878   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4879   return;
4880 }
4881
4882
4883 /**
4884  * Handler for client traffic
4885  *
4886  * @param cls closure
4887  * @param client identification of the client
4888  * @param message the actual message
4889  */
4890 static void
4891 handle_local_data (void *cls, struct GNUNET_SERVER_Client *client,
4892                    const struct GNUNET_MessageHeader *message)
4893 {
4894   struct GNUNET_MESH_LocalData *data_msg;
4895   struct MeshClient *c;
4896   struct MeshTunnel *t;
4897   struct MeshFlowControl *fc;
4898   MESH_TunnelNumber tid;
4899   size_t size;
4900
4901   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4902               "Got data from a client!\n");
4903
4904   /* Sanity check for client registration */
4905   if (NULL == (c = client_get (client)))
4906   {
4907     GNUNET_break (0);
4908     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4909     return;
4910   }
4911   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
4912
4913   data_msg = (struct GNUNET_MESH_LocalData *) message;
4914
4915   /* Sanity check for message size */
4916   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_LocalData);
4917   if (size < sizeof (struct GNUNET_MessageHeader))
4918   {
4919     GNUNET_break (0);
4920     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4921     return;
4922   }
4923
4924   /* Tunnel exists? */
4925   tid = ntohl (data_msg->tid);
4926   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_CLI)
4927   {
4928     GNUNET_break (0);
4929     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4930     return;
4931   }
4932   t = tunnel_get_by_local_id (c, tid);
4933   if (NULL == t)
4934   {
4935     GNUNET_break (0);
4936     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4937     return;
4938   }
4939
4940   /* Is the client in the tunnel? */
4941   if ( !( (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV &&
4942            t->owner &&
4943            t->owner->handle == client)
4944          ||
4945           (tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV &&
4946            t->client && 
4947            t->client->handle == client) ) )
4948   {
4949     GNUNET_break (0);
4950     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4951     return;
4952   }
4953
4954   /* Ok, everything is correct, send the message
4955    * (pretend we got it from a mesh peer)
4956    */
4957   {
4958     struct GNUNET_MESH_Data *payload;
4959     char cbuf[sizeof(struct GNUNET_MESH_Data) + size];
4960
4961     fc = tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV ? &t->prev_fc : &t->next_fc;
4962     if (GNUNET_YES == t->reliable)
4963     {
4964       struct MeshTunnelReliability *rel;
4965       struct MeshReliableMessage *copy;
4966
4967       rel = (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV) ? t->fwd_rel : t->bck_rel;
4968       copy = GNUNET_malloc (sizeof (struct MeshReliableMessage)
4969                             + sizeof(struct GNUNET_MESH_Data)
4970                             + size);
4971       copy->mid = rel->mid_sent++;
4972       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! DATA %u\n", copy->mid);
4973       copy->timestamp = GNUNET_TIME_absolute_get ();
4974       copy->rel = rel;
4975       rel->n_sent++;
4976       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " n_sent %u\n", rel->n_sent);
4977       GNUNET_CONTAINER_DLL_insert_tail (rel->head_sent, rel->tail_sent, copy);
4978       if (GNUNET_SCHEDULER_NO_TASK == rel->retry_task)
4979       {
4980         rel->retry_timer =
4981             GNUNET_TIME_relative_multiply (rel->expected_delay,
4982                                            MESH_RETRANSMIT_MARGIN);
4983         rel->retry_task =
4984             GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
4985                                           &tunnel_retransmit_message,
4986                                           rel);
4987       }
4988       payload = (struct GNUNET_MESH_Data *) &copy[1];
4989       payload->mid = htonl (copy->mid);
4990     }
4991     else
4992     {
4993       payload = (struct GNUNET_MESH_Data *) cbuf;
4994       payload->mid = htonl (fc->last_pid_recv + 1);
4995     }
4996     memcpy (&payload[1], &data_msg[1], size);
4997     payload->header.size = htons (sizeof (struct GNUNET_MESH_Data) + size);
4998     payload->header.type = htons (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV ?
4999                                   GNUNET_MESSAGE_TYPE_MESH_UNICAST :
5000                                   GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
5001     GNUNET_PEER_resolve(t->id.oid, &payload->oid);;
5002     payload->tid = htonl (t->id.tid);
5003     payload->ttl = htonl (default_ttl);
5004     payload->pid = htonl (fc->last_pid_recv + 1);
5005     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5006                 "  calling generic handler...\n");
5007     if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
5008       handle_mesh_unicast (NULL, &my_full_id, &payload->header);
5009     else
5010       handle_mesh_to_orig (NULL, &my_full_id, &payload->header);
5011   }
5012   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "receive done OK\n");
5013   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5014
5015   return;
5016 }
5017
5018
5019 /**
5020  * Handler for client's ACKs for payload traffic.
5021  *
5022  * @param cls Closure (unused).
5023  * @param client Identification of the client.
5024  * @param message The actual message.
5025  */
5026 static void
5027 handle_local_ack (void *cls, struct GNUNET_SERVER_Client *client,
5028                   const struct GNUNET_MessageHeader *message)
5029 {
5030   struct GNUNET_MESH_LocalAck *msg;
5031   struct MeshTunnel *t;
5032   struct MeshClient *c;
5033   MESH_TunnelNumber tid;
5034
5035   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a local ACK\n");
5036   /* Sanity check for client registration */
5037   if (NULL == (c = client_get (client)))
5038   {
5039     GNUNET_break (0);
5040     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5041     return;
5042   }
5043   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
5044
5045   msg = (struct GNUNET_MESH_LocalAck *) message;
5046
5047   /* Tunnel exists? */
5048   tid = ntohl (msg->tunnel_id);
5049   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
5050   t = tunnel_get_by_local_id (c, tid);
5051   if (NULL == t)
5052   {
5053     GNUNET_break (0);
5054     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
5055     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
5056     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5057     return;
5058   }
5059
5060   /* Does client own tunnel? I.E: Is this an ACK for BCK traffic? */
5061   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
5062   {
5063     /* The client owns the tunnel, ACK is for data to_origin, send BCK ACK. */
5064     t->prev_fc.last_ack_recv++;
5065     tunnel_send_ack (t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK, GNUNET_NO);
5066   }
5067   else
5068   {
5069     /* The client doesn't own the tunnel, this ACK is for FWD traffic. */
5070     t->next_fc.last_ack_recv++;
5071     tunnel_send_ack (t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK, GNUNET_YES);
5072   }
5073
5074   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5075
5076   return;
5077 }
5078
5079
5080
5081 /**
5082  * Iterator over all tunnels to send a monitoring client info about each tunnel.
5083  *
5084  * @param cls Closure (client handle).
5085  * @param key Key (hashed tunnel ID, unused).
5086  * @param value Tunnel info.
5087  *
5088  * @return GNUNET_YES, to keep iterating.
5089  */
5090 static int
5091 monitor_all_tunnels_iterator (void *cls,
5092                               const struct GNUNET_HashCode * key,
5093                               void *value)
5094 {
5095   struct GNUNET_SERVER_Client *client = cls;
5096   struct MeshTunnel *t = value;
5097   struct GNUNET_MESH_LocalMonitor *msg;
5098
5099   msg = GNUNET_malloc (sizeof(struct GNUNET_MESH_LocalMonitor));
5100   GNUNET_PEER_resolve(t->id.oid, &msg->owner);
5101   msg->tunnel_id = htonl (t->id.tid);
5102   msg->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
5103   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS);
5104   GNUNET_PEER_resolve (t->dest, &msg->destination);
5105
5106   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5107               "*  sending info about tunnel %s [%u]\n",
5108               GNUNET_i2s (&msg->owner), t->id.tid);
5109
5110   GNUNET_SERVER_notification_context_unicast (nc, client,
5111                                               &msg->header, GNUNET_NO);
5112   return GNUNET_YES;
5113 }
5114
5115
5116 /**
5117  * Handler for client's MONITOR request.
5118  *
5119  * @param cls Closure (unused).
5120  * @param client Identification of the client.
5121  * @param message The actual message.
5122  */
5123 static void
5124 handle_local_get_tunnels (void *cls, struct GNUNET_SERVER_Client *client,
5125                           const struct GNUNET_MessageHeader *message)
5126 {
5127   struct MeshClient *c;
5128
5129   /* Sanity check for client registration */
5130   if (NULL == (c = client_get (client)))
5131   {
5132     GNUNET_break (0);
5133     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5134     return;
5135   }
5136
5137   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5138               "Received get tunnels request from client %u\n",
5139               c->id);
5140   GNUNET_CONTAINER_multihashmap_iterate (tunnels,
5141                                          monitor_all_tunnels_iterator,
5142                                          client);
5143   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5144               "Get tunnels request from client %u completed\n",
5145               c->id);
5146   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5147 }
5148
5149
5150 /**
5151  * Handler for client's MONITOR_TUNNEL request.
5152  *
5153  * @param cls Closure (unused).
5154  * @param client Identification of the client.
5155  * @param message The actual message.
5156  */
5157 static void
5158 handle_local_show_tunnel (void *cls, struct GNUNET_SERVER_Client *client,
5159                           const struct GNUNET_MessageHeader *message)
5160 {
5161   const struct GNUNET_MESH_LocalMonitor *msg;
5162   struct GNUNET_MESH_LocalMonitor *resp;
5163   struct MeshClient *c;
5164   struct MeshTunnel *t;
5165
5166   /* Sanity check for client registration */
5167   if (NULL == (c = client_get (client)))
5168   {
5169     GNUNET_break (0);
5170     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5171     return;
5172   }
5173
5174   msg = (struct GNUNET_MESH_LocalMonitor *) message;
5175   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5176               "Received tunnel info request from client %u for tunnel %s[%X]\n",
5177               c->id,
5178               &msg->owner,
5179               ntohl (msg->tunnel_id));
5180   t = tunnel_get (&msg->owner, ntohl (msg->tunnel_id));
5181   if (NULL == t)
5182   {
5183     /* We don't know the tunnel FIXME */
5184     struct GNUNET_MESH_LocalMonitor warn;
5185
5186     warn = *msg;
5187     GNUNET_SERVER_notification_context_unicast (nc, client,
5188                                                 &warn.header,
5189                                                 GNUNET_NO);
5190     GNUNET_SERVER_receive_done (client, GNUNET_OK);
5191     return;
5192   }
5193
5194   /* Initialize context */
5195   resp = GNUNET_malloc (sizeof (struct GNUNET_MESH_LocalMonitor));
5196   *resp = *msg;
5197   GNUNET_PEER_resolve (t->dest, &resp->destination);
5198   resp->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
5199   GNUNET_SERVER_notification_context_unicast (nc, c->handle,
5200                                               &resp->header, GNUNET_NO);
5201   GNUNET_free (resp);
5202
5203   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5204               "Monitor tunnel request from client %u completed\n",
5205               c->id);
5206   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5207 }
5208
5209
5210 /**
5211  * Functions to handle messages from clients
5212  */
5213 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
5214   {&handle_local_new_client, NULL,
5215    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
5216   {&handle_local_tunnel_create, NULL,
5217    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
5218    sizeof (struct GNUNET_MESH_TunnelMessage)},
5219   {&handle_local_tunnel_destroy, NULL,
5220    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
5221    sizeof (struct GNUNET_MESH_TunnelMessage)},
5222   {&handle_local_data, NULL,
5223    GNUNET_MESSAGE_TYPE_MESH_LOCAL_DATA, 0},
5224   {&handle_local_ack, NULL,
5225    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK,
5226    sizeof (struct GNUNET_MESH_LocalAck)},
5227   {&handle_local_get_tunnels, NULL,
5228    GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS,
5229    sizeof (struct GNUNET_MessageHeader)},
5230   {&handle_local_show_tunnel, NULL,
5231    GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNEL,
5232      sizeof (struct GNUNET_MESH_LocalMonitor)},
5233   {NULL, NULL, 0, 0}
5234 };
5235
5236
5237 /**
5238  * Method called whenever a given peer connects.
5239  *
5240  * @param cls closure
5241  * @param peer peer identity this notification is about
5242  */
5243 static void
5244 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer)
5245 {
5246   struct MeshPeerInfo *peer_info;
5247   struct MeshPeerPath *path;
5248
5249   DEBUG_CONN ("Peer connected\n");
5250   DEBUG_CONN ("     %s\n", GNUNET_i2s (&my_full_id));
5251   peer_info = peer_get (peer);
5252   if (myid == peer_info->id)
5253   {
5254     DEBUG_CONN ("     (self)\n");
5255     path = path_new (1);
5256   }
5257   else
5258   {
5259     DEBUG_CONN ("     %s\n", GNUNET_i2s (peer));
5260     path = path_new (2);
5261     path->peers[1] = peer_info->id;
5262     GNUNET_PEER_change_rc (peer_info->id, 1);
5263     GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
5264   }
5265   path->peers[0] = myid;
5266   GNUNET_PEER_change_rc (myid, 1);
5267   peer_info_add_path (peer_info, path, GNUNET_YES);
5268   return;
5269 }
5270
5271
5272 /**
5273  * Method called whenever a peer disconnects.
5274  *
5275  * @param cls closure
5276  * @param peer peer identity this notification is about
5277  */
5278 static void
5279 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
5280 {
5281   struct MeshPeerInfo *pi;
5282   struct MeshPeerQueue *q;
5283   struct MeshPeerQueue *n;
5284
5285   DEBUG_CONN ("Peer disconnected\n");
5286   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
5287   if (NULL == pi)
5288   {
5289     GNUNET_break (0);
5290     return;
5291   }
5292   q = pi->queue_head;
5293   while (NULL != q)
5294   {
5295       n = q->next;
5296       /* TODO try to reroute this traffic instead */
5297       queue_destroy(q, GNUNET_YES);
5298       q = n;
5299   }
5300   if (NULL != pi->core_transmit)
5301   {
5302     GNUNET_CORE_notify_transmit_ready_cancel(pi->core_transmit);
5303     pi->core_transmit = NULL;
5304   }
5305     peer_remove_path (pi, pi->id, myid);
5306   if (myid == pi->id)
5307   {
5308     DEBUG_CONN ("     (self)\n");
5309   }
5310   GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
5311   return;
5312 }
5313
5314
5315 /**
5316  * Install server (service) handlers and start listening to clients.
5317  */
5318 static void
5319 server_init (void)
5320 {
5321   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
5322   GNUNET_SERVER_connect_notify (server_handle,
5323                                 &handle_local_client_connect, NULL);
5324   GNUNET_SERVER_disconnect_notify (server_handle,
5325                                    &handle_local_client_disconnect, NULL);
5326   nc = GNUNET_SERVER_notification_context_create (server_handle, 1);
5327
5328   clients_head = NULL;
5329   clients_tail = NULL;
5330   next_client_id = 0;
5331   GNUNET_SERVER_resume (server_handle);
5332 }
5333
5334
5335 /**
5336  * To be called on core init/fail.
5337  *
5338  * @param cls Closure (config)
5339  * @param server handle to the server for this service
5340  * @param identity the public identity of this peer
5341  */
5342 static void
5343 core_init (void *cls, struct GNUNET_CORE_Handle *server,
5344            const struct GNUNET_PeerIdentity *identity)
5345 {
5346   const struct GNUNET_CONFIGURATION_Handle *c = cls;
5347   static int i = 0;
5348
5349   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
5350   GNUNET_break (core_handle == server);
5351   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)) ||
5352     NULL == server)
5353   {
5354     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
5355     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5356                 " core id %s\n",
5357                 GNUNET_i2s (identity));
5358     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5359                 " my id %s\n",
5360                 GNUNET_i2s (&my_full_id));
5361     GNUNET_CORE_disconnect (core_handle);
5362     core_handle = GNUNET_CORE_connect (c, /* Main configuration */
5363                                        NULL,      /* Closure passed to MESH functions */
5364                                        &core_init,        /* Call core_init once connected */
5365                                        &core_connect,     /* Handle connects */
5366                                        &core_disconnect,  /* remove peers on disconnects */
5367                                        NULL,      /* Don't notify about all incoming messages */
5368                                        GNUNET_NO, /* For header only in notification */
5369                                        NULL,      /* Don't notify about all outbound messages */
5370                                        GNUNET_NO, /* For header-only out notification */
5371                                        core_handlers);    /* Register these handlers */
5372     if (10 < i++)
5373       GNUNET_abort();
5374   }
5375   server_init ();
5376   return;
5377 }
5378
5379
5380 /******************************************************************************/
5381 /************************      MAIN FUNCTIONS      ****************************/
5382 /******************************************************************************/
5383
5384 /**
5385  * Iterator over tunnel 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_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
5395 {
5396   struct MeshTunnel *t = value;
5397
5398   tunnel_destroy (t);
5399   return GNUNET_YES;
5400 }
5401
5402 /**
5403  * Iterator over peer hash map entries to destroy the tunnel during shutdown.
5404  *
5405  * @param cls closure
5406  * @param key current key code
5407  * @param value value in the hash map
5408  * @return GNUNET_YES if we should continue to iterate,
5409  *         GNUNET_NO if not.
5410  */
5411 static int
5412 shutdown_peer (void *cls, const struct GNUNET_HashCode * key, void *value)
5413 {
5414   struct MeshPeerInfo *p = value;
5415   struct MeshPeerQueue *q;
5416   struct MeshPeerQueue *n;
5417
5418   q = p->queue_head;
5419   while (NULL != q)
5420   {
5421       n = q->next;
5422       if (q->peer == p)
5423       {
5424         queue_destroy(q, GNUNET_YES);
5425       }
5426       q = n;
5427   }
5428   peer_info_destroy (p);
5429   return GNUNET_YES;
5430 }
5431
5432
5433 /**
5434  * Task run during shutdown.
5435  *
5436  * @param cls unused
5437  * @param tc unused
5438  */
5439 static void
5440 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
5441 {
5442   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
5443
5444   if (core_handle != NULL)
5445   {
5446     GNUNET_CORE_disconnect (core_handle);
5447     core_handle = NULL;
5448   }
5449   GNUNET_CONTAINER_multihashmap_iterate (tunnels, &shutdown_tunnel, NULL);
5450   GNUNET_CONTAINER_multihashmap_iterate (peers, &shutdown_peer, NULL);
5451   if (dht_handle != NULL)
5452   {
5453     GNUNET_DHT_disconnect (dht_handle);
5454     dht_handle = NULL;
5455   }
5456   if (nc != NULL)
5457   {
5458     GNUNET_SERVER_notification_context_destroy (nc);
5459     nc = NULL;
5460   }
5461   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
5462   {
5463     GNUNET_SCHEDULER_cancel (announce_id_task);
5464     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
5465   }
5466   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
5467 }
5468
5469
5470 /**
5471  * Process mesh requests.
5472  *
5473  * @param cls closure
5474  * @param server the initialized server
5475  * @param c configuration to use
5476  */
5477 static void
5478 run (void *cls, struct GNUNET_SERVER_Handle *server,
5479      const struct GNUNET_CONFIGURATION_Handle *c)
5480 {
5481   char *keyfile;
5482   struct GNUNET_CRYPTO_EccPrivateKey *pk;
5483
5484   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
5485   server_handle = server;
5486   GNUNET_SERVER_suspend (server_handle);
5487
5488   if (GNUNET_OK !=
5489       GNUNET_CONFIGURATION_get_value_filename (c, "PEER", "PRIVATE_KEY",
5490                                                &keyfile))
5491   {
5492     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5493                 _
5494                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5495                 "mesh", "peer/privatekey");
5496     GNUNET_SCHEDULER_shutdown ();
5497     return;
5498   }
5499
5500   if (GNUNET_OK !=
5501       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_PATH_TIME",
5502                                            &refresh_path_time))
5503   {
5504     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5505                 _
5506                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5507                 "mesh", "refresh path time");
5508     GNUNET_SCHEDULER_shutdown ();
5509     return;
5510   }
5511
5512   if (GNUNET_OK !=
5513       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "ID_ANNOUNCE_TIME",
5514                                            &id_announce_time))
5515   {
5516     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5517                 _
5518                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5519                 "mesh", "id announce time");
5520     GNUNET_SCHEDULER_shutdown ();
5521     return;
5522   }
5523
5524   if (GNUNET_OK !=
5525       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "CONNECT_TIMEOUT",
5526                                            &connect_timeout))
5527   {
5528     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5529                 _
5530                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5531                 "mesh", "connect timeout");
5532     GNUNET_SCHEDULER_shutdown ();
5533     return;
5534   }
5535
5536   if (GNUNET_OK !=
5537       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
5538                                              &max_msgs_queue))
5539   {
5540     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5541                 _
5542                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5543                 "mesh", "max msgs queue");
5544     GNUNET_SCHEDULER_shutdown ();
5545     return;
5546   }
5547
5548   if (GNUNET_OK !=
5549       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_TUNNELS",
5550                                              &max_tunnels))
5551   {
5552     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5553                 _
5554                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5555                 "mesh", "max tunnels");
5556     GNUNET_SCHEDULER_shutdown ();
5557     return;
5558   }
5559
5560   if (GNUNET_OK !=
5561       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
5562                                              &default_ttl))
5563   {
5564     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5565                 _
5566                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
5567                 "mesh", "default ttl", 64);
5568     default_ttl = 64;
5569   }
5570
5571   if (GNUNET_OK !=
5572       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_PEERS",
5573                                              &max_peers))
5574   {
5575     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5576                 _("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
5577                 "mesh", "max peers", 1000);
5578     max_peers = 1000;
5579   }
5580
5581   if (GNUNET_OK !=
5582       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DROP_PERCENT",
5583                                              &drop_percent))
5584   {
5585     drop_percent = 0;
5586   }
5587   else
5588   {
5589     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5590                 "Mesh is running with drop mode enabled. "
5591                 "This is NOT a good idea! "
5592                 "Remove the DROP_PERCENT option from your configuration.\n");
5593   }
5594
5595   if (GNUNET_OK !=
5596       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DHT_REPLICATION_LEVEL",
5597                                              &dht_replication_level))
5598   {
5599     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5600                 _
5601                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
5602                 "mesh", "dht replication level", 3);
5603     dht_replication_level = 3;
5604   }
5605
5606   tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
5607   incoming_tunnels = GNUNET_CONTAINER_multihashmap32_create (32);
5608   peers = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
5609   ports = GNUNET_CONTAINER_multihashmap32_create (32);
5610
5611   dht_handle = GNUNET_DHT_connect (c, 64);
5612   if (NULL == dht_handle)
5613   {
5614     GNUNET_break (0);
5615   }
5616   stats = GNUNET_STATISTICS_create ("mesh", c);
5617
5618   /* Scheduled the task to clean up when shutdown is called */
5619   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
5620                                 NULL);
5621   pk = GNUNET_CRYPTO_ecc_key_create_from_file (keyfile);
5622   GNUNET_free (keyfile);
5623   GNUNET_assert (NULL != pk);
5624   my_private_key = pk;
5625   GNUNET_CRYPTO_ecc_key_get_public (my_private_key, &my_public_key);
5626   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
5627                       &my_full_id.hashPubKey);
5628   myid = GNUNET_PEER_intern (&my_full_id);
5629   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5630               "Mesh for peer [%s] starting\n",
5631               GNUNET_i2s(&my_full_id));
5632
5633   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
5634                                      NULL,      /* Closure passed to MESH functions */
5635                                      &core_init,        /* Call core_init once connected */
5636                                      &core_connect,     /* Handle connects */
5637                                      &core_disconnect,  /* remove peers on disconnects */
5638                                      NULL,      /* Don't notify about all incoming messages */
5639                                      GNUNET_NO, /* For header only in notification */
5640                                      NULL,      /* Don't notify about all outbound messages */
5641                                      GNUNET_NO, /* For header-only out notification */
5642                                      core_handlers);    /* Register these handlers */
5643   if (NULL == core_handle)
5644   {
5645     GNUNET_break (0);
5646     GNUNET_SCHEDULER_shutdown ();
5647     return;
5648   }
5649   next_tid = 0;
5650   next_local_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
5651   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
5652   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Mesh service running\n");
5653 }
5654
5655
5656 /**
5657  * The main function for the mesh service.
5658  *
5659  * @param argc number of arguments from the command line
5660  * @param argv command line arguments
5661  * @return 0 ok, 1 on error
5662  */
5663 int
5664 main (int argc, char *const *argv)
5665 {
5666   int ret;
5667   int r;
5668
5669   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
5670   r = GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
5671                           NULL);
5672   ret = (GNUNET_OK == r) ? 0 : 1;
5673   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");
5674
5675   INTERVAL_SHOW;
5676
5677   return ret;
5678 }