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