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