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