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