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