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