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