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