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