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