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