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