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