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