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