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