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