a60793c7f1b0758aa7ec5417d6f4f0c93fafe9fd
[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   }
3503   queue = GNUNET_malloc (sizeof (struct MeshPeerQueue));
3504   queue->cls = cls;
3505   queue->type = type;
3506   queue->size = size;
3507   queue->peer = dst;
3508   queue->tunnel = t;
3509   if (GNUNET_YES == priority)
3510   {
3511     struct GNUNET_MESH_Data *d;
3512     uint32_t prev;
3513     uint32_t next;
3514
3515     GNUNET_CONTAINER_DLL_insert (dst->queue_head, dst->queue_tail, queue);
3516     d = (struct GNUNET_MESH_Data *) queue->cls;
3517     prev = d->pid;
3518     for (queue = dst->queue_tail; NULL != queue; queue = queue->prev)
3519     {
3520       if (queue->type != type)
3521         continue;
3522       d = (struct GNUNET_MESH_Data *) queue->cls;
3523       next = d->pid;
3524       d->pid = prev;
3525       prev = next;
3526     }
3527   }
3528   else
3529     GNUNET_CONTAINER_DLL_insert_tail (dst->queue_head, dst->queue_tail, queue);
3530   if (NULL == dst->core_transmit)
3531   {
3532     GNUNET_PEER_resolve (dst->id, &id);
3533     dst->core_transmit =
3534         GNUNET_CORE_notify_transmit_ready (core_handle,
3535                                            0,
3536                                            0,
3537                                            GNUNET_TIME_UNIT_FOREVER_REL,
3538                                            &id,
3539                                            size,
3540                                            &queue_send,
3541                                            dst);
3542   }
3543   t->pending_messages++;
3544 }
3545
3546
3547 /******************************************************************************/
3548 /********************      MESH NETWORK HANDLERS     **************************/
3549 /******************************************************************************/
3550
3551
3552 /**
3553  * Core handler for path creation
3554  *
3555  * @param cls closure
3556  * @param message message
3557  * @param peer peer identity this notification is about
3558  *
3559  * @return GNUNET_OK to keep the connection open,
3560  *         GNUNET_SYSERR to close it (signal serious error)
3561  */
3562 static int
3563 handle_mesh_path_create (void *cls, const struct GNUNET_PeerIdentity *peer,
3564                          const struct GNUNET_MessageHeader *message)
3565 {
3566   unsigned int own_pos;
3567   uint16_t size;
3568   uint16_t i;
3569   MESH_TunnelNumber tid;
3570   struct GNUNET_MESH_CreateTunnel *msg;
3571   struct GNUNET_PeerIdentity *pi;
3572   struct MeshPeerPath *path;
3573   struct MeshPeerInfo *dest_peer_info;
3574   struct MeshPeerInfo *orig_peer_info;
3575   struct MeshTunnel *t;
3576
3577   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3578               "Received a path create msg [%s]\n",
3579               GNUNET_i2s (&my_full_id));
3580   size = ntohs (message->size);
3581   if (size < sizeof (struct GNUNET_MESH_CreateTunnel))
3582   {
3583     GNUNET_break_op (0);
3584     return GNUNET_OK;
3585   }
3586
3587   size -= sizeof (struct GNUNET_MESH_CreateTunnel);
3588   if (size % sizeof (struct GNUNET_PeerIdentity))
3589   {
3590     GNUNET_break_op (0);
3591     return GNUNET_OK;
3592   }
3593   size /= sizeof (struct GNUNET_PeerIdentity);
3594   if (size < 1)
3595   {
3596     GNUNET_break_op (0);
3597     return GNUNET_OK;
3598   }
3599   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
3600   msg = (struct GNUNET_MESH_CreateTunnel *) message;
3601
3602   tid = ntohl (msg->tid);
3603   pi = (struct GNUNET_PeerIdentity *) &msg[1];
3604   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3605               "    path is for tunnel %s[%X].\n", GNUNET_i2s (pi), tid);
3606   t = tunnel_get (pi, tid);
3607   if (NULL == t) /* might be a local tunnel */
3608   {
3609     uint32_t opt;
3610
3611     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating tunnel\n");
3612     t = tunnel_new (GNUNET_PEER_intern (pi), tid, NULL, 0);
3613     if (NULL == t)
3614     {
3615       GNUNET_break (0);
3616       return GNUNET_OK;
3617     }
3618     t->port = ntohl (msg->port);
3619     opt = ntohl (msg->opt);
3620     if (0 != (opt & GNUNET_MESH_OPTION_NOBUFFER))
3621     {
3622       t->nobuffer = GNUNET_YES;
3623       t->queue_max = 1;
3624     }
3625     if (0 != (opt & GNUNET_MESH_OPTION_RELIABLE))
3626     {
3627       t->reliable = GNUNET_YES;
3628     }
3629     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  nobuffer:%d\n", t->nobuffer);
3630
3631     tunnel_reset_timeout (t, GNUNET_YES); // FIXME
3632   }
3633   t->state = MESH_TUNNEL_WAITING;
3634   dest_peer_info =
3635       GNUNET_CONTAINER_multihashmap_get (peers, &pi[size - 1].hashPubKey);
3636   if (NULL == dest_peer_info)
3637   {
3638     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3639                 "  Creating PeerInfo for destination.\n");
3640     dest_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
3641     dest_peer_info->id = GNUNET_PEER_intern (&pi[size - 1]);
3642     GNUNET_CONTAINER_multihashmap_put (peers, &pi[size - 1].hashPubKey,
3643                                        dest_peer_info,
3644                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3645   }
3646   orig_peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &pi->hashPubKey);
3647   if (NULL == orig_peer_info)
3648   {
3649     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3650                 "  Creating PeerInfo for origin.\n");
3651     orig_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
3652     orig_peer_info->id = GNUNET_PEER_intern (pi);
3653     GNUNET_CONTAINER_multihashmap_put (peers, &pi->hashPubKey, orig_peer_info,
3654                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3655   }
3656   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
3657   path = path_new (size);
3658   own_pos = 0;
3659   for (i = 0; i < size; i++)
3660   {
3661     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
3662                 GNUNET_i2s (&pi[i]));
3663     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
3664     if (path->peers[i] == myid)
3665       own_pos = i;
3666   }
3667   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
3668   if (own_pos == 0 && path->peers[own_pos] != myid)
3669   {
3670     /* create path: self not found in path through self */
3671     GNUNET_break_op (0);
3672     path_destroy (path);
3673     tunnel_destroy (t);
3674     return GNUNET_OK;
3675   }
3676   path_add_to_peers (path, GNUNET_NO);
3677   tunnel_use_path (t, path);
3678
3679   peer_info_add_tunnel (dest_peer_info, t);
3680
3681   if (own_pos == size - 1)
3682   {
3683     struct MeshClient *c;
3684
3685     /* Find target client */
3686     c = GNUNET_CONTAINER_multihashmap32_get (ports, t->port);
3687     if (NULL == c)
3688     {
3689       /* TODO send reject */
3690       return GNUNET_OK;
3691     }
3692
3693     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
3694     peer_info_add_path_to_origin (orig_peer_info, path, GNUNET_YES);
3695
3696     /* Assign local tid */
3697     while (NULL != tunnel_get_incoming (next_local_tid))
3698       next_local_tid = (next_local_tid + 1) | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
3699     t->local_tid_dest = next_local_tid++;
3700     next_local_tid = next_local_tid | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
3701
3702     if (GNUNET_YES == t->reliable)
3703     {
3704       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! Reliable\n");
3705       t->bck_rel = GNUNET_malloc (sizeof (struct MeshTunnelReliability));
3706       t->bck_rel->t = t;
3707       t->bck_rel->expected_delay = MESH_RETRANSMIT_TIME;
3708     }
3709
3710     tunnel_add_client (t, c);
3711     send_client_tunnel_create (t);
3712     send_path_ack (t);
3713   }
3714   else
3715   {
3716     struct MeshPeerPath *path2;
3717
3718     t->next_hop = path->peers[own_pos + 1];
3719     GNUNET_PEER_change_rc(t->next_hop, 1);
3720
3721     /* It's for somebody else! Retransmit. */
3722     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Retransmitting.\n");
3723     path2 = path_duplicate (path);
3724     peer_info_add_path (dest_peer_info, path2, GNUNET_NO);
3725     peer_info_add_path_to_origin (orig_peer_info, path, GNUNET_NO);
3726     send_create_path (t);
3727   }
3728   return GNUNET_OK;
3729 }
3730
3731
3732
3733 /**
3734  * Core handler for path ACKs
3735  *
3736  * @param cls closure
3737  * @param message message
3738  * @param peer peer identity this notification is about
3739  *
3740  * @return GNUNET_OK to keep the connection open,
3741  *         GNUNET_SYSERR to close it (signal serious error)
3742  */
3743 static int
3744 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
3745                       const struct GNUNET_MessageHeader *message)
3746 {
3747   struct GNUNET_MESH_PathACK *msg;
3748   struct MeshPeerInfo *peer_info;
3749   struct MeshPeerPath *p;
3750   struct MeshTunnel *t;
3751
3752   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a path ACK msg [%s]\n",
3753               GNUNET_i2s (&my_full_id));
3754   msg = (struct GNUNET_MESH_PathACK *) message;
3755   t = tunnel_get (&msg->oid, ntohl(msg->tid));
3756   if (NULL == t)
3757   {
3758     /* TODO notify that we don't know the tunnel */
3759     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel", 1, GNUNET_NO);
3760     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  don't know the tunnel %s [%X]!\n",
3761                 GNUNET_i2s (&msg->oid), ntohl(msg->tid));
3762     return GNUNET_OK;
3763   }
3764   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %s [%X]\n",
3765               GNUNET_i2s (&msg->oid), ntohl(msg->tid));
3766
3767   peer_info = peer_get (&msg->peer_id);
3768   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by peer %s\n",
3769               GNUNET_i2s (&msg->peer_id));
3770   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  via peer %s\n",
3771               GNUNET_i2s (peer));
3772
3773   /* Add path to peers? */
3774   p = t->path;
3775   if (NULL != p)
3776   {
3777     path_add_to_peers (p, GNUNET_YES);
3778   }
3779   else
3780   {
3781     GNUNET_break (0);
3782   }
3783   t->state = MESH_TUNNEL_READY;
3784   t->next_fc.last_ack_recv = (NULL == t->client) ? ntohl (msg->ack) : 0;
3785   t->prev_fc.last_ack_sent = ntohl (msg->ack);
3786
3787   /* Message for us? */
3788   if (0 == memcmp (&msg->oid, &my_full_id, sizeof (struct GNUNET_PeerIdentity)))
3789   {
3790     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
3791     if (NULL == t->owner)
3792     {
3793       GNUNET_break_op (0);
3794       return GNUNET_OK;
3795     }
3796     if (NULL != peer_info->dhtget)
3797     {
3798       GNUNET_DHT_get_stop (peer_info->dhtget);
3799       peer_info->dhtget = NULL;
3800     }
3801     tunnel_send_ack (t, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK, GNUNET_YES);
3802     tunnel_send_ack (t, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK, GNUNET_NO);
3803     return GNUNET_OK;
3804   }
3805
3806   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3807               "  not for us, retransmitting...\n");
3808   peer_info = peer_get (&msg->oid);
3809   send_prebuilt_message (message, t->prev_hop, t);
3810   return GNUNET_OK;
3811 }
3812
3813
3814 /**
3815  * Core handler for notifications of broken paths
3816  *
3817  * @param cls closure
3818  * @param message message
3819  * @param peer peer identity this notification is about
3820  *
3821  * @return GNUNET_OK to keep the connection open,
3822  *         GNUNET_SYSERR to close it (signal serious error)
3823  */
3824 static int
3825 handle_mesh_path_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
3826                          const struct GNUNET_MessageHeader *message)
3827 {
3828   struct GNUNET_MESH_PathBroken *msg;
3829   struct MeshTunnel *t;
3830
3831   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3832               "Received a PATH BROKEN msg from %s\n", GNUNET_i2s (peer));
3833   msg = (struct GNUNET_MESH_PathBroken *) message;
3834   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
3835               GNUNET_i2s (&msg->peer1));
3836   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
3837               GNUNET_i2s (&msg->peer2));
3838   t = tunnel_get (&msg->oid, ntohl (msg->tid));
3839   if (NULL == t)
3840   {
3841     GNUNET_break_op (0);
3842     return GNUNET_OK;
3843   }
3844   tunnel_notify_connection_broken (t, GNUNET_PEER_search (&msg->peer1),
3845                                    GNUNET_PEER_search (&msg->peer2));
3846   return GNUNET_OK;
3847
3848 }
3849
3850
3851 /**
3852  * Core handler for tunnel destruction
3853  *
3854  * @param cls closure
3855  * @param message message
3856  * @param peer peer identity this notification is about
3857  *
3858  * @return GNUNET_OK to keep the connection open,
3859  *         GNUNET_SYSERR to close it (signal serious error)
3860  */
3861 static int
3862 handle_mesh_tunnel_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
3863                             const struct GNUNET_MessageHeader *message)
3864 {
3865   struct GNUNET_MESH_TunnelDestroy *msg;
3866   struct MeshTunnel *t;
3867
3868   msg = (struct GNUNET_MESH_TunnelDestroy *) message;
3869   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3870               "Got a TUNNEL DESTROY packet from %s\n",
3871               GNUNET_i2s (peer));
3872   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3873               "  for tunnel %s [%u]\n",
3874               GNUNET_i2s (&msg->oid), ntohl (msg->tid));
3875   t = tunnel_get (&msg->oid, ntohl (msg->tid));
3876   if (NULL == t)
3877   {
3878     /* Probably already got the message from another path,
3879      * destroyed the tunnel and retransmitted to children.
3880      * Safe to ignore.
3881      */
3882     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel",
3883                               1, GNUNET_NO);
3884     return GNUNET_OK;
3885   }
3886   if (t->local_tid_dest >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
3887   {
3888     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "INCOMING TUNNEL %X %X\n",
3889                 t->local_tid, t->local_tid_dest);
3890   }
3891   if (GNUNET_PEER_search (peer) == t->prev_hop)
3892   {
3893     // TODO check owner's signature
3894     // TODO add owner's signatue to tunnel for retransmission
3895     peer_cancel_queues (t->prev_hop, t);
3896     GNUNET_PEER_change_rc (t->prev_hop, -1);
3897     t->prev_hop = 0;
3898   }
3899   else if (GNUNET_PEER_search (peer) == t->next_hop)
3900   {
3901     // TODO check dest's signature
3902     // TODO add dest's signatue to tunnel for retransmission
3903     peer_cancel_queues (t->next_hop, t);
3904     GNUNET_PEER_change_rc (t->next_hop, -1);
3905     t->next_hop = 0;
3906   }
3907   else
3908   {
3909     GNUNET_break_op (0);
3910     // TODO check both owner AND destination's signature to see which matches
3911     // TODO restransmit in appropriate direction
3912     return GNUNET_OK;
3913   }
3914   tunnel_destroy_empty (t);
3915
3916   // TODO: add timeout to destroy the tunnel anyway
3917   return GNUNET_OK;
3918 }
3919
3920
3921 /**
3922  * Generic handler for mesh network payload traffic.
3923  *
3924  * @param peer Peer identity this notification is about.
3925  * @param message Data message.
3926  * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
3927  *
3928  * @return GNUNET_OK to keep the connection open,
3929  *         GNUNET_SYSERR to close it (signal serious error)
3930  */
3931 static int
3932 handle_mesh_data (const struct GNUNET_PeerIdentity *peer,
3933                   const struct GNUNET_MessageHeader *message,
3934                   int fwd)
3935 {
3936   struct GNUNET_MESH_Data *msg;
3937   struct MeshFlowControl *fc;
3938   struct MeshTunnelReliability *rel;
3939   struct MeshTunnel *t;
3940   struct MeshClient *c;
3941   GNUNET_PEER_Id hop;
3942   uint32_t pid;
3943   uint32_t ttl;
3944   size_t size;
3945
3946   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a %s message from %s\n",
3947               GNUNET_MESH_DEBUG_M2S (ntohs (message->type)),
3948               GNUNET_i2s (peer));
3949   /* Check size */
3950   size = ntohs (message->size);
3951   if (size <
3952       sizeof (struct GNUNET_MESH_Data) +
3953       sizeof (struct GNUNET_MessageHeader))
3954   {
3955     GNUNET_break (0);
3956     return GNUNET_OK;
3957   }
3958   msg = (struct GNUNET_MESH_Data *) message;
3959   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
3960               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
3961   /* Check tunnel */
3962   t = tunnel_get (&msg->oid, ntohl (msg->tid));
3963   if (NULL == t)
3964   {
3965     /* TODO notify back: we don't know this tunnel */
3966     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
3967     GNUNET_break_op (0);
3968     return GNUNET_OK;
3969   }
3970
3971   /*  Initialize FWD/BCK data */
3972   pid = ntohl (msg->pid);
3973   fc =  fwd ? &t->prev_fc : &t->next_fc;
3974   c =   fwd ? t->client   : t->owner;
3975   rel = fwd ? t->bck_rel  : t->fwd_rel;
3976   hop = fwd ? t->next_hop : t->prev_hop;
3977   if (GMC_is_pid_bigger (pid, fc->last_ack_sent))
3978   {
3979     GNUNET_STATISTICS_update (stats, "# unsolicited data", 1, GNUNET_NO);
3980     GNUNET_break_op (0);
3981     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3982                 "Received PID %u, (prev %u), ACK %u\n",
3983                 pid, fc->last_pid_recv, fc->last_ack_sent);
3984     return GNUNET_OK;
3985   }
3986
3987   tunnel_reset_timeout (t, fwd);
3988   if (NULL != c)
3989   {
3990     /* TODO signature verification */
3991     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  it's for us! sending to client\n");
3992     GNUNET_STATISTICS_update (stats, "# data received", 1, GNUNET_NO);
3993     if (GMC_is_pid_bigger (pid, fc->last_pid_recv))
3994     {
3995       uint32_t mid;
3996
3997       mid = ntohl (msg->mid);
3998       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3999                   " pid %u (mid %u) not seen yet\n", pid, mid);
4000       fc->last_pid_recv = pid;
4001
4002       if (GNUNET_NO == t->reliable ||
4003           ( !GMC_is_pid_bigger (rel->mid_recv, mid) &&
4004             GMC_is_pid_bigger (rel->mid_recv + 64, mid) ) )
4005       {
4006         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4007                     "!!! RECV %u\n", ntohl (msg->mid));
4008         if (GNUNET_YES == t->reliable)
4009         {
4010           /* Is this the exact next expected messasge? */
4011           if (mid == rel->mid_recv)
4012           {
4013             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "as expected\n");
4014             rel->mid_recv++;
4015             tunnel_send_client_data (t, msg, fwd);
4016             tunnel_send_client_buffered_data (t, c, rel);
4017           }
4018           else
4019           {
4020             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "save for later\n");
4021             tunnel_add_buffered_data (t, msg, rel);
4022           }
4023         }
4024         else /* Tunnel unreliable, send to clients directly */
4025         {
4026           tunnel_send_client_data (t, msg, fwd);
4027         }
4028       }
4029       else
4030       {
4031         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4032                     " MID %u not expected (%u - %u), dropping!\n",
4033                     ntohl (msg->mid), rel->mid_recv, rel->mid_recv + 64);
4034       }
4035     }
4036     else
4037     {
4038 //       GNUNET_STATISTICS_update (stats, "# duplicate PID", 1, GNUNET_NO);
4039       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4040                   " Pid %u not expected (%u+), dropping!\n",
4041                   pid, fc->last_pid_recv + 1);
4042     }
4043     tunnel_send_ack (t, GNUNET_MESSAGE_TYPE_MESH_UNICAST, fwd);
4044     return GNUNET_OK;
4045   }
4046   fc->last_pid_recv = pid;
4047   if (0 == hop)
4048   {
4049     GNUNET_break (0);
4050     return GNUNET_OK;
4051   }
4052   ttl = ntohl (msg->ttl);
4053   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ttl);
4054   if (ttl == 0)
4055   {
4056     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
4057     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
4058     tunnel_send_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK, fwd);
4059     return GNUNET_OK;
4060   }
4061
4062   if (myid != hop)
4063   {
4064     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  not for us, retransmitting...\n");
4065     send_prebuilt_message (message, hop, t);
4066     GNUNET_STATISTICS_update (stats, "# unicast forwarded", 1, GNUNET_NO);
4067   }
4068   return GNUNET_OK;
4069 }
4070
4071
4072 /**
4073  * Core handler for mesh network traffic going from the origin to a peer
4074  *
4075  * @param cls Closure (unused).
4076  * @param message Message received.
4077  * @param peer Peer who sent the message.
4078  *
4079  * @return GNUNET_OK to keep the connection open,
4080  *         GNUNET_SYSERR to close it (signal serious error)
4081  */
4082 static int
4083 handle_mesh_unicast (void *cls, const struct GNUNET_PeerIdentity *peer,
4084                      const struct GNUNET_MessageHeader *message)
4085 {
4086   return handle_mesh_data (peer, message, GNUNET_YES);
4087 }
4088
4089 /**
4090  * Core handler for mesh network traffic towards the owner of a tunnel.
4091  *
4092  * @param cls Closure (unused).
4093  * @param message Message received.
4094  * @param peer Peer who sent the message.
4095  *
4096  * @return GNUNET_OK to keep the connection open,
4097  *         GNUNET_SYSERR to close it (signal serious error)
4098  */
4099 static int
4100 handle_mesh_to_orig (void *cls, const struct GNUNET_PeerIdentity *peer,
4101                      const struct GNUNET_MessageHeader *message)
4102 {
4103   return handle_mesh_data (peer, message, GNUNET_NO);
4104 }
4105
4106
4107 /**
4108  * Core handler for mesh network traffic end-to-end ACKs.
4109  *
4110  * @param cls Closure.
4111  * @param message Message.
4112  * @param peer Peer identity this notification is about.
4113  *
4114  * @return GNUNET_OK to keep the connection open,
4115  *         GNUNET_SYSERR to close it (signal serious error)
4116  */
4117 static int
4118 handle_mesh_data_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
4119                       const struct GNUNET_MessageHeader *message)
4120 {
4121   struct GNUNET_MESH_DataACK *msg;
4122   struct MeshTunnelReliability *rel;
4123   struct MeshReliableMessage *copy;
4124   struct MeshReliableMessage *next;
4125   struct MeshTunnel *t;
4126   GNUNET_PEER_Id id;
4127   uint32_t ack;
4128   uint16_t type;
4129   int work;
4130
4131   type = ntohs (message->type);
4132   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a %s message from %s!\n",
4133               GNUNET_MESH_DEBUG_M2S (type), GNUNET_i2s (peer));
4134   msg = (struct GNUNET_MESH_DataACK *) message;
4135
4136   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4137   if (NULL == t)
4138   {
4139     /* TODO notify that we dont know this tunnel (whom)? */
4140     GNUNET_STATISTICS_update (stats, "# ack on unknown tunnel", 1, GNUNET_NO);
4141     return GNUNET_OK;
4142   }
4143   ack = ntohl (msg->mid);
4144   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ACK %u\n", ack);
4145
4146   /* Is this a forward or backward ACK? */
4147   id = GNUNET_PEER_search (peer);
4148   if (t->next_hop == id && GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK == type)
4149   {
4150     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
4151     if (NULL == t->owner)
4152     {
4153       send_prebuilt_message (message, t->prev_hop, t);
4154       return GNUNET_OK;
4155     }
4156     rel = t->fwd_rel;
4157   }
4158   else if (t->prev_hop == id && GNUNET_MESSAGE_TYPE_MESH_TO_ORIG_ACK == type)
4159   {
4160     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
4161     if (NULL == t->client)
4162     {
4163       send_prebuilt_message (message, t->next_hop, t);
4164       return GNUNET_OK;
4165     }
4166     rel = t->bck_rel;
4167   }
4168   else
4169   {
4170     GNUNET_break_op (0);
4171     return GNUNET_OK;
4172   }
4173
4174   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! ACK %u\n", ack);
4175   for (work = GNUNET_NO, copy = rel->head_sent; copy != NULL; copy = next)
4176   {
4177    if (GMC_is_pid_bigger (copy->mid, ack))
4178     {
4179       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!!  head %u, out!\n", copy->mid);
4180       tunnel_free_sent_reliable (t, msg, rel);
4181       break;
4182     }
4183     work = GNUNET_YES;
4184     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!!  id %u\n", copy->mid);
4185     next = copy->next;
4186     tunnel_free_reliable_message (copy);
4187   }
4188   /* Once buffers have been free'd, send ACK */
4189   tunnel_send_ack (t, type, GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK == type);
4190
4191   /* If some message was free'd, update the retransmission delay*/
4192   if (GNUNET_YES == work)
4193   {
4194     if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
4195     {
4196       GNUNET_SCHEDULER_cancel (rel->retry_task);
4197       if (NULL == rel->head_sent)
4198       {
4199         rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
4200       }
4201       else
4202       {
4203         struct GNUNET_TIME_Absolute new_target;
4204         struct GNUNET_TIME_Relative delay;
4205
4206         delay = GNUNET_TIME_relative_multiply (rel->retry_timer,
4207                                                MESH_RETRANSMIT_MARGIN);
4208         new_target = GNUNET_TIME_absolute_add (rel->head_sent->timestamp,
4209                                                delay);
4210         delay = GNUNET_TIME_absolute_get_remaining (new_target);
4211         rel->retry_task =
4212             GNUNET_SCHEDULER_add_delayed (delay,
4213                                           &tunnel_retransmit_message,
4214                                           rel);
4215       }
4216     }
4217     else
4218       GNUNET_break (0);
4219   }
4220   return GNUNET_OK;
4221 }
4222
4223 /**
4224  * Core handler for mesh network traffic point-to-point acks.
4225  *
4226  * @param cls closure
4227  * @param message message
4228  * @param peer peer identity this notification is about
4229  *
4230  * @return GNUNET_OK to keep the connection open,
4231  *         GNUNET_SYSERR to close it (signal serious error)
4232  */
4233 static int
4234 handle_mesh_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
4235                  const struct GNUNET_MessageHeader *message)
4236 {
4237   struct GNUNET_MESH_ACK *msg;
4238   struct MeshTunnel *t;
4239   struct MeshFlowControl *fc;
4240   GNUNET_PEER_Id id;
4241   uint32_t ack;
4242
4243   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK packet from %s!\n",
4244               GNUNET_i2s (peer));
4245   msg = (struct GNUNET_MESH_ACK *) message;
4246
4247   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4248
4249   if (NULL == t)
4250   {
4251     /* TODO notify that we dont know this tunnel (whom)? */
4252     GNUNET_STATISTICS_update (stats, "# ack on unknown tunnel", 1, GNUNET_NO);
4253     return GNUNET_OK;
4254   }
4255   ack = ntohl (msg->pid);
4256   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ACK %u\n", ack);
4257
4258   /* Is this a forward or backward ACK? */
4259   id = GNUNET_PEER_search (peer);
4260   if (t->next_hop == id)
4261   {
4262     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
4263     fc = &t->next_fc;
4264   }
4265   else if (t->prev_hop == id)
4266   {
4267     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
4268     fc = &t->prev_fc;
4269   }
4270   else
4271   {
4272     GNUNET_break_op (0);
4273     return GNUNET_OK;
4274   }
4275
4276   if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task &&
4277       GMC_is_pid_bigger (ack, fc->last_ack_recv))
4278   {
4279     GNUNET_SCHEDULER_cancel (fc->poll_task);
4280     fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
4281     fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
4282   }
4283   fc->last_ack_recv = ack;
4284   peer_unlock_queue (id);
4285
4286   tunnel_send_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK, t->next_hop == id);
4287
4288   return GNUNET_OK;
4289 }
4290
4291
4292 /**
4293  * Core handler for mesh network traffic point-to-point ack polls.
4294  *
4295  * @param cls closure
4296  * @param message message
4297  * @param peer peer identity this notification is about
4298  *
4299  * @return GNUNET_OK to keep the connection open,
4300  *         GNUNET_SYSERR to close it (signal serious error)
4301  */
4302 static int
4303 handle_mesh_poll (void *cls, const struct GNUNET_PeerIdentity *peer,
4304                   const struct GNUNET_MessageHeader *message)
4305 {
4306   struct GNUNET_MESH_Poll *msg;
4307   struct MeshTunnel *t;
4308   struct MeshFlowControl *fc;
4309   GNUNET_PEER_Id id;
4310   uint32_t pid;
4311   uint32_t old;
4312
4313   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an POLL packet from %s!\n",
4314               GNUNET_i2s (peer));
4315
4316   msg = (struct GNUNET_MESH_Poll *) message;
4317
4318   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4319
4320   if (NULL == t)
4321   {
4322     /* TODO notify that we dont know this tunnel (whom)? */
4323     GNUNET_STATISTICS_update (stats, "# poll on unknown tunnel", 1, GNUNET_NO);
4324     GNUNET_break_op (0);
4325     return GNUNET_OK;
4326   }
4327
4328   /* Is this a forward or backward ACK? */
4329   id = GNUNET_PEER_search(peer);
4330   pid = ntohl (msg->pid);
4331   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  PID %u\n", pid);
4332   if (t->next_hop == id)
4333   {
4334     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  from FWD\n");
4335     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  was %u\n", t->next_fc.last_pid_recv);
4336     fc = &t->next_fc;
4337     old = fc->last_pid_recv;
4338     fc->last_pid_recv = pid;
4339     tunnel_send_ack (t, GNUNET_MESSAGE_TYPE_MESH_POLL, GNUNET_NO);
4340   }
4341   else if (t->prev_hop == id)
4342   {
4343     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  from BCK\n");
4344     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  was %u\n", t->prev_fc.last_pid_recv);
4345     fc = &t->prev_fc;
4346     old = fc->last_pid_recv;
4347     fc->last_pid_recv = pid;
4348     tunnel_send_ack (t, GNUNET_MESSAGE_TYPE_MESH_POLL, GNUNET_YES);
4349   }
4350   else
4351     GNUNET_break (0);
4352
4353   if (GNUNET_YES == t->reliable)
4354     fc->last_pid_recv = old;
4355
4356   return GNUNET_OK;
4357 }
4358
4359
4360 /**
4361  * Core handler for mesh keepalives.
4362  *
4363  * @param cls closure
4364  * @param message message
4365  * @param peer peer identity this notification is about
4366  * @return GNUNET_OK to keep the connection open,
4367  *         GNUNET_SYSERR to close it (signal serious error)
4368  *
4369  * TODO: Check who we got this from, to validate route.
4370  */
4371 static int
4372 handle_mesh_keepalive (void *cls, const struct GNUNET_PeerIdentity *peer,
4373                        const struct GNUNET_MessageHeader *message)
4374 {
4375   struct GNUNET_MESH_TunnelKeepAlive *msg;
4376   struct MeshTunnel *t;
4377
4378   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a keepalive packet from %s\n",
4379               GNUNET_i2s (peer));
4380
4381   msg = (struct GNUNET_MESH_TunnelKeepAlive *) message;
4382   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4383
4384   if (NULL == t)
4385   {
4386     /* TODO notify that we dont know that tunnel */
4387     GNUNET_STATISTICS_update (stats, "# keepalive on unknown tunnel", 1,
4388                               GNUNET_NO);
4389     return GNUNET_OK;
4390   }
4391
4392   tunnel_reset_timeout (t, GNUNET_YES); // FIXME
4393   if (NULL != t->client || 0 == t->next_hop || myid == t->next_hop)
4394     return GNUNET_OK;
4395
4396   GNUNET_STATISTICS_update (stats, "# keepalives forwarded", 1, GNUNET_NO);
4397   send_prebuilt_message (message, t->next_hop, t);
4398   return GNUNET_OK;
4399   }
4400
4401
4402
4403 /**
4404  * Functions to handle messages from core
4405  */
4406 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
4407   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
4408   {&handle_mesh_path_broken, GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN,
4409    sizeof (struct GNUNET_MESH_PathBroken)},
4410   {&handle_mesh_tunnel_destroy, GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY,
4411    sizeof (struct GNUNET_MESH_TunnelDestroy)},
4412   {&handle_mesh_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
4413   {&handle_mesh_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
4414   {&handle_mesh_data_ack, GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK,
4415     sizeof (struct GNUNET_MESH_DataACK)},
4416   {&handle_mesh_data_ack, GNUNET_MESSAGE_TYPE_MESH_TO_ORIG_ACK,
4417     sizeof (struct GNUNET_MESH_DataACK)},
4418   {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE,
4419     sizeof (struct GNUNET_MESH_TunnelKeepAlive)},
4420   {&handle_mesh_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
4421     sizeof (struct GNUNET_MESH_ACK)},
4422   {&handle_mesh_poll, GNUNET_MESSAGE_TYPE_MESH_POLL,
4423     sizeof (struct GNUNET_MESH_Poll)},
4424   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
4425    sizeof (struct GNUNET_MESH_PathACK)},
4426   {NULL, 0, 0}
4427 };
4428
4429
4430
4431 /******************************************************************************/
4432 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
4433 /******************************************************************************/
4434
4435
4436 #if LATER
4437 /**
4438  * notify_client_connection_failure: notify a client that the connection to the
4439  * requested remote peer is not possible (for instance, no route found)
4440  * Function called when the socket is ready to queue more data. "buf" will be
4441  * NULL and "size" zero if the socket was closed for writing in the meantime.
4442  *
4443  * @param cls closure
4444  * @param size number of bytes available in buf
4445  * @param buf where the callee should write the message
4446  * @return number of bytes written to buf
4447  */
4448 static size_t
4449 notify_client_connection_failure (void *cls, size_t size, void *buf)
4450 {
4451   int size_needed;
4452   struct MeshPeerInfo *peer_info;
4453   struct GNUNET_MESH_PeerControl *msg;
4454   struct GNUNET_PeerIdentity id;
4455
4456   if (0 == size && NULL == buf)
4457   {
4458     // TODO retry? cancel?
4459     return 0;
4460   }
4461
4462   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
4463   peer_info = (struct MeshPeerInfo *) cls;
4464   msg = (struct GNUNET_MESH_PeerControl *) buf;
4465   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
4466   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
4467 //     msg->tunnel_id = htonl(peer_info->t->tid);
4468   GNUNET_PEER_resolve (peer_info->id, &id);
4469   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
4470
4471   return size_needed;
4472 }
4473 #endif
4474
4475
4476 /**
4477  * Send keepalive packets for a tunnel.
4478  *
4479  * @param cls Closure (tunnel for which to send the keepalive).
4480  * @param tc Notification context.
4481  * 
4482  * FIXME: add a refresh reset in case of normal unicast traffic is doing the job
4483  */
4484 static void
4485 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4486 {
4487   struct MeshTunnel *t = cls;
4488   struct GNUNET_MESH_TunnelKeepAlive *msg;
4489   size_t size = sizeof (struct GNUNET_MESH_TunnelKeepAlive);
4490   char cbuf[size];
4491
4492   t->maintenance_task = GNUNET_SCHEDULER_NO_TASK;
4493   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) ||
4494       NULL == t->owner || 0 == t->local_tid)
4495   {
4496     return;
4497   }
4498
4499   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4500               "sending keepalive for tunnel %d\n", t->id.tid);
4501
4502   msg = (struct GNUNET_MESH_TunnelKeepAlive *) cbuf;
4503   msg->header.size = htons (size);
4504   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE);
4505   msg->oid = my_full_id;
4506   msg->tid = htonl (t->id.tid);
4507   send_prebuilt_message (&msg->header, t->next_hop, t);
4508
4509   t->maintenance_task =
4510       GNUNET_SCHEDULER_add_delayed (refresh_path_time, &path_refresh, t);
4511 }
4512
4513
4514 /**
4515  * Function to process paths received for a new peer addition. The recorded
4516  * paths form the initial tunnel, which can be optimized later.
4517  * Called on each result obtained for the DHT search.
4518  *
4519  * @param cls closure
4520  * @param exp when will this value expire
4521  * @param key key of the result
4522  * @param get_path path of the get request
4523  * @param get_path_length lenght of get_path
4524  * @param put_path path of the put request
4525  * @param put_path_length length of the put_path
4526  * @param type type of the result
4527  * @param size number of bytes in data
4528  * @param data pointer to the result data
4529  */
4530 static void
4531 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
4532                     const struct GNUNET_HashCode * key,
4533                     const struct GNUNET_PeerIdentity *get_path,
4534                     unsigned int get_path_length,
4535                     const struct GNUNET_PeerIdentity *put_path,
4536                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
4537                     size_t size, const void *data)
4538 {
4539   struct MeshPeerInfo *peer = cls;
4540   struct MeshPeerPath *p;
4541   struct GNUNET_PeerIdentity pi;
4542   int i;
4543
4544   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
4545   GNUNET_PEER_resolve (peer->id, &pi);
4546   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", GNUNET_i2s (&pi));
4547
4548   p = path_build_from_dht (get_path, get_path_length,
4549                            put_path, put_path_length);
4550   path_add_to_peers (p, GNUNET_NO);
4551   path_destroy (p);
4552   for (i = 0; i < peer->ntunnels; i++)
4553   {
4554     struct GNUNET_PeerIdentity id;
4555
4556     GNUNET_PEER_resolve (peer->tunnels[i]->id.oid, &id);
4557     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ... tunnel %s:%X (%X / %X)\n",
4558                 GNUNET_i2s (&id), peer->tunnels[i]->id.tid,
4559                 peer->tunnels[i]->local_tid, 
4560                 peer->tunnels[i]->local_tid_dest);
4561     if (peer->tunnels[i]->state == MESH_TUNNEL_SEARCHING)
4562     {
4563       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ... connect!\n");
4564       peer_connect (peer, peer->tunnels[i]);
4565     }
4566   }
4567
4568   return;
4569 }
4570
4571
4572 /******************************************************************************/
4573 /*********************       MESH LOCAL HANDLES      **************************/
4574 /******************************************************************************/
4575
4576
4577 /**
4578  * Handler for client connection.
4579  *
4580  * @param cls Closure (unused).
4581  * @param client Client handler.
4582  */
4583 static void
4584 handle_local_client_connect (void *cls, struct GNUNET_SERVER_Client *client)
4585 {
4586   struct MeshClient *c;
4587
4588   if (NULL == client)
4589     return;
4590   c = GNUNET_malloc (sizeof (struct MeshClient));
4591   c->handle = client;
4592   GNUNET_SERVER_client_keep (client);
4593   GNUNET_SERVER_client_set_user_context (client, c);
4594   GNUNET_CONTAINER_DLL_insert (clients_head, clients_tail, c);
4595 }
4596
4597
4598 /**
4599  * Handler for client disconnection
4600  *
4601  * @param cls closure
4602  * @param client identification of the client; NULL
4603  *        for the last call when the server is destroyed
4604  */
4605 static void
4606 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
4607 {
4608   struct MeshClient *c;
4609   struct MeshClient *next;
4610
4611   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected: %p\n", client);
4612   if (client == NULL)
4613   {
4614     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (SERVER DOWN)\n");
4615     return;
4616   }
4617
4618   c = client_get (client);
4619   if (NULL != c)
4620   {
4621     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u)\n",
4622                 c->id);
4623     GNUNET_SERVER_client_drop (c->handle);
4624     c->shutting_down = GNUNET_YES;
4625     if (NULL != c->own_tunnels)
4626     {
4627       GNUNET_CONTAINER_multihashmap32_iterate (c->own_tunnels,
4628                                                &tunnel_destroy_iterator, c);
4629       GNUNET_CONTAINER_multihashmap32_destroy (c->own_tunnels);
4630     }
4631
4632     if (NULL != c->incoming_tunnels)
4633     {
4634       GNUNET_CONTAINER_multihashmap32_iterate (c->incoming_tunnels,
4635                                              &tunnel_destroy_iterator, c);
4636       GNUNET_CONTAINER_multihashmap32_destroy (c->incoming_tunnels);
4637     }
4638
4639     if (NULL != c->ports)
4640       GNUNET_CONTAINER_multihashmap32_destroy (c->ports);
4641     next = c->next;
4642     GNUNET_CONTAINER_DLL_remove (clients_head, clients_tail, c);
4643     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT FREE at %p\n", c);
4644     GNUNET_free (c);
4645     GNUNET_STATISTICS_update (stats, "# clients", -1, GNUNET_NO);
4646     c = next;
4647   }
4648   else
4649   {
4650     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " context NULL!\n");
4651   }
4652   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "done!\n");
4653   return;
4654 }
4655
4656
4657 /**
4658  * Handler for new clients
4659  *
4660  * @param cls closure
4661  * @param client identification of the client
4662  * @param message the actual message, which includes messages the client wants
4663  */
4664 static void
4665 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
4666                          const struct GNUNET_MessageHeader *message)
4667 {
4668   struct GNUNET_MESH_ClientConnect *cc_msg;
4669   struct MeshClient *c;
4670   unsigned int size;
4671   uint32_t *p;
4672   unsigned int i;
4673
4674   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected %p\n", client);
4675
4676   /* Check data sanity */
4677   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
4678   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
4679   if (0 != (size % sizeof (uint32_t)))
4680   {
4681     GNUNET_break (0);
4682     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4683     return;
4684   }
4685   size /= sizeof (uint32_t);
4686
4687   /* Initialize new client structure */
4688   c = GNUNET_SERVER_client_get_user_context (client, struct MeshClient);
4689   c->id = next_client_id++; /* overflow not important: just for debug */
4690   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  client id %u\n", c->id);
4691   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  client has %u ports\n", size);
4692   if (size > 0)
4693   {
4694     uint32_t u32;
4695
4696     p = (uint32_t *) &cc_msg[1];
4697     c->ports = GNUNET_CONTAINER_multihashmap32_create (size);
4698     for (i = 0; i < size; i++)
4699     {
4700       u32 = ntohl (p[i]);
4701       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    port: %u\n", u32);
4702
4703       /* store in client's hashmap */
4704       GNUNET_CONTAINER_multihashmap32_put (c->ports, u32, c,
4705                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
4706       /* store in global hashmap */
4707       /* FIXME only allow one client to have the port open,
4708        *       have a backup hashmap with waiting clients */
4709       GNUNET_CONTAINER_multihashmap32_put (ports, u32, c,
4710                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
4711     }
4712   }
4713
4714   c->own_tunnels = GNUNET_CONTAINER_multihashmap32_create (32);
4715   c->incoming_tunnels = GNUNET_CONTAINER_multihashmap32_create (32);
4716   GNUNET_SERVER_notification_context_add (nc, client);
4717   GNUNET_STATISTICS_update (stats, "# clients", 1, GNUNET_NO);
4718
4719   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4720   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
4721 }
4722
4723
4724 /**
4725  * Handler for requests of new tunnels
4726  *
4727  * @param cls Closure.
4728  * @param client Identification of the client.
4729  * @param message The actual message.
4730  */
4731 static void
4732 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
4733                             const struct GNUNET_MessageHeader *message)
4734 {
4735   struct GNUNET_MESH_TunnelMessage *t_msg;
4736   struct MeshPeerInfo *peer_info;
4737   struct MeshTunnel *t;
4738   struct MeshClient *c;
4739   MESH_TunnelNumber tid;
4740
4741   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel requested\n");
4742
4743   /* Sanity check for client registration */
4744   if (NULL == (c = client_get (client)))
4745   {
4746     GNUNET_break (0);
4747     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4748     return;
4749   }
4750   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
4751
4752   /* Message size sanity check */
4753   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
4754   {
4755     GNUNET_break (0);
4756     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4757     return;
4758   }
4759
4760   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
4761   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  towards %s\n",
4762               GNUNET_i2s (&t_msg->peer));
4763   /* Sanity check for tunnel numbering */
4764   tid = ntohl (t_msg->tunnel_id);
4765   if (0 == (tid & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
4766   {
4767     GNUNET_break (0);
4768     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4769     return;
4770   }
4771   /* Sanity check for duplicate tunnel IDs */
4772   if (NULL != tunnel_get_by_local_id (c, tid))
4773   {
4774     GNUNET_break (0);
4775     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4776     return;
4777   }
4778
4779   /* Create tunnel */
4780   while (NULL != tunnel_get_by_pi (myid, next_tid))
4781     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
4782   t = tunnel_new (myid, next_tid, c, tid);
4783   next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
4784   if (NULL == t)
4785   {
4786     GNUNET_break (0);
4787     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4788     return;
4789   }
4790   t->port = ntohl (t_msg->port);
4791   tunnel_set_options (t, ntohl (t_msg->opt));
4792   if (GNUNET_YES == t->reliable)
4793   {
4794     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! Reliable\n");
4795     t->fwd_rel = GNUNET_malloc (sizeof (struct MeshTunnelReliability));
4796     t->fwd_rel->t = t;
4797     t->fwd_rel->expected_delay = MESH_RETRANSMIT_TIME;
4798   }
4799
4800   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED TUNNEL %s[%x]:%u (%x)\n",
4801               GNUNET_i2s (&my_full_id), t->id.tid, t->port, t->local_tid);
4802
4803   peer_info = peer_get (&t_msg->peer);
4804   peer_info_add_tunnel (peer_info, t);
4805   peer_connect (peer_info, t);
4806   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4807   return;
4808 }
4809
4810
4811 /**
4812  * Handler for requests of deleting tunnels
4813  *
4814  * @param cls closure
4815  * @param client identification of the client
4816  * @param message the actual message
4817  */
4818 static void
4819 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
4820                              const struct GNUNET_MessageHeader *message)
4821 {
4822   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
4823   struct MeshClient *c;
4824   struct MeshTunnel *t;
4825   MESH_TunnelNumber tid;
4826
4827   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4828               "Got a DESTROY TUNNEL from client!\n");
4829
4830   /* Sanity check for client registration */
4831   if (NULL == (c = client_get (client)))
4832   {
4833     GNUNET_break (0);
4834     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4835     return;
4836   }
4837   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
4838
4839   /* Message sanity check */
4840   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
4841   {
4842     GNUNET_break (0);
4843     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4844     return;
4845   }
4846
4847   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
4848
4849   /* Retrieve tunnel */
4850   tid = ntohl (tunnel_msg->tunnel_id);
4851   t = tunnel_get_by_local_id(c, tid);
4852   if (NULL == t)
4853   {
4854     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
4855     GNUNET_break (0);
4856     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4857     return;
4858   }
4859
4860   /* Cleanup after the tunnel */
4861   client_delete_tunnel (c, t);
4862   if (c == t->client)
4863   {
4864     t->client = NULL;
4865   }
4866   if (c == t->owner)
4867   {
4868     peer_info_remove_tunnel (peer_get_short (t->dest), t);
4869     t->owner = NULL;
4870   }
4871
4872   /* The tunnel will be destroyed when the last message is transmitted. */
4873   tunnel_destroy_empty (t);
4874
4875   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4876   return;
4877 }
4878
4879
4880 /**
4881  * Handler for client traffic
4882  *
4883  * @param cls closure
4884  * @param client identification of the client
4885  * @param message the actual message
4886  */
4887 static void
4888 handle_local_data (void *cls, struct GNUNET_SERVER_Client *client,
4889                    const struct GNUNET_MessageHeader *message)
4890 {
4891   struct GNUNET_MESH_LocalData *data_msg;
4892   struct MeshClient *c;
4893   struct MeshTunnel *t;
4894   struct MeshFlowControl *fc;
4895   MESH_TunnelNumber tid;
4896   size_t size;
4897
4898   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4899               "Got data from a client!\n");
4900
4901   /* Sanity check for client registration */
4902   if (NULL == (c = client_get (client)))
4903   {
4904     GNUNET_break (0);
4905     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4906     return;
4907   }
4908   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
4909
4910   data_msg = (struct GNUNET_MESH_LocalData *) message;
4911
4912   /* Sanity check for message size */
4913   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_LocalData);
4914   if (size < sizeof (struct GNUNET_MessageHeader))
4915   {
4916     GNUNET_break (0);
4917     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4918     return;
4919   }
4920
4921   /* Tunnel exists? */
4922   tid = ntohl (data_msg->tid);
4923   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_CLI)
4924   {
4925     GNUNET_break (0);
4926     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4927     return;
4928   }
4929   t = tunnel_get_by_local_id (c, tid);
4930   if (NULL == t)
4931   {
4932     GNUNET_break (0);
4933     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4934     return;
4935   }
4936
4937   /* Is the client in the tunnel? */
4938   if ( !( (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV &&
4939            t->owner &&
4940            t->owner->handle == client)
4941          ||
4942           (tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV &&
4943            t->client && 
4944            t->client->handle == client) ) )
4945   {
4946     GNUNET_break (0);
4947     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4948     return;
4949   }
4950
4951   /* Ok, everything is correct, send the message
4952    * (pretend we got it from a mesh peer)
4953    */
4954   {
4955     struct GNUNET_MESH_Data *payload;
4956     char cbuf[sizeof(struct GNUNET_MESH_Data) + size];
4957
4958     fc = tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV ? &t->prev_fc : &t->next_fc;
4959     if (GNUNET_YES == t->reliable)
4960     {
4961       struct MeshTunnelReliability *rel;
4962       struct MeshReliableMessage *copy;
4963
4964       rel = (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV) ? t->fwd_rel : t->bck_rel;
4965       copy = GNUNET_malloc (sizeof (struct MeshReliableMessage)
4966                             + sizeof(struct GNUNET_MESH_Data)
4967                             + size);
4968       copy->mid = rel->mid_sent++;
4969       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! DATA %u\n", copy->mid);
4970       copy->timestamp = GNUNET_TIME_absolute_get ();
4971       copy->rel = rel;
4972       rel->n_sent++;
4973       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " n_sent %u\n", rel->n_sent);
4974       GNUNET_CONTAINER_DLL_insert_tail (rel->head_sent, rel->tail_sent, copy);
4975       if (GNUNET_SCHEDULER_NO_TASK == rel->retry_task)
4976       {
4977         rel->retry_timer =
4978             GNUNET_TIME_relative_multiply (rel->expected_delay,
4979                                            MESH_RETRANSMIT_MARGIN);
4980         rel->retry_task =
4981             GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
4982                                           &tunnel_retransmit_message,
4983                                           rel);
4984       }
4985       payload = (struct GNUNET_MESH_Data *) &copy[1];
4986       payload->mid = htonl (copy->mid);
4987     }
4988     else
4989     {
4990       payload = (struct GNUNET_MESH_Data *) cbuf;
4991       payload->mid = htonl (fc->last_pid_recv + 1);
4992     }
4993     memcpy (&payload[1], &data_msg[1], size);
4994     payload->header.size = htons (sizeof (struct GNUNET_MESH_Data) + size);
4995     payload->header.type = htons (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV ?
4996                                   GNUNET_MESSAGE_TYPE_MESH_UNICAST :
4997                                   GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
4998     GNUNET_PEER_resolve(t->id.oid, &payload->oid);;
4999     payload->tid = htonl (t->id.tid);
5000     payload->ttl = htonl (default_ttl);
5001     payload->pid = htonl (fc->last_pid_recv + 1);
5002     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5003                 "  calling generic handler...\n");
5004     if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
5005       handle_mesh_unicast (NULL, &my_full_id, &payload->header);
5006     else
5007       handle_mesh_to_orig (NULL, &my_full_id, &payload->header);
5008   }
5009   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "receive done OK\n");
5010   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5011
5012   return;
5013 }
5014
5015
5016 /**
5017  * Handler for client's ACKs for payload traffic.
5018  *
5019  * @param cls Closure (unused).
5020  * @param client Identification of the client.
5021  * @param message The actual message.
5022  */
5023 static void
5024 handle_local_ack (void *cls, struct GNUNET_SERVER_Client *client,
5025                   const struct GNUNET_MessageHeader *message)
5026 {
5027   struct GNUNET_MESH_LocalAck *msg;
5028   struct MeshTunnel *t;
5029   struct MeshClient *c;
5030   MESH_TunnelNumber tid;
5031
5032   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a local ACK\n");
5033   /* Sanity check for client registration */
5034   if (NULL == (c = client_get (client)))
5035   {
5036     GNUNET_break (0);
5037     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5038     return;
5039   }
5040   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
5041
5042   msg = (struct GNUNET_MESH_LocalAck *) message;
5043
5044   /* Tunnel exists? */
5045   tid = ntohl (msg->tunnel_id);
5046   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
5047   t = tunnel_get_by_local_id (c, tid);
5048   if (NULL == t)
5049   {
5050     GNUNET_break (0);
5051     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
5052     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
5053     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5054     return;
5055   }
5056
5057   /* Does client own tunnel? I.E: Is this an ACK for BCK traffic? */
5058   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
5059   {
5060     /* The client owns the tunnel, ACK is for data to_origin, send BCK ACK. */
5061     t->prev_fc.last_ack_recv++;
5062     tunnel_send_ack (t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK, GNUNET_NO);
5063   }
5064   else
5065   {
5066     /* The client doesn't own the tunnel, this ACK is for FWD traffic. */
5067     t->next_fc.last_ack_recv++;
5068     tunnel_send_ack (t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK, GNUNET_YES);
5069   }
5070
5071   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5072
5073   return;
5074 }
5075
5076
5077
5078 /**
5079  * Iterator over all tunnels to send a monitoring client info about each tunnel.
5080  *
5081  * @param cls Closure (client handle).
5082  * @param key Key (hashed tunnel ID, unused).
5083  * @param value Tunnel info.
5084  *
5085  * @return GNUNET_YES, to keep iterating.
5086  */
5087 static int
5088 monitor_all_tunnels_iterator (void *cls,
5089                               const struct GNUNET_HashCode * key,
5090                               void *value)
5091 {
5092   struct GNUNET_SERVER_Client *client = cls;
5093   struct MeshTunnel *t = value;
5094   struct GNUNET_MESH_LocalMonitor *msg;
5095
5096   msg = GNUNET_malloc (sizeof(struct GNUNET_MESH_LocalMonitor));
5097   GNUNET_PEER_resolve(t->id.oid, &msg->owner);
5098   msg->tunnel_id = htonl (t->id.tid);
5099   msg->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
5100   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS);
5101   GNUNET_PEER_resolve (t->dest, &msg->destination);
5102
5103   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5104               "*  sending info about tunnel %s [%u]\n",
5105               GNUNET_i2s (&msg->owner), t->id.tid);
5106
5107   GNUNET_SERVER_notification_context_unicast (nc, client,
5108                                               &msg->header, GNUNET_NO);
5109   return GNUNET_YES;
5110 }
5111
5112
5113 /**
5114  * Handler for client's MONITOR request.
5115  *
5116  * @param cls Closure (unused).
5117  * @param client Identification of the client.
5118  * @param message The actual message.
5119  */
5120 static void
5121 handle_local_get_tunnels (void *cls, struct GNUNET_SERVER_Client *client,
5122                           const struct GNUNET_MessageHeader *message)
5123 {
5124   struct MeshClient *c;
5125
5126   /* Sanity check for client registration */
5127   if (NULL == (c = client_get (client)))
5128   {
5129     GNUNET_break (0);
5130     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5131     return;
5132   }
5133
5134   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5135               "Received get tunnels request from client %u\n",
5136               c->id);
5137   GNUNET_CONTAINER_multihashmap_iterate (tunnels,
5138                                          monitor_all_tunnels_iterator,
5139                                          client);
5140   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5141               "Get tunnels request from client %u completed\n",
5142               c->id);
5143   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5144 }
5145
5146
5147 /**
5148  * Handler for client's MONITOR_TUNNEL request.
5149  *
5150  * @param cls Closure (unused).
5151  * @param client Identification of the client.
5152  * @param message The actual message.
5153  */
5154 static void
5155 handle_local_show_tunnel (void *cls, struct GNUNET_SERVER_Client *client,
5156                           const struct GNUNET_MessageHeader *message)
5157 {
5158   const struct GNUNET_MESH_LocalMonitor *msg;
5159   struct GNUNET_MESH_LocalMonitor *resp;
5160   struct MeshClient *c;
5161   struct MeshTunnel *t;
5162
5163   /* Sanity check for client registration */
5164   if (NULL == (c = client_get (client)))
5165   {
5166     GNUNET_break (0);
5167     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5168     return;
5169   }
5170
5171   msg = (struct GNUNET_MESH_LocalMonitor *) message;
5172   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5173               "Received tunnel info request from client %u for tunnel %s[%X]\n",
5174               c->id,
5175               &msg->owner,
5176               ntohl (msg->tunnel_id));
5177   t = tunnel_get (&msg->owner, ntohl (msg->tunnel_id));
5178   if (NULL == t)
5179   {
5180     /* We don't know the tunnel FIXME */
5181     struct GNUNET_MESH_LocalMonitor warn;
5182
5183     warn = *msg;
5184     GNUNET_SERVER_notification_context_unicast (nc, client,
5185                                                 &warn.header,
5186                                                 GNUNET_NO);
5187     GNUNET_SERVER_receive_done (client, GNUNET_OK);
5188     return;
5189   }
5190
5191   /* Initialize context */
5192   resp = GNUNET_malloc (sizeof (struct GNUNET_MESH_LocalMonitor));
5193   *resp = *msg;
5194   GNUNET_PEER_resolve (t->dest, &resp->destination);
5195   resp->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
5196   GNUNET_SERVER_notification_context_unicast (nc, c->handle,
5197                                               &resp->header, GNUNET_NO);
5198   GNUNET_free (resp);
5199
5200   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5201               "Monitor tunnel request from client %u completed\n",
5202               c->id);
5203   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5204 }
5205
5206
5207 /**
5208  * Functions to handle messages from clients
5209  */
5210 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
5211   {&handle_local_new_client, NULL,
5212    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
5213   {&handle_local_tunnel_create, NULL,
5214    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
5215    sizeof (struct GNUNET_MESH_TunnelMessage)},
5216   {&handle_local_tunnel_destroy, NULL,
5217    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
5218    sizeof (struct GNUNET_MESH_TunnelMessage)},
5219   {&handle_local_data, NULL,
5220    GNUNET_MESSAGE_TYPE_MESH_LOCAL_DATA, 0},
5221   {&handle_local_ack, NULL,
5222    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK,
5223    sizeof (struct GNUNET_MESH_LocalAck)},
5224   {&handle_local_get_tunnels, NULL,
5225    GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS,
5226    sizeof (struct GNUNET_MessageHeader)},
5227   {&handle_local_show_tunnel, NULL,
5228    GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNEL,
5229      sizeof (struct GNUNET_MESH_LocalMonitor)},
5230   {NULL, NULL, 0, 0}
5231 };
5232
5233
5234 /**
5235  * Method called whenever a given peer connects.
5236  *
5237  * @param cls closure
5238  * @param peer peer identity this notification is about
5239  */
5240 static void
5241 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer)
5242 {
5243   struct MeshPeerInfo *peer_info;
5244   struct MeshPeerPath *path;
5245
5246   DEBUG_CONN ("Peer connected\n");
5247   DEBUG_CONN ("     %s\n", GNUNET_i2s (&my_full_id));
5248   peer_info = peer_get (peer);
5249   if (myid == peer_info->id)
5250   {
5251     DEBUG_CONN ("     (self)\n");
5252     path = path_new (1);
5253   }
5254   else
5255   {
5256     DEBUG_CONN ("     %s\n", GNUNET_i2s (peer));
5257     path = path_new (2);
5258     path->peers[1] = peer_info->id;
5259     GNUNET_PEER_change_rc (peer_info->id, 1);
5260     GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
5261   }
5262   path->peers[0] = myid;
5263   GNUNET_PEER_change_rc (myid, 1);
5264   peer_info_add_path (peer_info, path, GNUNET_YES);
5265   return;
5266 }
5267
5268
5269 /**
5270  * Method called whenever a peer disconnects.
5271  *
5272  * @param cls closure
5273  * @param peer peer identity this notification is about
5274  */
5275 static void
5276 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
5277 {
5278   struct MeshPeerInfo *pi;
5279   struct MeshPeerQueue *q;
5280   struct MeshPeerQueue *n;
5281
5282   DEBUG_CONN ("Peer disconnected\n");
5283   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
5284   if (NULL == pi)
5285   {
5286     GNUNET_break (0);
5287     return;
5288   }
5289   q = pi->queue_head;
5290   while (NULL != q)
5291   {
5292       n = q->next;
5293       /* TODO try to reroute this traffic instead */
5294       queue_destroy(q, GNUNET_YES);
5295       q = n;
5296   }
5297   if (NULL != pi->core_transmit)
5298   {
5299     GNUNET_CORE_notify_transmit_ready_cancel(pi->core_transmit);
5300     pi->core_transmit = NULL;
5301   }
5302     peer_remove_path (pi, pi->id, myid);
5303   if (myid == pi->id)
5304   {
5305     DEBUG_CONN ("     (self)\n");
5306   }
5307   GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
5308   return;
5309 }
5310
5311
5312 /**
5313  * Install server (service) handlers and start listening to clients.
5314  */
5315 static void
5316 server_init (void)
5317 {
5318   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
5319   GNUNET_SERVER_connect_notify (server_handle,
5320                                 &handle_local_client_connect, NULL);
5321   GNUNET_SERVER_disconnect_notify (server_handle,
5322                                    &handle_local_client_disconnect, NULL);
5323   nc = GNUNET_SERVER_notification_context_create (server_handle, 1);
5324
5325   clients_head = NULL;
5326   clients_tail = NULL;
5327   next_client_id = 0;
5328   GNUNET_SERVER_resume (server_handle);
5329 }
5330
5331
5332 /**
5333  * To be called on core init/fail.
5334  *
5335  * @param cls Closure (config)
5336  * @param server handle to the server for this service
5337  * @param identity the public identity of this peer
5338  */
5339 static void
5340 core_init (void *cls, struct GNUNET_CORE_Handle *server,
5341            const struct GNUNET_PeerIdentity *identity)
5342 {
5343   const struct GNUNET_CONFIGURATION_Handle *c = cls;
5344   static int i = 0;
5345
5346   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
5347   GNUNET_break (core_handle == server);
5348   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)) ||
5349     NULL == server)
5350   {
5351     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
5352     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5353                 " core id %s\n",
5354                 GNUNET_i2s (identity));
5355     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5356                 " my id %s\n",
5357                 GNUNET_i2s (&my_full_id));
5358     GNUNET_CORE_disconnect (core_handle);
5359     core_handle = GNUNET_CORE_connect (c, /* Main configuration */
5360                                        NULL,      /* Closure passed to MESH functions */
5361                                        &core_init,        /* Call core_init once connected */
5362                                        &core_connect,     /* Handle connects */
5363                                        &core_disconnect,  /* remove peers on disconnects */
5364                                        NULL,      /* Don't notify about all incoming messages */
5365                                        GNUNET_NO, /* For header only in notification */
5366                                        NULL,      /* Don't notify about all outbound messages */
5367                                        GNUNET_NO, /* For header-only out notification */
5368                                        core_handlers);    /* Register these handlers */
5369     if (10 < i++)
5370       GNUNET_abort();
5371   }
5372   server_init ();
5373   return;
5374 }
5375
5376
5377 /******************************************************************************/
5378 /************************      MAIN FUNCTIONS      ****************************/
5379 /******************************************************************************/
5380
5381 /**
5382  * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
5383  *
5384  * @param cls closure
5385  * @param key current key code
5386  * @param value value in the hash map
5387  * @return GNUNET_YES if we should continue to iterate,
5388  *         GNUNET_NO if not.
5389  */
5390 static int
5391 shutdown_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
5392 {
5393   struct MeshTunnel *t = value;
5394
5395   tunnel_destroy (t);
5396   return GNUNET_YES;
5397 }
5398
5399 /**
5400  * Iterator over peer hash map entries to destroy the tunnel during shutdown.
5401  *
5402  * @param cls closure
5403  * @param key current key code
5404  * @param value value in the hash map
5405  * @return GNUNET_YES if we should continue to iterate,
5406  *         GNUNET_NO if not.
5407  */
5408 static int
5409 shutdown_peer (void *cls, const struct GNUNET_HashCode * key, void *value)
5410 {
5411   struct MeshPeerInfo *p = value;
5412   struct MeshPeerQueue *q;
5413   struct MeshPeerQueue *n;
5414
5415   q = p->queue_head;
5416   while (NULL != q)
5417   {
5418       n = q->next;
5419       if (q->peer == p)
5420       {
5421         queue_destroy(q, GNUNET_YES);
5422       }
5423       q = n;
5424   }
5425   peer_info_destroy (p);
5426   return GNUNET_YES;
5427 }
5428
5429
5430 /**
5431  * Task run during shutdown.
5432  *
5433  * @param cls unused
5434  * @param tc unused
5435  */
5436 static void
5437 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
5438 {
5439   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
5440
5441   if (core_handle != NULL)
5442   {
5443     GNUNET_CORE_disconnect (core_handle);
5444     core_handle = NULL;
5445   }
5446   GNUNET_CONTAINER_multihashmap_iterate (tunnels, &shutdown_tunnel, NULL);
5447   GNUNET_CONTAINER_multihashmap_iterate (peers, &shutdown_peer, NULL);
5448   if (dht_handle != NULL)
5449   {
5450     GNUNET_DHT_disconnect (dht_handle);
5451     dht_handle = NULL;
5452   }
5453   if (nc != NULL)
5454   {
5455     GNUNET_SERVER_notification_context_destroy (nc);
5456     nc = NULL;
5457   }
5458   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
5459   {
5460     GNUNET_SCHEDULER_cancel (announce_id_task);
5461     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
5462   }
5463   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
5464 }
5465
5466
5467 /**
5468  * Process mesh requests.
5469  *
5470  * @param cls closure
5471  * @param server the initialized server
5472  * @param c configuration to use
5473  */
5474 static void
5475 run (void *cls, struct GNUNET_SERVER_Handle *server,
5476      const struct GNUNET_CONFIGURATION_Handle *c)
5477 {
5478   char *keyfile;
5479   struct GNUNET_CRYPTO_EccPrivateKey *pk;
5480
5481   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
5482   server_handle = server;
5483   GNUNET_SERVER_suspend (server_handle);
5484
5485   if (GNUNET_OK !=
5486       GNUNET_CONFIGURATION_get_value_filename (c, "PEER", "PRIVATE_KEY",
5487                                                &keyfile))
5488   {
5489     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5490                 _
5491                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5492                 "mesh", "peer/privatekey");
5493     GNUNET_SCHEDULER_shutdown ();
5494     return;
5495   }
5496
5497   if (GNUNET_OK !=
5498       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_PATH_TIME",
5499                                            &refresh_path_time))
5500   {
5501     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5502                 _
5503                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5504                 "mesh", "refresh path time");
5505     GNUNET_SCHEDULER_shutdown ();
5506     return;
5507   }
5508
5509   if (GNUNET_OK !=
5510       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "ID_ANNOUNCE_TIME",
5511                                            &id_announce_time))
5512   {
5513     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5514                 _
5515                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5516                 "mesh", "id announce time");
5517     GNUNET_SCHEDULER_shutdown ();
5518     return;
5519   }
5520
5521   if (GNUNET_OK !=
5522       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "CONNECT_TIMEOUT",
5523                                            &connect_timeout))
5524   {
5525     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5526                 _
5527                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5528                 "mesh", "connect timeout");
5529     GNUNET_SCHEDULER_shutdown ();
5530     return;
5531   }
5532
5533   if (GNUNET_OK !=
5534       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
5535                                              &max_msgs_queue))
5536   {
5537     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5538                 _
5539                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5540                 "mesh", "max msgs queue");
5541     GNUNET_SCHEDULER_shutdown ();
5542     return;
5543   }
5544
5545   if (GNUNET_OK !=
5546       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_TUNNELS",
5547                                              &max_tunnels))
5548   {
5549     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5550                 _
5551                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5552                 "mesh", "max tunnels");
5553     GNUNET_SCHEDULER_shutdown ();
5554     return;
5555   }
5556
5557   if (GNUNET_OK !=
5558       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
5559                                              &default_ttl))
5560   {
5561     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5562                 _
5563                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
5564                 "mesh", "default ttl", 64);
5565     default_ttl = 64;
5566   }
5567
5568   if (GNUNET_OK !=
5569       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_PEERS",
5570                                              &max_peers))
5571   {
5572     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5573                 _("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
5574                 "mesh", "max peers", 1000);
5575     max_peers = 1000;
5576   }
5577
5578   if (GNUNET_OK !=
5579       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DROP_PERCENT",
5580                                              &drop_percent))
5581   {
5582     drop_percent = 0;
5583   }
5584   else
5585   {
5586     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5587                 "Mesh is running with drop mode enabled. "
5588                 "This is NOT a good idea! "
5589                 "Remove the DROP_PERCENT option from your configuration.\n");
5590   }
5591
5592   if (GNUNET_OK !=
5593       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DHT_REPLICATION_LEVEL",
5594                                              &dht_replication_level))
5595   {
5596     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5597                 _
5598                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
5599                 "mesh", "dht replication level", 3);
5600     dht_replication_level = 3;
5601   }
5602
5603   tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
5604   incoming_tunnels = GNUNET_CONTAINER_multihashmap32_create (32);
5605   peers = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
5606   ports = GNUNET_CONTAINER_multihashmap32_create (32);
5607
5608   dht_handle = GNUNET_DHT_connect (c, 64);
5609   if (NULL == dht_handle)
5610   {
5611     GNUNET_break (0);
5612   }
5613   stats = GNUNET_STATISTICS_create ("mesh", c);
5614
5615   /* Scheduled the task to clean up when shutdown is called */
5616   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
5617                                 NULL);
5618   pk = GNUNET_CRYPTO_ecc_key_create_from_file (keyfile);
5619   GNUNET_free (keyfile);
5620   GNUNET_assert (NULL != pk);
5621   my_private_key = pk;
5622   GNUNET_CRYPTO_ecc_key_get_public (my_private_key, &my_public_key);
5623   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
5624                       &my_full_id.hashPubKey);
5625   myid = GNUNET_PEER_intern (&my_full_id);
5626   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5627               "Mesh for peer [%s] starting\n",
5628               GNUNET_i2s(&my_full_id));
5629
5630   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
5631                                      NULL,      /* Closure passed to MESH functions */
5632                                      &core_init,        /* Call core_init once connected */
5633                                      &core_connect,     /* Handle connects */
5634                                      &core_disconnect,  /* remove peers on disconnects */
5635                                      NULL,      /* Don't notify about all incoming messages */
5636                                      GNUNET_NO, /* For header only in notification */
5637                                      NULL,      /* Don't notify about all outbound messages */
5638                                      GNUNET_NO, /* For header-only out notification */
5639                                      core_handlers);    /* Register these handlers */
5640   if (NULL == core_handle)
5641   {
5642     GNUNET_break (0);
5643     GNUNET_SCHEDULER_shutdown ();
5644     return;
5645   }
5646   next_tid = 0;
5647   next_local_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
5648   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
5649   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Mesh service running\n");
5650 }
5651
5652
5653 /**
5654  * The main function for the mesh service.
5655  *
5656  * @param argc number of arguments from the command line
5657  * @param argv command line arguments
5658  * @return 0 ok, 1 on error
5659  */
5660 int
5661 main (int argc, char *const *argv)
5662 {
5663   int ret;
5664   int r;
5665
5666   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
5667   r = GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
5668                           NULL);
5669   ret = (GNUNET_OK == r) ? 0 : 1;
5670   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");
5671
5672   INTERVAL_SHOW;
5673
5674   return ret;
5675 }