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