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