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