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