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