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