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