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