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