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