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