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