910d96eee5c6fff32e0cd8cc97f650eabca07eb8
[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_POLL:
3155       case GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE:
3156         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3157                     "   prebuilt message\n");
3158         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3159                     "   type %s\n",
3160                     GNUNET_MESH_DEBUG_M2S (queue->type));
3161         break;
3162       case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
3163         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   type create path\n");
3164         break;
3165       default:
3166         GNUNET_break (0);
3167         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3168                     "   type %s unknown!\n",
3169                     GNUNET_MESH_DEBUG_M2S (queue->type));
3170     }
3171     GNUNET_free_non_null (queue->cls);
3172   }
3173   GNUNET_CONTAINER_DLL_remove (queue->peer->queue_head,
3174                                queue->peer->queue_tail,
3175                                queue);
3176
3177   /* Delete from appropriate fc in the tunnel */
3178   if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == queue->type ||
3179       GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == queue->type )
3180   {
3181     if (queue->peer->id == queue->tunnel->prev_hop)
3182       fc = &queue->tunnel->prev_fc;
3183     else if (queue->peer->id == queue->tunnel->next_hop)
3184       fc = &queue->tunnel->next_fc;
3185     else
3186     {
3187       GNUNET_break (0);
3188       GNUNET_free (queue);
3189       return;
3190     }
3191     fc->queue_n--;
3192   }
3193   GNUNET_free (queue);
3194 }
3195
3196
3197 /**
3198  * @brief Get the next transmittable message from the queue.
3199  *
3200  * This will be the head, except in the case of being a data packet
3201  * not allowed by the destination peer.
3202  *
3203  * @param peer Destination peer.
3204  *
3205  * @return The next viable MeshPeerQueue element to send to that peer.
3206  *         NULL when there are no transmittable messages.
3207  */
3208 struct MeshPeerQueue *
3209 queue_get_next (const struct MeshPeerInfo *peer)
3210 {
3211   struct MeshPeerQueue *q;
3212
3213   struct GNUNET_MESH_Data *dmsg;
3214   struct MeshTunnel* t;
3215   uint32_t pid;
3216   uint32_t ack;
3217
3218   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   selecting message\n");
3219   for (q = peer->queue_head; NULL != q; q = q->next)
3220   {
3221     t = q->tunnel;
3222     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3223                 "*     %s\n",
3224                 GNUNET_MESH_DEBUG_M2S (q->type));
3225     dmsg = (struct GNUNET_MESH_Data *) q->cls;
3226     pid = ntohl (dmsg->pid);
3227     switch (q->type)
3228     {
3229       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
3230         ack = t->next_fc.last_ack_recv;
3231         break;
3232       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
3233         ack = t->prev_fc.last_ack_recv;
3234         break;
3235       default:
3236         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3237                     "*   OK!\n");
3238         return q;
3239     }
3240     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3241                 "*     ACK: %u, PID: %u, MID: %u\n",
3242                 ack, pid, ntohl (dmsg->mid));
3243     if (GNUNET_NO == GMC_is_pid_bigger (pid, ack))
3244     {
3245       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3246                   "*   OK!\n");
3247       return q;
3248     }
3249     else
3250     {
3251       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3252                   "*     NEXT!\n");
3253     }
3254   }
3255   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3256                 "*   nothing found\n");
3257   return NULL;
3258 }
3259
3260
3261 static size_t
3262 queue_send (void *cls, size_t size, void *buf)
3263 {
3264   struct MeshPeerInfo *peer = cls;
3265   struct GNUNET_MessageHeader *msg;
3266   struct MeshPeerQueue *queue;
3267   struct MeshTunnel *t;
3268   struct GNUNET_PeerIdentity dst_id;
3269   struct MeshFlowControl *fc;
3270   size_t data_size;
3271   uint32_t pid;
3272   uint16_t type;
3273
3274   peer->core_transmit = NULL;
3275
3276   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* Queue send\n");
3277   queue = queue_get_next (peer);
3278
3279   /* Queue has no internal mesh traffic nor sendable payload */
3280   if (NULL == queue)
3281   {
3282     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   not ready, return\n");
3283     if (NULL == peer->queue_head)
3284       GNUNET_break (0); /* Core tmt_rdy should've been canceled */
3285     return 0;
3286   }
3287   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   not empty\n");
3288
3289   GNUNET_PEER_resolve (peer->id, &dst_id);
3290   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3291               "*   towards %s\n",
3292               GNUNET_i2s (&dst_id));
3293   /* Check if buffer size is enough for the message */
3294   if (queue->size > size)
3295   {
3296       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3297                   "*   not enough room, reissue\n");
3298       peer->core_transmit =
3299           GNUNET_CORE_notify_transmit_ready (core_handle,
3300                                              GNUNET_NO,
3301                                              0,
3302                                              GNUNET_TIME_UNIT_FOREVER_REL,
3303                                              &dst_id,
3304                                              queue->size,
3305                                              &queue_send,
3306                                              peer);
3307       return 0;
3308   }
3309   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   size ok\n");
3310
3311   t = queue->tunnel;
3312   GNUNET_assert (0 < t->pending_messages);
3313   t->pending_messages--;
3314   type = 0;
3315
3316   /* Fill buf */
3317   switch (queue->type)
3318   {
3319     case 0:
3320     case GNUNET_MESSAGE_TYPE_MESH_ACK:
3321     case GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK:
3322     case GNUNET_MESSAGE_TYPE_MESH_TO_ORIG_ACK:
3323     case GNUNET_MESSAGE_TYPE_MESH_POLL:
3324     case GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN:
3325     case GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY:
3326     case GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY:
3327     case GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE:
3328       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3329                   "*   raw: %s\n",
3330                   GNUNET_MESH_DEBUG_M2S (queue->type));
3331       /* Fall through */
3332     case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
3333     case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
3334       data_size = send_core_data_raw (queue->cls, size, buf);
3335       msg = (struct GNUNET_MessageHeader *) buf;
3336       type = ntohs (msg->type);
3337       break;
3338     case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
3339       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   path create\n");
3340       data_size = send_core_path_create (queue->cls, size, buf);
3341       break;
3342     case GNUNET_MESSAGE_TYPE_MESH_PATH_ACK:
3343       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   path ack\n");
3344       data_size = send_core_path_ack (queue->cls, size, buf);
3345       break;
3346     default:
3347       GNUNET_break (0);
3348       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3349                   "*   type unknown: %u\n",
3350                   queue->type);
3351       data_size = 0;
3352   }
3353
3354   if (0 < drop_percent &&
3355       GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 101) < drop_percent)
3356   {
3357     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3358                 "Dropping message of type %s\n",
3359                 GNUNET_MESH_DEBUG_M2S(queue->type));
3360     data_size = 0;
3361   }
3362   /* Free queue, but cls was freed by send_core_* */
3363   queue_destroy (queue, GNUNET_NO);
3364
3365   /* Send ACK if needed, after accounting for sent ID in fc->queue_n */
3366   pid = ((struct GNUNET_MESH_Data *) buf)->pid;
3367   pid = ntohl (pid);
3368   switch (type)
3369   {
3370     case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
3371       t->next_fc.last_pid_sent = pid;
3372       tunnel_send_ack (t, GNUNET_MESSAGE_TYPE_MESH_UNICAST, GNUNET_YES);
3373       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3374                   "!!! FWD  %u\n",
3375                   ntohl ( ((struct GNUNET_MESH_Data *) buf)->mid ) );
3376       break;
3377     case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
3378       t->prev_fc.last_pid_sent = pid;
3379       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3380                   "!!! BCK  %u\n",
3381                   ntohl ( ((struct GNUNET_MESH_Data *) buf)->mid ) );
3382       tunnel_send_ack (t, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, GNUNET_NO);
3383       break;
3384     default:
3385       break;
3386   }
3387
3388   /* If more data in queue, send next */
3389   queue = queue_get_next (peer);
3390   if (NULL != queue)
3391   {
3392       struct GNUNET_PeerIdentity id;
3393
3394       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   more data!\n");
3395       GNUNET_PEER_resolve (peer->id, &id);
3396       peer->core_transmit =
3397           GNUNET_CORE_notify_transmit_ready(core_handle,
3398                                             0,
3399                                             0,
3400                                             GNUNET_TIME_UNIT_FOREVER_REL,
3401                                             &id,
3402                                             queue->size,
3403                                             &queue_send,
3404                                             peer);
3405   }
3406   if (peer->id == t->next_hop)
3407     fc = &t->next_fc;
3408   else if (peer->id == t->prev_hop)
3409     fc = &t->prev_fc;
3410   else
3411   {
3412     GNUNET_break (0);
3413     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "id: %u, next: %u, prev: %u\n",
3414                 peer->id, t->next_hop, t->prev_hop);
3415     return data_size;
3416   }
3417   if (NULL != peer->queue_head)
3418   {
3419     if (GNUNET_SCHEDULER_NO_TASK == fc->poll_task && fc->queue_n > 0)
3420     {
3421       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3422                   "*   %s starting poll timeout\n",
3423                   GNUNET_i2s (&my_full_id));
3424       fc->t = t;
3425       fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
3426                                                     &tunnel_poll, fc);
3427     }
3428   }
3429   else
3430   {
3431     if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
3432     {
3433       GNUNET_SCHEDULER_cancel (fc->poll_task);
3434       fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
3435     }
3436   }
3437   if (GNUNET_YES == t->destroy && 0 == t->pending_messages)
3438   {
3439     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*  destroying tunnel!\n");
3440     tunnel_destroy (t);
3441   }
3442   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*  Return %d\n", data_size);
3443   return data_size;
3444 }
3445
3446
3447 /**
3448  * @brief Queue and pass message to core when possible.
3449  * 
3450  * If type is payload (UNICAST, TO_ORIGIN) checks for queue status and
3451  * accounts for it. In case the queue is full, the message is dropped and
3452  * a break issued.
3453  * 
3454  * Otherwise, message is treated as internal and allowed to go regardless of 
3455  * queue status.
3456  *
3457  * @param cls Closure (@c type dependant). It will be used by queue_send to
3458  *            build the message to be sent if not already prebuilt.
3459  * @param type Type of the message, 0 for a raw message.
3460  * @param size Size of the message.
3461  * @param dst Neighbor to send message to.
3462  * @param t Tunnel this message belongs to.
3463  */
3464 static void
3465 queue_add (void *cls, uint16_t type, size_t size,
3466            struct MeshPeerInfo *dst, struct MeshTunnel *t)
3467 {
3468   struct MeshPeerQueue *queue;
3469   struct GNUNET_PeerIdentity id;
3470   struct MeshFlowControl *fc;
3471   int priority;
3472
3473   fc = NULL;
3474   priority = GNUNET_NO;
3475   if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == type)
3476   {
3477     fc = &t->next_fc;
3478   }
3479   else if (GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == type)
3480   {
3481     fc = &t->prev_fc;
3482   }
3483   if (NULL != fc)
3484   {
3485     if (fc->queue_n >= t->queue_max)
3486     {
3487       /* If this isn't a retransmission, drop the message */
3488       if (GNUNET_NO == t->reliable ||
3489           (NULL == t->owner && GNUNET_MESSAGE_TYPE_MESH_UNICAST == type) ||
3490           (NULL == t->client && GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == type))
3491       {
3492         GNUNET_STATISTICS_update (stats, "# messages dropped (buffer full)",
3493                                   1, GNUNET_NO);
3494         GNUNET_break (0);
3495         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3496                     "queue full: %u/%u\n",
3497                     fc->queue_n, t->queue_max);
3498         return; /* Drop this message */
3499       }
3500       priority = GNUNET_YES;
3501     }
3502     fc->queue_n++;
3503     if (GMC_is_pid_bigger(fc->last_pid_sent + 1, fc->last_ack_recv) &&
3504         GNUNET_SCHEDULER_NO_TASK == fc->poll_task)
3505       fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
3506                                                     &tunnel_poll,
3507                                                     fc);
3508   }
3509   queue = GNUNET_malloc (sizeof (struct MeshPeerQueue));
3510   queue->cls = cls;
3511   queue->type = type;
3512   queue->size = size;
3513   queue->peer = dst;
3514   queue->tunnel = t;
3515   if (GNUNET_YES == priority)
3516   {
3517     struct GNUNET_MESH_Data *d;
3518     uint32_t prev;
3519     uint32_t next;
3520
3521     GNUNET_CONTAINER_DLL_insert (dst->queue_head, dst->queue_tail, queue);
3522     d = (struct GNUNET_MESH_Data *) queue->cls;
3523     prev = d->pid;
3524     for (queue = dst->queue_tail; NULL != queue; queue = queue->prev)
3525     {
3526       if (queue->type != type)
3527         continue;
3528       d = (struct GNUNET_MESH_Data *) queue->cls;
3529       next = d->pid;
3530       d->pid = prev;
3531       prev = next;
3532     }
3533   }
3534   else
3535     GNUNET_CONTAINER_DLL_insert_tail (dst->queue_head, dst->queue_tail, queue);
3536   
3537   if (NULL == dst->core_transmit)
3538   {
3539     GNUNET_PEER_resolve (dst->id, &id);
3540     dst->core_transmit =
3541         GNUNET_CORE_notify_transmit_ready (core_handle,
3542                                            0,
3543                                            0,
3544                                            GNUNET_TIME_UNIT_FOREVER_REL,
3545                                            &id,
3546                                            size,
3547                                            &queue_send,
3548                                            dst);
3549   }
3550   t->pending_messages++;
3551 }
3552
3553
3554 /******************************************************************************/
3555 /********************      MESH NETWORK HANDLERS     **************************/
3556 /******************************************************************************/
3557
3558
3559 /**
3560  * Core handler for path creation
3561  *
3562  * @param cls closure
3563  * @param message message
3564  * @param peer peer identity this notification is about
3565  *
3566  * @return GNUNET_OK to keep the connection open,
3567  *         GNUNET_SYSERR to close it (signal serious error)
3568  */
3569 static int
3570 handle_mesh_path_create (void *cls, const struct GNUNET_PeerIdentity *peer,
3571                          const struct GNUNET_MessageHeader *message)
3572 {
3573   unsigned int own_pos;
3574   uint16_t size;
3575   uint16_t i;
3576   MESH_TunnelNumber tid;
3577   struct GNUNET_MESH_CreateTunnel *msg;
3578   struct GNUNET_PeerIdentity *pi;
3579   struct MeshPeerPath *path;
3580   struct MeshPeerInfo *dest_peer_info;
3581   struct MeshPeerInfo *orig_peer_info;
3582   struct MeshTunnel *t;
3583
3584   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3585               "Received a path create msg [%s]\n",
3586               GNUNET_i2s (&my_full_id));
3587   size = ntohs (message->size);
3588   if (size < sizeof (struct GNUNET_MESH_CreateTunnel))
3589   {
3590     GNUNET_break_op (0);
3591     return GNUNET_OK;
3592   }
3593
3594   size -= sizeof (struct GNUNET_MESH_CreateTunnel);
3595   if (size % sizeof (struct GNUNET_PeerIdentity))
3596   {
3597     GNUNET_break_op (0);
3598     return GNUNET_OK;
3599   }
3600   size /= sizeof (struct GNUNET_PeerIdentity);
3601   if (size < 1)
3602   {
3603     GNUNET_break_op (0);
3604     return GNUNET_OK;
3605   }
3606   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
3607   msg = (struct GNUNET_MESH_CreateTunnel *) message;
3608
3609   tid = ntohl (msg->tid);
3610   pi = (struct GNUNET_PeerIdentity *) &msg[1];
3611   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3612               "    path is for tunnel %s[%X].\n", GNUNET_i2s (pi), tid);
3613   t = tunnel_get (pi, tid);
3614   if (NULL == t) /* might be a local tunnel */
3615   {
3616     uint32_t opt;
3617
3618     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating tunnel\n");
3619     t = tunnel_new (GNUNET_PEER_intern (pi), tid, NULL, 0);
3620     if (NULL == t)
3621     {
3622       GNUNET_break (0);
3623       return GNUNET_OK;
3624     }
3625     t->port = ntohl (msg->port);
3626     opt = ntohl (msg->opt);
3627     if (0 != (opt & GNUNET_MESH_OPTION_NOBUFFER))
3628     {
3629       t->nobuffer = GNUNET_YES;
3630       t->queue_max = 1;
3631     }
3632     if (0 != (opt & GNUNET_MESH_OPTION_RELIABLE))
3633     {
3634       t->reliable = GNUNET_YES;
3635     }
3636     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  nobuffer:%d\n", t->nobuffer);
3637
3638     tunnel_reset_timeout (t, GNUNET_YES); // FIXME
3639   }
3640   t->state = MESH_TUNNEL_WAITING;
3641   dest_peer_info =
3642       GNUNET_CONTAINER_multihashmap_get (peers, &pi[size - 1].hashPubKey);
3643   if (NULL == dest_peer_info)
3644   {
3645     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3646                 "  Creating PeerInfo for destination.\n");
3647     dest_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
3648     dest_peer_info->id = GNUNET_PEER_intern (&pi[size - 1]);
3649     GNUNET_CONTAINER_multihashmap_put (peers, &pi[size - 1].hashPubKey,
3650                                        dest_peer_info,
3651                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3652   }
3653   orig_peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &pi->hashPubKey);
3654   if (NULL == orig_peer_info)
3655   {
3656     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3657                 "  Creating PeerInfo for origin.\n");
3658     orig_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
3659     orig_peer_info->id = GNUNET_PEER_intern (pi);
3660     GNUNET_CONTAINER_multihashmap_put (peers, &pi->hashPubKey, orig_peer_info,
3661                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3662   }
3663   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
3664   path = path_new (size);
3665   own_pos = 0;
3666   for (i = 0; i < size; i++)
3667   {
3668     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
3669                 GNUNET_i2s (&pi[i]));
3670     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
3671     if (path->peers[i] == myid)
3672       own_pos = i;
3673   }
3674   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
3675   if (own_pos == 0 && path->peers[own_pos] != myid)
3676   {
3677     /* create path: self not found in path through self */
3678     GNUNET_break_op (0);
3679     path_destroy (path);
3680     tunnel_destroy (t);
3681     return GNUNET_OK;
3682   }
3683   path_add_to_peers (path, GNUNET_NO);
3684   tunnel_use_path (t, path);
3685
3686   peer_info_add_tunnel (dest_peer_info, t);
3687
3688   if (own_pos == size - 1)
3689   {
3690     struct MeshClient *c;
3691
3692     /* Find target client */
3693     c = GNUNET_CONTAINER_multihashmap32_get (ports, t->port);
3694     if (NULL == c)
3695     {
3696       /* TODO send reject */
3697       return GNUNET_OK;
3698     }
3699
3700     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
3701     peer_info_add_path_to_origin (orig_peer_info, path, GNUNET_YES);
3702
3703     /* Assign local tid */
3704     while (NULL != tunnel_get_incoming (next_local_tid))
3705       next_local_tid = (next_local_tid + 1) | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
3706     t->local_tid_dest = next_local_tid++;
3707     next_local_tid = next_local_tid | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
3708
3709     if (GNUNET_YES == t->reliable)
3710     {
3711       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! Reliable\n");
3712       t->bck_rel = GNUNET_malloc (sizeof (struct MeshTunnelReliability));
3713       t->bck_rel->t = t;
3714       t->bck_rel->expected_delay = MESH_RETRANSMIT_TIME;
3715     }
3716
3717     tunnel_add_client (t, c);
3718     send_client_tunnel_create (t);
3719     send_path_ack (t);
3720   }
3721   else
3722   {
3723     struct MeshPeerPath *path2;
3724
3725     t->next_hop = path->peers[own_pos + 1];
3726     GNUNET_PEER_change_rc(t->next_hop, 1);
3727
3728     /* It's for somebody else! Retransmit. */
3729     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Retransmitting.\n");
3730     path2 = path_duplicate (path);
3731     peer_info_add_path (dest_peer_info, path2, GNUNET_NO);
3732     peer_info_add_path_to_origin (orig_peer_info, path, GNUNET_NO);
3733     send_create_path (t);
3734   }
3735   return GNUNET_OK;
3736 }
3737
3738
3739
3740 /**
3741  * Core handler for path ACKs
3742  *
3743  * @param cls closure
3744  * @param message message
3745  * @param peer peer identity this notification is about
3746  *
3747  * @return GNUNET_OK to keep the connection open,
3748  *         GNUNET_SYSERR to close it (signal serious error)
3749  */
3750 static int
3751 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
3752                       const struct GNUNET_MessageHeader *message)
3753 {
3754   struct GNUNET_MESH_PathACK *msg;
3755   struct MeshPeerInfo *peer_info;
3756   struct MeshPeerPath *p;
3757   struct MeshTunnel *t;
3758
3759   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a path ACK msg [%s]\n",
3760               GNUNET_i2s (&my_full_id));
3761   msg = (struct GNUNET_MESH_PathACK *) message;
3762   t = tunnel_get (&msg->oid, ntohl(msg->tid));
3763   if (NULL == t)
3764   {
3765     /* TODO notify that we don't know the tunnel */
3766     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel", 1, GNUNET_NO);
3767     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  don't know the tunnel %s [%X]!\n",
3768                 GNUNET_i2s (&msg->oid), ntohl(msg->tid));
3769     return GNUNET_OK;
3770   }
3771   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %s [%X]\n",
3772               GNUNET_i2s (&msg->oid), ntohl(msg->tid));
3773
3774   peer_info = peer_get (&msg->peer_id);
3775   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by peer %s\n",
3776               GNUNET_i2s (&msg->peer_id));
3777   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  via peer %s\n",
3778               GNUNET_i2s (peer));
3779
3780   /* Add path to peers? */
3781   p = t->path;
3782   if (NULL != p)
3783   {
3784     path_add_to_peers (p, GNUNET_YES);
3785   }
3786   else
3787   {
3788     GNUNET_break (0);
3789   }
3790   t->state = MESH_TUNNEL_READY;
3791   t->next_fc.last_ack_recv = (NULL == t->client) ? ntohl (msg->ack) : 0;
3792   t->prev_fc.last_ack_sent = ntohl (msg->ack);
3793
3794   /* Message for us? */
3795   if (0 == memcmp (&msg->oid, &my_full_id, sizeof (struct GNUNET_PeerIdentity)))
3796   {
3797     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
3798     if (NULL == t->owner)
3799     {
3800       GNUNET_break_op (0);
3801       return GNUNET_OK;
3802     }
3803     if (NULL != peer_info->dhtget)
3804     {
3805       GNUNET_DHT_get_stop (peer_info->dhtget);
3806       peer_info->dhtget = NULL;
3807     }
3808     tunnel_send_ack (t, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK, GNUNET_YES);
3809     tunnel_send_ack (t, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK, GNUNET_NO);
3810     return GNUNET_OK;
3811   }
3812
3813   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3814               "  not for us, retransmitting...\n");
3815   peer_info = peer_get (&msg->oid);
3816   send_prebuilt_message (message, t->prev_hop, t);
3817   return GNUNET_OK;
3818 }
3819
3820
3821 /**
3822  * Core handler for notifications of broken paths
3823  *
3824  * @param cls closure
3825  * @param message message
3826  * @param peer peer identity this notification is about
3827  *
3828  * @return GNUNET_OK to keep the connection open,
3829  *         GNUNET_SYSERR to close it (signal serious error)
3830  */
3831 static int
3832 handle_mesh_path_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
3833                          const struct GNUNET_MessageHeader *message)
3834 {
3835   struct GNUNET_MESH_PathBroken *msg;
3836   struct MeshTunnel *t;
3837
3838   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3839               "Received a PATH BROKEN msg from %s\n", GNUNET_i2s (peer));
3840   msg = (struct GNUNET_MESH_PathBroken *) message;
3841   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
3842               GNUNET_i2s (&msg->peer1));
3843   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
3844               GNUNET_i2s (&msg->peer2));
3845   t = tunnel_get (&msg->oid, ntohl (msg->tid));
3846   if (NULL == t)
3847   {
3848     GNUNET_break_op (0);
3849     return GNUNET_OK;
3850   }
3851   tunnel_notify_connection_broken (t, GNUNET_PEER_search (&msg->peer1),
3852                                    GNUNET_PEER_search (&msg->peer2));
3853   return GNUNET_OK;
3854
3855 }
3856
3857
3858 /**
3859  * Core handler for tunnel destruction
3860  *
3861  * @param cls closure
3862  * @param message message
3863  * @param peer peer identity this notification is about
3864  *
3865  * @return GNUNET_OK to keep the connection open,
3866  *         GNUNET_SYSERR to close it (signal serious error)
3867  */
3868 static int
3869 handle_mesh_tunnel_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
3870                             const struct GNUNET_MessageHeader *message)
3871 {
3872   struct GNUNET_MESH_TunnelDestroy *msg;
3873   struct MeshTunnel *t;
3874
3875   msg = (struct GNUNET_MESH_TunnelDestroy *) message;
3876   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3877               "Got a TUNNEL DESTROY packet from %s\n",
3878               GNUNET_i2s (peer));
3879   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3880               "  for tunnel %s [%u]\n",
3881               GNUNET_i2s (&msg->oid), ntohl (msg->tid));
3882   t = tunnel_get (&msg->oid, ntohl (msg->tid));
3883   if (NULL == t)
3884   {
3885     /* Probably already got the message from another path,
3886      * destroyed the tunnel and retransmitted to children.
3887      * Safe to ignore.
3888      */
3889     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel",
3890                               1, GNUNET_NO);
3891     return GNUNET_OK;
3892   }
3893   if (t->local_tid_dest >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
3894   {
3895     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "INCOMING TUNNEL %X %X\n",
3896                 t->local_tid, t->local_tid_dest);
3897   }
3898   if (GNUNET_PEER_search (peer) == t->prev_hop)
3899   {
3900     // TODO check owner's signature
3901     // TODO add owner's signatue to tunnel for retransmission
3902     peer_cancel_queues (t->prev_hop, t);
3903     GNUNET_PEER_change_rc (t->prev_hop, -1);
3904     t->prev_hop = 0;
3905   }
3906   else if (GNUNET_PEER_search (peer) == t->next_hop)
3907   {
3908     // TODO check dest's signature
3909     // TODO add dest's signatue to tunnel for retransmission
3910     peer_cancel_queues (t->next_hop, t);
3911     GNUNET_PEER_change_rc (t->next_hop, -1);
3912     t->next_hop = 0;
3913   }
3914   else
3915   {
3916     GNUNET_break_op (0);
3917     // TODO check both owner AND destination's signature to see which matches
3918     // TODO restransmit in appropriate direction
3919     return GNUNET_OK;
3920   }
3921   tunnel_destroy_empty (t);
3922
3923   // TODO: add timeout to destroy the tunnel anyway
3924   return GNUNET_OK;
3925 }
3926
3927
3928 /**
3929  * Generic handler for mesh network payload traffic.
3930  *
3931  * @param peer Peer identity this notification is about.
3932  * @param message Data message.
3933  * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
3934  *
3935  * @return GNUNET_OK to keep the connection open,
3936  *         GNUNET_SYSERR to close it (signal serious error)
3937  */
3938 static int
3939 handle_mesh_data (const struct GNUNET_PeerIdentity *peer,
3940                   const struct GNUNET_MessageHeader *message,
3941                   int fwd)
3942 {
3943   struct GNUNET_MESH_Data *msg;
3944   struct MeshFlowControl *fc;
3945   struct MeshTunnelReliability *rel;
3946   struct MeshTunnel *t;
3947   struct MeshClient *c;
3948   GNUNET_PEER_Id hop;
3949   uint32_t pid;
3950   uint32_t ttl;
3951   uint16_t type;
3952   size_t size;
3953
3954   /* Check size */
3955   size = ntohs (message->size);
3956   if (size <
3957       sizeof (struct GNUNET_MESH_Data) +
3958       sizeof (struct GNUNET_MessageHeader))
3959   {
3960     GNUNET_break (0);
3961     return GNUNET_OK;
3962   }
3963   type =ntohs (message->type);
3964   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a %s message from %s\n",
3965               GNUNET_MESH_DEBUG_M2S (type), GNUNET_i2s (peer));
3966   msg = (struct GNUNET_MESH_Data *) message;
3967   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
3968               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
3969   /* Check tunnel */
3970   t = tunnel_get (&msg->oid, ntohl (msg->tid));
3971   if (NULL == t)
3972   {
3973     /* TODO notify back: we don't know this tunnel */
3974     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
3975     GNUNET_break_op (0);
3976     return GNUNET_OK;
3977   }
3978
3979   /*  Initialize FWD/BCK data */
3980   pid = ntohl (msg->pid);
3981   fc =  fwd ? &t->prev_fc : &t->next_fc;
3982   c =   fwd ? t->client   : t->owner;
3983   rel = fwd ? t->bck_rel  : t->fwd_rel;
3984   hop = fwd ? t->next_hop : t->prev_hop;
3985   if (GMC_is_pid_bigger (pid, fc->last_ack_sent))
3986   {
3987     GNUNET_STATISTICS_update (stats, "# unsolicited data", 1, GNUNET_NO);
3988     GNUNET_break_op (0);
3989     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3990                 "Received PID %u, (prev %u), ACK %u\n",
3991                 pid, fc->last_pid_recv, fc->last_ack_sent);
3992     return GNUNET_OK;
3993   }
3994
3995   tunnel_reset_timeout (t, fwd);
3996   if (NULL != c)
3997   {
3998     /* TODO signature verification */
3999     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  it's for us! sending to client\n");
4000     GNUNET_STATISTICS_update (stats, "# data received", 1, GNUNET_NO);
4001     if (GMC_is_pid_bigger (pid, fc->last_pid_recv))
4002     {
4003       uint32_t mid;
4004
4005       mid = ntohl (msg->mid);
4006       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4007                   " pid %u (mid %u) not seen yet\n", pid, mid);
4008       fc->last_pid_recv = pid;
4009
4010       if (GNUNET_NO == t->reliable ||
4011           ( !GMC_is_pid_bigger (rel->mid_recv, mid) &&
4012             GMC_is_pid_bigger (rel->mid_recv + 64, mid) ) )
4013       {
4014         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4015                     "!!! RECV %u\n", ntohl (msg->mid));
4016         if (GNUNET_YES == t->reliable)
4017         {
4018           /* Is this the exact next expected messasge? */
4019           if (mid == rel->mid_recv)
4020           {
4021             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "as expected\n");
4022             rel->mid_recv++;
4023             tunnel_send_client_data (t, msg, fwd);
4024             tunnel_send_client_buffered_data (t, c, rel);
4025           }
4026           else
4027           {
4028             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "save for later\n");
4029             tunnel_add_buffered_data (t, msg, rel);
4030           }
4031         }
4032         else /* Tunnel unreliable, send to clients directly */
4033         {
4034           tunnel_send_client_data (t, msg, fwd);
4035         }
4036       }
4037       else
4038       {
4039         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4040                     " MID %u not expected (%u - %u), dropping!\n",
4041                     ntohl (msg->mid), rel->mid_recv, rel->mid_recv + 64);
4042       }
4043     }
4044     else
4045     {
4046 //       GNUNET_STATISTICS_update (stats, "# duplicate PID", 1, GNUNET_NO);
4047       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4048                   " Pid %u not expected (%u+), dropping!\n",
4049                   pid, fc->last_pid_recv + 1);
4050     }
4051     tunnel_send_ack (t, type, fwd);
4052     return GNUNET_OK;
4053   }
4054   fc->last_pid_recv = pid;
4055   if (0 == hop)
4056   {
4057     GNUNET_STATISTICS_update (stats, "# data on dying tunnel", 1, GNUNET_NO);
4058     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "data on dying tunnel %s[%X]\n",
4059                 GNUNET_PEER_resolve2 (t->id.oid), ntohl (msg->tid));
4060     return GNUNET_OK; /* Next hop has destoyed the tunnel, drop */
4061   }
4062   ttl = ntohl (msg->ttl);
4063   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ttl);
4064   if (ttl == 0)
4065   {
4066     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
4067     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
4068     tunnel_send_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK, fwd);
4069     return GNUNET_OK;
4070   }
4071
4072   if (myid != hop)
4073   {
4074     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  not for us, retransmitting...\n");
4075     send_prebuilt_message (message, hop, t);
4076     GNUNET_STATISTICS_update (stats, "# unicast forwarded", 1, GNUNET_NO);
4077   }
4078   return GNUNET_OK;
4079 }
4080
4081
4082 /**
4083  * Core handler for mesh network traffic going from the origin to a peer
4084  *
4085  * @param cls Closure (unused).
4086  * @param message Message received.
4087  * @param peer Peer who sent the message.
4088  *
4089  * @return GNUNET_OK to keep the connection open,
4090  *         GNUNET_SYSERR to close it (signal serious error)
4091  */
4092 static int
4093 handle_mesh_unicast (void *cls, const struct GNUNET_PeerIdentity *peer,
4094                      const struct GNUNET_MessageHeader *message)
4095 {
4096   return handle_mesh_data (peer, message, GNUNET_YES);
4097 }
4098
4099 /**
4100  * Core handler for mesh network traffic towards the owner of a tunnel.
4101  *
4102  * @param cls Closure (unused).
4103  * @param message Message received.
4104  * @param peer Peer who sent the message.
4105  *
4106  * @return GNUNET_OK to keep the connection open,
4107  *         GNUNET_SYSERR to close it (signal serious error)
4108  */
4109 static int
4110 handle_mesh_to_orig (void *cls, const struct GNUNET_PeerIdentity *peer,
4111                      const struct GNUNET_MessageHeader *message)
4112 {
4113   return handle_mesh_data (peer, message, GNUNET_NO);
4114 }
4115
4116
4117 /**
4118  * Core handler for mesh network traffic end-to-end ACKs.
4119  *
4120  * @param cls Closure.
4121  * @param message Message.
4122  * @param peer Peer identity this notification is about.
4123  *
4124  * @return GNUNET_OK to keep the connection open,
4125  *         GNUNET_SYSERR to close it (signal serious error)
4126  */
4127 static int
4128 handle_mesh_data_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
4129                       const struct GNUNET_MessageHeader *message)
4130 {
4131   struct GNUNET_MESH_DataACK *msg;
4132   struct MeshTunnelReliability *rel;
4133   struct MeshReliableMessage *copy;
4134   struct MeshReliableMessage *next;
4135   struct MeshTunnel *t;
4136   GNUNET_PEER_Id id;
4137   uint32_t ack;
4138   uint16_t type;
4139   int work;
4140
4141   type = ntohs (message->type);
4142   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a %s message from %s!\n",
4143               GNUNET_MESH_DEBUG_M2S (type), GNUNET_i2s (peer));
4144   msg = (struct GNUNET_MESH_DataACK *) message;
4145
4146   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4147   if (NULL == t)
4148   {
4149     /* TODO notify that we dont know this tunnel (whom)? */
4150     GNUNET_STATISTICS_update (stats, "# ack on unknown tunnel", 1, GNUNET_NO);
4151     return GNUNET_OK;
4152   }
4153   ack = ntohl (msg->mid);
4154   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ACK %u\n", ack);
4155
4156   /* Is this a forward or backward ACK? */
4157   id = GNUNET_PEER_search (peer);
4158   if (t->next_hop == id && GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK == type)
4159   {
4160     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
4161     if (NULL == t->owner)
4162     {
4163       send_prebuilt_message (message, t->prev_hop, t);
4164       return GNUNET_OK;
4165     }
4166     rel = t->fwd_rel;
4167   }
4168   else if (t->prev_hop == id && GNUNET_MESSAGE_TYPE_MESH_TO_ORIG_ACK == type)
4169   {
4170     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
4171     if (NULL == t->client)
4172     {
4173       send_prebuilt_message (message, t->next_hop, t);
4174       return GNUNET_OK;
4175     }
4176     rel = t->bck_rel;
4177   }
4178   else
4179   {
4180     GNUNET_break_op (0);
4181     return GNUNET_OK;
4182   }
4183
4184   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! ACK %u\n", ack);
4185   for (work = GNUNET_NO, copy = rel->head_sent; copy != NULL; copy = next)
4186   {
4187    if (GMC_is_pid_bigger (copy->mid, ack))
4188     {
4189       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!!  head %u, out!\n", copy->mid);
4190       tunnel_free_sent_reliable (t, msg, rel);
4191       break;
4192     }
4193     work = GNUNET_YES;
4194     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!!  id %u\n", copy->mid);
4195     next = copy->next;
4196     tunnel_free_reliable_message (copy);
4197   }
4198   /* Once buffers have been free'd, send ACK */
4199   tunnel_send_ack (t, type, GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK == type);
4200
4201   /* If some message was free'd, update the retransmission delay*/
4202   if (GNUNET_YES == work)
4203   {
4204     if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
4205     {
4206       GNUNET_SCHEDULER_cancel (rel->retry_task);
4207       if (NULL == rel->head_sent)
4208       {
4209         rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
4210       }
4211       else
4212       {
4213         struct GNUNET_TIME_Absolute new_target;
4214         struct GNUNET_TIME_Relative delay;
4215
4216         delay = GNUNET_TIME_relative_multiply (rel->retry_timer,
4217                                                MESH_RETRANSMIT_MARGIN);
4218         new_target = GNUNET_TIME_absolute_add (rel->head_sent->timestamp,
4219                                                delay);
4220         delay = GNUNET_TIME_absolute_get_remaining (new_target);
4221         rel->retry_task =
4222             GNUNET_SCHEDULER_add_delayed (delay,
4223                                           &tunnel_retransmit_message,
4224                                           rel);
4225       }
4226     }
4227     else
4228       GNUNET_break (0);
4229   }
4230   return GNUNET_OK;
4231 }
4232
4233 /**
4234  * Core handler for mesh network traffic point-to-point acks.
4235  *
4236  * @param cls closure
4237  * @param message message
4238  * @param peer peer identity this notification is about
4239  *
4240  * @return GNUNET_OK to keep the connection open,
4241  *         GNUNET_SYSERR to close it (signal serious error)
4242  */
4243 static int
4244 handle_mesh_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
4245                  const struct GNUNET_MessageHeader *message)
4246 {
4247   struct GNUNET_MESH_ACK *msg;
4248   struct MeshTunnel *t;
4249   struct MeshFlowControl *fc;
4250   GNUNET_PEER_Id id;
4251   uint32_t ack;
4252
4253   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK packet from %s!\n",
4254               GNUNET_i2s (peer));
4255   msg = (struct GNUNET_MESH_ACK *) message;
4256
4257   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4258
4259   if (NULL == t)
4260   {
4261     /* TODO notify that we dont know this tunnel (whom)? */
4262     GNUNET_STATISTICS_update (stats, "# ack on unknown tunnel", 1, GNUNET_NO);
4263     return GNUNET_OK;
4264   }
4265   ack = ntohl (msg->pid);
4266   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ACK %u\n", ack);
4267
4268   /* Is this a forward or backward ACK? */
4269   id = GNUNET_PEER_search (peer);
4270   if (t->next_hop == id)
4271   {
4272     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
4273     fc = &t->next_fc;
4274   }
4275   else if (t->prev_hop == id)
4276   {
4277     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
4278     fc = &t->prev_fc;
4279   }
4280   else
4281   {
4282     GNUNET_break_op (0);
4283     return GNUNET_OK;
4284   }
4285
4286   if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task &&
4287       GMC_is_pid_bigger (ack, fc->last_ack_recv))
4288   {
4289     GNUNET_SCHEDULER_cancel (fc->poll_task);
4290     fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
4291     fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
4292   }
4293   fc->last_ack_recv = ack;
4294   peer_unlock_queue (id);
4295
4296   tunnel_send_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK, t->next_hop == id);
4297
4298   return GNUNET_OK;
4299 }
4300
4301
4302 /**
4303  * Core handler for mesh network traffic point-to-point ack polls.
4304  *
4305  * @param cls closure
4306  * @param message message
4307  * @param peer peer identity this notification is about
4308  *
4309  * @return GNUNET_OK to keep the connection open,
4310  *         GNUNET_SYSERR to close it (signal serious error)
4311  */
4312 static int
4313 handle_mesh_poll (void *cls, const struct GNUNET_PeerIdentity *peer,
4314                   const struct GNUNET_MessageHeader *message)
4315 {
4316   struct GNUNET_MESH_Poll *msg;
4317   struct MeshTunnel *t;
4318   struct MeshFlowControl *fc;
4319   GNUNET_PEER_Id id;
4320   uint32_t pid;
4321   uint32_t old;
4322
4323   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an POLL packet from %s!\n",
4324               GNUNET_i2s (peer));
4325
4326   msg = (struct GNUNET_MESH_Poll *) message;
4327
4328   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4329
4330   if (NULL == t)
4331   {
4332     /* TODO notify that we dont know this tunnel (whom)? */
4333     GNUNET_STATISTICS_update (stats, "# poll on unknown tunnel", 1, GNUNET_NO);
4334     GNUNET_break_op (0);
4335     return GNUNET_OK;
4336   }
4337
4338   /* Is this a forward or backward ACK? */
4339   id = GNUNET_PEER_search (peer);
4340   pid = ntohl (msg->pid);
4341   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  PID %u\n", pid);
4342   if (t->next_hop == id)
4343   {
4344     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  from FWD\n");
4345     fc = &t->next_fc;
4346     old = fc->last_pid_recv;
4347   }
4348   else if (t->prev_hop == id)
4349   {
4350     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  from BCK\n");
4351     fc = &t->prev_fc;
4352     old = fc->last_pid_recv;
4353   }
4354   else
4355   {
4356     GNUNET_break (0);
4357     return GNUNET_OK;
4358   }
4359
4360   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  was %u\n", fc->last_pid_recv);
4361   fc->last_pid_recv = pid;
4362   tunnel_send_ack (t, GNUNET_MESSAGE_TYPE_MESH_POLL, t->prev_hop == id);
4363
4364   if (GNUNET_YES == t->reliable)
4365     fc->last_pid_recv = old;
4366
4367   return GNUNET_OK;
4368 }
4369
4370
4371 /**
4372  * Core handler for mesh keepalives.
4373  *
4374  * @param cls closure
4375  * @param message message
4376  * @param peer peer identity this notification is about
4377  * @return GNUNET_OK to keep the connection open,
4378  *         GNUNET_SYSERR to close it (signal serious error)
4379  *
4380  * TODO: Check who we got this from, to validate route.
4381  */
4382 static int
4383 handle_mesh_keepalive (void *cls, const struct GNUNET_PeerIdentity *peer,
4384                        const struct GNUNET_MessageHeader *message)
4385 {
4386   struct GNUNET_MESH_TunnelKeepAlive *msg;
4387   struct MeshTunnel *t;
4388
4389   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a keepalive packet from %s\n",
4390               GNUNET_i2s (peer));
4391
4392   msg = (struct GNUNET_MESH_TunnelKeepAlive *) message;
4393   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4394
4395   if (NULL == t)
4396   {
4397     /* TODO notify that we dont know that tunnel */
4398     GNUNET_STATISTICS_update (stats, "# keepalive on unknown tunnel", 1,
4399                               GNUNET_NO);
4400     return GNUNET_OK;
4401   }
4402
4403   tunnel_reset_timeout (t, GNUNET_YES); // FIXME
4404   if (NULL != t->client || 0 == t->next_hop || myid == t->next_hop)
4405     return GNUNET_OK;
4406
4407   GNUNET_STATISTICS_update (stats, "# keepalives forwarded", 1, GNUNET_NO);
4408   send_prebuilt_message (message, t->next_hop, t);
4409   return GNUNET_OK;
4410   }
4411
4412
4413
4414 /**
4415  * Functions to handle messages from core
4416  */
4417 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
4418   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
4419   {&handle_mesh_path_broken, GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN,
4420    sizeof (struct GNUNET_MESH_PathBroken)},
4421   {&handle_mesh_tunnel_destroy, GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY,
4422    sizeof (struct GNUNET_MESH_TunnelDestroy)},
4423   {&handle_mesh_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
4424   {&handle_mesh_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
4425   {&handle_mesh_data_ack, GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK,
4426     sizeof (struct GNUNET_MESH_DataACK)},
4427   {&handle_mesh_data_ack, GNUNET_MESSAGE_TYPE_MESH_TO_ORIG_ACK,
4428     sizeof (struct GNUNET_MESH_DataACK)},
4429   {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE,
4430     sizeof (struct GNUNET_MESH_TunnelKeepAlive)},
4431   {&handle_mesh_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
4432     sizeof (struct GNUNET_MESH_ACK)},
4433   {&handle_mesh_poll, GNUNET_MESSAGE_TYPE_MESH_POLL,
4434     sizeof (struct GNUNET_MESH_Poll)},
4435   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
4436    sizeof (struct GNUNET_MESH_PathACK)},
4437   {NULL, 0, 0}
4438 };
4439
4440
4441
4442 /******************************************************************************/
4443 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
4444 /******************************************************************************/
4445
4446
4447 #if LATER
4448 /**
4449  * notify_client_connection_failure: notify a client that the connection to the
4450  * requested remote peer is not possible (for instance, no route found)
4451  * Function called when the socket is ready to queue more data. "buf" will be
4452  * NULL and "size" zero if the socket was closed for writing in the meantime.
4453  *
4454  * @param cls closure
4455  * @param size number of bytes available in buf
4456  * @param buf where the callee should write the message
4457  * @return number of bytes written to buf
4458  */
4459 static size_t
4460 notify_client_connection_failure (void *cls, size_t size, void *buf)
4461 {
4462   int size_needed;
4463   struct MeshPeerInfo *peer_info;
4464   struct GNUNET_MESH_PeerControl *msg;
4465   struct GNUNET_PeerIdentity id;
4466
4467   if (0 == size && NULL == buf)
4468   {
4469     // TODO retry? cancel?
4470     return 0;
4471   }
4472
4473   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
4474   peer_info = (struct MeshPeerInfo *) cls;
4475   msg = (struct GNUNET_MESH_PeerControl *) buf;
4476   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
4477   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
4478 //     msg->tunnel_id = htonl(peer_info->t->tid);
4479   GNUNET_PEER_resolve (peer_info->id, &id);
4480   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
4481
4482   return size_needed;
4483 }
4484 #endif
4485
4486
4487 /**
4488  * Send keepalive packets for a tunnel.
4489  *
4490  * @param cls Closure (tunnel for which to send the keepalive).
4491  * @param tc Notification context.
4492  * 
4493  * FIXME: add a refresh reset in case of normal unicast traffic is doing the job
4494  */
4495 static void
4496 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4497 {
4498   struct MeshTunnel *t = cls;
4499   struct GNUNET_MESH_TunnelKeepAlive *msg;
4500   size_t size = sizeof (struct GNUNET_MESH_TunnelKeepAlive);
4501   char cbuf[size];
4502
4503   t->maintenance_task = GNUNET_SCHEDULER_NO_TASK;
4504   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) ||
4505       NULL == t->owner || 0 == t->local_tid)
4506   {
4507     return;
4508   }
4509
4510   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4511               "sending keepalive for tunnel %d\n", t->id.tid);
4512
4513   msg = (struct GNUNET_MESH_TunnelKeepAlive *) cbuf;
4514   msg->header.size = htons (size);
4515   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE);
4516   msg->oid = my_full_id;
4517   msg->tid = htonl (t->id.tid);
4518   send_prebuilt_message (&msg->header, t->next_hop, t);
4519
4520   t->maintenance_task =
4521       GNUNET_SCHEDULER_add_delayed (refresh_path_time, &path_refresh, t);
4522 }
4523
4524
4525 /**
4526  * Function to process paths received for a new peer addition. The recorded
4527  * paths form the initial tunnel, which can be optimized later.
4528  * Called on each result obtained for the DHT search.
4529  *
4530  * @param cls closure
4531  * @param exp when will this value expire
4532  * @param key key of the result
4533  * @param get_path path of the get request
4534  * @param get_path_length lenght of get_path
4535  * @param put_path path of the put request
4536  * @param put_path_length length of the put_path
4537  * @param type type of the result
4538  * @param size number of bytes in data
4539  * @param data pointer to the result data
4540  */
4541 static void
4542 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
4543                     const struct GNUNET_HashCode * key,
4544                     const struct GNUNET_PeerIdentity *get_path,
4545                     unsigned int get_path_length,
4546                     const struct GNUNET_PeerIdentity *put_path,
4547                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
4548                     size_t size, const void *data)
4549 {
4550   struct MeshPeerInfo *peer = cls;
4551   struct MeshPeerPath *p;
4552   struct GNUNET_PeerIdentity pi;
4553   int i;
4554
4555   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
4556   GNUNET_PEER_resolve (peer->id, &pi);
4557   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", GNUNET_i2s (&pi));
4558
4559   p = path_build_from_dht (get_path, get_path_length,
4560                            put_path, put_path_length);
4561   path_add_to_peers (p, GNUNET_NO);
4562   path_destroy (p);
4563   for (i = 0; i < peer->ntunnels; i++)
4564   {
4565     struct GNUNET_PeerIdentity id;
4566
4567     GNUNET_PEER_resolve (peer->tunnels[i]->id.oid, &id);
4568     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ... tunnel %s:%X (%X / %X)\n",
4569                 GNUNET_i2s (&id), peer->tunnels[i]->id.tid,
4570                 peer->tunnels[i]->local_tid, 
4571                 peer->tunnels[i]->local_tid_dest);
4572     if (peer->tunnels[i]->state == MESH_TUNNEL_SEARCHING)
4573     {
4574       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ... connect!\n");
4575       peer_connect (peer, peer->tunnels[i]);
4576     }
4577   }
4578
4579   return;
4580 }
4581
4582
4583 /******************************************************************************/
4584 /*********************       MESH LOCAL HANDLES      **************************/
4585 /******************************************************************************/
4586
4587
4588 /**
4589  * Handler for client connection.
4590  *
4591  * @param cls Closure (unused).
4592  * @param client Client handler.
4593  */
4594 static void
4595 handle_local_client_connect (void *cls, struct GNUNET_SERVER_Client *client)
4596 {
4597   struct MeshClient *c;
4598
4599   if (NULL == client)
4600     return;
4601   c = GNUNET_malloc (sizeof (struct MeshClient));
4602   c->handle = client;
4603   GNUNET_SERVER_client_keep (client);
4604   GNUNET_SERVER_client_set_user_context (client, c);
4605   GNUNET_CONTAINER_DLL_insert (clients_head, clients_tail, c);
4606 }
4607
4608
4609 /**
4610  * Handler for client disconnection
4611  *
4612  * @param cls closure
4613  * @param client identification of the client; NULL
4614  *        for the last call when the server is destroyed
4615  */
4616 static void
4617 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
4618 {
4619   struct MeshClient *c;
4620   struct MeshClient *next;
4621
4622   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected: %p\n", client);
4623   if (client == NULL)
4624   {
4625     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (SERVER DOWN)\n");
4626     return;
4627   }
4628
4629   c = client_get (client);
4630   if (NULL != c)
4631   {
4632     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u)\n",
4633                 c->id);
4634     GNUNET_SERVER_client_drop (c->handle);
4635     c->shutting_down = GNUNET_YES;
4636     if (NULL != c->own_tunnels)
4637     {
4638       GNUNET_CONTAINER_multihashmap32_iterate (c->own_tunnels,
4639                                                &tunnel_destroy_iterator, c);
4640       GNUNET_CONTAINER_multihashmap32_destroy (c->own_tunnels);
4641     }
4642
4643     if (NULL != c->incoming_tunnels)
4644     {
4645       GNUNET_CONTAINER_multihashmap32_iterate (c->incoming_tunnels,
4646                                              &tunnel_destroy_iterator, c);
4647       GNUNET_CONTAINER_multihashmap32_destroy (c->incoming_tunnels);
4648     }
4649
4650     if (NULL != c->ports)
4651       GNUNET_CONTAINER_multihashmap32_destroy (c->ports);
4652     next = c->next;
4653     GNUNET_CONTAINER_DLL_remove (clients_head, clients_tail, c);
4654     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT FREE at %p\n", c);
4655     GNUNET_free (c);
4656     GNUNET_STATISTICS_update (stats, "# clients", -1, GNUNET_NO);
4657     c = next;
4658   }
4659   else
4660   {
4661     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " context NULL!\n");
4662   }
4663   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "done!\n");
4664   return;
4665 }
4666
4667
4668 /**
4669  * Handler for new clients
4670  *
4671  * @param cls closure
4672  * @param client identification of the client
4673  * @param message the actual message, which includes messages the client wants
4674  */
4675 static void
4676 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
4677                          const struct GNUNET_MessageHeader *message)
4678 {
4679   struct GNUNET_MESH_ClientConnect *cc_msg;
4680   struct MeshClient *c;
4681   unsigned int size;
4682   uint32_t *p;
4683   unsigned int i;
4684
4685   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected %p\n", client);
4686
4687   /* Check data sanity */
4688   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
4689   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
4690   if (0 != (size % sizeof (uint32_t)))
4691   {
4692     GNUNET_break (0);
4693     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4694     return;
4695   }
4696   size /= sizeof (uint32_t);
4697
4698   /* Initialize new client structure */
4699   c = GNUNET_SERVER_client_get_user_context (client, struct MeshClient);
4700   c->id = next_client_id++; /* overflow not important: just for debug */
4701   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  client id %u\n", c->id);
4702   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  client has %u ports\n", size);
4703   if (size > 0)
4704   {
4705     uint32_t u32;
4706
4707     p = (uint32_t *) &cc_msg[1];
4708     c->ports = GNUNET_CONTAINER_multihashmap32_create (size);
4709     for (i = 0; i < size; i++)
4710     {
4711       u32 = ntohl (p[i]);
4712       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    port: %u\n", u32);
4713
4714       /* store in client's hashmap */
4715       GNUNET_CONTAINER_multihashmap32_put (c->ports, u32, c,
4716                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
4717       /* store in global hashmap */
4718       /* FIXME only allow one client to have the port open,
4719        *       have a backup hashmap with waiting clients */
4720       GNUNET_CONTAINER_multihashmap32_put (ports, u32, c,
4721                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
4722     }
4723   }
4724
4725   c->own_tunnels = GNUNET_CONTAINER_multihashmap32_create (32);
4726   c->incoming_tunnels = GNUNET_CONTAINER_multihashmap32_create (32);
4727   GNUNET_SERVER_notification_context_add (nc, client);
4728   GNUNET_STATISTICS_update (stats, "# clients", 1, GNUNET_NO);
4729
4730   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4731   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
4732 }
4733
4734
4735 /**
4736  * Handler for requests of new tunnels
4737  *
4738  * @param cls Closure.
4739  * @param client Identification of the client.
4740  * @param message The actual message.
4741  */
4742 static void
4743 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
4744                             const struct GNUNET_MessageHeader *message)
4745 {
4746   struct GNUNET_MESH_TunnelMessage *t_msg;
4747   struct MeshPeerInfo *peer_info;
4748   struct MeshTunnel *t;
4749   struct MeshClient *c;
4750   MESH_TunnelNumber tid;
4751
4752   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel requested\n");
4753
4754   /* Sanity check for client registration */
4755   if (NULL == (c = client_get (client)))
4756   {
4757     GNUNET_break (0);
4758     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4759     return;
4760   }
4761   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
4762
4763   /* Message size sanity check */
4764   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
4765   {
4766     GNUNET_break (0);
4767     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4768     return;
4769   }
4770
4771   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
4772   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  towards %s\n",
4773               GNUNET_i2s (&t_msg->peer));
4774   /* Sanity check for tunnel numbering */
4775   tid = ntohl (t_msg->tunnel_id);
4776   if (0 == (tid & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
4777   {
4778     GNUNET_break (0);
4779     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4780     return;
4781   }
4782   /* Sanity check for duplicate tunnel IDs */
4783   if (NULL != tunnel_get_by_local_id (c, tid))
4784   {
4785     GNUNET_break (0);
4786     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4787     return;
4788   }
4789
4790   /* Create tunnel */
4791   while (NULL != tunnel_get_by_pi (myid, next_tid))
4792     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
4793   t = tunnel_new (myid, next_tid, c, tid);
4794   next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
4795   if (NULL == t)
4796   {
4797     GNUNET_break (0);
4798     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4799     return;
4800   }
4801   t->port = ntohl (t_msg->port);
4802   tunnel_set_options (t, ntohl (t_msg->opt));
4803   if (GNUNET_YES == t->reliable)
4804   {
4805     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! Reliable\n");
4806     t->fwd_rel = GNUNET_malloc (sizeof (struct MeshTunnelReliability));
4807     t->fwd_rel->t = t;
4808     t->fwd_rel->expected_delay = MESH_RETRANSMIT_TIME;
4809   }
4810
4811   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED TUNNEL %s[%x]:%u (%x)\n",
4812               GNUNET_i2s (&my_full_id), t->id.tid, t->port, t->local_tid);
4813
4814   peer_info = peer_get (&t_msg->peer);
4815   peer_info_add_tunnel (peer_info, t);
4816   peer_connect (peer_info, t);
4817   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4818   return;
4819 }
4820
4821
4822 /**
4823  * Handler for requests of deleting tunnels
4824  *
4825  * @param cls closure
4826  * @param client identification of the client
4827  * @param message the actual message
4828  */
4829 static void
4830 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
4831                              const struct GNUNET_MessageHeader *message)
4832 {
4833   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
4834   struct MeshClient *c;
4835   struct MeshTunnel *t;
4836   MESH_TunnelNumber tid;
4837
4838   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4839               "Got a DESTROY TUNNEL from client!\n");
4840
4841   /* Sanity check for client registration */
4842   if (NULL == (c = client_get (client)))
4843   {
4844     GNUNET_break (0);
4845     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4846     return;
4847   }
4848   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
4849
4850   /* Message sanity check */
4851   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
4852   {
4853     GNUNET_break (0);
4854     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4855     return;
4856   }
4857
4858   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
4859
4860   /* Retrieve tunnel */
4861   tid = ntohl (tunnel_msg->tunnel_id);
4862   t = tunnel_get_by_local_id(c, tid);
4863   if (NULL == t)
4864   {
4865     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
4866     GNUNET_break (0);
4867     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4868     return;
4869   }
4870
4871   /* Cleanup after the tunnel */
4872   client_delete_tunnel (c, t);
4873   if (c == t->client)
4874   {
4875     t->client = NULL;
4876   }
4877   if (c == t->owner)
4878   {
4879     peer_info_remove_tunnel (peer_get_short (t->dest), t);
4880     t->owner = NULL;
4881   }
4882
4883   /* The tunnel will be destroyed when the last message is transmitted. */
4884   tunnel_destroy_empty (t);
4885
4886   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4887   return;
4888 }
4889
4890
4891 /**
4892  * Handler for client traffic
4893  *
4894  * @param cls closure
4895  * @param client identification of the client
4896  * @param message the actual message
4897  */
4898 static void
4899 handle_local_data (void *cls, struct GNUNET_SERVER_Client *client,
4900                    const struct GNUNET_MessageHeader *message)
4901 {
4902   struct GNUNET_MESH_LocalData *data_msg;
4903   struct MeshClient *c;
4904   struct MeshTunnel *t;
4905   struct MeshFlowControl *fc;
4906   MESH_TunnelNumber tid;
4907   size_t size;
4908
4909   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4910               "Got data from a client!\n");
4911
4912   /* Sanity check for client registration */
4913   if (NULL == (c = client_get (client)))
4914   {
4915     GNUNET_break (0);
4916     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4917     return;
4918   }
4919   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
4920
4921   data_msg = (struct GNUNET_MESH_LocalData *) message;
4922
4923   /* Sanity check for message size */
4924   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_LocalData);
4925   if (size < sizeof (struct GNUNET_MessageHeader))
4926   {
4927     GNUNET_break (0);
4928     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4929     return;
4930   }
4931
4932   /* Tunnel exists? */
4933   tid = ntohl (data_msg->tid);
4934   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_CLI)
4935   {
4936     GNUNET_break (0);
4937     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4938     return;
4939   }
4940   t = tunnel_get_by_local_id (c, tid);
4941   if (NULL == t)
4942   {
4943     GNUNET_break (0);
4944     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4945     return;
4946   }
4947
4948   /* Is the client in the tunnel? */
4949   if ( !( (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV &&
4950            t->owner &&
4951            t->owner->handle == client)
4952          ||
4953           (tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV &&
4954            t->client && 
4955            t->client->handle == client) ) )
4956   {
4957     GNUNET_break (0);
4958     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4959     return;
4960   }
4961
4962   /* Ok, everything is correct, send the message
4963    * (pretend we got it from a mesh peer)
4964    */
4965   {
4966     struct GNUNET_MESH_Data *payload;
4967     char cbuf[sizeof(struct GNUNET_MESH_Data) + size];
4968
4969     fc = tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV ? &t->prev_fc : &t->next_fc;
4970     if (GNUNET_YES == t->reliable)
4971     {
4972       struct MeshTunnelReliability *rel;
4973       struct MeshReliableMessage *copy;
4974
4975       rel = (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV) ? t->fwd_rel : t->bck_rel;
4976       copy = GNUNET_malloc (sizeof (struct MeshReliableMessage)
4977                             + sizeof(struct GNUNET_MESH_Data)
4978                             + size);
4979       copy->mid = rel->mid_sent++;
4980       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! DATA %u\n", copy->mid);
4981       copy->timestamp = GNUNET_TIME_absolute_get ();
4982       copy->rel = rel;
4983       rel->n_sent++;
4984       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " n_sent %u\n", rel->n_sent);
4985       GNUNET_CONTAINER_DLL_insert_tail (rel->head_sent, rel->tail_sent, copy);
4986       if (GNUNET_SCHEDULER_NO_TASK == rel->retry_task)
4987       {
4988         rel->retry_timer =
4989             GNUNET_TIME_relative_multiply (rel->expected_delay,
4990                                            MESH_RETRANSMIT_MARGIN);
4991         rel->retry_task =
4992             GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
4993                                           &tunnel_retransmit_message,
4994                                           rel);
4995       }
4996       payload = (struct GNUNET_MESH_Data *) &copy[1];
4997       payload->mid = htonl (copy->mid);
4998     }
4999     else
5000     {
5001       payload = (struct GNUNET_MESH_Data *) cbuf;
5002       payload->mid = htonl (fc->last_pid_recv + 1);
5003     }
5004     memcpy (&payload[1], &data_msg[1], size);
5005     payload->header.size = htons (sizeof (struct GNUNET_MESH_Data) + size);
5006     payload->header.type = htons (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV ?
5007                                   GNUNET_MESSAGE_TYPE_MESH_UNICAST :
5008                                   GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
5009     GNUNET_PEER_resolve(t->id.oid, &payload->oid);;
5010     payload->tid = htonl (t->id.tid);
5011     payload->ttl = htonl (default_ttl);
5012     payload->pid = htonl (fc->last_pid_recv + 1);
5013     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5014                 "  calling generic handler...\n");
5015     if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
5016       handle_mesh_unicast (NULL, &my_full_id, &payload->header);
5017     else
5018       handle_mesh_to_orig (NULL, &my_full_id, &payload->header);
5019   }
5020   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "receive done OK\n");
5021   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5022
5023   return;
5024 }
5025
5026
5027 /**
5028  * Handler for client's ACKs for payload traffic.
5029  *
5030  * @param cls Closure (unused).
5031  * @param client Identification of the client.
5032  * @param message The actual message.
5033  */
5034 static void
5035 handle_local_ack (void *cls, struct GNUNET_SERVER_Client *client,
5036                   const struct GNUNET_MessageHeader *message)
5037 {
5038   struct GNUNET_MESH_LocalAck *msg;
5039   struct MeshTunnel *t;
5040   struct MeshClient *c;
5041   MESH_TunnelNumber tid;
5042
5043   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a local ACK\n");
5044   /* Sanity check for client registration */
5045   if (NULL == (c = client_get (client)))
5046   {
5047     GNUNET_break (0);
5048     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5049     return;
5050   }
5051   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
5052
5053   msg = (struct GNUNET_MESH_LocalAck *) message;
5054
5055   /* Tunnel exists? */
5056   tid = ntohl (msg->tunnel_id);
5057   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
5058   t = tunnel_get_by_local_id (c, tid);
5059   if (NULL == t)
5060   {
5061     GNUNET_break (0);
5062     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
5063     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
5064     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5065     return;
5066   }
5067
5068   /* Does client own tunnel? I.E: Is this an ACK for BCK traffic? */
5069   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
5070   {
5071     /* The client owns the tunnel, ACK is for data to_origin, send BCK ACK. */
5072     t->prev_fc.last_ack_recv++;
5073     tunnel_send_ack (t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK, GNUNET_NO);
5074   }
5075   else
5076   {
5077     /* The client doesn't own the tunnel, this ACK is for FWD traffic. */
5078     t->next_fc.last_ack_recv++;
5079     tunnel_send_ack (t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK, GNUNET_YES);
5080   }
5081
5082   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5083
5084   return;
5085 }
5086
5087
5088
5089 /**
5090  * Iterator over all tunnels to send a monitoring client info about each tunnel.
5091  *
5092  * @param cls Closure (client handle).
5093  * @param key Key (hashed tunnel ID, unused).
5094  * @param value Tunnel info.
5095  *
5096  * @return GNUNET_YES, to keep iterating.
5097  */
5098 static int
5099 monitor_all_tunnels_iterator (void *cls,
5100                               const struct GNUNET_HashCode * key,
5101                               void *value)
5102 {
5103   struct GNUNET_SERVER_Client *client = cls;
5104   struct MeshTunnel *t = value;
5105   struct GNUNET_MESH_LocalMonitor *msg;
5106
5107   msg = GNUNET_malloc (sizeof(struct GNUNET_MESH_LocalMonitor));
5108   GNUNET_PEER_resolve(t->id.oid, &msg->owner);
5109   msg->tunnel_id = htonl (t->id.tid);
5110   msg->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
5111   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS);
5112   GNUNET_PEER_resolve (t->dest, &msg->destination);
5113
5114   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5115               "*  sending info about tunnel %s [%u]\n",
5116               GNUNET_i2s (&msg->owner), t->id.tid);
5117
5118   GNUNET_SERVER_notification_context_unicast (nc, client,
5119                                               &msg->header, GNUNET_NO);
5120   return GNUNET_YES;
5121 }
5122
5123
5124 /**
5125  * Handler for client's MONITOR request.
5126  *
5127  * @param cls Closure (unused).
5128  * @param client Identification of the client.
5129  * @param message The actual message.
5130  */
5131 static void
5132 handle_local_get_tunnels (void *cls, struct GNUNET_SERVER_Client *client,
5133                           const struct GNUNET_MessageHeader *message)
5134 {
5135   struct MeshClient *c;
5136
5137   /* Sanity check for client registration */
5138   if (NULL == (c = client_get (client)))
5139   {
5140     GNUNET_break (0);
5141     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5142     return;
5143   }
5144
5145   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5146               "Received get tunnels request from client %u\n",
5147               c->id);
5148   GNUNET_CONTAINER_multihashmap_iterate (tunnels,
5149                                          monitor_all_tunnels_iterator,
5150                                          client);
5151   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5152               "Get tunnels request from client %u completed\n",
5153               c->id);
5154   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5155 }
5156
5157
5158 /**
5159  * Handler for client's MONITOR_TUNNEL request.
5160  *
5161  * @param cls Closure (unused).
5162  * @param client Identification of the client.
5163  * @param message The actual message.
5164  */
5165 static void
5166 handle_local_show_tunnel (void *cls, struct GNUNET_SERVER_Client *client,
5167                           const struct GNUNET_MessageHeader *message)
5168 {
5169   const struct GNUNET_MESH_LocalMonitor *msg;
5170   struct GNUNET_MESH_LocalMonitor *resp;
5171   struct MeshClient *c;
5172   struct MeshTunnel *t;
5173
5174   /* Sanity check for client registration */
5175   if (NULL == (c = client_get (client)))
5176   {
5177     GNUNET_break (0);
5178     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5179     return;
5180   }
5181
5182   msg = (struct GNUNET_MESH_LocalMonitor *) message;
5183   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5184               "Received tunnel info request from client %u for tunnel %s[%X]\n",
5185               c->id,
5186               &msg->owner,
5187               ntohl (msg->tunnel_id));
5188   t = tunnel_get (&msg->owner, ntohl (msg->tunnel_id));
5189   if (NULL == t)
5190   {
5191     /* We don't know the tunnel FIXME */
5192     struct GNUNET_MESH_LocalMonitor warn;
5193
5194     warn = *msg;
5195     GNUNET_SERVER_notification_context_unicast (nc, client,
5196                                                 &warn.header,
5197                                                 GNUNET_NO);
5198     GNUNET_SERVER_receive_done (client, GNUNET_OK);
5199     return;
5200   }
5201
5202   /* Initialize context */
5203   resp = GNUNET_malloc (sizeof (struct GNUNET_MESH_LocalMonitor));
5204   *resp = *msg;
5205   GNUNET_PEER_resolve (t->dest, &resp->destination);
5206   resp->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
5207   GNUNET_SERVER_notification_context_unicast (nc, c->handle,
5208                                               &resp->header, GNUNET_NO);
5209   GNUNET_free (resp);
5210
5211   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5212               "Monitor tunnel request from client %u completed\n",
5213               c->id);
5214   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5215 }
5216
5217
5218 /**
5219  * Functions to handle messages from clients
5220  */
5221 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
5222   {&handle_local_new_client, NULL,
5223    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
5224   {&handle_local_tunnel_create, NULL,
5225    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
5226    sizeof (struct GNUNET_MESH_TunnelMessage)},
5227   {&handle_local_tunnel_destroy, NULL,
5228    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
5229    sizeof (struct GNUNET_MESH_TunnelMessage)},
5230   {&handle_local_data, NULL,
5231    GNUNET_MESSAGE_TYPE_MESH_LOCAL_DATA, 0},
5232   {&handle_local_ack, NULL,
5233    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK,
5234    sizeof (struct GNUNET_MESH_LocalAck)},
5235   {&handle_local_get_tunnels, NULL,
5236    GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS,
5237    sizeof (struct GNUNET_MessageHeader)},
5238   {&handle_local_show_tunnel, NULL,
5239    GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNEL,
5240      sizeof (struct GNUNET_MESH_LocalMonitor)},
5241   {NULL, NULL, 0, 0}
5242 };
5243
5244
5245 /**
5246  * Method called whenever a given peer connects.
5247  *
5248  * @param cls closure
5249  * @param peer peer identity this notification is about
5250  */
5251 static void
5252 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer)
5253 {
5254   struct MeshPeerInfo *peer_info;
5255   struct MeshPeerPath *path;
5256
5257   DEBUG_CONN ("Peer connected\n");
5258   DEBUG_CONN ("     %s\n", GNUNET_i2s (&my_full_id));
5259   peer_info = peer_get (peer);
5260   if (myid == peer_info->id)
5261   {
5262     DEBUG_CONN ("     (self)\n");
5263     path = path_new (1);
5264   }
5265   else
5266   {
5267     DEBUG_CONN ("     %s\n", GNUNET_i2s (peer));
5268     path = path_new (2);
5269     path->peers[1] = peer_info->id;
5270     GNUNET_PEER_change_rc (peer_info->id, 1);
5271     GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
5272   }
5273   path->peers[0] = myid;
5274   GNUNET_PEER_change_rc (myid, 1);
5275   peer_info_add_path (peer_info, path, GNUNET_YES);
5276   return;
5277 }
5278
5279
5280 /**
5281  * Method called whenever a peer disconnects.
5282  *
5283  * @param cls closure
5284  * @param peer peer identity this notification is about
5285  */
5286 static void
5287 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
5288 {
5289   struct MeshPeerInfo *pi;
5290   struct MeshPeerQueue *q;
5291   struct MeshPeerQueue *n;
5292
5293   DEBUG_CONN ("Peer disconnected\n");
5294   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
5295   if (NULL == pi)
5296   {
5297     GNUNET_break (0);
5298     return;
5299   }
5300   q = pi->queue_head;
5301   while (NULL != q)
5302   {
5303       n = q->next;
5304       /* TODO try to reroute this traffic instead */
5305       queue_destroy(q, GNUNET_YES);
5306       q = n;
5307   }
5308   if (NULL != pi->core_transmit)
5309   {
5310     GNUNET_CORE_notify_transmit_ready_cancel(pi->core_transmit);
5311     pi->core_transmit = NULL;
5312   }
5313     peer_remove_path (pi, pi->id, myid);
5314   if (myid == pi->id)
5315   {
5316     DEBUG_CONN ("     (self)\n");
5317   }
5318   GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
5319   return;
5320 }
5321
5322
5323 /**
5324  * Install server (service) handlers and start listening to clients.
5325  */
5326 static void
5327 server_init (void)
5328 {
5329   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
5330   GNUNET_SERVER_connect_notify (server_handle,
5331                                 &handle_local_client_connect, NULL);
5332   GNUNET_SERVER_disconnect_notify (server_handle,
5333                                    &handle_local_client_disconnect, NULL);
5334   nc = GNUNET_SERVER_notification_context_create (server_handle, 1);
5335
5336   clients_head = NULL;
5337   clients_tail = NULL;
5338   next_client_id = 0;
5339   GNUNET_SERVER_resume (server_handle);
5340 }
5341
5342
5343 /**
5344  * To be called on core init/fail.
5345  *
5346  * @param cls Closure (config)
5347  * @param server handle to the server for this service
5348  * @param identity the public identity of this peer
5349  */
5350 static void
5351 core_init (void *cls, struct GNUNET_CORE_Handle *server,
5352            const struct GNUNET_PeerIdentity *identity)
5353 {
5354   const struct GNUNET_CONFIGURATION_Handle *c = cls;
5355   static int i = 0;
5356
5357   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
5358   GNUNET_break (core_handle == server);
5359   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)) ||
5360     NULL == server)
5361   {
5362     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
5363     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5364                 " core id %s\n",
5365                 GNUNET_i2s (identity));
5366     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5367                 " my id %s\n",
5368                 GNUNET_i2s (&my_full_id));
5369     GNUNET_CORE_disconnect (core_handle);
5370     core_handle = GNUNET_CORE_connect (c, /* Main configuration */
5371                                        NULL,      /* Closure passed to MESH functions */
5372                                        &core_init,        /* Call core_init once connected */
5373                                        &core_connect,     /* Handle connects */
5374                                        &core_disconnect,  /* remove peers on disconnects */
5375                                        NULL,      /* Don't notify about all incoming messages */
5376                                        GNUNET_NO, /* For header only in notification */
5377                                        NULL,      /* Don't notify about all outbound messages */
5378                                        GNUNET_NO, /* For header-only out notification */
5379                                        core_handlers);    /* Register these handlers */
5380     if (10 < i++)
5381       GNUNET_abort();
5382   }
5383   server_init ();
5384   return;
5385 }
5386
5387
5388 /******************************************************************************/
5389 /************************      MAIN FUNCTIONS      ****************************/
5390 /******************************************************************************/
5391
5392 /**
5393  * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
5394  *
5395  * @param cls closure
5396  * @param key current key code
5397  * @param value value in the hash map
5398  * @return GNUNET_YES if we should continue to iterate,
5399  *         GNUNET_NO if not.
5400  */
5401 static int
5402 shutdown_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
5403 {
5404   struct MeshTunnel *t = value;
5405
5406   tunnel_destroy (t);
5407   return GNUNET_YES;
5408 }
5409
5410 /**
5411  * Iterator over peer hash map entries to destroy the tunnel during shutdown.
5412  *
5413  * @param cls closure
5414  * @param key current key code
5415  * @param value value in the hash map
5416  * @return GNUNET_YES if we should continue to iterate,
5417  *         GNUNET_NO if not.
5418  */
5419 static int
5420 shutdown_peer (void *cls, const struct GNUNET_HashCode * key, void *value)
5421 {
5422   struct MeshPeerInfo *p = value;
5423   struct MeshPeerQueue *q;
5424   struct MeshPeerQueue *n;
5425
5426   q = p->queue_head;
5427   while (NULL != q)
5428   {
5429       n = q->next;
5430       if (q->peer == p)
5431       {
5432         queue_destroy(q, GNUNET_YES);
5433       }
5434       q = n;
5435   }
5436   peer_info_destroy (p);
5437   return GNUNET_YES;
5438 }
5439
5440
5441 /**
5442  * Task run during shutdown.
5443  *
5444  * @param cls unused
5445  * @param tc unused
5446  */
5447 static void
5448 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
5449 {
5450   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
5451
5452   if (core_handle != NULL)
5453   {
5454     GNUNET_CORE_disconnect (core_handle);
5455     core_handle = NULL;
5456   }
5457   GNUNET_CONTAINER_multihashmap_iterate (tunnels, &shutdown_tunnel, NULL);
5458   GNUNET_CONTAINER_multihashmap_iterate (peers, &shutdown_peer, NULL);
5459   if (dht_handle != NULL)
5460   {
5461     GNUNET_DHT_disconnect (dht_handle);
5462     dht_handle = NULL;
5463   }
5464   if (nc != NULL)
5465   {
5466     GNUNET_SERVER_notification_context_destroy (nc);
5467     nc = NULL;
5468   }
5469   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
5470   {
5471     GNUNET_SCHEDULER_cancel (announce_id_task);
5472     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
5473   }
5474   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
5475 }
5476
5477
5478 /**
5479  * Process mesh requests.
5480  *
5481  * @param cls closure
5482  * @param server the initialized server
5483  * @param c configuration to use
5484  */
5485 static void
5486 run (void *cls, struct GNUNET_SERVER_Handle *server,
5487      const struct GNUNET_CONFIGURATION_Handle *c)
5488 {
5489   char *keyfile;
5490   struct GNUNET_CRYPTO_EccPrivateKey *pk;
5491
5492   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
5493   server_handle = server;
5494   GNUNET_SERVER_suspend (server_handle);
5495
5496   if (GNUNET_OK !=
5497       GNUNET_CONFIGURATION_get_value_filename (c, "PEER", "PRIVATE_KEY",
5498                                                &keyfile))
5499   {
5500     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5501                 _
5502                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5503                 "mesh", "peer/privatekey");
5504     GNUNET_SCHEDULER_shutdown ();
5505     return;
5506   }
5507
5508   if (GNUNET_OK !=
5509       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_PATH_TIME",
5510                                            &refresh_path_time))
5511   {
5512     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5513                 _
5514                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5515                 "mesh", "refresh path time");
5516     GNUNET_SCHEDULER_shutdown ();
5517     return;
5518   }
5519
5520   if (GNUNET_OK !=
5521       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "ID_ANNOUNCE_TIME",
5522                                            &id_announce_time))
5523   {
5524     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5525                 _
5526                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5527                 "mesh", "id announce time");
5528     GNUNET_SCHEDULER_shutdown ();
5529     return;
5530   }
5531
5532   if (GNUNET_OK !=
5533       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "CONNECT_TIMEOUT",
5534                                            &connect_timeout))
5535   {
5536     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5537                 _
5538                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5539                 "mesh", "connect timeout");
5540     GNUNET_SCHEDULER_shutdown ();
5541     return;
5542   }
5543
5544   if (GNUNET_OK !=
5545       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
5546                                              &max_msgs_queue))
5547   {
5548     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5549                 _
5550                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5551                 "mesh", "max msgs queue");
5552     GNUNET_SCHEDULER_shutdown ();
5553     return;
5554   }
5555
5556   if (GNUNET_OK !=
5557       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_TUNNELS",
5558                                              &max_tunnels))
5559   {
5560     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5561                 _
5562                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5563                 "mesh", "max tunnels");
5564     GNUNET_SCHEDULER_shutdown ();
5565     return;
5566   }
5567
5568   if (GNUNET_OK !=
5569       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
5570                                              &default_ttl))
5571   {
5572     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5573                 _
5574                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
5575                 "mesh", "default ttl", 64);
5576     default_ttl = 64;
5577   }
5578
5579   if (GNUNET_OK !=
5580       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_PEERS",
5581                                              &max_peers))
5582   {
5583     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5584                 _("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
5585                 "mesh", "max peers", 1000);
5586     max_peers = 1000;
5587   }
5588
5589   if (GNUNET_OK !=
5590       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DROP_PERCENT",
5591                                              &drop_percent))
5592   {
5593     drop_percent = 0;
5594   }
5595   else
5596   {
5597     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5598                 "Mesh is running with drop mode enabled. "
5599                 "This is NOT a good idea! "
5600                 "Remove the DROP_PERCENT option from your configuration.\n");
5601   }
5602
5603   if (GNUNET_OK !=
5604       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DHT_REPLICATION_LEVEL",
5605                                              &dht_replication_level))
5606   {
5607     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5608                 _
5609                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
5610                 "mesh", "dht replication level", 3);
5611     dht_replication_level = 3;
5612   }
5613
5614   tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
5615   incoming_tunnels = GNUNET_CONTAINER_multihashmap32_create (32);
5616   peers = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
5617   ports = GNUNET_CONTAINER_multihashmap32_create (32);
5618
5619   dht_handle = GNUNET_DHT_connect (c, 64);
5620   if (NULL == dht_handle)
5621   {
5622     GNUNET_break (0);
5623   }
5624   stats = GNUNET_STATISTICS_create ("mesh", c);
5625
5626   /* Scheduled the task to clean up when shutdown is called */
5627   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
5628                                 NULL);
5629   pk = GNUNET_CRYPTO_ecc_key_create_from_file (keyfile);
5630   GNUNET_free (keyfile);
5631   GNUNET_assert (NULL != pk);
5632   my_private_key = pk;
5633   GNUNET_CRYPTO_ecc_key_get_public (my_private_key, &my_public_key);
5634   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
5635                       &my_full_id.hashPubKey);
5636   myid = GNUNET_PEER_intern (&my_full_id);
5637   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5638               "Mesh for peer [%s] starting\n",
5639               GNUNET_i2s(&my_full_id));
5640
5641   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
5642                                      NULL,      /* Closure passed to MESH functions */
5643                                      &core_init,        /* Call core_init once connected */
5644                                      &core_connect,     /* Handle connects */
5645                                      &core_disconnect,  /* remove peers on disconnects */
5646                                      NULL,      /* Don't notify about all incoming messages */
5647                                      GNUNET_NO, /* For header only in notification */
5648                                      NULL,      /* Don't notify about all outbound messages */
5649                                      GNUNET_NO, /* For header-only out notification */
5650                                      core_handlers);    /* Register these handlers */
5651   if (NULL == core_handle)
5652   {
5653     GNUNET_break (0);
5654     GNUNET_SCHEDULER_shutdown ();
5655     return;
5656   }
5657   next_tid = 0;
5658   next_local_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
5659   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
5660   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Mesh service running\n");
5661 }
5662
5663
5664 /**
5665  * The main function for the mesh service.
5666  *
5667  * @param argc number of arguments from the command line
5668  * @param argv command line arguments
5669  * @return 0 ok, 1 on error
5670  */
5671 int
5672 main (int argc, char *const *argv)
5673 {
5674   int ret;
5675   int r;
5676
5677   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
5678   r = GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
5679                           NULL);
5680   ret = (GNUNET_OK == r) ? 0 : 1;
5681   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");
5682
5683   INTERVAL_SHOW;
5684
5685   return ret;
5686 }