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