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