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